package main import ( "math/big" "bytes" "math" "crypto/sha256" "fmt" ) const targetBits = 24 type ProofOfWork struct { block *Block targetBit *big.Int } func NewProofOfWork(block *Block) *ProofOfWork { var IntTarget = big.NewInt(1) IntTarget.Lsh(IntTarget, uint(256 - 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 [32]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) == -1 { fmt.Printf("found hash: %x ", hash) break } else { nonce++ } } return nonce, hash[:] }