Write the first blockchain in Java

Source: Internet
Author: User
Tags tojson

Original address: https://www.cnblogs.com/zacky31/p/9057193.html

Goal:

    • Create a "blockchain" of the most basic
    • Implement a simple mine-digging system

Premise:

  Have a certain foundation for object-oriented programming

Attention:

  It is important to note that this will not be a complete feature, on the contrary, this is an example of proof of concept that can help you learn more about blockchain.

Get ready:

I'm going to use Java and of course you can use any object-oriented language.

Environment:

    • JDK 8
    • Idea
    • Maven

Let's go

Blockchain is like multiple blocks connected together. Each of these blocks will have its own signature, which contains the block information and some data (such as transaction information) in front of it.

Each block contains not only the block information before it, but also itself. If the previous piece of content changes, its hash value will change, causing all the blocks behind it to change. by calculating and comparing the obtained hash value, we can determine whether the blockchain is legal. In other words, changing any content in the blockchain will change the signature of the entire blockchain.

Based on the above analysis, we first create a Block class.

Importjava.util.Date; Public classBlock { PublicString Hash;//Storing digital signatures     PublicString PreHash;//signature of the front block    PrivateString data; Private LongTimeStamp;  PublicBlock (String data, String preHash) { This. data =data;  This. PreHash =PreHash;  This. TimeStamp =NewDate (). GetTime (); }}

  Next, we need a way to generate the signature. There are many cryptographic algorithms to choose from, and the use of SHA256 is just right here.

Importjava.security.MessageDigest; Public classStringutil { Public Staticstring applySha256 (String input) {Try{MessageDigest Digest= Messagedigest.getinstance ("SHA-256"); byte[] hash = Digest.digest (Input.getbytes ("UTF-8"))); StringBuilder hexstring=NewStringBuilder ();  for(inti = 0; i < hash.length; i++) {String hex= Integer.tohexstring (0xFF &Hash[i]); if(hex.length () = = 1) hexstring.append (' 0 ');            Hexstring.append (hex); }            returnhexstring.tostring (); } Catch(Exception e) {Throw NewRuntimeException (e); }    }}

 Now, we add a method for calculating the digital signature to the Block class and modify its construction method.

 public   Block (string data, String PreHash) {        /span>this . Data = data;         this . PreHash = PreHash;  this . TimeStamp = new   Date (). GetTime ();     this . Hash = Calculatehash ();   public   string Calculatehash () {string Calculatedhash  = stringutil.applysha256 (PreHash + long.tostring (timeStamp) +        data);     return   Calculatedhash; }

Here, you can write a Main method to see the effect.

 Public classMain { Public Static voidMain (string[] args) {Block First=NewBlock ("Hi I am the first block", "0"); System.out.println ("Hash for Block 1:" +First.hash); Block Second=NewBlock ("Hi I am the second block", First.hash); System.out.println ("Hash for Block 2:" +Second.hash); Block Third=NewBlock ("Hi I am the third block", Second.hash); System.out.println ("Hash for Block 3:" +Third.hash); }}

You can see that each block has its own unique digital signature, and, of course, it's not a blockchain yet, so keep these blocks in a ArrayList. Run again after modifying the Main class.

ImportCom.google.gson.GsonBuilder;Importjava.util.ArrayList; Public classMain { Public StaticArraylist<block> Blockchain =NewArraylist<block>();  Public Static voidMain (string[] args) {Blockchain.add (NewBlock ("Hi I am the first block", "0")); Blockchain.add (NewBlock ("Hi I am the second block", Blockchain.get (Blockchain.size ()-1) (hash)) ; Blockchain.add (NewBlock ("Hi I am the third block", Blockchain.get (Blockchain.size ()-1) (hash)) ; String Blockchainjson=NewGsonbuilder (). setprettyprinting (). Create (). ToJson (blockchain);    System.out.println (Blockchainjson); }}

Now, you need a way to validate the created blockchain. Write a Ischainvalid () method. Any change in the block will cause this method to fail.

 Public StaticBoolean Ischainvalid () {Block currentblock;        Block Previousblock;  for(inti = 1; I < blockchain.size (); i++) {Currentblock=Blockchain.get (i); Previousblock= Blockchain.get (i-1); if(!currentBlock.hash.equals (Currentblock.calculatehash ())) {System.out.println ("Current hashes not equal!"); return false; }            if(!previousBlock.hash.equals (Currentblock.prehash)) {System.out.println ("Previous Hashes not equal!"); return false            }        }        return true; }

Next, try digging mine!

  

In the Block class, a new variant is added to the Calculatehash () method, and the Mineblock () method is required. The difficulty variable in this method is used to control the amount of computation. When the set value is low, most computers will be able to figure it out quickly.

Importjava.util.Date; Public classBlock { PublicString Hash;  PublicString PreHash; PrivateString data; Private LongTimeStamp; Private intnonce;  PublicBlock (String data, String preHash) { This. data =data;  This. PreHash =PreHash;  This. TimeStamp =NewDate (). GetTime ();  This. hash =Calculatehash (); }     Publicstring Calculatehash () {string Calculatedhash= stringutil.applysha256 (PreHash + long.tostring (timeStamp) + integer.tostring (nonce) +data); returnCalculatedhash; }     Public voidMineblock (intdifficulty) {String target=NewString (New Char[difficulty]). Replace (' + ', ' 0 ');  while(!hash.substring (0, difficulty). Equals (target) {nonce++; Hash=Calculatehash (); } System.out.println ("Block mined!!!" +hash); }}

We can define a static variable in the Main class. Try to call the Mineblock () method every time you create a new block.

ImportCom.google.gson.GsonBuilder;Importjava.util.ArrayList;Importjava.util.Date; Public classMain { Public StaticArraylist<block> Blockchain =NewArraylist<block>();  Public Static intDifficulty = 5;  Public Static voidMain (string[] args) {LongBeginTime1 =NewDate (). GetTime (); Blockchain.add (NewBlock ("Hi I am the first block", "0")); System.out.println ("Trying to mine block 1 ..."); Blockchain.get (0). Mineblock (difficulty); LongEndTime1 =NewDate (). GetTime (); System.out.println ("Mining Block 1 Cost" + (ENDTIME1-beginTime1)); LongBeginTime2 =NewDate (). GetTime (); Blockchain.add (NewBlock ("Hi I am the second block", Blockchain.get (Blockchain.size ()-1) (hash)) ; System.out.println ("Trying to mine block 2 ..."); Blockchain.get (1). Mineblock (difficulty); LongEndTime2 =NewDate (). GetTime (); System.out.println ("Mining Block 1 Cost" + (EndTime2-beginTime2)); LongBeginTime3 =NewDate (). GetTime (); Blockchain.add (NewBlock ("Hi I am the third block", Blockchain.get (Blockchain.size ()-1) (hash)) ; System.out.println ("Trying to mine block 3 ..."); Blockchain.get (2). Mineblock (difficulty); LongEndTime3 =NewDate (). GetTime (); System.out.println ("Mining Block 1 Cost" + (EndTime3-BeginTime3)); System.out.println ("\nblockchain is Valid:" +ischainvalid ()); String Blockchainjson=NewGsonbuilder (). setprettyprinting (). Create (). ToJson (blockchain);    System.out.println (Blockchainjson); }     Public StaticBoolean Ischainvalid () {Block currentblock;        Block Previousblock; String Hashtarget=NewString (New Char[difficulty]). Replace (' + ', ' 0 ');  for(inti = 1; I < blockchain.size (); i++) {Currentblock=Blockchain.get (i); Previousblock= Blockchain.get (i-1); if(!currentBlock.hash.equals (Currentblock.calculatehash ())) {System.out.println ("Current hashes not equal!"); return false; }            if(!previousBlock.hash.equals (Currentblock.prehash)) {System.out.println ("Previous Hashes not equal!"); return false; }            if(!currentblock.hash.substring (0, difficulty). Equals (Hashtarget)) {System.out.println ("This block hasn ' t been mined"); return false; }        }        return true; }}

Operation found that the mining process is still time-consuming. Change the amount of the calculation to 7, almost every one minute to dig ...

If someone tampered with the data during this process, it would result in:

    • Blockchain will be invalid
    • Not able to create a longer blockchain
    • The integrity chain in the network will have a long blockchain with time advantage

However, if tampering with the data has a greater computational speed, it can be tampered with successfully.

In this way, basically a blockchain has been implemented.

Write the first blockchain in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.