但是完全搞懂区块链并非易事,至少对我来讲是这样。我喜欢在实践中学习,通过写代码来学习技术会掌握得更牢固。通过构建一个区块链可以加深对区块链的理解。
准备工作
我们知道区块链是由区块的记录构成的不可变、有序的链结构,记录可以是交易、文件或任何你想要的数据,重要的是它们是通过哈希值(hashes)链接起来的。- u6 Q2 ^( m, B6 b0 G2 K- z
如果你不知道哈希值是什么,这里有一个解释。
这份指南的目标人群:阅读这篇文章,要求读者对Python有基本的了解,能编写基本的Python代码,并且需要对HTTP请求有基本的理解。' @' A( j( m8 r- s- k4 V" F. U
环境准备:确保已经安装Python3.6+,pip,Flask,requests。安装方法:! x; b6 [! G: G4 Q# J9 z/ t: e
pipinstallFlask==0.12.2requests==2.18.4
同时还需要一个HTTP客户端,比如Postman,cURL或其它客户端。
一、开始创建BlockChain" a% O/ H3 W R% g
打开你最喜欢的文本编辑器或者IDE,比如PyCharm,新建一个文件blockchain.py,本文所有的代码都写在这一个文件中。如果你丢了它,你总是可以引用源代码。
BlockChain类* e# ]' t: w6 M' X5 M; I* X5 S
首先创建一个Blockchain类,在构造函数中创建了两个列表,一个用于储存区块链,一个用于储存交易。; n% l. |) Y. r3 n7 F
以下是BlockChain类的框架:1 n7 }- J9 W+ Z& O" v' B
- classBlockchain(object):
- def__init__(self):
- self.chain=[]! b1 {0 v9 L+ B) H0 G# g: }
- self.current_transactions=[]
- defnew_block(self):+ B2 v' _. e+ N5 j9 C. s) y
- #CreatesanewBlockandaddsittothechain
- pass
- defnew_transaction(self):( {) C3 P! g9 Z H+ y1 w/ ~
- #Addsanewtransactiontothelistoftransactions! _! @$ r, J. l" _
- pass/ P9 e9 ]0 C5 ~
- @staticmethod
- defhash(block): D/ ~7 z% x' i6 `, P& ~
- #HashesaBlock+ U3 r; r9 w5 U0 ]8 d7 ~( O M
- pass: X0 T) f5 F a- W5 X- Y
- @property6 {- v5 |' s0 u2 K6 s0 b u! z
- deflast_block(self):
- #ReturnsthelastBlockinthechain
- pass
-我们的区块链类的蓝图-3 |5 ~, |# t3 }% M
Blockchain类用来管理链条,它能存储交易,加入新块等,下面我们来进一步完善这些方法。' p8 K! \4 u! x0 p m1 b& c
块结构
每个区块包含属性:索引(index),Unix时间戳(timestamp),交易列表(transactions),工作量证明(稍后解释)以及前一个区块的Hash值。7 F" }# L8 T/ b1 v6 H/ w# e
以下是一个区块结构:' `5 L2 Z7 ]& }6 i9 C8 n) e- V& b$ U
- block={
- 'index':1,- d8 d! L) f% P! Q: r/ u
- 'timestamp':1506057125.900785,
- 'transactions':[
- {2 i* |' M& t! ?. a/ d% p& F3 T/ S
- 'sender':"8527147fe1f5426f9dd545de4b27ee00",
- 'recipient':"a77f5cdfa2934df3954a5c7c7da5df1f",
- 'amount':5,
- }. @6 T, q! x# V! S* ^$ b
- ],/ T" F# y- t, v1 b) Z
- 'proof':324984774000,3 {3 D. t1 {$ F( a+ Z# y. i @
- 'previous_hash':"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
- }
-链上一个区块的例子-/ [! h! m7 O' G2 p
到这里,区块链的概念就清楚了,每个新的区块都包含上一个区块的Hash,这是关键的一点,它保障了区块链不可变性。如果攻击者破坏了前面的某个区块,那么后面所有区块的Hash都会变得不正确。
确定这有用吗?嗯,你可以花点彻底了解它——这可是区块链背后的核心理念。# }" x* Q6 q6 X& M. R
加入交易! H% z9 b. r8 k# v( j0 K
接下来我们需要添加一个交易,来完善下new_transaction()方法。' x; Z: G* K" v: o: I
- classBlockchain(object):
- ...: B- b( \) z& q9 t* D1 e1 L9 t
- defnew_transaction(self,sender,recipient,amount):; y' u9 F/ C5 s; v" u' y1 H& d
- """" k7 B2 B0 G7 C# Y( B; {
- 生成新交易信息,信息将加入到下一个待挖的区块中
- :paramsender:AddressoftheSender. ^, t, y! y; R) h. M! p9 ~
- :paramrecipient:AddressoftheRecipient6 O, ?3 P+ E; v
- :paramamount:Amount
- :return:TheindexoftheBlockthatwillholdthistransaction
- """
- self.current_transactions.append({
- 'sender':sender,( e4 `; ?, A/ [
- 'recipient':recipient,8 T$ R7 D6 Q& e1 C' x) B5 {
- 'amount':amount,
- })4 {* i! u# ~8 ~1 ?) u* @
- returnself.last_block['index']+1
new_transaction()方法向列表中添加一个交易记录,并返回该记录将被添加到的区块(下一个待挖掘的区块)的索引,等下在用户提交交易时会有用。
创建区块
当Blockchain实例化后,我们需要构造一个创世块(没有前区块的第一个区块),并且给它加上一个“工作量证明”。+ |4 k4 d! H+ U, n/ p+ N
每个区块都需要经过工作量证明,俗称挖矿,稍后会继续讲解。
为了构造创世块,我们还需要完善new_block()、new_transaction()和hash()方法:
- importhashlib* v. O( }% Y4 A! U) }) O2 w
- importjson" T( L" L; e' t. t$ t
- fromtimeimporttime! z0 i+ @) j n) t
- classBlockchain(object):
- def__init__(self):
- self.current_transactions=[]! ^# A. r# Y* _
- self.chain=[]
- #Createthegenesisblock6 T. E* u k/ `0 i3 I4 M
- self.new_block(previous_hash=1,proof=100), M+ h( L* ], g" w" n7 W' K5 q" _
- defnew_block(self,proof,previous_hash=None):
- """
- 生成新块
- :paramproof:TheproofgivenbytheProofofWorkalgorithm. Z7 |, d. `$ Y O: W
- :paramprevious_hash:(Optional)HashofpreviousBlock
- :return:NewBlock
- """, d% l3 {3 k0 l2 ^$ f
- block={3 [9 r a8 C$ C# W5 e0 o$ K, A
- 'index':len(self.chain)+1,
- 'timestamp':time(),2 [- ]4 w* C. _6 D4 N! H
- 'transactions':self.current_transactions,
- 'proof':proof,
- 'previous_hash':previous_hashorself.hash(self.chain[-1]),
- }) a9 z7 t/ V: H# i y
- #Resetthecurrentlistoftransactions
- self.current_transactions=[]+ Y3 }6 J: Q, Y x- ]4 @% U
- self.chain.append(block)
- returnblock' ]/ A+ G- u; }6 ]
- defnew_transaction(self,sender,recipient,amount):/ z# ]6 j# H" X% ]5 o
- """" d0 c. I' }; [6 j q3 J7 n
- 生成新的交易信息,信息将加入到下一个待挖的区块中/ N* L; l5 E' U7 N
- :paramsender:AddressoftheSender9 i* M8 T1 x W$ B4 J1 |8 L% {- M
- :paramrecipient:AddressoftheRecipient/ q1 M( T* F: E0 O
- :paramamount:Amount3 \" h) Z* [. M; V; _; J$ ]+ J& o
- :return:TheindexoftheBlockthatwillholdthistransaction
- """
- self.current_transactions.append({
- 'sender':sender,. l& H+ S3 F `% [6 o+ Z. {9 X9 V
- 'recipient':recipient,! H% @& F% C) S* C! ]( n
- 'amount':amount,) p9 m" j8 {6 p* ^7 y
- })
- returnself.last_block['index']+1
- @property3 l; C+ \9 [- g! ~9 s
- deflast_block(self):
- returnself.chain[-1]
- @staticmethod
- defhash(block):* I5 |+ h, Z2 g# T8 Y! V1 H
- """7 i/ A% [: M* p% m7 g+ J" _) d3 ?& v
- 生成块的SHA-256hash值& D. x1 B; _' l4 C
- :paramblock:Block
- :return:
- """
#WemustmakesurethattheDictionaryisOrdered,orwe'llhaveinconsistenthashes
block_string=json.dumps(block,sort_keys=True).encode()0 L$ i+ u7 U0 {# X0 l
returnhashlib.sha256(block_string).hexdigest()
上述应该是非常直接的——我已经添加了一些注释和字符来帮助大家理解。当表达出我们的区块链时,我们也快要完成了。但现在,你肯定在疑惑新区块是如何被创建、伪造或是挖出的。
理解工作量证明
新的区块依赖工作量证明算法(PoW)来构造。PoW的目标是找出一个符合特定条件的数字,这个数字很难计算出来,但容易验证。这就是工作量证明的核心思想。
为了方便理解,我们举个例子:
假设一个整数x乘以另一个整数y的积的Hash值必须以0结尾,即hash(x*y)=ac23dc…0。设变量x=5,求y的值?用Python实现如下:
- fromhashlibimportsha256% D: t6 B0 L. C5 S( s- w" X2 m
- x=5
- y=0#y未知
- whilesha256(f'{x*y}'.encode()).hexdigest()[-1]!="0":
- y+=17 g) k2 G$ R I: n% ~3 N7 ]) x4 B
- print(f'Thesolutionisy={y}')
结果y=21,因为:- Q5 j; y: E3 g6 C N* q5 O
hash(5*21)=1253e9373e...5e3600155e860
在比特币中,使用称为Hashcash的工作量证明算法,它和上面的问题很类似。矿工们为了争夺创建区块的权利而争相计算结果。通常,计算难度与目标字符串需要满足的特定字符的数量成正比,矿工算出结果后,会获得比特币奖励。3 g2 A0 Y3 c% E$ ]2 x1 }$ H& V
当然,在网络上非常容易验证这个结果。' r K1 U$ Y' t# J9 k; q6 _
实现工作量证明
让我们来实现一个相似PoW算法,规则是:8 K& `+ I$ V4 `! d
寻找一个数p,使得它与前一个区块的proof拼接成的字符串的Hash值以4个零开头。# X! n0 T5 d$ V. `8 Y% W
- importhashlib. N5 q* Q: Y1 }' ^8 S
- importjson
- fromtimeimporttime
- fromuuidimportuuid48 D) _% k5 o& Y) B5 r+ m4 I$ A
- classBlockchain(object):9 n& X; n( Y! Y2 w; ?
- ...; u1 \- G( v+ \$ T# P
- defproof_of_work(self,last_proof):
- """
- 简单的工作量证明:$ o2 J+ t; X+ {7 c; n @0 W9 g) Q
- -查找一个p'使得hash(pp')以4个0开头
- -p是上一个块的证明,p'是当前的证明3 s& a' C% Z* y7 X' r
- :paramlast_proof:
- :return:' V5 y0 l% G/ N: r% k
- """
- proof=0" b7 Q- H q( l$ U7 f, Y
- whileself.valid_proof(last_proof,proof)isFalse:% K/ c4 l7 _% e* H" P6 z& o
- proof+=1
- returnproof
- @staticmethod
- defvalid_proof(last_proof,proof):& u# }/ ^/ {& N, d2 ]
- """
- 验证证明:是否hash(last_proof,proof)以4个0开头?
- :paramlast_proof:PreviousProof
- :paramproof:CurrentProof; N8 _' C& e8 E: Z& ^
- :return:Trueifcorrect,Falseifnot.3 V! e; L( h+ n0 k+ }$ A
- """
- guess=f'{last_proof}{proof}'.encode()5 ?+ [& p o. S1 q
- guess_hash=hashlib.sha256(guess).hexdigest()
- returnguess_hash[:4]=="0000"
- ```
衡量算法复杂度的办法是修改零开头的个数。使用4个来用于演示,你会发现多一个零都会大大增加计算出结果所需的时间。0 m3 w7 D% N6 N% m
现在Blockchain类基本已经完成了,接下来使用HTTPrequests来进行交互。
##二、BlockChain作为API接口4 i% a- ? f: c# X( P' `2 f
我们将使用PythonFlask框架,这是一个轻量Web应用框架,它方便将网络请求映射到Python函数,现在我们来让Blockchain运行在基于Flaskweb上。
我们将创建三个接口:. _* M" k/ j$ _+ e/ \: b5 k
- ```/transactions/new```创建一个交易并添加到区块
- ```/mine```告诉服务器去挖掘新的区块
- ```/chain```返回整个区块链/ F* X) k1 i; K n8 z4 ~# i! M
- ###创建节点$ K( w; g8 s$ t
- 我们的Flask服务器将扮演区块链网络中的一个节点。我们先添加一些框架代码:
- importhashlib& ~$ l2 s* R8 J9 j3 F( V# i) d
- importjson
- fromtextwrapimportdedent
- fromtimeimporttime
- fromuuidimportuuid4
- fromflaskimportFlask
- classBlockchain(object):* l7 R- A) [4 f2 b, K# U
- …
- InstantiateourNode
- app=Flask(name)
- Generateagloballyuniqueaddressforthisnode& j" G3 Y8 R4 V
- node_identifier=str(uuid4()).replace(’-’,‘’)
- InstantiatetheBlockchain$ U9 C/ B7 H3 Q" |8 w7 J
- blockchain=Blockchain()
- @app.route(’/mine’,methods=[‘GET’])) k' d5 L1 y0 {! j* b5 D4 L
- defmine():
- return“We’llmineanewBlock” V0 ^8 X+ C& m0 b: a
- @app.route(’/transactions/new’,methods=[‘POST’])
- defnew_transaction():
- return“We’lladdanewtransaction”
- @app.route(’/chain’,methods=[‘GET’])8 Y$ W# S9 ~# B s2 i# g
- deffull_chain():! [3 @1 w0 R/ Y9 Z7 {
- response={- }4 j8 n# N' ^$ ~6 T: g
- ‘chain’:blockchain.chain,; O6 m" v' g$ r
- ‘length’:len(blockchain.chain),
- }. N v& j1 ` _
- returnjsonify(response),2007 Z' `; J9 _: K* l
- ifname==‘main’:, g6 i" o6 ?/ @9 \2 n
- app.run(host=‘0.0.0.0’,port=5000)5 Q9 v7 F* d4 B& X4 G
- ```3 a+ V& ]; ]2 I) [% y
- 简单的说明一下以上代码:
- 第15行:创建一个节点。在这里阅读更多关于Flask的东西。9 f: W% x9 Z2 w& p" a m1 _
- 第18行:为节点创建一个随机的名字。4 i: T4 d2 {6 K& P+ m# H/ N
- 第21行:实例Blockchain类。
- 第24–26行:创建/mineGET接口。; [7 u7 N# `4 G" x3 l# K$ j
- 第28–30行:创建/transactions/newPOST接口,可以给接口发送交易数据。
- 第32–38行:创建/chain接口,返回整个区块链。; C8 d I- _/ M
- 第40–41行:服务运行在端口5000上。
- 发送交易& }" C' v0 z8 P& C6 g8 ~/ X4 f
- 发送到节点的交易数据结构如下:
- { Q6 a" o+ S8 d( X; E: z0 U
- "sender":"myaddress",* y8 o" e \0 E
- "recipient":"someoneelse'saddress",: c/ _/ ~0 v) o" Z
- "amount":57 i& y. I, E; L1 f Q; C
- }
- 之前已经有添加交易的方法,基于接口来添加交易就很简单了:$ |: K7 ~4 L n4 |
- importhashlib+ X2 \: w( V3 t6 O, D' n! F
- importjson4 E* }7 K) p9 Y- Q# \0 S# W
- fromtextwrapimportdedent2 s- u- V- L; x9 \) l6 i
- fromtimeimporttime
- fromuuidimportuuid4- x; i) F: o( U, V( \! l/ }: y
- fromflaskimportFlask,jsonify,request3 T* M- i7 J' G& A' O1 T
- ...- A3 w, r% Q f) m" T
- @app.route('/transactions/new',methods=['POST'])
- defnew_transaction():% C7 E. j, v( h- H) Y( k) H
- values=request.get_json()
- #CheckthattherequiredfieldsareinthePOST'eddata8 v8 Q$ b ]4 {7 P
- required=['sender','recipient','amount']+ e; Q6 t* \# r. i
- ifnotall(kinvaluesforkinrequired):6 G2 K: e2 Y/ v
- return'Missingvalues',400
- #CreateanewTransaction/ F& N% V1 g1 C; ?: d9 Y' U
- index=blockchain.new_transaction(values['sender'],values['recipient'],values['amount'])/ U1 n, x+ u( A$ ?; J' p2 n
- response={'message':f'TransactionwillbeaddedtoBlock{index}'}: b o9 v4 @; d2 a
- returnjsonify(response),201
- ```# S: s3 |* P% c* F2 c; }, |
- -创建交易的方法-' i! M2 h! |/ Y0 @; n3 a; v1 w
- ###挖矿
- 挖矿正是神奇所在,它很简单,做了一下三件事:! z1 d2 P3 p: Z
- 计算工作量证明PoW8 `0 N0 s$ y1 ?
- 通过新增一个交易授予矿工(自己)一个币
- 构造新区块并将其添加到链中" y' Y' l9 v- o, ?1 P
- importhashlib% R! j; T4 @2 p: G, n( g4 X
- importjson$ T# y, m# |1 [! H; ~/ u5 y
- fromtimeimporttime7 @2 F1 e) x) J& R* N
- fromuuidimportuuid4& e6 N3 n0 L1 A$ @' T z6 {
- fromflaskimportFlask,jsonify,request
- …: v4 C4 r( J- c- u/ t% e7 V2 ?: g. ?) n
- @app.route(’/mine’,methods=[‘GET’]); C# b. z0 e& P. K6 c+ Z8 r
- defmine():
- #Weruntheproofofworkalgorithmtogetthenextproof…' }0 @! y+ Q/ T/ o2 T+ B; q
- last_block=blockchain.last_block
- last_proof=last_block[‘proof’]
- proof=blockchain.proof_of_work(last_proof)
- #给工作量证明的节点提供奖励.0 |$ B6 D6 G" z i' [
- #发送者为"0"表明是新挖出的币.& a) d) X2 k' @, E" j
- blockchain.new_transaction(
- sender="0", _# b6 f' O7 c2 v5 L# h; p8 ?
- recipient=node_identifier,0 N1 y |2 X6 ^$ o9 T
- amount=1,
- )
- #ForgethenewBlockbyaddingittothechain
- previous_hash=blockchain.hash(last_block)* f5 u& O0 S4 q9 _( M& ] z
- block=blockchain.new_block(proof,previous_hash)
- response={
- 'message':"NewBlockForged",
- 'index':block['index'],
- 'transactions':block['transactions'],
- 'proof':block['proof'],
- 'previous_hash':block['previous_hash'],
- }
- returnjsonify(response),200
- ```
注意交易的接收者是我们自己的服务器节点,我们做的大部分工作都只是围绕Blockchain类方法进行交互。到此,我们的区块链就算完成了,我们来实际运行下。% u' c/ h8 v. ?0 N; L, y
三、运行区块链
你可以使用cURL或Postman去和API进行交互
启动server:
$pythonblockchain.py
*Runningonhttp://127.0.0.1:5000/(PressCTRL+Ctoquit)
让我们通过发送GET请求到http://localhost:5000/mine来进行挖矿:
-使用Postman以创建一个GET请求-
通过发送POST请求到http://localhost:5000/transactions/new,添加一个新交易:# c" H( p- ~5 a" k: e _
-使用Postman以创建一个POST请求-
如果不是使用Postman,则用一下的cURL语句也是一样的:6 F% R( w5 g+ L' O0 T
$curl-XPOST-H"Content-Type:application/json"-d'{9 w/ Y7 g+ ~6 ^ Q
"sender":"d4ee26eee15148ee92c6cd394edd974e",/ u# O1 I0 ]; Y, s6 |; v2 k
"recipient":"someone-other-address",' {. T$ N$ c. J+ }) b |. G, ]: g+ Y
"amount":5
}'"http://localhost:5000/transactions/new"
在挖了两次矿之后,就有3个块了,通过请求http://localhost:5000/chain可以得到所有的块信息:
- {+ ?! g9 x) I% _- Q+ a% [1 d
- "chain":[0 ]+ M9 R/ E0 P/ I" N
- {
- "index":1,
- "previous_hash":1,
- "proof":100,/ \! @9 L1 n0 J3 o+ _
- "timestamp":1506280650.770839,
- "transactions":[]/ J" P, N5 I) f
- },6 C: Z# N# ^* f1 h# K
- {
- "index":2,4 m+ X4 K, l) u2 M7 t
- "previous_hash":"c099bc...bfb7",: B' `! P. m2 b7 m- m; C
- "proof":35293,
- "timestamp":1506280664.717925,) S3 q e8 p% J7 m$ D1 k1 H& a
- "transactions":[! ^; H8 F) H$ P* {. |2 ]
- {
- "amount":1,
- "recipient":"8bbcb347e0634905b0cac7955bae152b",
- "sender":"0"0 x7 F N: G0 U P2 a
- }. `' D m# t4 j5 x+ l
- ]. B5 k5 x) S. ` J. M4 X5 x
- },
- {2 n# u$ W( r$ n p9 ~) r/ u; m
- "index":3,- i1 |! Y& Z& Q, N: n5 q \
- "previous_hash":"eff91a...10f2",3 x! E2 R( g" Z, d& `: B
- "proof":35089,0 k. D) M1 i0 U
- "timestamp":1506280666.1086972,* a$ n# ^# Z S: V
- "transactions":[
- {, `+ D9 R5 M* c" U0 a& }: I) P
- "amount":1,
- "recipient":"8bbcb347e0634905b0cac7955bae152b",
- "sender":"0"9 x4 r! y ~% ~: H+ r' r" `
- }3 O+ _- k+ A) [/ O, f6 } f% U3 d7 c- f
- ]8 t" R3 R; P3 ^* ^
- }
- ],4 V/ c: z/ @- g/ a6 k
- "length":3# w! Z$ |( Q. o B0 T
- }
四、一致性(共识)
非常棒,我们已经有了一个基本的区块链可以接受交易和挖矿。但是区块链系统应该是分布式的。既然是分布式的,那么我们究竟拿什么保证所有节点有同样的链呢?这就是一致性问题,我们要想在网络上有多个节点,就必须实现一个一致性的算法。! r+ f! q* q: T! d4 \- Z1 Q1 @
注册节点
在实现一致性算法之前,我们需要找到一种方式让一个节点知道它相邻的节点。每个节点都需要保存一份包含网络中其它节点的记录。因此让我们新增几个接口:
/nodes/register接收URL形式的新节点列表* B1 K8 {+ X# e$ f8 u6 c
/nodes/resolve执行一致性算法,解决任何冲突,确保节点拥有正确的链
我们修改下Blockchain的init函数并提供一个注册节点方法:
- ...! w; }7 r! z+ Y {& h: P
- fromurllib.parseimporturlparse: c3 T0 M9 } \7 ?
- ...; O8 V! j( Z0 @% Y8 e4 A
- classBlockchain(object):
- def__init__(self):- n$ O. ~, I' A( W% ]
- ...
- self.nodes=set()
- ...8 m: q- S+ D/ I- p7 h' b7 m
- defregister_node(self,address):
- """: d1 d6 {# z' O- d9 L) m* b: p# i
- Addanewnodetothelistofnodes& m$ T6 E2 e: d) S
- :paramaddress:Addressofnode.Eg.'http://192.168.0.5:5000'
- :return:None
- """( l! u- n, ?* y- `8 i0 b
- parsed_url=urlparse(address)" V: M3 X% L( m3 Q- u; {3 d9 D
- self.nodes.add(parsed_url.netloc)
- ```
- 我们用set()来储存节点,这是一种避免重复添加节点的简单方法——这意味着无论我们添加特定节点多少次,它实际上都只添加了一次。5 D, Q( ]5 Q5 G) U3 O% ]
- ###实现共识算法! S7 N, L, \7 U8 N2 Z/ Z/ ?5 k
- 前面提到,冲突是指不同的节点拥有不同的链,为了解决这个问题,规定最长的、有效的链才是最终的链,换句话说,网络中有效最长链才是实际的链。我们使用以下的算法,来达到网络中的共识。
- …1 f7 M! ]5 `; N0 m
- importrequests
- classBlockchain(object)0 M! f' ]$ q* X0 `
- …4 D4 L. f; j0 e' W, [- Z: ?
- defvalid_chain(self,chain):/ f ?: l9 Y: I, ?3 K. f" G8 q1 l
- """/ l$ _& J+ [9 R+ N# ?
- Determineifagivenblockchainisvalid" R8 ~2 ^4 X: [# s$ Q& m, u9 ?# N. g
- :paramchain:Ablockchain
- :return:Trueifvalid,Falseifnot
- """
- last_block=chain[0]
- current_index=10 \1 ~3 K9 @" k" P
- whilecurrent_indexmax_lengthandself.valid_chain(chain):" X& [9 f# O5 D) B; D9 q4 C
- max_length=length5 c6 X* \6 ]5 v2 b4 a+ l" A: q% j
- new_chain=chain
- #Replaceourchainifwediscoveredanew,validchainlongerthanours* Y9 i+ [$ @7 b0 @$ e
- ifnew_chain:
- self.chain=new_chain( B% Z3 F) ?. f- I3 h% o
- returnTrue3 F7 W- J) f Q) A* y5 a
- returnFalse$ z2 X, B' _: F! V: g3 \' t! D
- ```
第1个方法valid_chain()用来检查是否是有效链,遍历每个块验证hash和proof。& I- N5 K6 c$ E% a0 [
第2个方法resolve_conflicts()用来解决冲突,遍历所有的邻居节点,并用上一个方法检查链的有效性,如果发现有效更长链,就替换掉自己的链。
让我们添加两个路由,一个用来注册节点,一个用来解决冲突。
- @app.route('/nodes/register',methods=['POST'])8 \% @( s( M$ P0 e7 V
- defregister_nodes():3 c7 K1 j6 N0 y4 f( |6 d% s
- values=request.get_json()
- nodes=values.get('nodes')
- ifnodesisNone:
- return"Error:Pleasesupplyavalidlistofnodes",400
- fornodeinnodes:
- blockchain.register_node(node)" ~$ E: v7 m- p* j8 I! N
- response={
- 'message':'Newnodeshavebeenadded',
- 'total_nodes':list(blockchain.nodes),
- }
- returnjsonify(response),201
- @app.route('/nodes/resolve',methods=['GET'])
- defconsensus():
- replaced=blockchain.resolve_conflicts()% O, P# t& G; _3 S
- ifreplaced:
- response={; Q1 Q! r5 t! G( j8 a2 _
- 'message':'Ourchainwasreplaced',
- 'new_chain':blockchain.chain0 o( C8 t, I! N7 A/ T! |! j7 }3 a* _
- }% s9 H0 Y m& }
- else:
- response={
- 'message':'Ourchainisauthoritative',+ Q% e+ i* d1 K2 p5 |
- 'chain':blockchain.chain, q6 M, p- }+ z! l. e7 e
- }
- returnjsonify(response),200* X6 {$ L. K6 C* ?: c7 ~8 c
- ```
你可以在不同的机器运行节点,或在一台机机开启不同的网络端口来模拟多节点的网络,这里在同一台机器开启不同的端口演示,在不同的终端运行一下命令,就启动了两个节点:```http://localhost:5000```和```http://localhost:5001```。
# `' N7 j7 ]' R$ z
-注册一个新的节点-
然后在节点2上挖两个块,确保是更长的链,然后在节点1上访问GET/nodes/resolve,这时节点1的链会通过共识算法被节点2的链取代。



