第一节 工作量证明

2018-07-20  本文已影响13人  半亩房顶

又开新坑,感觉要废了,但是忍不住想学啊,堪堪另安排了一些时间,学起来吧

主要内容

大致上总结下第一节的内容

以上几个点中,感觉较多的就是了解性质的
主要想说明下工作量证明的具体过程

type ProofOfWork struct {
    //当前要验证的区块
    Block *Block
    //大数据存储 难度
    target *big.Int
}

const targetBit = 10

工作量证明的结构如上,一个结构体,包含一个区块的指针以及一个挖矿难度的值,big int类型
targetBit 是难度的值,值越大则越难挖矿

//创建新的工作量证明对象
func NewProofOfWork(block *Block) *ProofOfWork {

    //创建一个初始值为1的target 左移256 - targetBit
    target := big.NewInt(1)
    target = target.Lsh(target, 256-targetBit)

    return &ProofOfWork{block, target}
}

这一段是创建工作量证明结构的代码,关键在于生成难度值,设定一个big int,左移256-targetBit位,形成一个数字,如 00010000...000(共256位)

//挖矿
func (proofOfWork *ProofOfWork) Run() ([]byte, int64) {

    nonce := 0

    var hash [32]byte
    var hashInt big.Int

    for {
        //将block的属性拼接成字节数组
        dataBytes := proofOfWork.prepareData(nonce)
        //生成hash
        hash = sha256.Sum256(dataBytes)
        //hash转换为int(Hex->Dec)
        hashInt.SetBytes(hash[:])

        //判hash有效性 满足条件, 跳出循环
        if proofOfWork.target.Cmp(&hashInt) == 1 {
            break
        }

        nonce = nonce + 1
    }

    return hash[:], int64(nonce)
}

这段代码是工作量证明中具体的判别代码,通过不断的自加nonce,将求得的hash与难度值做对比,此时发现获取到了一个比难度值小的hash的时候,即完成工作量证明,跳出循环

以上,欢迎讨论,欢迎转载

上一篇 下一篇

猜你喜欢

热点阅读