增加了节点同步时验证的区块链

关键代码

  1. #验证区块链
  2. def validate(blocks):
  3. bool = True
  4. #上一个区块
  5. previous_index = 0
  6. previous_hash = 0
  7. for block in blocks:
  8. index = block["index"]
  9. hash = block["hash"]
  10. if (index > 0):
  11. #如果index是衔接的
  12. if (previous_index == index-1):
  13. pass
  14. else:
  15. bool = False
  16. #如果上一个区块的当前hash和当前区块的上一个hash值能对上
  17. if (previous_hash == block["previous_hash"]):
  18. pass
  19. else:
  20. bool = False
  21. if bool:
  22. #把当前的变为上一个
  23. previous_index = index
  24. previous_hash = hash
  25. if (index == 0):
  26. previous_index = index
  27. previous_hash = hash
  28. pass
  29. return bool

用法:

分别启动2个节点:

  1. python3 blockchain -p 8001
  1. python3 blockchain -p 8002

浏览器打开 http://localhost:8001/nodes/add/localhost/8002

返回数据说明8002节点添加成功

  1. [
  2. {
  3. "ip": "localhost",
  4. "port": 8002
  5. }
  6. ]

在浏览器打开 http://localhost:8002/say/tom

这是在8002节点增加了一个区块。

在浏览器中打开 http://localhost:8001/blocks/all

可以看到8001节点只有一个跟块,因为没有同步。

  1. [
  2. {
  3. "data": "Genesis Block",
  4. "hash": "0e7a7f285f4c1ef2856c7b24ce7b11de15cddff7e7c2a733a16aa8c7f78085ae",
  5. "index": 0,
  6. "previous_hash": 0,
  7. "timestamp": 1533901217798
  8. }
  9. ]

然后我们在8001节点上同步:http://localhost:8001/blocks/sync

显示:

  1. "synced"

说明同步节点并且验证成功。

接下来查看所有的节点:http://localhost:8001/blocks/all

  1. [
  2. {
  3. "data": "Genesis Block",
  4. "hash": "d476a30fcfefa496c3f01a345b3b6d2a8234390da98cfc3c0899eec8037d437b",
  5. "index": 0,
  6. "previous_hash": 0,
  7. "timestamp": 1533901225899
  8. },
  9. {
  10. "data": "tom",
  11. "hash": "f3fbe9b7b0e74c47f1e2452b422f50d80dca8f05b7912c98843a2c69a4d48433",
  12. "index": 1,
  13. "previous_hash": "d476a30fcfefa496c3f01a345b3b6d2a8234390da98cfc3c0899eec8037d437b",
  14. "timestamp": 1533901358960
  15. }
  16. ]

说明8001的区块链已经验证了8002的区块链,并且实现了节点同步。