Hi 游客

更多精彩,请登录!

比特池塘 区块链技术 正文

区块链POW证明代码实现demo

朋友一起走
132 0 0
这里介绍工作量证明POW, POW是属于共识机制的内容。
0 ]- ]$ Y) Q/ K! B7 L  tPoW机制中根据矿工的工作量来执行货币的分配和记账权的确定。算力竞争的胜者将获得相应区块记账权和比特币奖励。因此,矿机芯片的算力越高,挖矿的时间更长,就可以获得更多的数字货币。
' R$ u1 M0 s, T. C5 G优点:
0 W, A* ?$ ?. t' e  H算法简单,容易实现;节点间无需交换额外的信息即可达成共识;破坏系统需要投入极大的成本。7 O( u0 |7 ]0 T' V0 q
缺点:/ [6 p: \( Y# H- y" M, I6 s* @
浪费能源;区块的确认时间难以缩短;新的区块链必须找到一种不同的散列算法,否则就会面临比特币的算力攻击;容易产生分叉,需要等待多个确认;永远没有最终性,需要检查点机制来弥补最终性。
1 n( H) G* B7 b3 w# Q+ i. a! l目前基于PoW共识机制的数字货币有很多,比特币、莱特币、狗狗币、达士币、门罗币等初期的数字货币大多都是PoW共识机制。
# C$ F' U+ Y# o2 a其他的共识机制还有
& \* {" O6 {1 L1 F  E- t9 V& V2 A8 VPoS(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共识机制- S% y+ @# E) C, l7 t5 {* {& L

' g0 I  W" t% o* F0 f8 U这些共识机制,后面有时间会补充上的,今天主要介绍POW! ?" Y. @$ G3 U4 ^9 Y
pow很简单,原理就是 利用计算力,在选择一个nonce的值结合区块的数据算出hash,使得hash的前面多少位都是0.$ ~8 b+ B6 ]; Z/ O* E+ K. v
nonce是一个用来找到满足条件的hash值的数字,nonce值一直迭代,直到hash值有效为止。在我们案例中一个有效的hash值是最少有4个前导0。找到nonce值以满足合适条件的hash值的过程就叫做挖矿。6 F" a) H' o) r5 U/ h
下面给出代码:
' I  H" b, p  _# p$ n; {
  1. golang版+ e: K, w1 v+ X: E; \8 |
  2. package mainimport (    "bytes"
    $ X- d2 @8 j% x1 j& B/ k5 o
  3.     "crypto/sha256"; e9 s6 X) W0 j. T. q. U1 A
  4.     "fmt"( k* x/ g9 o0 E! B5 g" W" y
  5.     "math", F* p1 K+ p5 u. y! V+ M
  6.     "math/big")// 前导0,难度const targetBits  = 8type ProofOfWork struct {- i7 G& }  B- D4 p8 M% K+ E
  7.     block *Block
    ! s( L# s' U. S
  8.     targetBit *big.Int
    / }2 _% e5 Y: m: M, v" u
  9. }func NewProofOfWork(block *Block) *ProofOfWork  {    // 设置64位全1' s( e5 A' o  `+ l3 G
  10.     var IntTarget = big.NewInt(1)    //00000000000000000000000000001
    7 y. @- E+ h+ a; }) ~3 G8 _4 V
  11.     //10000000000000000000000000000
    % b1 K# v( y, V/ a
  12.     //00000000000100000000000000000
    , ]+ R1 }2 D: ^3 b3 w
  13.     //0000001
    # c' R2 ~* z6 e% Q$ ~: y! n
  14.     // 右移 targetBits位
    8 L4 h6 \! Y5 g  s3 \
  15.     IntTarget.Lsh(IntTarget, uint(256 - targetBits))    return &ProofOfWork{block:block, targetBit:IntTarget}
    % {7 m; ]( {6 y8 p
  16. }func (pow *ProofOfWork)PrepareRawData(nonce int64)[]byte  {
    . }" T: Y0 i# E
  17.     block := pow.block; v- C7 s4 P1 |
  18.     tmp := [][]byte{
    ; |  E8 ~" ^3 h: T# p
  19.         Int2Byte(block.Version),; r0 b! W) q' a' I
  20.         block.PrevBlockHash,
    " l6 L2 V. X6 m7 [: c  s- o
  21.         Int2Byte(block.TimeStamp),
    ! z- N; |* e! }5 H
  22.         block.MerkeRoot,4 n' g4 v& Q3 m% U3 f6 w
  23.         Int2Byte(nonce),- V* B5 W; n2 L! L
  24.         Int2Byte(targetBits),; y% P  g) K* X1 j5 t% @0 K
  25.         block.Data}
    - f" ?9 Y6 N# [7 D: K
  26.     data := bytes.Join(tmp, []byte{})    return data
    0 Z+ x" f' }% ~) n8 t* j
  27. }func (pow *ProofOfWork)Run() (int64, []byte) {    var nonce int64
    ) V& Z/ T. X* A% ]
  28.     var hash [32]byte
    / M6 T# z- ^: {' f; d
  29.     var HashInt big.Int
    5 @& |; g+ |: M4 p
  30.     fmt.Printf("target hash:", pow.targetBit.Bytes())    for nonce $ k# V& [4 C+ n  _" x: t# r4 W, P
  31. python版
    1 s& Z: J# z7 B/ ]5 K' O* r/ E9 x
  32. function isValidHashDifficulty(hash, difficulty) {  for (var i = 0, b = hash.length; i = difficulty;" V' _& P4 N8 I5 q) }# d
  33. }import hashlib"""
    9 `# p7 q8 j& ]) ~: w
  34. 工作量证明9 k% E: K6 a' ?+ t
  35. """class ProofofWork():! A8 K! s. @9 P6 z
  36.     """
    6 L$ k% m. C; d
  37.     pow1 d0 P" R7 N% Y; _
  38.     """8 F# z3 O( r% h) k+ j
  39.     def __init__(self, block):
    ; r; ]4 t2 c/ Q' |1 |! T
  40.         self.block = block    def mine(self):6 _! F) V  q8 r8 `: I1 V6 [7 S
  41.         """: E7 a* M/ B2 W$ }  T" S( d
  42.         挖矿函数: z3 t0 {2 a$ r3 o$ f& G8 }: ]
  43.         :return:" D: z  ~& V  E0 o$ s
  44.         """
      }( P0 ?8 y- z
  45.         i = 09 t- X4 _& c5 e. p  \# J( R' N& n/ h
  46.         prefix = '0000'
    ; _- D* A! A+ T" |0 |( p- ?  P. a! W
  47.         while True:+ B* q. {, \# s2 j* D3 `
  48.             nonce = str(i)
    - ?- g! o" S' L, C) O% g
  49.             message = hashlib.sha256()
    1 ^' j3 c2 ?' U; y7 U7 i1 Q
  50.             message.update(str(self.block.data).encode('utf-8'))
    ; _) V/ [  E- R" Q. N
  51.             message.update(nonce.encode("utf-8"))
    % |$ ?' `- @. e2 u8 P  a
  52.             digest = message.hexdigest()            if digest.startswith(prefix):                return nonce, digest
    3 w, F" {2 X6 _1 ^& D6 J6 D1 e
  53.             i += 1
    / b& m3 ]& W+ {' N- s
复制代码
BitMere.com 比特池塘系信息发布平台,比特池塘仅提供信息存储空间服务。
声明:该文观点仅代表作者本人,本文不代表比特池塘立场,且不构成建议,请谨慎对待。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

成为第一个吐槽的人

朋友一起走 初中生
  • 粉丝

    0

  • 关注

    0

  • 主题

    16