“This is the fifth day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

Blockchain Consensus Algorithm Series — PoW (PART 1)

One, foreword

When it comes to blockchain, we should first understand what P2P is. P2P is not a financial term, but a peer-to-peer network. Satoshi Nakamoto proposed in his white paper that peer-to-peer payment systems such as wechat Pay and Alipay, which need to go through a third party, are meaningless.

Our P2P is such a concept that does not need to go through the third party. An important reason for its emergence is to avoid the existence of third parties and centers.

All nodes in a P2P network function the same, no one node is special, they provide services to each other.

Because there is no third party, there is no center, so it ensures the transparency, freedom and equality of data.

The bitcoin we hear about uses PoW consensus algorithms. PoW stands for proof-of-work. It is to calculate a value, so that after the value combined with the data meets the requirements, it will immediately broadcast the whole network packaged block, after the whole network node receives the broadcast, it will verify its correctness. If the node cheats, it will not pass the verification, and the packaged block will be discarded and cannot be recorded in the ledger. Mining costs are so high, if the cheating leads to the block being discarded and the Bitcoin is lost, it will be a loss. So miners are willing to abide by the consensus protocols of the bitcoin system.

Second, PoW code implementation

Let’s first define the block structure:

Type Block struct {// last Block hash PreHash string // current Block hash HashCode string // TimeStamp string // difficulty factor Diff int // Transaction information Data string // block height Index int Nonce int}Copy the code

Based on Bitcoin, we set the information for this block to the following: hash of the previous block, hash of the current block, timestamp, difficulty coefficient, transaction information, block height, random value.

And then we create a creation block.

// create the firstblock var firstblock Block firstblock.PreHash = "" firstblock.TimeStamp = time.now ().string () firstblock.Diff = 3 firstblock.Index = 1 firstblock.Nonce = 0 // Use sha256 to hash firstblock.HashCode  =GneHashValue(firstblock) return firstblock }Copy the code

Since it is the first block, the previous block is empty, the timestamp is the current time, we temporarily set the difficulty to 3, because it is the first block, so the block height is 1, random value can be arbitrarily, we will use 0. Then we need to compute the hash value for the current block, which we’ll use sha256 to compute. We’ll talk about that next time.

\