[GO]go语言实现区块链工作证明(pow)原理

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\n", hash)
            break
        } else {
            nonce++
        }
    }
    return nonce, hash[:]
}

猜你喜欢

转载自www.cnblogs.com/baylorqu/p/9767651.html