将区块链作为API使用起来
使用Python的Flask框架。它是一个微型框架,它可以很容易地将端点映射到Python函数。这让我们使用HTTP请求在web上与 Blockchain 进行交互。
我们将创建三个方法:
- /transactions/new 创建一个新的交易到一个区块。/mine 告诉我们的服务器去挖掘一个新的区块。/chain返回完整的 Blockchain 。
设置Flask
我们的“服务器”将在 Blockchain 网络中形成单独节点,创建一些样板代码如下所示:
1.importhashlib
2.importjson
3.fromtextwrapimportdedent
4.fromtimeimporttime
5.fromuuidimportuuid4
6.
7.fromflaskimportFlask
8.
9.
10.classBlockchain(object):
11.…
12.
13.
14.#InstantiateourNode
15.app=Flask(__name__)
16.
17.#Generateagloballyuniqueaddressforthisnode
18.node_identifier=str(uuid4()).replace(‘-‘,”)
19.
20.#InstantiatetheBlockchain
21.blockchain=Blockchain()
22.
23.
24.@app.route(‘/mine’,methods=[‘GET’])
25.defmine():
26.return“We’llmineanewBlock”
27.
28.@app.route(‘/transactions/new’,methods=[‘POST’])
29.defnew_transaction():
30.return“We’lladdanewtransaction”
31.
32.@app.route(‘/chain’,methods=[‘GET’])
33.deffull_chain():
34.response={
35.‘chain’:blockchain.chain,
36.‘length’:len(blockchain.chain),
37.}
38.returnjsonify(response),200
39.
40.if__name__==‘__main__’:
41.app.run(host=’0.0.0.0′,port=5000)
关于在上面代码中添加的内容的简要说明如下:
Line 15:实例化节点。Line 18:为我们的节点创建一个随机名称。Line 21:实例化我们的Blockchain类。Line 24–26:创建/mine 端点,这是一个GET请求。Line 28–30:创建 /transactions/new端点,这是一个POST 请求,因为我们将向它发送数据。Line 32–38:创建/chain端点,它返回完整的 Blockchain 。Line 40–41:在端口5000上运行服务器。交易端点
这就是交易请求的样子。这是用户发送给服务器的内容:
1.{
2.“sender”:“myaddress”,
3.“recipient”:“someoneelse’saddress”,
4.“amount”:5
5.}
由于已经有了将交易添加到区块的类的方法,其余的都很简单。让我们编写添加交易的函数:
1.importhashlib
2.importjson
3.fromtextwrapimportdedent
4.fromtimeimporttime
5.fromuuidimportuuid4
6.
7.fromflaskimportFlask,jsonify,request
8.
9.…
10.
11.@app.route(‘/transactions/new’,methods=[‘POST’])
12.defnew_transaction():
13.values=request.get_json()
14.
15.#CheckthattherequiredfieldsareinthePOST’eddata
16.required=[‘sender’,‘recipient’,‘amount’]
17.ifnotall(kinvaluesforkinrequired):
18.return‘Missingvalues’,400
19.
20.#CreateanewTransaction
21.index=blockchain.new_transaction(values[‘sender’],values[‘recipient’],values[‘amount’])
22.
23.response={‘message’:f’TransactionwillbeaddedtoBlock{index}’}
24.returnjsonify(response),201
Amethod for creating Transactions
挖矿端点
挖矿端点必须做三件事:
(1)计算工作量证明。
(2)通过增加一笔交易,奖赏给矿工(也就是我们自己)一定量的数字货币。
(3)通过将新区块添加到链中来锻造区块。
1.importhashlib
2.importjson
3.
4.fromtimeimporttime
5.fromuuidimportuuid4
6.
7.fromflaskimportFlask,jsonify,request
8.
9.…
10.
11.@app.route(‘/mine’,methods=[‘GET’])
12.defmine():
13.#Weruntheproofofworkalgorithmtogetthenextproof…
14.last_block=blockchain.last_block
15.last_proof=last_block[‘proof’]
16.proof=blockchain.proof_of_work(last_proof)
17.
18.#Wemustreceivearewardforfindingtheproof.
19.#Thesenderis“0”tosignifythatthisnodehasminedanewcoin.
20.blockchain.new_transaction(
21.sender=”0″,
22.recipient=node_identifier,
23.amount=1,
24.)
25.
26.#ForgethenewBlockbyaddingittothechain
27.previous_hash=blockchain.hash(last_block)
28.block=blockchain.new_block(proof,previous_hash)
29.
30.response={
31.‘message’:“NewBlockForged”,
32.‘index’:block[‘index’],
33.‘transactions’:block[‘transactions’],
34.‘proof’:block[‘proof’],
35.‘previous_hash’:block[‘previous_hash’],
36.}
37.returnjsonify(response),200
被挖掘出来的区块的接收者是我们节点的地址。在这里所做的大部分工作只是与Blockchain class中的方法进行交互。在这一点上,我们已经完成了,并且可以开始与我们的 Blockchain 进行交互了。