zoukankan      html  css  js  c++  java
  • [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
    ", hash)
                break
            } else {
                nonce++
            }
        }
        return nonce, hash[:]
    }
  • 相关阅读:
    谍战系列
    干将莫邪
    漫话安全众测
    一句话安全
    jsp一句话
    struts2的DevMode模式
    morse code
    Nessus的安装/激活/更新
    WinPcap4.13无法安装解决方法
    安全用网,你应该知道的事
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9767651.html
Copyright © 2011-2022 走看看