美文网首页
区块链共识机制POW(工作证明Proof of Work)

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

作者: 哎呀妈咪 | 来源:发表于2018-06-27 10:11 被阅读0次
/*
工作量证明步骤:
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
}

相关文章

  • 共识机制

    共识机制 标签(空格分隔): 区块链 共识机制 [TOC] PoW(Proof of Work):工作量证明机制 ...

  • 共识算法系列之二:区块链共识算法

    区块链中比较常见的共识机制主要有工作量证明POW(Proof of Work)、权益证明POS(Proof of ...

  • 区块链概况整理

    区块链的一些概念 区块链三要素 共享帐本 共识算法工作量证明机制(PoW,Proof of Work)股权证明机制...

  • 走近区块链‖06共识机制

    目前区块链共识机制有很多种,这里列举一些比较典型的共识机制。 1.Proof-of-Work(PoW),工作量证明...

  • 【Day9-王承顺】共识机制

    PoW Proof of Work(工作量证明),这是比特币区块链采用的共识机制。这个机制在1998年在B-mon...

  • PDBFT共识算法

    早期的公有链系统大多采用基于工作量证明(POW,proof of work)的共识机制,在这种机制下,硬件性能直接...

  • POW-(工作量证明)

    PoW 共识机制 概述 PoW(Proof of Work),即工作量证明,闻名于比特币,俗称“挖矿”。PoW是指...

  • Blockchain主流共识算法

    区块链主流的共识算法主要有:POW、POS、DPOS、PBFT、RAFT POW:Proof of work,工作...

  • 3.POW挖矿验证算法实现

    Pow(Proof Of Work)的中文翻译是:工作量证明,是区块链共识机制的一种。 我们都知道比特币系统是由全...

  • 【区块链】区块链中的共识机制

    一、PoW-工作量证明机制 工作量证明机制(Proof of Work 简称PoW)是共识机制中的一种,可简单理解...

网友评论

      本文标题:区块链共识机制POW(工作证明Proof of Work)

      本文链接:https://www.haomeiwen.com/subject/njfbyftx.html