Proof of Work, work to prove. POW consensus algorithm is mainly determined by calculating the difficulty value out who is going to block. Workload POW refers equation solving, who first solved the problem, and who have the right to block out. The equation is calculated by a block in front of a hash value and a random value nonce hash value of the next block, the first to find the nonce, who can be the first to calculate the hash value of the next block, in this way It is called difficult to calculate the value of the equation because there is no fixed solution, but to keep trying, this equation solution is called hash collision, the probability of an event, the more the number of collisions, the more difficulty solving equations Big. Bitcoin is the use of POW consensus algorithm
Specific algorithm implementation principle
This involves two important concepts, is a difficulty factor, is a nonce, nonce can be understood as a random number, it is in mining to find a qualified nonce value. 4 is assumed here that the degree of difficulty (degree of difficulty is the initial credits bit 4), the data block plus a packed nonce value, nonce value has been incremented from zero, these packed data calculated hash values, hash meet top there are 4 0, that is successful mining. Difficulty factor is how much, hash foremost we need to meet the number 0.
struct {Block type Index int // block height TimeStamp Int64 the Data String // transactions the Hash String prehash String a Nonce int Difficulty // int difficulty factor }
// Create a new block pow mining FUNC CreateNewBlock (lastBlock * Block, Data String) * Block { var newBlock Block newBlock.Index = lastBlock.Index +. 1 newBlock.TimeStamp Time.now = (). The Unix () newBlock.Data = Data newBlock.Prehash = lastBlock.Hash newBlock.Difficulty = difiiculty newBlock.Nonce = 0 // excavation - difficulty coefficient values and the number of hash values of the current block is the same as the foregoing 0 for { // calculated hash cuhash: = hex.EncodeToString (BlockHash (newBlock)) fmt.Println ( "in mining", cuhash) newBlock.Hash = cuhash IF isBlockValid (newBlock) {
// check whether the new block legitimate FUNC VerflyBlock (newBlock Block, lastBlock Block) {BOOL IF lastBlock.Index + 1'd! = {Newblock.Index return to false } IF newblock.Prehash! = {LastBlock.Hash return to false } return true
}
func main() {
var genBlock = GenesisBlock() newBlock := CreateNewBlock(genBlock,"新区块") fmt.Println(newBlock)
}
Export
1 2 3 4 5 6
Ac6665903c0cd2f000e17483fbcf6e3e8fa365de2b55663e7c94167f816d1489 mining in mining in a46e18c7938ccb2d0554232f94c6e8db933fae509adafd4091f5f0b51951e6ae mining in 3738b5eb5f8f956974fc767058a6d7c94da0fc406e86df2d508b9b87fc109171 mining in 0000694b1acaec754175f0a49a1aa190e122b58e9f58125bd18ceec898f8d811 mining success & {11,530,267,247 new block 0000694b1acaec754175f0a49a1aa190e122b58e9f58125bd18ceec898f8d811 a8df431924b17633bdf0303763661aa7a41c2608cd99f6527542e1326c718152 12167 4}