1. 程式人生 > 實用技巧 >區塊鏈V2版本實現之三

區塊鏈V2版本實現之三

部分程式碼(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 }

顯示效果: