简单区块链Python实现

快来打我* 2023-05-29 05:14 125阅读 0赞

什么是区块链

区块链是一种数据结构,也是一个分布式数据库。

从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都记录了主链或主链的一部分。
在这里插入图片描述

组成

区块头

区块头主要包含的三组元数据分别是:(1)用于连接前面的区块、索引自父区块哈希值的数据;(2)挖矿难度、时间戳、Nonce(随机数,用于工作量证明算法的计数器,也可理解为记录解密该区块相关数学题的答案的值);(3)能够总结并快速归纳校验区块中所有交易数据的Merkle(默克尔)树根数据。当然区块头不仅仅包含这些元数据,还有其他比如:版本号、难度值等。
从这个结构来看,区块链的大部分功能都由区块头实现。

区块主体

区块主体所记录的交易信息是区块所承载的任务数据,具体包括交易双方的私钥、交易的数量、电子货币的数字签名等。

比特币系统大约每10分钟会创建一个区块,这个区块包含了这段时间里全网范围内发生的所有交易。每一个区块都保存了上一个区块的哈希值,使得每个区块都能找到其前一个区块,这样就将这些区块连接起来,形成了一个链式的结构。
在这里插入图片描述

区块字段

  • Difficulty 此区块的难度级别
  • ExtraData 与此区块相关的附加数据 在区块链早期使用比较多,现在用的很少
  • gasLimit 当前区块允许使用的最大gas, gas表示一种计算量, 使用的算力单位
  • gasUsed 当前区块已经使用的gas
  • Hash 当前区块的哈希值。如果区块没有被确认,这个字段会是null值
  • LogsBloom 由日志信息组成的一个Bloom过滤器 (数据结构),区块没被确认- 是值为null
  • Miner 取得该区块记账权的矿工
  • mixHash 一个Hash值,当与nonce组合时,证明此区块已经执行了足够的计算
  • nonce 一个Hash值,当与mixHash组合时,证明此区块已经执行了足够的计算
  • Number 当前区块的计数(创世纪块的区块序号为0,对于每个后续区块,区块序号都增加1)
  • parentHash 父区块头的Hash值(这也是使得区块变成区块链的原因)
  • receiptsRoot 包含此区块所列的所有交易收据的树的根节点Hash值
  • Sha3Uncles 数据块的哈希值
  • Size 当前区块的字节大小
  • stateRoot 区块状态树的根哈希
  • Timestamp 区块打包时的unix时间戳
  • totalDifficulty 区块链到当前区块的总难度
  • Transactions 交易的对象
  • transactionsRoot 区块的交易树的根哈希
  • Uncles 叔哈希数组 树区块详见 https://blog.csdn.net/weixin\_42874184/article/details/81735695

在这里插入图片描述

Python实现

实现了工作量证明,难度计算,哈希部分

  1. import hashlib
  2. import datetime
  3. import random
  4. class Block:
  5. def __init__(self, index, transaction, pre_hash, difficulty, nonce):
  6. self.index = index
  7. self._timestamp = datetime.datetime.now()
  8. self._transaction = transaction
  9. self._pre_hash = pre_hash
  10. self._nonce = nonce
  11. self._difficulty = difficulty
  12. self.hash = self.gen_hash()
  13. @property
  14. def get_hash(self):
  15. return self.hash
  16. @property
  17. def get_index(self):
  18. return self.index
  19. @property
  20. def get_transaction(self):
  21. return self._transaction
  22. @property
  23. def get_difficulty(self):
  24. return self._difficulty
  25. @property
  26. def get_timestamp(self):
  27. return self._timestamp
  28. @property
  29. def get_pre_hash(self):
  30. return self._pre_hash
  31. @property
  32. def get_nonce(self):
  33. return self._nonce
  34. def gen_hash(self):
  35. sha = hashlib.sha256()
  36. data = str(self.index) + str(self._timestamp) + str(self._transaction) + str(self._pre_hash) + str(self._nonce) + str(self._difficulty)
  37. sha.update(data.encode("utf8"))
  38. return sha.hexdigest()
  39. class Blockchain:
  40. def __init__(self, max_blocks):
  41. self._chain_list = [Block(0, "The First Block", '0', '1', random.randrange(0, 99999))]
  42. self._previous_block = self._chain_list[0]
  43. self._current_block = 1
  44. self.max_blocks = max_blocks
  45. @staticmethod
  46. def create_next_block(self):
  47. last_block = self._chain_list[self._current_block - 1]
  48. last_difficulty = last_block.get_difficulty
  49. this_index = last_block.index + 1
  50. this_transaction = "New Block " + str(this_index) + " has been generated successfully."
  51. nonce = random.randrange(0, 99999)
  52. this_difficulty = self.proof_of_work(nonce)
  53. pre_hash = last_block.hash
  54. self._chain_list.append(Block(this_index, this_transaction, pre_hash, this_difficulty, nonce))
  55. self._current_block += 1
  56. def last_block(self):
  57. return self._chain_list[-1]
  58. def proof_of_work(self, nonce):
  59. proof = 0
  60. while self.valid_proof(self, proof, nonce) is False:
  61. proof += 1
  62. return proof
  63. @staticmethod
  64. def valid_proof(self, proof, nonce):
  65. guess = f'{proof}{nonce}'.encode()
  66. guess_hash = hashlib.sha256(guess).hexdigest()
  67. pattern = "0000"
  68. return guess_hash[:len(pattern)] == pattern
  69. def run(self):
  70. for i in range(self.max_blocks):
  71. self.create_next_block(self)
  72. def show_block(self, index):
  73. print("----------------------------------------")
  74. print("ID: ", self._chain_list[index].get_index)
  75. print("Time", self._chain_list[index].get_transaction)
  76. print("Cur Hash", self._chain_list[index].get_hash)
  77. print("Pre Hash", self._chain_list[index].get_pre_hash)
  78. print("Difficulty", self._chain_list[index].get_difficulty)
  79. print("Trans", self._chain_list[index].get_transaction)
  80. print("Nonce", self._chain_list[index].get_nonce)
  81. print("----------------------------------------")
  82. myBlockChain = Blockchain(100)
  83. myBlockChain.run()
  84. for i in range(myBlockChain.max_blocks):
  85. myBlockChain.show_block(i)

在这里插入图片描述

参考文献

https://segmentfault.com/a/1190000014483104
https://blog.csdn.net/qq874455953/article/details/83718022

更多内容访问 omegaxyz.com
网站所有代码采用Apache 2.0授权
网站文章采用知识共享许可协议BY-NC-SA4.0授权
© 2020 • OmegaXYZ-版权所有 转载请注明出处

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读

    相关 简单区块Python实现

    什么是区块链 区块链是一种数据结构,也是一个分布式数据库。 从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形

    相关 简单易懂的区块

    区块链是一个公共的分布式账本数据库。下面简要介绍下区块链。 01 传统的网络交易如何进行呢? 举个例子,我的同学阿坤打算结婚了,我打算给他发红包,打开手机的银行APP,

    相关 Python & 区块

    一个完整的区块栗子 每个区块都有其索引,时间戳(Unix 时间),交易列表,证明 proof(稍后解释),以及前序区块的哈希值。 block = {

    相关 区块 简单实现介绍

    区块链的基础概念很简单:一个分布式数据库,存储一个不断加长的 list,list 中包含着许多有序的记录。然而,在通常情况下,当我们谈到区块链的时候也会谈起使用区块链来解决的问