Hi 游客

更多精彩,请登录!

比特池塘 区块链技术 正文

区块链POW证明代码实现demo

朋友一起走
81 0 0
这里介绍工作量证明POW, POW是属于共识机制的内容。- C1 y! c- j7 G& Q* X
PoW机制中根据矿工的工作量来执行货币的分配和记账权的确定。算力竞争的胜者将获得相应区块记账权和比特币奖励。因此,矿机芯片的算力越高,挖矿的时间更长,就可以获得更多的数字货币。
/ }9 R4 j) N7 }3 W* V4 [) D1 a2 W+ r优点:9 j$ U0 E$ R# z
算法简单,容易实现;节点间无需交换额外的信息即可达成共识;破坏系统需要投入极大的成本。, f" n2 U+ w3 U+ R. j. [! D% u' Z
缺点:. T* c! q) a3 e
浪费能源;区块的确认时间难以缩短;新的区块链必须找到一种不同的散列算法,否则就会面临比特币的算力攻击;容易产生分叉,需要等待多个确认;永远没有最终性,需要检查点机制来弥补最终性。2 w$ ~3 B% A- X0 W$ `' [$ g! }
目前基于PoW共识机制的数字货币有很多,比特币、莱特币、狗狗币、达士币、门罗币等初期的数字货币大多都是PoW共识机制。
5 d, x4 z% S  a其他的共识机制还有# d# n2 Z8 n- }9 e; N; h
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共识机制' F! G5 {3 M! U$ N2 ]5 h: O$ h
# g: w8 M" n4 S& t4 I5 L' p
这些共识机制,后面有时间会补充上的,今天主要介绍POW& c8 W& b6 w# U) i0 }
pow很简单,原理就是 利用计算力,在选择一个nonce的值结合区块的数据算出hash,使得hash的前面多少位都是0.
  f+ J6 Z! |4 L' g2 Znonce是一个用来找到满足条件的hash值的数字,nonce值一直迭代,直到hash值有效为止。在我们案例中一个有效的hash值是最少有4个前导0。找到nonce值以满足合适条件的hash值的过程就叫做挖矿。0 Q1 S) O7 P* D
下面给出代码:
! [' {* ^+ Q$ f8 S/ H
  1. golang版
    4 K: E$ q6 R5 N' v3 \
  2. package mainimport (    "bytes"7 {  x* T9 S/ Q+ m3 F/ j% Q' c5 Z
  3.     "crypto/sha256"
    0 s1 c7 n" v4 l& n0 ^( u0 [
  4.     "fmt"; Y& m; Q; K! x4 |7 t
  5.     "math"
    ) t5 k8 M3 ~% m' \
  6.     "math/big")// 前导0,难度const targetBits  = 8type ProofOfWork struct {
    % P( m- u6 I4 n7 V
  7.     block *Block8 x8 @6 r( P3 e2 s
  8.     targetBit *big.Int; a% G  C& n4 y" c2 C/ z
  9. }func NewProofOfWork(block *Block) *ProofOfWork  {    // 设置64位全1, C7 ^3 \5 j$ {: A5 ?+ ^7 ]! k
  10.     var IntTarget = big.NewInt(1)    //00000000000000000000000000001
    ) |8 s* _0 e- c" J1 q* [  G' s
  11.     //10000000000000000000000000000
    ) s$ D! e5 n" |2 \! J5 s
  12.     //00000000000100000000000000000
    3 l. V' ~! d! \$ M
  13.     //0000001
    - m) Q& G6 f9 J) J
  14.     // 右移 targetBits位" I" ?! K  \7 s
  15.     IntTarget.Lsh(IntTarget, uint(256 - targetBits))    return &ProofOfWork{block:block, targetBit:IntTarget}
    : O8 O4 Y) ~1 L# z
  16. }func (pow *ProofOfWork)PrepareRawData(nonce int64)[]byte  {
      f: F- o" \: F4 J" ]5 I
  17.     block := pow.block. c7 B" h6 C% y8 R
  18.     tmp := [][]byte{
    ; O' w3 D1 \" ^4 {0 S0 z/ K
  19.         Int2Byte(block.Version),
    2 F- \- B0 n' x3 z1 F& z& X' ~: n
  20.         block.PrevBlockHash,
    . C3 e2 e3 U" r6 S* Y! h+ K
  21.         Int2Byte(block.TimeStamp),2 @9 ]. ]; i5 I7 H
  22.         block.MerkeRoot,
    7 X! \( n+ Y7 N/ x( c7 ^
  23.         Int2Byte(nonce),+ V2 D" i8 J* ^2 ], C6 O
  24.         Int2Byte(targetBits),
    4 F7 D4 l6 N$ J. D/ L
  25.         block.Data}
    * `- f; v1 ^7 ~. N
  26.     data := bytes.Join(tmp, []byte{})    return data
    + }5 R# Q" t4 V. a% L3 y/ t3 g
  27. }func (pow *ProofOfWork)Run() (int64, []byte) {    var nonce int64
    ; s( Z: p: @) o' u9 W
  28.     var hash [32]byte, {+ x1 {  S0 y
  29.     var HashInt big.Int
    & P3 g, e- U/ B! C$ d; A2 J8 Q
  30.     fmt.Printf("target hash:", pow.targetBit.Bytes())    for nonce ! T4 v8 |" ~% C! Z! X
  31. python版
    ; Q: n* U0 J0 m7 `9 w+ }# a
  32. function isValidHashDifficulty(hash, difficulty) {  for (var i = 0, b = hash.length; i = difficulty;
    ( I; l2 L# _7 }5 i  U  G6 D1 E
  33. }import hashlib"""
    * p' g1 d( S  Z+ C- {/ R
  34. 工作量证明  Y- _) V. K$ U, O; L6 M2 i
  35. """class ProofofWork():
    + i8 N8 D2 d$ T& a
  36.     """
    + a2 w6 q" y  o8 G
  37.     pow
    7 [) b7 p; m9 ]) J9 Z5 i; J& |& x
  38.     """
    3 L8 d& |, w9 w( V
  39.     def __init__(self, block):8 Z8 B2 q/ F# X6 W1 h
  40.         self.block = block    def mine(self):6 ^  C9 z& m  i1 F9 j) [2 j2 a- T
  41.         """
    ! D  S/ M3 S( m# u2 P
  42.         挖矿函数+ }; Y% x* J! b1 \- g% T' j3 K
  43.         :return:
    5 p( {+ _2 y) y! m8 |4 A0 m4 N
  44.         """+ K) h' y( e9 ~% B0 b! M
  45.         i = 0
    * y* e$ U; }6 o6 {& X
  46.         prefix = '0000'
    ( o( R  K7 p9 _& K2 U7 v# F1 K
  47.         while True:# X4 C& t$ g& W, e" o
  48.             nonce = str(i)
    / [. a, [1 `4 K7 K! o9 P6 a  z: j# R
  49.             message = hashlib.sha256()  B% r% I2 y# Y
  50.             message.update(str(self.block.data).encode('utf-8'))
    ! \" Q4 m* e3 t0 J& r
  51.             message.update(nonce.encode("utf-8"))
    + U6 D# x3 B: F- X, I
  52.             digest = message.hexdigest()            if digest.startswith(prefix):                return nonce, digest( |0 @/ ~: L& e* T7 w" f' J# ^
  53.             i += 1
    4 o3 h! Z* X2 M) @: S2 A& _
复制代码
BitMere.com 比特池塘系信息发布平台,比特池塘仅提供信息存储空间服务。
声明:该文观点仅代表作者本人,本文不代表比特池塘立场,且不构成建议,请谨慎对待。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

成为第一个吐槽的人

朋友一起走 初中生
  • 粉丝

    0

  • 关注

    0

  • 主题

    16