Hash Principle
Corollary 2: If the content of a block changes, its hash must change.
Then we can map blocks to hashes one-to-one, and the hash of each block is calculated for the "block header" (Head). That is to say, the feature values of the block header are connected together in order to form a very long string, and then the hash of the string is calculated.
Hash = SHA256 (block header), SHA256 is the hash algorithm of the blockchain, because the hash length of the blockchain is 256 bits. This formula only contains the block header, not the block body, that is to say, the hash is uniquely determined by the block header. But it doesn't matter, the block header contains a lot of content, including the hash of the current block body and the hash of the previous block. This means that if the content of the current block body changes, or the hash of the previous block changes, it will definitely cause the hash of the current block to change. If someone modifies a block, the hash of that block changes. In order for subsequent blocks to still be connected to it (because the next block contains the hash of the previous block), the person must modify all subsequent blocks in turn, otherwise the changed block will be removed from the blockchain . The calculation of hash is very time-consuming, and it is almost impossible to modify multiple blocks in a short period of time unless someone masters more than 51% of the computing power of the entire network. It is through this linkage mechanism that the blockchain guarantees its own reliability. Once data is written, it cannot be tampered with. It's like history, what happens is what happens, and it can't be changed from now on.
mining
The block header contains a difficulty factor, which determines the difficulty of computing the hash. For example, the difficulty factor of the 100000th block is 14484.16236122. The blockchain protocol stipulates that the target value (target) can be obtained by dividing a constant by the difficulty factor. Obviously, the higher the difficulty factor, the smaller the target value. The validity of the hash is closely related to the target value. Only the hash smaller than the target value is valid, otherwise the hash is invalid and must be recalculated. Since the target value is very small, the chance of the hash being smaller than this value is extremely slim, and it may be calculated 1 billion times before it is counted as one hit. This is the fundamental reason why mining is so slow. In addition to this, we know that the hash of the current block is uniquely determined by the block header. If you want to repeatedly calculate the hash for the same block, it means that the block header must keep changing, otherwise it is impossible to calculate different hashes. All feature values in the block header are fixed. In order to make the block header change, a random item called Nonce is added. Nonce is a random value. The role of miners is to guess the value of Nonce, so that the hash of the block header can be smaller than the target value, so that it can be written into the blockchain. Nonce is very difficult to guess, and currently it can only be tested one by one through exhaustive method. According to the protocol, Nonce is a 32-bit binary value, which can be up to 2.147 billion. The Nonce value of the 100000th block is 274148111. It can be understood that the miner starts from 0 and has been calculating 274 million times before getting a valid Nonce value, so that the calculated hash can meet the conditions. And due to the continuous adjustment of the difficulty coefficient, the mining effect will become lower and lower, because the blockchain designer is worried that the computing performance of the computer will become stronger and the mining difficulty will be reduced, so he made a design: the difficulty coefficient is every two weeks ( 2016 blocks) adjusted once. If in these two weeks, the average block generation speed is 9 minutes, it means that it is 10% faster than the legal speed, so the next difficulty coefficient will be increased by 10%; if the average generation speed is 11 minutes, it means that It is 10% slower than the legal speed, so the next difficulty factor will be reduced by 10%. The higher the difficulty factor is (the lower the target value), the harder it is to mine.
Simple blockchain construction code
First define a Block. In a blockchain, each block is stored with a timestamp and an index. In SnakeCoin, we will store both. To help ensure the integrity of the entire blockchain, each block has a hash value as an identifier. Like Bitcoin, the hash value of each block is obtained by hashing the block's index, timestamp, and data. Data can be anything.
import hashlib as hasher import datetime as date class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.hash_block() def hash_block(self): sha = hasher.sha256() sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode('utf-8')) return sha.hexdigest()
Create initial block and subsequent blocks
def create_genesis_block(): # Manually construct a block with # index zero and arbitrary previous hash return Block(0, date.datetime.now(), "Genesis Block", "0") def next_block(last_block): this_index = last_block.index + 1 this_timestamp = date.datetime.now() this_data = "Hey! I'm block " + str(this_index) this_hash = last_block.hash return Block(this_index, this_timestamp, this_data, this_hash)
Call and run screenshots
# Create the blockchain and add the genesis block blockchain = [create_genesis_block()] previous_block = blockchain[0] # How many blocks should we add to the chain # after the genesis block num_of_blocks_to_add = 20 # Add blocks to the chain for i in range(0, num_of_blocks_to_add): block_to_add = next_block(previous_block) blockchain.append(block_to_add) previous_block = block_to_add # Tell everyone about it! print ("Block #{} has been added to the blockchain!".format(block_to_add.index)) print ("Hash: {}\n".format(block_to_add.hash))
What is the use of blockchain? - useless
The most prominent feature of blockchain is decentralization, which avoids the problem that traditional database managers can easily modify data, but in order to ensure such a feature, it also pays a heavy price, which is low efficiency and serious energy consumption. Because each time data is written, it takes a long time to synchronize all nodes, and in order to delay the time to write data, “miners” are required to perform high-value invalid operations.
So the question is, what does it mean to replace the so-called "decentralized distributed data storage" with such a price? In the final analysis, it is only to solve the problem of users' distrust of core managers. Who can guarantee 100% security of their own servers or databases, especially for some countries where enterprises and even government agencies are unstable, everyone is more worried about the security and validity of their property bills. This is the main reason why Bitcoin has been hyped by some people. So back to our real life, from the current situation, I think our state-controlled financial institutions (big banks) and the financial software (WeChat, Alipay) we usually use are safe and reliable. , so for us, the current existence, value and importance of blockchain products are not as strong as those advertised on the Internet, and we hope that everyone will not blindly follow the trend.
Reference article
https://zhuanlan.zhihu.com/p/28073110