PoW机制中根据矿工的工作量来执行货币的分配和记账权的确定。算力竞争的胜者将获得相应区块记账权和比特币奖励。因此,矿机芯片的算力越高,挖矿的时间更长,就可以获得更多的数字货币。
优点:- l! w/ a9 h* Z. J, D
算法简单,容易实现;节点间无需交换额外的信息即可达成共识;破坏系统需要投入极大的成本。9 N+ u5 j# E! e9 L. y
缺点:, k) p$ Z% t+ h- |, y& N7 l7 B
浪费能源;区块的确认时间难以缩短;新的区块链必须找到一种不同的散列算法,否则就会面临比特币的算力攻击;容易产生分叉,需要等待多个确认;永远没有最终性,需要检查点机制来弥补最终性。* m% k$ k+ W" R' m$ Y( f
目前基于PoW共识机制的数字货币有很多,比特币、莱特币、狗狗币、达士币、门罗币等初期的数字货币大多都是PoW共识机制。/ t% t3 g6 l% V, z
其他的共识机制还有
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共识机制) Z! x- x* G) U
3 f. ]- t! c, u+ H. @9 E
这些共识机制,后面有时间会补充上的,今天主要介绍POW" B9 i& \( N8 R. T" u5 Z; S
pow很简单,原理就是 利用计算力,在选择一个nonce的值结合区块的数据算出hash,使得hash的前面多少位都是0.
nonce是一个用来找到满足条件的hash值的数字,nonce值一直迭代,直到hash值有效为止。在我们案例中一个有效的hash值是最少有4个前导0。找到nonce值以满足合适条件的hash值的过程就叫做挖矿。1 T( Y! @- B; I' v+ ~
下面给出代码:
- golang版9 b2 P* l$ Q5 t8 B% N# T' K
- package mainimport ( "bytes"3 |( @: M9 p& w( b+ C& ~
- "crypto/sha256"' Z, h4 U' R. T* z: q0 C. g5 m7 y) {
- "fmt". n6 t& c/ R( T0 ^/ x* Z1 g
- "math"; ~4 z+ D, I: j0 o9 J& @
- "math/big")// 前导0,难度const targetBits = 8type ProofOfWork struct {1 o" ~2 d0 L( H% }( V1 q* ~. l; E
- block *Block8 ?* f) }6 I7 o, T m
- targetBit *big.Int. V& q; K4 o$ V
- }func NewProofOfWork(block *Block) *ProofOfWork { // 设置64位全1$ p* i1 }* W4 D2 h, w3 d6 u
- var IntTarget = big.NewInt(1) //000000000000000000000000000014 @# D |" G- y2 w1 `) c
- //10000000000000000000000000000
- //00000000000100000000000000000
- //0000001
- // 右移 targetBits位0 h# |+ k* e! C, F
- IntTarget.Lsh(IntTarget, uint(256 - targetBits)) return &ProofOfWork{block:block, targetBit:IntTarget}: b" i0 L+ l0 H" r+ \
- }func (pow *ProofOfWork)PrepareRawData(nonce int64)[]byte {
- block := pow.block
- tmp := [][]byte{& v" k! y3 @7 ~% w
- Int2Byte(block.Version),: ^+ r9 v; w' A5 N+ a4 S" M
- block.PrevBlockHash,
- Int2Byte(block.TimeStamp),8 Z: Q8 S* } J t* I3 a% Q7 a
- block.MerkeRoot,: S3 f* u/ s5 U T1 {
- Int2Byte(nonce),
- Int2Byte(targetBits),
- block.Data}
- data := bytes.Join(tmp, []byte{}) return data
- }func (pow *ProofOfWork)Run() (int64, []byte) { var nonce int64
- var hash [32]byte6 G/ @* k( ?6 v
- var HashInt big.Int
- fmt.Printf("target hash:", pow.targetBit.Bytes()) for nonce
- python版
- function isValidHashDifficulty(hash, difficulty) { for (var i = 0, b = hash.length; i = difficulty;$ B" P( ^4 |3 a6 i9 t, m
- }import hashlib"""
- 工作量证明8 p0 h. |9 ^* e
- """class ProofofWork():: [6 u0 [5 P% i% b
- """: M" _' T4 R. Z% _1 ]$ R* ]
- pow
- """
- def __init__(self, block):+ l( n! ?4 t G( h* J, R
- self.block = block def mine(self):
- """
- 挖矿函数$ G! ]8 G5 j( L+ g$ F
- :return:
- """
- i = 0$ J- ` X+ b" i, m' D2 ^( O. U
- prefix = '0000'
- while True:. ?( F+ m" l" J% r; P# e1 V+ ?
- nonce = str(i)0 v$ M8 i% }% b9 R+ c7 Z7 Z/ e' x
- message = hashlib.sha256()
- message.update(str(self.block.data).encode('utf-8'))" ~, T f* q z- w# p0 [/ H4 b; R+ |
- message.update(nonce.encode("utf-8"))' v* R( \/ m. w$ M& |9 @5 y$ I% X2 ]
- digest = message.hexdigest() if digest.startswith(prefix): return nonce, digest0 I/ M9 @( Y( z7 z4 F4 s' n
- i += 17 h, B/ E% J/ F. p. U; w) h* Z