package mainimport (
"math/big"
"bytes"
"math"
"crypto/sha256"
"fmt"
)const targetBits = type ProofOfWork struct {
block *Block
targetBit *big.Int
}func NewProofOfWork(block *Block) *ProofOfWork {
var IntTarget = big.NewInt()
IntTarget.Lsh(IntTarget, uint( - targetBits))
return &ProofOfWork{block, IntTarget}
}func (pow *ProofOfWork)PrepareRowData(nonce int64) []byte {
block := pow.block
tmp := [][]byte{
IntToByte(block.Version),
block.PreBlockHash,
IntToByte(block.TimeStamp),
block.MerkelRoot,
IntToByte(nonce),
IntToByte(targetBits),
block.Data,
}
data := bytes.Join(tmp, []byte{})//join接收两个参数,第一个二维数组,第二个这里设置为空的连接符
return data
}func (pow *ProofOfWork)Run() (int64, []byte) {
var nonce int64
var hash []byte
var HashInt big.Int
for nonce < math.MaxInt64 {
data := pow.PrepareRowData(nonce)
hash = sha256.Sum256(data)
HashInt.SetBytes(hash[:])
if HashInt.Cmp(pow.targetBit) == - {
fmt.Printf("found hash: %x\n", hash)
break
} else {
nonce++
}
}
return nonce, hash[:]
}