区块链代码实现(区块链编程)
使用Python的Flask框架。它是一个微型框架,它可以很容易地将端点映射到Python函数。这让我们使用HTTP请求在web上与 Blockchain 进行交互。
我们将创建三个方法:
/transactions/new 创建一个新的交易到一个区块。/mine 告诉我们的服务器去挖掘一个新的区块。/chain 返回完整的 Blockchain 。设置Flask我们的“服务器”将在 Blockchain 网络中形成单独节点,创建一些样板代码如下所示:
1. import hashlib
2. import json
3. from textwrap import dedent
4. from time import time
5. from uuid import uuid4
6.
7. from flask import Flask
8.
9.
10. class Blockchain(object):
11. …
12.
13.
14. # Instantiate our Node
15. app = Flask(__name__)
16.
17. # Generate a globally unique address for this node
18. node_identifier = str(uuid4()).replace(‘-‘, ”)
19.
20. # Instantiate the Blockchain
21. blockchain = Blockchain()
22.
23.
24. @app.route(‘/mine’, methods=[‘GET’])
25. def mine():
26. return “We’ll mine a new Block”
27.
28. @app.route(‘/transactions/new’, methods=[‘POST’])
29. def new_transaction():
30. return “We’ll add a new transaction”
31.
32. @app.route(‘/chain’, methods=[‘GET’])
33. def full_chain():
34. response = {
35. ‘chain’: blockchain.chain,
36. ‘length’: len(blockchain.chain),
37. }
38. return jsonify(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”: “my address”,
3. “recipient”: “someone else’s address”,
4. “amount”: 5
5. }
由于已经有了将交易添加到区块的类的方法,其余的都很简单。让我们编写添加交易的函数:
挖矿端点1. import hashlib
2. import json
3. from textwrap import dedent
4. from time import time
5. from uuid import uuid4
6.
7. from flask import Flask, jsonify, request
8.
9. …
10.
11. @app.route(‘/transactions/new’, methods=[‘POST’])
12. def new_transaction():
13. values = request.get_json()
14.
15. # Check that the required fields are in the POST’ed data
16. required = [‘sender’, ‘recipient’, ‘amount’]
17. if not all(k in values for k in required):
18. return ‘Missing values’, 400
19.
20. # Create a new Transaction
21. index = blockchain.new_transaction(values[‘sender’], values[‘recipient’], values[‘amount’])
22.
23. response = {‘message’: f’Transaction will be added to Block {index}’}
24. return jsonify(response), 201
Amethod for creating Transactions
挖矿端点必须做三件事:
(1)计算工作量证明。
(2)通过增加一笔交易,奖赏给矿工(也就是我们自己)一定量的数字货币。
(3)通过将新区块添加到链中来锻造区块。
1. import hashlib
2. import json
3.
4. from time import time
5. from uuid import uuid4
6.
7. from flask import Flask, jsonify, request
8.
9. …
10.
11. @app.route(‘/mine’, methods=[‘GET’])
12. def mine():
13. # We run the proof of work algorithm to get the next proof…
14. last_block = blockchain.last_block
15. last_proof = last_block[‘proof’]
16. proof = blockchain.proof_of_work(last_proof)
17.
18. # We must receive a reward for finding the proof.
19. # The sender is “0” to signify that this node has mined a new coin.
20. blockchain.new_transaction(
21. sender=”0″,
22. recipient=node_identifier,
23. amount=1,
24. )
25.
26. # Forge the new Block by adding it to the chain
27. previous_hash = blockchain.hash(last_block)
28. block = blockchain.new_block(proof, previous_hash)
29.
30. response = {
31. ‘message’: “New Block Forged”,
32. ‘index’: block[‘index’],
33. ‘transactions’: block[‘transactions’],
34. ‘proof’: block[‘proof’],
35. ‘previous_hash’: block[‘previous_hash’],
36. }
37. return jsonify(response), 200
被挖掘出来的区块的接收者是我们节点的地址。在这里所做的大部分工作只是与Blockchain class中的方法进行交互。在这一点上,我们已经完成了,并且可以开始与我们的 Blockchain 进行交互了。