Building a blockchain based on the Java language (i)--Basic prototype

Source: Internet
Author: User
Tags sha256 algorithm


Introduction

Blockchain technology is a more revolutionary technology than artificial intelligence, artificial intelligence is only to improve human productivity, and blockchain will change the production relations of human society, it will subvert the existing cooperative way of human society. Understanding and mastering blockchain-related knowledge and technology is something that every developer has to do, so that we can hold on to the dividends of this wave of trends.

This article will build a simplified version of blockchain based on the Java language to implement the digital currency.

Creating chunks
A blockchain is a data structure that is logically linked from the back to the block that contains the transaction information. Chunks are sequentially linked from the back to the chain, with each chunk pointing to the previous block. In Bitcoin, for example, each chunk contains the following information fields:

Chunk size: Chunk data size in bytes
Chunk header: Several fields that make up a chunk header
Block Hash value
Parent Chunk Header Hash value
Timestamp: Approximate time of chunk generation
Merkle Root: The hash value of the Merkle root of the transaction in this chunk
Difficulty target: difficulty target of the block workload proving algorithm
Nonce: counter for workload proof algorithm
Trade counter: Number of trades
Trading: Transaction information recorded in a block
See: "Mastering Bitcoin" (second edition) 9th chapter--Blockchain
Block data structure

Here, we are primarily to implement the simplest blockchain structure, which contains only the following information fields:

/**

    • Block
    • @author Wangwei
    • @date 2018/02/02br/>*/
      @Data
      < p="">

      /**

      • Chunk Hash value
        */
        Private String Hash;
        /**
      • The hash value of the previous chunk
        */
        Private String Previoushash;
        /**
      • Chunk data
        */
        Private String data;
        /**
      • Block creation time (units: seconds)
        */
        Private long TimeStamp;

      Public Block () {
      }

      Public Block (String hash, string Previoushash, string data, long TimeStamp) {
      This ();
      This.hash = hash;
      This.previoushash = Previoushash;
      This.data = data;
      This.timestamp = TimeStamp;
      }
      }
      Chunk Hash Value calculation

Cryptographic hash value, a digital fingerprint obtained by hashing the chunk header two times with the SHA256 algorithm. The hash value is used to ensure blockchain security. Hash calculations are computationally sensitive operations, and even in high-performance computers It takes some time to complete calculations (which is why people buy high-performance GPUs for Bitcoin mining). The blockchain architecture design intentionally makes hash calculations difficult, in order to increase the difficulty of adding a block, thereby preventing blocks from being arbitrarily modified when added.

/**

    • <p> Create a new block </p>
    • @param previoushash
    • @param data
    • @return
      */
      public static Block Newblock (string previoushash, string data) {
      Block block = new Block ("", Previoushash, Data.getbytes (), Instant.now (). Getepochsecond ());
      Block.sethash ();
      return block;
      }

/**

    • Calculate Chunk Hash
    • <p>
    • NOTE: When preparing chunk data, be sure to convert from the original data type to byte[] and not directly from the string
    • @return
      */
      private void Sethash () {
      Byte[] prevblockhashbytes = {};
      if (Stringutils.isnoneblank (This.getprevblockhash ())) {
      Prevblockhashbytes = new BigInteger (This.getprevblockhash (), +). Tobytearray ();
      }

      byte[] headers = Byteutils.merge (
      Prevblockhashbytes,
      This.getdata (). GetBytes (),
      Byteutils.tobytes (This.gettimestamp ()));

      This.sethash (Digestutils.sha256hex (headers));
      }
      Create a chunk chain
      Blockchain is essentially an ordered, backlink linked list of data structures. This means that the block is stored in the order in which it was inserted, and each block holds a link to the previous block. This structure guarantees that the newly inserted block can be quickly obtained while obtaining its hash value. This structure ensures that the newly inserted block can be quickly obtained and the hash value is obtained at the same time (efficiently).

Block chain data structure

/**

    • <p> Blockchain </p>
    • @author Wangwei
    • @date 2018/02/02
      */
      public class Blockchain {

      @Getter
      Private list<block> blocklist;

      Public Blockchain (list<block> blocklist) {
      This.blocklist = blocklist;
      }
      }
      Add a chunk

Added a way to add a chunk chain
/**

    • <p> Add Chunks </p>
    • @param data
      */
      public void Addblock (String data) {
      Block Previousblock = Blocklist.get (Blocklist.size ()-1);
      This.addblock (Block.newblock (Previousblock.gethash (), data));
      }

/**

    • <p> Add Chunks </p>
    • @param block block
      */
      public void Addblock (block block) {
      This.blockList.add (block);
      }
      Genesis Block

Before adding chunks, the blockchain must have a creation block, adding a new Genesis block method to the block:
/**

    • <p> Create a Genesis block </p>
    • @return
      */
      public static Block Newgenesisblock () {
      Return Block.newblock ("", "Genesis Block");
      }
      Create a chunk chain

Then add the method of creating the blockchain in Blockchain:
/**

    • <p> Create a block chain </p>
    • @return
      */
      public static Blockchain Newblockchain () {
      list<block> blocks = new linkedlist<> ();
      Blocks.add (Block.newgenesisblock ());
      return new Blockchain (blocks);
      }
      Test run
      /**
    • Test
    • @author Wangwei
    • @date 2018/02/05
      */
      public class Blockchaintest {

      public static void Main (string[] args) {

      Blockchain blockchain = Blockchain.newBlockchain();blockchain.addBlock("Send 1 BTC to Ivan");blockchain.addBlock("Send 2 more BTC to Ivan");for (Block block : blockchain.getBlockList()) {    System.out.println("Prev. hash: " + block.getPreviousHash());    System.out.println("Data: " + block.getData());    System.out.println("Hash: " + block.getHash());    System.out.println();}

      }
      }

/**

    • Output the following information:
      */
      Prev. Hash:
      Data:genesis Block
      Hash:4492cb9d396a9a52e7ff17ef3782f022ddcdc7b2c276bc6dd3d448b0655eb3d4

Prev. hash:4492cb9d396a9a52e7ff17ef3782f022ddcdc7b2c276bc6dd3d448b0655eb3d4
Data:send 1 BTC to Ivan
Hash:cd716d59d98ad673035ab7035ece751718ea9842944a4743c298bebc0fe24c04

Prev. HASH:CD716D59D98AD673035AB7035ECE751718EA9842944A4743C298BEBC0FE24C04
Data:send 2 more BTC to Ivan
hash:42f78d6a86f88aa9b5b10e468494dfd1b3f558a9fb74a01eb348c2cbfc5d000a
Recommend a Java in-house learning Group: 725633148, the group to find management free to receive learning materials and videos. Nothing wrong is free to collect! Big man small white are welcome, we learn together progress together!

Summarize
We built a very simple blockchain prototype: It's just an array of blocks, each of which is connected to the previous block. The actual blockchain is much more complex.

Lack of transaction information: Our blockchain does not have any trading information.
Lack of proof of workload: our production block is very simple and fast, in the actual blockchain, producing a chunk requires a lot of computation.
Lack of consensus mechanism: blockchain is a distributed database of non-single decision-makers. Therefore, a new chunk must be confirmed and approved by the other participants in the network
In a future article, we'll cover these features.

Building a blockchain based on the Java language (i)--Basic prototype

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.