区块链共识机制POW(工作证明Proof of Work)
2018-06-27 本文已影响0人
哎呀妈咪
/*
工作量证明步骤:
1、准备公开数据data
2、使用一个计数器counter,初始化为0
3、计算data + counter 的hash值
4、检查条件是否满足某种要求:满足结束,不满足,counter+1,然后重复3-4步骤
*/
package main
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
"log"
"math"
"math/big"
)
func main() {
//proof of work的核心算法,挖矿
var hashInt big.Int
var hash [32]byte
nonce := 0
maxNonce := math.MaxInt64
for nonce < maxNonce {
data := bytes.Join([][]byte{[]byte("aabbcc"), IntToHex(int64(nonce))}, []byte{})
hash = sha256.Sum256(data)
// hash转换成Big Integer,方便做比较
hashInt.SetBytes(hash[:])
fmt.Printf("\r%x", hash)
// 比较hashInt和target的大小。hashInt<target时返回-1;hashInt>target时返回+1;否则返回0。
if hashInt.Cmp(target()) == -1 {
break
} else {
nonce++
}
}
// fmt.Printf("%x", hash)
}
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 target() *big.Int {
//设置big.NewInt的初始化位1
target := big.NewInt(1)
//左移256-24位,也就是
target.Lsh(target, uint(256-24))
return target
}