Blockchain - It is said that this thing is very popular now?

As Bitcoin is known to everyone, the term blockchain is becoming more and more popular. All kinds of media, whether they know it or don't understand it, have reported it. For a time, this thing was spread like a god, and the blockchain is in the end. what is it then? In fact, it is not as complicated as we think. Its essence is actually a database. Yes, it is not wrong. It is a special distributed database.
The main role of the blockchain is to store information. Any information that needs to be saved can be written to and read from the blockchain, so it is a database. Anyone can set up a server, join the blockchain network, and become a node. In the world of blockchain, there is no central node, each node is equal and holds the entire database. You can write/read data to any node, because all nodes will eventually be synchronized to ensure the consistency of the blockchain.
A blockchain consists of blocks. Blocks are much like database records. Every time data is written, a block is created. Each block contains two parts ( Head and Body ). The block header contains a number of characteristic values ​​of the current block . For example, the generation time, the hash of the actual data (ie the block body), the hash of the previous block, etc. The block body is the actual data . It's almost the same as a linked list, nothing fancy.

Hash Principle

We know that hashing is a seemingly reversible encryption process, and the blockchain is based on the theory of hashing and gives 2 inferences:
Inference 1: The hash of each block is different, and the block can be identified by the hash.
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

Everyone must be interested in this word, what is it used for? It exists for only one purpose - to waste resources .
Since synchronization between nodes must be guaranteed, new blocks cannot be added too quickly. Otherwise, you haven't finished generating, and there is a new block on the other side, and you have to synchronize the block to recalculate, which is too messy. So the inventor of the blockchain made it difficult to add new blocks. He deliberately set up massive calculations. That is, it is only through an extremely large amount of computation that a valid hash of the current block can be obtained to add a new block to the blockchain. Due to the large amount of calculation, it can't get up quickly. Moreover, the difficulty of the calculation can also be dynamically adjusted, and now the difficulty is maintained at an average efficiency of 10 minutes.
The specific algorithm is:

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

http://www.ruanyifeng.com/blog/2017/12/blockchain-tutorial.html?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324463425&siteId=291194637