
关键代码
#验证区块链 def validate(blocks): bool = True #上一个区块 previous_index = 0 previous_hash = 0 for block in blocks: index = block["index"] hash = block["hash"] if (index > 0): #如果 index 是衔接的 if (previous_index == index-1): pass else: bool = False #如果上一个区块的当前 hash 和当前区块的上一个 hash 值能对上 if (previous_hash == block["previous_hash"]): pass else: bool = False if bool: #把当前的变为上一个 previous_index = index previous_hash = hash if (index == 0): previous_index = index previous_hash = hash pass return bool 用法: 分别启动 2 个节点:
python3 blockchain -p 8001 python3 blockchain -p 8002 浏览器打开 http://localhost:8001/nodes/add/localhost/8002
返回数据说明 8002 节点添加成功
[ { "ip": "localhost", "port": 8002 } ] 在浏览器打开 http://localhost:8002/say/tom
这是在 8002 节点增加了一个区块。
在浏览器中打开 http://localhost:8001/blocks/all
可以看到 8001 节点只有一个跟块,因为没有同步。
[ { "data": "Genesis Block", "hash": "0e7a7f285f4c1ef2856c7b24ce7b11de15cddff7e7c2a733a16aa8c7f78085ae", "index": 0, "previous_hash": 0, "timestamp": 1533901217798 } ] 然后我们在 8001 节点上同步: http://localhost:8001/blocks/sync
显示:
"synced" 说明同步节点并且验证成功。
接下来查看所有的节点: http://localhost:8001/blocks/all
[ { "data": "Genesis Block", "hash": "d476a30fcfefa496c3f01a345b3b6d2a8234390da98cfc3c0899eec8037d437b", "index": 0, "previous_hash": 0, "timestamp": 1533901225899 }, { "data": "tom", "hash": "f3fbe9b7b0e74c47f1e2452b422f50d80dca8f05b7912c98843a2c69a4d48433", "index": 1, "previous_hash": "d476a30fcfefa496c3f01a345b3b6d2a8234390da98cfc3c0899eec8037d437b", "timestamp": 1533901358960 } ] 说明 8001 的区块链已经验证了 8002 的区块链,并且实现了节点同步。
详情访问:
1 guolin2016 2018-08-10 23:25:50 +08:00 你可能慢慢的写后,发现 python 性能很差 |
2 cr4fun OP @guolin2016 然后呢?然后用 go 重写一次是吧~ |
3 pynix 2018-08-11 00:20:22 +08:00 只是教学级的,性能不是问题。。 |
4 btc4698 2018-08-12 21:46:47 +08:00 技术很炫酷,如果尝试着把区块链技术运用到其他某些方向,可能会给公众创造更大的价值,我有一些不太完善的想法想和你交流。 |