部分代码(proofofwork.go文件中IsValid函数实现):
1 func (pow *ProofOfWork) IsValid() bool { 2 //在校验的时候,block的数据是完整的,我们要做的是校验一下,Hash,block数据,和Nonce是否满足难度值要求 3 4 //获取block数据 5 //拼接nonce 6 //做sha256 7 //比较 8 9 data := pow.prepareData(pow.block.Nonce) 10 hash := sha256.Sum256(data) 11 12 var tmp big.Int 13 tmp.SetBytes(hash[:]) 14 15 //if tmp.Cmp(pow.target) == -1 { 16 // return true 17 //} 18 // return false 19 20 return tmp.Cmp(pow.target) == -1 21 }
部分代码(main.go文件中字段补充打印):
1 package main 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 func main() { 9 fmt.Printf("HelloWorld!!!\n") 10 11 ////区块实例化 12 //block := NewBlock(genesisInfo,[]byte{0x0000000000000000}) 13 bc := NewBlockChain() 14 bc.AddBlock("哈哈哈哈哈") 15 16 for i, block := range bc.Blocks{ 17 //区块打印 18 fmt.Printf("+++++++++++++++ %d ++++++++++++++\n", i) 19 fmt.Printf("Version : %d\n", block.Version) 20 fmt.Printf("PrevBlockHash : %x\n", block.PrevBlockHash) 21 fmt.Printf("MerKleRoot : %x\n", block.MerKleRoot) 22 23 timeFormat := time.Unix(int64(block.TimeStamp), 0).Format("2006-01-02 15:04:05") 24 fmt.Printf("TimeStamp : %s\n", timeFormat) 25 26 fmt.Printf("Difficulity : %d\n", block.Difficulity) 27 fmt.Printf("Nonce : %d\n", block.Nonce) 28 fmt.Printf("Hash : %x\n", block.Hash) 29 fmt.Printf("Data : %s\n", block.Data) 30 31 pow := NewProofOfWork(block) 32 fmt.Printf("IsValid : %v\n", pow.IsValid()) 33 } 34 }
显示效果:
原文:https://www.cnblogs.com/shizhe99/p/14076966.html