Block chain 100 Talk: Know the answer to the praise of the mining process _ technology Road

Source: Internet
Author: User
Tags utc time stamp

A few days ago sorted out the excavation and calculation of the force of the introduction, the pen friends after reading and told me to try to dig mine, I silently gave him a bit of praise, and then feel that should do something to help him, and then looked for some of the bit money to dig the process of introduction, this article is fierce, want to dig mine students to seriously look at the ~

In addition, the purpose of "block chain 100" is to develop a systematic knowledge map of block chains, for everyone to consult and understand the block chain technology, a point of the introduction, from the bottom of the text, welcome at the end of the message you want to know what, or for the article error correction Oh, if you can contribute to the better ~ 1 mining process

The algorithm of bit-coin mining can be simply summed up to do two times sha256 hash operation on Block head, and the result if it is less than the difficult target stipulated in the block head, that is, the mining success.

The structure of the block header is as follows

So the algorithm can be expressed as

Block_header = version + Previous_block_hash + merkle_root + time + target_bits + nonce

to I in range (0, 2**32):

     If sha256 (sha256 (Block_header)) < target_bits:       




A brief review of the mining process.

The mining node first validates the transaction, eliminates the problem, and then chooses which deals are to be packaged into chunks through a set of custom criteria, such as the ratio of transaction fees to the size of the bytes occupied by the transaction, which is considered profitable. Of course, the node can also deliberately choose to join a transaction, or deliberately ignore certain transactions, each mining node has a large degree of discretionary power.

If you are digging through a mine pool, the pool's servers will sift through the trades and assign them to each of the mining machines involved in a separate task. This task is less difficult than the total digging difficulty, completed a small difficulty calculation, that is, confirmed the workload of their participation. Each of the different ore machine calculation problems will not be repeated, when one of the mining machine successfully dug, the other miners according to the workload distribution to obtain the total income.

Once you have screened the transaction data, sorted by time, 22 hashes, and reduced layers, you can calculate a merkle tree by these transactions, and you can determine a unique summary, which is the root of the merkl tree.

Changes in any node in the Merkle tree can result in changes to the Merkle root, which allows you to verify that the transaction data in the block has been altered.

Then we get the information about each block header that is needed to dig the mine in turn. The size of the area is only 80 bytes, mining only need to operate on the block head. The transaction data are fixed by the Merkle tree and do not need to be included. The so-called block chain, in fact, through the block head and linked together. The following schematic illustrates the composition of block chains and blocks in a simpler and clearer way.

<figure style= "margin:0px; padding:0px; " >! [Image] ( 7cimageview2/2/w/1240)


Bit-Coin block chain diagram

The information in the block header is mostly fixed or computable before digging.

Version number

Follow the Bitcoin client and will not change over time. Even if you want to change, there will be a core developer of bitcoin to coordinate the upgrade strategy, which can be understood as a static constant.

Hash summary for previous block

Hash at once. The previous block is already packed.

The roots of Mrs Merkel's tree

The results have just been obtained, based on the list of transactions included in this transaction.


The time when the package was taken. Also do not need to be very accurate, before and after a few seconds, a few 10 seconds also can.

Difficulty target

Refer to the average generation time of the blocks generated in the last two weeks. In two weeks, if an average of 10 minutes to produce a block, two weeks will produce 2016 blocks, the software will calculate the latest 2016 blocks generated time, and then compare, and then adjust the difficulty, so that the next generation of block expected time to stay in about 10 minutes. Since the last 2016 blocks have been identified, the number is also determined.

Random number Nonce

This is the target of mine digging. This is a 32-digit number.

Random numbers can vary, and are tested from 0 to maximum 2^32. Until the last occurrence of the hash result, its number is below the difficulty target value. But with the current computing power, a mine machine will not be able to calculate all the changes in a second, so it is also necessary to change the accompanying message in the coin trading in the block, so that Merkle root also changes, so there are more possibilities to find the nonce that meet the requirements.

The qualifying block conditions are as follows:

SHA256D (Blockherder) < F (nbits)

Among them, sha256d (blockherder) is the mining result, F (nbits) is the target value of difficulty, both are 256 bits, both as large integer processing, direct contrast size to determine whether it meets the difficulty requirements.

In order to save the block chain storage space, the 256-bit target value is saved in the 32-bit nbits field by a certain transform lossless compression. The specific transformation method is to split the 4 bytes of the nbits, the 1th byte represents the number of digits to the right, with V1, the second 3 bytes record the value, in V3, then there are:

F (nbits) =v_3 * 2^ (8* (v_1-3))

In addition, there is a minimum degree of difficulty, that is to say, F (nbits) has a maximum value, the minimum difficulty of Bitcoin nbits=0x1d00ffff, the corresponding maximum target value is:


So digging can be a figurative analogy to flip a coin, like 256 coins, given the number 1,2,3 ... 256, each time the hash operation, like a coin, 256 coins at the same time thrown, landing after the request number n all the coins all positive upward.

In mining, the first deal is a currency transaction. Coin trading can be accompanied by a text message that can be used to provide more nonce. For example, Ching the information implanted in the Genesis block.

The Times 03/jan/2009 Chancellor in brink of second bailout for banks 2 algorithm verification

Having finished the basic principle, we began to use the actual data to validate the algorithm. We take block 277316 For example, the information comes from the website

The reason for choosing this block is to make reference to the introduction of the book "Mastering Bitcoin". The Chinese community translation of this book and the English version of the original in the introduction of this part of the discrepancy, and the author Antonopoulos did not do a complete calculation; no mention of a key point, is the problem of byte order, I believe many people may step on this pit. The details of the restoration can help the reader to fully understand the algorithm part of the book which describes the work proof.

Information for Bitcoin block 277316

Hash value 3 algorithm demo for bit-currency block 277316

Next, demonstrate the specific checking algorithm.

The first step, the preparation of data, conversion time

2 (decimal of version number) 0000000000000002a7bbd25a417c0374cc55261021e8a9ca74442b01284f0569 (16 in the previous block hash value) c91c008c26e50763e9f548bb8b2fc323735f73577effbc55502c51eb4cc7cf2e  (Merkle root 16)

2013-12-27 23:11:54 (UTC time)

419668748  (decimal for difficulty target)

924591752  (decimal for random numbers)

Convert time, remember, must be converted to UTC time stamp, here encountered a hole, be careful. The algorithm itself is not difficult, the difficulty is that you need to put all of the data are prepared correctly.

>>> import datetime

>>> from datetime import timezone

>>> Datetime.datetime.strptime (' 2013-12-27 23:11:54 ', '%y-%m-%d%h:%m:%s '). Replace (TZINFO=TIMEZONE.UTC). Timestamp ()


Step two, convert all to 16


0000000000000002a7bbd25a417c0374cc55261021e8a9ca74442b01284f0569c91c008c26e50763e9f548bb8b2fc323735f73577effbc55502c51eb4 cc7cf2e




Step three, convert from Big-endian to Little-endian

The discovery of this step is unusually arduous, consuming a lot of inquiries and attempts, great pits, great pits, and keep in mind. The inventor Ben Cong may have changed to a more machine-coded method Little-endian to make the machine more computationally fast.







Again, the algorithm is not difficult, the most difficult place is in the process of checking in person, you have to put all the hidden knowledge dug out. In Chinese materials, very few people have done the entire check, and once the real understanding of the process of checking, you will find the algorithm of Bitcoin is really not difficult.

Step Fourth, string concatenation, start validation

Import Binascii from

hashlib import sha256 as SK = ' 0200000069054f28012b4474caa9e821102655cc74037c415ad2bba702000000000000002ecfc74ceb512c5055bcff7e57735f7323c32f8bbb48f5e96 307e5268c001cc93a09be520ca3031988261c37

' HK = binascii.unhexlify (k)

res = Binascii.hexlify (s (s) (HK). Digest ( )). Digest () [::-1])

Why do you want to convert the order again in your code? Again, because of the byte order problem, we use the usual and the website display, all use the big end order, so need to convert over.

The end result is


16 into the front 15 0, then 1. In order to get this number, it takes me nearly one weeks to start from the Elliptic Curve encryption algorithm began to learn, and then to a variety of raw materials to read, but also downloaded the difficult source code, the forum has also been doubled. Seeing a pile of 0 ahead, it felt like the dawn of victory was coming.

No hurry, we still have to verify the final step, whether to meet the difficult target. Satisfied, of course, because we are validating the results, but if it is in the forward calculation of the mining process, it must be validated.

The number of the difficulty target corresponds to the

0x03a30c*0x0100** (0x19-0x03) =


16 into the front 15 0, then 3.

The calculated result is less than the difficulty target and meets the requirement. The result must be the number published on the website.

The correct hash value

In the mining, nonce random number is unknown, from 0 to 2^32, but this number is not really small, only 4294967296. At present, a mine machine at 14T per second of the calculation force, all calculated to the upper limit also does not need a second. As mentioned above, in this case, you need to use the collateral information in the currency transaction, and the extra string becomes extra nonce.

To this result we explain what it means at the end of 2013, when this block was generated, which needed to calculate the force to reach the 8T/S device, that is, 8*10^15 of violence per second, which worked continuously for 10 minutes. This for 2018 years now is really nothing, a mine machine, not more than two or three bricks, the size of the 14t/s, only need 6, 7 minutes alone can be dug. But at that time, 8T is also the whole network 1 per thousand of the calculation, need the best mine at the time to work together hundred units. And if the calculation uses an ordinary desktop computer, it will take 26 years. If you use the best 2018-year mobile phone Iphonex, you can do 70 calculations per second, then it will take 4 million years.

Through the above algorithm we have a complete review of the bit-currency block chain workload proof algorithm, if you completely clear the idea, you can manually realize their own mining procedures, or another attempt to design a number of new block chain products. The most difficult technology, we hope to be able to understand at the bottom, but to push through the clouds, in fact, the underlying logic is not hard.

However, the technology in Bitcoin is far more than mining algorithms, encryption algorithms, script Intelligent contract, various protocols, various networks, transaction verification, each is full of magic, and access between, can not help but let people marvel at the depth and breadth of knowledge. Whatever bitcoin is, it will be, but the first block-chain technology to be used in Bitcoin has spread, and the complexity and logic of the whole system is fascinating indeed. 4 One more thing ...

The Genesis block can also be validated by the above method, with curious friends to try. Although the Genesis block was later hard-coded in the client, it was still dug out.


For the Genesis block, the version number is 1.

Hash summary of the previous block, guess what it will be. For the Genesis block, there is no previous block.

The difficulty target is 1, which is defined as the first 32 digits of a sha256 result is 0, that is, the corresponding 16 binary string should have 8 0, then the difficulty bits is 0x1d00ffff. This figure is derived from the knowledge of probability theory and is also a rule of Ben Cong.

And then use the above solution to solve the random number can be.

The process of digging the ore is finished, do you see it? Feel like you can try digging and digging.

The content of this article comes from: Know

Author: Tony

The following is our community introduction, welcome to all kinds of cooperation, communication, learning:

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: 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.