前言
在前一篇“golang-區(qū)塊鏈學(xué)習(xí)01”的基礎(chǔ)上户魏,增加我們區(qū)塊鏈的工作量證明。
知識(shí)點(diǎn)
1兰珍、區(qū)塊鏈ProofOfWork(工作量證明)概念温亲,因?yàn)樗腥硕枷肷蓞^(qū)塊來(lái)獲取獎(jiǎng)勵(lì),為了公平起見(jiàn)匕得,我們規(guī)定要想成功生成一個(gè)區(qū)塊必須完成指定難度的任務(wù)才行继榆。也就是誰(shuí)先完成指定難度的任務(wù)就將成功生成一個(gè)區(qū)塊巾表。先預(yù)留個(gè)彩蛋,結(jié)合實(shí)例的工作量證明將在文末總結(jié)略吨。
golang實(shí)現(xiàn)簡(jiǎn)單的工作量證明
1集币、定義一個(gè)工作量難度。比如要求生產(chǎn)的區(qū)塊的hash值前面五位必須為0翠忠。即hash類(lèi)似:00000xxxxxxxxxxx的樣式鞠苟。
2、在Block的結(jié)構(gòu)中增加一個(gè)Nonce變量秽之,通過(guò)不斷修改Nonce的值当娱,不斷計(jì)算整個(gè)區(qū)的hash值,直到滿足上面的要求即可考榨。
3跨细、代碼實(shí)例
創(chuàng)建一個(gè)proofofwork.go文件。定義一個(gè)工作量證明的結(jié)構(gòu)體
type ProofOfWork struct {
block *Block // 即將生成的區(qū)塊對(duì)象
target *big.Int //生成區(qū)塊的難度
}
創(chuàng)建實(shí)例化工作量證明結(jié)構(gòu)體.
const targetBits = 20
func NewProofOfWork(b *Block) *ProofOfWork {
target := big.NewInt(1)
//難度:target=10的18次方(即要求計(jì)算出的hash值小于這個(gè)target)
target.Lsh(target, uint(256-targetBits))
pow := &ProofOfWork{b, target}
return pow
}
計(jì)算hash值的算法
func (pow *ProofOfWork) Run() (int, []byte) {
var hashInt big.Int
var hash [32]byte
nonce := 0// 從0自增
fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
// 循環(huán)從nonce=0一直計(jì)算到nonce=2的64次方的值河质,知道算出符合要求的hash值
for nonce < maxNonce {
// 準(zhǔn)備計(jì)算hash的數(shù)據(jù)
data := pow.prepareData(nonce)
hash = sha256.Sum256(data)// 計(jì)算hash
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])
// 難度證明
if hashInt.Cmp(pow.target) == -1 {
break// 符合
} else {
nonce++// 不符合繼續(xù)計(jì)算
}
}
fmt.Printf("\n\n")
return nonce, hash[:]
}
準(zhǔn)備數(shù)據(jù)
func (pow *ProofOfWork) prepareData(nonce int) []byte {
data := bytes.Join([][]byte{
pow.block.PrevBlockHash,
pow.block.Data,
IntToHex(pow.block.TimeStamp),
IntToHex(int64(targetBits)),
IntToHex(int64(nonce)),
}, []byte{})
return data
}
附件
慣例上碼冀惭。所有的代碼文件清單。
/lession02/src/coin/main.go
package main
import (
"fmt"
"core"
"strconv"
)
func main() {
fmt.Printf("%d\n",uint(256-20))
bc := core.NewBlockChain()
bc.AddBlock("send 1 btc to Ivan")
bc.AddBlock("send 2 btc to Ivan")
for _, block := range bc.Blocks {
fmt.Printf("PrevBlockHash:%x\n", block.PrevBlockHash)
fmt.Printf("Data:%s\n", block.Data)
fmt.Printf("Hash:%x\n", block.Hash)
fmt.Printf("TimeStamp:%d\n", block.TimeStamp)
fmt.Printf("Nonce:%d\n", block.Nonce)
pow := core.NewProofOfWork(block)
fmt.Printf("Pow is %s\n", strconv.FormatBool(pow.Validate()))
println()
}
}
/lession02/src/core/block.go
package core
import (
"time"
"strconv"
"bytes"
"crypto/sha256"
)
type Block struct {
TimeStamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
Nonce int
}
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}
pow := NewProofOfWork(block)
block.Nonce, block.Hash = pow.Run()
return block
}
func (b *Block) SetHash() {
strTimeStamp := []byte(strconv.FormatInt(b.TimeStamp, 10))
headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, strTimeStamp}, []byte{})
hash := sha256.Sum256(headers)
b.Hash = hash[:]
}
func NewGenesisBlock() *Block {
return NewBlock("Genesis Block", []byte{})
}
/lession02/src/core/blockchain.go
package core
type BlockChain struct {
Blocks []*Block
}
func (bc *BlockChain) AddBlock(data string) {
preBlock := bc.Blocks[len(bc.Blocks)-1]
newBlock := NewBlock(data, preBlock.Hash)
bc.Blocks = append(bc.Blocks, newBlock)
}
func NewBlockChain() *BlockChain {
return &BlockChain{[]*Block{NewGenesisBlock()}}
}
/lession02/src/core/proofofwork.go
package core
import (
"math"
"math/big"
"fmt"
"crypto/sha256"
"bytes"
)
var (
maxNonce = math.MaxInt64
)
const targetBits = 20
type ProofOfWork struct {
block *Block
target *big.Int
}
func NewProofOfWork(b *Block) *ProofOfWork {
target := big.NewInt(1)
target.Lsh(target, uint(256-targetBits))
pow := &ProofOfWork{b, target}
return pow
}
func (pow *ProofOfWork) prepareData(nonce int) []byte {
data := bytes.Join([][]byte{
pow.block.PrevBlockHash,
pow.block.Data,
IntToHex(pow.block.TimeStamp),
IntToHex(int64(targetBits)),
IntToHex(int64(nonce)),
}, []byte{})
return data
}
func (pow *ProofOfWork) Run() (int, []byte) {
var hashInt big.Int
var hash [32]byte
nonce := 0
fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
for nonce < maxNonce {
data := pow.prepareData(nonce)
hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
break
} else {
nonce++
}
}
fmt.Printf("\n\n")
return nonce, hash[:]
}
func (pow *ProofOfWork) Validate() bool {
var hashInt big.Int
data := pow.prepareData(pow.block.Nonce)
hash := sha256.Sum256(data)
hashInt.SetBytes(hash[:])
isValid := hashInt.Cmp(pow.target) == -1
return isValid
}
/lession02/src/core/utils.go
package core
import (
"bytes"
"encoding/binary"
"log"
"crypto/sha256"
)
func IntToHex(num int64) []byte {
buff := new(bytes.Buffer)
err := binary.Write(buff, binary.BigEndian, num)
if err != nil {
log.Panic(err)
}
return buff.Bytes()
}
func DataToHash(data []byte) []byte {
hash := sha256.Sum256(data)
return hash[:]
}