原文链接:用Python从零开始创建区块链
本文是根据原文步骤执行完成后,写一下自己的理解。
代码文件blockchain.py:
import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
from urllib.parse import urlparse
import requests
class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
self.nodes = set()
#create the genesis block
self.new_block(previous_hash = 1, proof = 100)
def new_block(self, proof, previous_hash = None):
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash':previous_hash or self.hash(self.chain[-1]),
}
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient':recipient,
'amount':amount,
})
return self.last_block['index'] + 1
@staticmethod
def hash(block):
# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys = True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
#return the last block in the chain
return self.chain[-1]
def proof_of_work(self, last_proof):
proof = 0
while self.valid_proof(last_proof,proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
#guess = f'{last_proof}{proof}'.encode()
guess = '{last_proof}{proof}'.format(last_proof = last_proof, proof = proof).encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == '0000'
def valid_chain(self, chain):
last_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
print('{last_block}'.format(last_block=last_block))
print('{block}'.format(block=block))
print("/n-------------------\n")
if block['previous_hash'] != self.hash(last_block):
return False
if not self.valid_proof(last_block['proof'],block['proof']):
return False
last_block = block
current_index += 1
return True
def register_node(self, address):
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
def resolve_conflicts(self):
neighbours = self.nodes
new_chain = None
max_lenth = len(self.chain)
for node in neighbours:
response = requests.get("http://{node}/chain".format(node=node))
length = response.json()['length']
chain = response.json()['chain']
if length > max_lenth and self.valid_chain(chain):
max_lenth = length
new_chain = chain
if new_chain:
self.chain = new_chain
return True
return False
#instantiate our node 创建一个节点
app = Flask(__name__)
#generate a globally unique address for this node 为节点创建一个名字
node_identifier = str(uuid4()).replace('_', '')
#instantiate the Blockchain
blockchain = Blockchain()
#创建/mine GET接口
@app.route('/mine', methods=['GET'])
def mine():
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 = blockchain.new_block(proof)
response = {
'message': "New Block Forged",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
@app.route('/transactions/new', methods=['POST'])#创建/transactions/new POST接口,可以给接口发送交易数据.
def new_transaction():
values = request.get_json()
print(values)
required = ['sender', 'recipient', 'amount']
if not all (k in values for k in required):
return 'Missing values', 400
index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
response = {'message': 'Transaction will be added to Block {index}'.format(index = index)}
return jsonify(response), 201
@app.route('/chain', methods=['GET']) #创建 /chain 接口, 返回整个区块链。
def full_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain),
}
return jsonify(response), 200
@app.route('/nodes/register', methods=['POST'])
def register_nodes():
values = request.get_json()
nodes = values.get('nodes')
if nodes is None:
return 'Error: Please supply a valid list of nodes', 400
for node in nodes:
blockchain.register_node(node)
print(node)
response = {
'message': 'New nodes have been added',
'total nodes': list(blockchain.nodes)
}
return jsonify(response), 201
@app.route('/nodes/resolve', methods=['GET'])
def consensus():
replaced = blockchain.resolve_conflicts()
if replaced:
response = {
'message':'Our chain was replaced',
'new chain':blockchain.chain
}
else:
response = {
'message': 'Our chain is authoritative',
'chain': blockchain.chain
}
return jsonify(response), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
原文是使用python3.6开发,由于安装时出现了一点错误,怎么都不成功,所以我使用的是ubuntu16.04自带的python3.5,不同之处仅仅是在代码文件中的f字符串改成了format处理,其他都相同。
(吐槽一句:最终调试时,软件版本导致的各种错误,恶心恶心恶心!!)
分析代码:
Blockchain的数据结构:
chain[]:存放挖出来的一个个区块block
current_transactions[]:存放两次挖矿之间的每一笔交易信息,即待写入下一区块的交易
nodes:存放网络中的节点
Blockchain中的方法:
new_block:创建一个新的区块,并加入本地chain[]中,内容包括索引(即第几个块),时间戳,交易信息,随机数,上一个区块的hash(没有存储本区块的hash)。返回值:新创建的这个区块
new_transaction:创建一笔新的交易,并存储在current_transactions中,等待加入下一个区块中。内容包括:发送者,接受者,交易数量。返回值:最后一个区块的索引值
hash:计算并返回一个区块block的hash值
last_block:返回最后一个区块
proof_of_work:从1开始枚举随机数,调用valid_proof函数验证是否满足条件,直到找到满足条件的才停止,返回这个随机数proof
valid_proof:根据给定的上一区块的随机数和本区块随机数,验证这两者拼接后的hash值是否满足条件(寻找随机数是与上一区块随机数相关的,以此保证只有上一区块产生后才能开始挖下一个区块)
valid_chain:验证一条区块链是否是一条合法的区块链,验证的内容包括上一区块hash是否合法(保证上一区块是没有被篡改的),还包括验证随机数是否合法
resolve_conficts:解决冲突。依次请求并接收其他所有节点nodes的区块链,如果比自己的链长并且是一条合法的链,则将本地的区块链替换成更长的那一条链。(与实际区块链运行不太相符吧,感觉应该是一个节点挖矿成功后广播成功信息,其他节点接收到这条广播,然后对比自己的链。而不是本地节点请求所有节点的链,如果节点非常多的话,肯定会花费一些时间)
register_node:注册节点,收到其他节点的加入信息,加入本地节点列表nodes
下面就是使用flask进行http交互了。
mine():先是调用proof_of_work方法寻找随机数,即挖矿的过程。寻找成功后,添加一笔新的交易即挖矿奖励交易。然后打包产生一个新的区块。
new_transaction():接收交易信息,并创建一笔新的交易
full_chain():返回当前本地存储的整条链
register_nodes():接收节点加入信息,并把它添加在本地nodes列表中
consensus():共识,即收到请求后调用resolve_conflicts方法,保持当前链为最长链。
执行一遍后确实加深了对区块链的理解。但是好多功能并不能自动的运行,需要借助postman软件来发送和接收一些请求。具体怎么改进实现自动运行,额,,我也不会,求大神指点。