区块链共识机制POW(工作证明Proof of Work)

/*
工作量证明步骤:
1、准备公开数据data
2、使用一个计数器counter,初始化为0
3、计算data + counter 的hash值
4、检查条件是否满足某种要求:满足结束,不满足,counter+1,然后重复3-4步骤
*/
package main

import (
    "bytes"
    "crypto/sha256"
    "encoding/binary"
    "fmt"
    "log"
    "math"
    "math/big"
)

func main() {
    //proof of work的核心算法,挖矿
    var hashInt big.Int
    var hash [32]byte
    nonce := 0
    maxNonce := math.MaxInt64

    for nonce < maxNonce {
        data := bytes.Join([][]byte{[]byte("aabbcc"), IntToHex(int64(nonce))}, []byte{})
        hash = sha256.Sum256(data)
        // hash转换成Big Integer,方便做比较
        hashInt.SetBytes(hash[:])
        fmt.Printf("\r%x", hash)

        // 比较hashInt和target的大小。hashInt<target时返回-1;hashInt>target时返回+1;否则返回0。
        if hashInt.Cmp(target()) == -1 {
            break
        } else {
            nonce++
        }
    }
    //  fmt.Printf("%x", hash)

}

func IntToHex(num int64) []byte {
    buff := new(bytes.Buffer)
    err := binary.Write(buff, binary.BigEndian, num)
    if err != nil {
        log.Panic(err)
    }
    return buff.Bytes()
}

func target() *big.Int {
    //设置big.NewInt的初始化位1
    target := big.NewInt(1)
    //左移256-24位,也就是
    target.Lsh(target, uint(256-24))

    return target
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值