Hi Guest

More contents, please log on!

Bitmere.com 区块链技术 Content

区块链POW证明代码实现demo

朋友一起走
23 0 0
这里介绍工作量证明POW, POW是属于共识机制的内容。
PoW机制中根据矿工的工作量来执行货币的分配和记账权的确定。算力竞争的胜者将获得相应区块记账权和比特币奖励。因此,矿机芯片的算力越高,挖矿的时间更长,就可以获得更多的数字货币。
优点:
算法简单,容易实现;节点间无需交换额外的信息即可达成共识;破坏系统需要投入极大的成本。
缺点:
浪费能源;区块的确认时间难以缩短;新的区块链必须找到一种不同的散列算法,否则就会面临比特币的算力攻击;容易产生分叉,需要等待多个确认;永远没有最终性,需要检查点机制来弥补最终性。
目前基于PoW共识机制的数字货币有很多,比特币、莱特币、狗狗币、达士币、门罗币等初期的数字货币大多都是PoW共识机制。
其他的共识机制还有
PoS(Proof of Stake)DPOS(Delegated Proof-of-Stake)DAG(Directed acyclic graph)PBFT(Practical Byzantine Fault Tolerance)Pool验证池dBFT(delegated BFT)PoA(Proof-of-Authority)RPCA(Ripple Protocol consensus algorithm)Hcash——PoW+PoS共识机制

这些共识机制,后面有时间会补充上的,今天主要介绍POW
pow很简单,原理就是 利用计算力,在选择一个nonce的值结合区块的数据算出hash,使得hash的前面多少位都是0.
nonce是一个用来找到满足条件的hash值的数字,nonce值一直迭代,直到hash值有效为止。在我们案例中一个有效的hash值是最少有4个前导0。找到nonce值以满足合适条件的hash值的过程就叫做挖矿。
下面给出代码:
  1. golang版
  2. package mainimport (    "bytes"
  3.     "crypto/sha256"
  4.     "fmt"
  5.     "math"
  6.     "math/big")// 前导0,难度const targetBits  = 8type ProofOfWork struct {
  7.     block *Block
  8.     targetBit *big.Int
  9. }func NewProofOfWork(block *Block) *ProofOfWork  {    // 设置64位全1
  10.     var IntTarget = big.NewInt(1)    //00000000000000000000000000001
  11.     //10000000000000000000000000000
  12.     //00000000000100000000000000000
  13.     //0000001
  14.     // 右移 targetBits位
  15.     IntTarget.Lsh(IntTarget, uint(256 - targetBits))    return &ProofOfWork{block:block, targetBit:IntTarget}
  16. }func (pow *ProofOfWork)PrepareRawData(nonce int64)[]byte  {
  17.     block := pow.block
  18.     tmp := [][]byte{
  19.         Int2Byte(block.Version),
  20.         block.PrevBlockHash,
  21.         Int2Byte(block.TimeStamp),
  22.         block.MerkeRoot,
  23.         Int2Byte(nonce),
  24.         Int2Byte(targetBits),
  25.         block.Data}
  26.     data := bytes.Join(tmp, []byte{})    return data
  27. }func (pow *ProofOfWork)Run() (int64, []byte) {    var nonce int64
  28.     var hash [32]byte
  29.     var HashInt big.Int
  30.     fmt.Printf("target hash:", pow.targetBit.Bytes())    for nonce
  31. python版
  32. function isValidHashDifficulty(hash, difficulty) {  for (var i = 0, b = hash.length; i = difficulty;
  33. }import hashlib"""
  34. 工作量证明
  35. """class ProofofWork():
  36.     """
  37.     pow
  38.     """
  39.     def __init__(self, block):
  40.         self.block = block    def mine(self):
  41.         """
  42.         挖矿函数
  43.         :return:
  44.         """
  45.         i = 0
  46.         prefix = '0000'
  47.         while True:
  48.             nonce = str(i)
  49.             message = hashlib.sha256()
  50.             message.update(str(self.block.data).encode('utf-8'))
  51.             message.update(nonce.encode("utf-8"))
  52.             digest = message.hexdigest()            if digest.startswith(prefix):                return nonce, digest
  53.             i += 1
Copy the Code
BitMere.com is Information release platform,just provides information storage space services.
The opinions expressed are solely those of the author,Does not constitute advice, please treat with caution.
You have to log in before you can reply Login | 立即注册

Points Rules

Write the first review

朋友一起走 初中生
  • Follow

    0

  • Following

    0

  • Articles

    16

Promoted