import hashlib
import json
from time import time
from uuid import uuid4
class Blockchain(object):
…
def proof_of_work(self, last_proof):
“”"
简单的工作量证明:
- 查找一个 p’ 使得 hash(pp’) 以4个0开头
- p 是上一个块的证明, p’ 是当前的证明
:param last_proof:
:return:
“”"
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
“”"
验证证明: 是否hash(last_proof, proof)以4个0开头?
:param last_proof: Previous Proof
:param proof: Current Proof
:return: True if correct, False if not.
“”"
guess = f’{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == “0000”
衡量算法复杂度的办法是修改零开头的个数。使用4个来用于演示,你会发现多一个零都会大大增加计算出结果所需的时间。现在Blockchain类基本已经完成了,接下来使用HTTP requests来进行交互。
### Blockchain作为API接口
我们将使用Python Flask框架,这是一个轻量Web应用框架,它方便将网络请求映射到 Python函数,现在我们来让Blockchain运行在基于Flask web上。
我们将创建三个接口:
* /transactions/new 创建一个交易并添加到区块
* /mine 告诉服务器去挖掘新的区块
* /chain 返回整个区块链
#### 创建节点
我们的Flask服务器将扮演区块链网络中的一个节点。我们先添加一些框架代码:
import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4
from flask import Flask
class Blockchain(object):
…
Instantiate our Node
app = Flask(name)
Generate a globally unique address for this node
node_identifier = str(uuid4()).replace(‘-’, ‘’)
Instantiate the Blockchain
blockchain = Blockchain()
@app.route(‘/mine’, methods=[‘GET’])
def mine():
return “We’ll mine a new Block”
@app.route(‘/transactions/new’, methods=[‘POST’])
def new_transaction():
return “We’ll add a new transaction”
@app.route(‘/chain’, methods=[‘GET’])
def full_chain():
response = {
‘chain’: blockchain.chain,
‘length’: len(blockchain.chain),
}
return jsonify(response), 200
if name == ‘__main__’:
app.run(host=‘0.0.0.0’, port=5000)
简单的说明一下以上代码:
第15行: 创建一个节点.
第18行: 为节点创建一个随机的名字.
第21行: 实例Blockchain类.
第24–26行: 创建/mine GET接口。
第28–30行: 创建/transactions/new POST接口,可以给接口发送交易数据.
第32–38行: 创建 /chain 接口, 返回整个区块链.
第40–41行: 服务运行在端口5000上.
#### 发送交易
发送到节点的交易数据结构如下:
{
“sender”: “my address”,
“recipient”: “someone else’s address”,
“amount”: 5
}
之前已经有添加交易的方法,基于接口来添加交易就很简单了
import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
…
@app.route(‘/transactions/new’, methods=[‘POST’])
def new_transaction():
values = request.get_json()
# Check that the required fields are in the POST’ed data
required = [‘sender’, ‘recipient’, ‘amount’]
if not all(k in values for k in required):
return ‘Missing values’, 400
# Create a new Transaction
index = blockchain.new_transaction(values[‘sender’], values[‘recipient’], values[‘amount’])
response = {‘message’: f’Transaction will be added to Block {index}'}
return jsonify(response), 201
#### 挖矿
挖矿正是神奇所在,它很简单,做了一下三件事:
1. 计算工作量证明PoW
2. 通过新增一个交易授予矿工(自己)一个币
3. 构造新区块并将其添加到链中
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
…
@app.route(‘/mine’, methods=[‘GET’])
def mine():
# We run the proof of work algorithm to get the next proof…
last_block = blockchain.last_block
last_proof = last_block[‘proof’]
proof = blockchain.proof_of_work(last_proof)
# 给工作量证明的节点提供奖励.
# 发送者为 “0” 表明是新挖出的币
blockchain.new_transaction(
sender=“0”,
recipient=node_identifier,
amount=1,
)
# Forge the new Block by adding it to the chain
block &#

最低0.47元/天 解锁文章
239

被折叠的 条评论
为什么被折叠?



