“学习区块链的最快方法就是自己亲手搭建一个”
“学习区块链的最快方法就是自己亲手搭建一个”
本文接上篇:手把手教你搭建区块链(中)
如果您已经掌握了一些基础的python知识,那么跟着本文搭建区块链对您来说将不是一件难事儿。
STEP 3
与我们的区块链互动
您可以使用cURL或Postman通过网络与我们的API进行互动:
启动服务器:
$ python blockchain.py* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
让我们先尝试通过向http://localhost:5000/mine发出GET请求来挖掘一个块:

接着,让我们再向http://localhost:5000/transactions/new发出POST请求来创建新交易:

raw中包含我们的交易结构正文。
当然如果您不使用Postman,也可以使用cURL发出同样的请求:
$ curl -X POST -H "Content-Type: application/json" -d '{"sender": "d4ee26eee15148ee92c6cd394edd974e","recipient": "someone-other-address","amount": 5}' "http://localhost:5000/transactions/new"
让我们通过请求http://localhost:5000/chain检查整个区块链:
{"chain": [{"index": 1,"previous_hash": 1,"proof": 100,"timestamp": 1506280650.770839,"transactions": []},{"index": 2,"previous_hash": "c099bc...bfb7","proof": 35293,"timestamp": 1506280664.717925,"transactions": [{"amount": 1,"recipient": "8bbcb347e0634905b0cac7955bae152b","sender": "0"}]},{"index": 3,"previous_hash": "eff91a...10f2","proof": 35089,"timestamp": 1506280666.1086972,"transactions": [{"amount": 1,"recipient": "8bbcb347e0634905b0cac7955bae152b","sender": "0"}]}],"length": 3}
STEP 4
共识
现在我们有了一个基本的区块链,可以接收交易并允许我们挖掘新的区块。
但是,区块链的全部意义在于它们应该去中心化以及如果区块分散管理、我们如何确保它们都反映同一条链?
这就是共识问题,如果我们要在网络中使用多个节点,就必须实施共识算法。
在实现共识算法之前,我们需要一种让节点知道网络上相邻节点的方法。我们网络上的每个节点都应保留网络上其他节点的注册表:
#接受URL形式的新节点列表/nodes/register#实现共识算法,该算法可以解决所有冲突-确保每个节点都位于正确的链/nodes/resolve
我们需要修改区块链的构造函数,并提供一种注册节点的方法,下面这段代码是一种将相邻节点添加到我们网络中的方法:
...from urllib.parse import urlparse...class Blockchain(object):def __init__(self):...self.nodes = set()...def register_node(self, address):"""Add a new node to the list of nodes:param address: <str> Address of node. Eg. 'http://192.168.0.5:5000':return: None"""parsed_url = urlparse(address)self.nodes.add(parsed_url.netloc)
请注意,我们使用了set()方法来保存节点列表,这是确保添加新节点是幂等的低成本方法,这意味着无论我们添加特定节点多少次,它都只会出现一次。
”如何实现共识算法“
如前所述,冲突是当一个节点与另一节点所处在不同的链时。为解决此问题,我们规定只有最长的有效链才具有权威性。
换句话说,网络上最长的链是共识链。
使用此算法,我们可以在网络中的节点之间达成共识。
...import requestsclass Blockchain(object)...def valid_chain(self, chain):"""Determine if a given blockchain is valid:param chain: <list> A blockchain:return: <bool> True if valid, False if not"""last_block = chain[0]current_index = 1while current_index < len(chain):block = chain[current_index]print(f'{last_block}')print(f'{block}')print("\n-----------\n")# Check that the hash of the block is correctif block['previous_hash'] != self.hash(last_block):return False# Check that the Proof of Work is correctif not self.valid_proof(last_block['proof'], block['proof']):return Falselast_block = blockcurrent_index += 1return Truedef resolve_conflicts(self):"""This is our Consensus Algorithm, it resolves conflictsby replacing our chain with the longest one in the network.:return: <bool> True if our chain was replaced, False if not"""neighbours = self.nodesnew_chain = None# We're only looking for chains longer than oursmax_length = len(self.chain)# Grab and verify the chains from all the nodes in our networkfor node in neighbours:response = requests.get(f'http://{node}/chain')if response.status_code == 200:length = response.json()['length']chain = response.json()['chain']# Check if the length is longer and the chain is validif length > max_length and self.valid_chain(chain):max_length = lengthnew_chain = chain# Replace our chain if we discovered a new, valid chain longer than oursif new_chain:self.chain = new_chainreturn Truereturn False
第一个方法validate_chain()负责通过循环遍历每个块并验证哈希和证明来检查链是否有效。
resolve_conflicts()是一种遍历我们所有相邻节点,下载其链并使用上述方法进行验证的方法。如果找到有效链,其长度大于我们的长度,我们将替换我们的长度。
我们将两个路由注册到我们的API中,一个用于添加相邻节点,另一个用于解决冲突:
@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", 400for node in nodes:blockchain.register_node(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
此时,您可以根据需要使用其他计算机,并在网络上启动不同的节点;或使用同一台计算机上的不同端口启动进程。
注册一个新节点:
然后,我们在节点2上挖掘了一些新块,以确保链更长。
之后,在节点1上调用GET/nodes/resolve,其中该链已经被共识算法替换:

这样就行了……去找一些朋友在一起来测试您的区块链吧~
本系列到此结束,全文共三篇,前两篇分别是:
希望它们能激发您的创造力,我们有理由相信,区块链将迅速改变我们对经济,中心化和记录保存的看法。
作者:修恩
上一篇:你的公司需要区块链吗?
▎推荐阅读
——End——

『声明:修恩笔记所有文章仅供参考,不构成任何投资建议策略。』


据说长得好看的人都点了👇