Building a blockchain from scratch (ii)--proof of workload

Source: Internet
Author: User
Tags arithmetic hash pow prev printf
--– Blockchain starts from zero-the second (proof of work) ———— ——————— – @Author mobei Fly Sand ————————

Introduction
In the previous article, we implemented the most basic data structure model of the blockchain, adding chunks and connecting to the previous block. However, our implementation is very simple, and the real bitcoin blockchain, each chunk of the addition of the need to go through a large number of calculations to complete, this process is known as mining.
Proof of workload mechanism
One of the key ideas of blockchain is that it takes a lot of difficult computational effort to store the transaction data on the blockchain. This working mechanism ensures the security and consistency of the entire blockchain data. At the same time, the miners who complete the calculation will receive a token reward accordingly.

This mechanism is very similar to our real life: we must work hard to earn money to sustain our lives. In the blockchain, the miners in the network work hard to maintain the blockchain network, add chunks to it, and gain a certain token reward. As a result of their work, a block is combined in a secure way into the blockchain, ensuring the stability of the entire blockchain database. It is also important to note that a miner has completed the results of the calculations and must have the approval of all other miners (proved correct) in order to be completed.

This set of calculations and proving mechanisms is called proof-of-work (proof of workload). Computational work is very, very difficult because it consumes a lot of computational power resources, and even very high-performing computers cannot calculate the correct results very quickly. In addition, as time goes on, the difficulty of this calculation will increase with the aim of guaranteeing the block rate of 6 new chunks per hour. In Bitcoin, the goal of this work is to find a chunk hash (hash) that satisfies a particular requirement. This chunk hash is a testament to the results of the work. Therefore, the purpose of the calculation is to find the proof value.

The last thing to note is that it is very difficult to calculate this particular hash, but it is very simple for someone to verify that the hash value is correct, and it can be done in a single swoop.

Hashing
Hash: Hashing | Hash column

Let's talk about hashing (hash), a friend who is very familiar with this piece can skip this section directly.

A hash is a computer algorithm that calculates the hash value of any size data, and the length of the hash is fixed, 256bit. This computed hash can be used as the only representation of this data. The hashing algorithm has several key features:

Irreversibility. The original data cannot be deduced from a hash value. Therefore, the hash is not encrypted. Uniqueness. Each data has and has only one unique hash value.
Different nature. The slightest change in the original data will get a completely different hash value.

For example:
SHA256 ("Wangwei1")--1e898b7c9adaad86c20139a302ccd5277f81040cab68dc2aecfc684773532652
SHA256 ("Wangwei2")--c9cc7417c17318c8aab448cc8ace24c53b6dcf350f5c5fd8e91cbc3b011a179d
Hashing algorithms are widely used to verify the consistency of files. For example, the software provider will usually attach a verification code (checksums) on the installation package, when we download a software installation package, you can use the hash function to calculate the hash value of the software installation package, and then the software installation package to compare the test code, you can know the download of the installation package is complete, Whether there is data loss.

In the blockchain, the hash value is used to guarantee the consistency of the block. Each chunk is used to hash the data that contains the hash value of the previous blockchain, so anyone who wants to modify the chunk's data is almost impossible, and he must recalculate all the hashes of the entire blockchain from the creation block to the newest chunk.

You can make up your mind how much this workload, according to the current computer computing power, it is almost impossible

Hashcash
The work of Bitcoin proves to be using the Hashcash algorithm, an algorithm that was originally used for anti-spam, which can be disassembled in the following steps:

Access to a publicly known data (in a mail case, the recipient's email address; Bitcoin case, the chunk header)
Add a counter counter, the initial value is set to 0;
Computes the hash value of the data and counter stitching string;
Checks if the hash value of the previous step satisfies a condition, satisfies the stop calculation, counter adds 1, and then repeats steps 3rd and 4th until the specific condition is met.
This is a rough algorithm: You change the counter, calculate a new hash value, check it, increase the counter, calculate a new hash value, cycle, which is why it takes a lot of computer computing power resources.

Let's take a closer look at what this particular condition refers to. In the original Hashcash algorithm, this particular requirement is that the first 20bit of the computed hash must be all zeros,

In bitcoin, the requirement for the number of 0 starts in front of the hash value is constantly adjusted over time, for the purpose of design, although the computer's computing power will continue to increase and more and more miners join the network, it is necessary to ensure that every 10min production of a block.

Let's demonstrate this algorithm:

# computes the hash value of the string ' I like donuts '
SHA256 ("I Like Donuts")-- 
f80867f6efd4484c23b0e7184e53fe4af6ab49b97f5293fcd50d5b2bfa73a4d0

# Stitching a counter value (CA07CA) and hashing again
SHA256 (" I like Donutsca07ca ")-- 
0000002f7c1fe31cb82acdc082cfec47620b7e4ab94f2bf9e096c436fc8cee06

The CA07CA here is the hexadecimal value of the counter, and he represents a decimal value of 13240266

That is, starting from 0, calculated a total of 13,240,266 times, only to calculate the I like donuts this data hash value, satisfies the first 6 bits (3 bytes) all is zero.

Code implementation:

Ideas:
1) Mining (Pow) is needed before each chunk is added to the blockchain.
2) in the mining process, the resulting hash value, if less than the difficulty target value is added into the block, or continue to dig, until the correct hash is found
3) Finally, verify that the chunk hash is valid

Defining POW Classes

/** * Proof of work * *
 @author wangwei
 * @date 2018/02/04 * *
 @Data public
class Proofofwork {

    /**
     * * Difficulty target bit */public
    static final int target_bits =;

    /**
     * block * */
    private block block;
    /**
     * Difficulty target value */
    private BigInteger target;

    Private Proofofwork (block block, BigInteger target) {
        This.block = block;
        This.target = target;
    }

    /**
     * Create a new workload certificate, set the difficulty target value
     * <p>
     * Shift operation to 1, move 1 to the left (256-target_bits) bit, get our difficulty target value
     * 
     @ param Block
     * @return 
     *
    /public static Proofofwork Newproofofwork (block block) {
        BigInteger Targetvalue = biginteger.valueof (1). Shiftleft ((256-target_bits));
        return new Proofofwork (block, targetvalue);
    }
}

Set a difficulty target bit target_bits, indicating that the final mining dug out the hash value, converted to binary, compared with 256, the length of a few bit less, that is, the number of bits in front of the binary is 0.

The larger the target_bits, the smaller the final targetvalue, the more small the hash is required to calculate, that is, the difficulty of mining is getting bigger.
Our target_bits here are fixed, but in real Bitcoin, the difficulty goal is to dynamically adjust as time pushes. See: "Mastering bitcoin (second edition)", chapter 10th
Because the values are large, the Bitinteger type is used here.

Preparing data

/**
 * Prepare data
 * <p>
 * NOTE: When preparing chunk data, be sure to convert from the original data type to byte[] and not directly from the string
 * @param nonce
 * @return
 *
/private String preparedata (long nonce) {
   byte[] prevblockhashbytes = {};
   if (Stringutils.isnoneblank (This.getblock (). Getprevblockhash ())) {
       prevblockhashbytes = new BigInteger ( This.getblock (). Getprevblockhash (). Tobytearray ();
   }

   Return Byteutils.merge (
           prevblockhashbytes,
           this.getblock (). GetData (). GetBytes (),
           Byteutils.tobytes (This.getblock (). Gettimestamp ()),
           byteutils.tobytes (target_bits),
           byteutils.tobytes (nonce)
    );
}

The following information is involved in the hash operation:
1: The hash value of the previous chunk (parent block);
2: Transaction data in chunks;
3: Time of block generation;
4: Difficulty target;
5: counter for the workload proof algorithm.
See: "Mastering bitcoin (second edition)", chapter No. 09
POW algorithm:

/**
 * Run work proof, start mining, find less than the difficulty target value of the hash
 *
 * @return *
 /public
Powresult run () {
    long nonce = 0;
    String Shahex = "";
    System.out.printf ("Mining the block containing:%s \ n", This.getblock (). GetData ());

    Long startTime = System.currenttimemillis ();
    while (Nonce < Long.max_value) {
        String data = This.preparedata (nonce);
        Shahex = Digestutils.sha256hex (data);
        if (new BigInteger (Shahex, +). CompareTo (this.target) = =-1) {
            System.out.printf ("Elapsed time:%s seconds \ n", Flo at) (System.currenttimemillis ()-startTime)/+);
            System.out.printf ("Correct hash Hex:%s \ n \ nthe", shahex);
            break;
         } else {
            nonce++;
         }
     }
     return new Powresult (nonce, Shahex);
}

Loop body inside the main following four steps:
Preparing data
Perform sha256 operations
Convert to Biginter type
Compare with Target
Finally, return the correct hash value and the arithmetic counter nonce
Verify Chunk Hash validity

/**
 * Verify that the chunk is valid
 * * @return */Public
Boolean validate () {
    String data = This.preparedata ( This.getblock (). Getnonce ());
    return new BigInteger (data), Digestutils.sha256hex compareTo (this.target) = =-1;
}

Modify Chunk Add logic

/**
 * <p> Create new block </p>
 *
 * @param previoushash
 * @param data
 * @return
*/ public static Block Newblock (string previoushash, String data) {
    block block = new Block ("", Previoushash, data, Inst Ant.now (). Getepochsecond (), 0);
    Proofofwork POW = proofofwork.newproofofwork (block);
    Powresult Powresult = Pow.run ();
    Block.sethash (Powresult.gethash ());
    Block.setnonce (Powresult.getnonce ());
    return block;
}

Creating chunks
Creating a POW Algorithm object
Execute POW algorithm
Save the returned hash as well as the arithmetic counter
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.getprevblockhash ());
            System.out.println ("Data:" + block.getdata ());
            System.out.println ("Hash:" + Block.gethash ());

            System.out.println ("Nonce:" + block.getnonce ());
            Proofofwork POW = proofofwork.newproofofwork (block);
        SYSTEM.OUT.PRINTLN ("Pow valid:" + pow.validate () + "\ n"); }}}/** * Set target_bits = 20 to get the following result: */Mining The block containing:genesis block Elapsed time:2.118 seconds C Orrect Hash hex:00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 Mining The block Containing:send 1 BTC to Ivan Elapsed time:1.069 seconds correct hash hex:00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7f Ea5 Mining The Block containing:send 2 more BTC to Ivan Elapsed time:4.258 seconds correct hash hex:00000777f93efe91 d9aabcba14ab3d8ab8e0255b89818cdb9b93cfa844ad0c7f Prev.hash:Data:Genesis Block Hash: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 nonce:522163 Pow valid:true Prev.hash: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 data:send 1 BTC to Ivan Hash: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5 nonce:474758 Pow valid:true Prev.hash: 00000A38C0D7F2EBBD20773E93770298AA8BC0CC6D85FCA8756FE0646AE7FEA5 data:send 2 more BTC to Ivan Hash: 00000777f93efe91d9aabcba14ab3d8ab8e0255b89818cdb9b93cfa844ad0c7f nonce:1853839 Pow Valid:true

Summary
We are stepping closer to the real blockchain architecture, and we have implemented the mining mechanism, but we still have a lot of key features that are not implemented: The persistence of blockchain databases, wallets, addresses, transactions, consensus mechanisms, which we follow step by step to achieve.
Go from: https://wangwei.one/posts/7890ab7e.html

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.