请选择 进入手机版 | 继续访问电脑版

4Ameta

 找回密码
 立即注册
搜索
查看: 121|回复: 0

write a blockchain in Python【2】Create a blockchain

[复制链接]

8

主题

8

帖子

47

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
47
发表于 2022-9-3 13:55:54 | 显示全部楼层 |阅读模式
write a blockchain in Python【2】

1.2 create a chain
Create a blockchain and create ` blockchain.py`

When the blockchain is initialized, we create a Genesis block and add it to the chain (here we use an array),
After creating the blockchain, we added two blocks to the blockchain,
Then verify the validity of the blockchain and the running result is valid,
Then we changed the data of a block, and the result of re verification was invalid.


  1. from Block import Block
  2. import time

  3. class BlockChain:
  4.     def __init__(self):
  5.         # Initialize the chain and add Genesis block
  6.         self.chain = [self._create_genesis_block()]

  7.     @staticmethod
  8.     def _create_genesis_block():
  9.         '''
  10.         Generate Genesis block
  11.          : Return: Genesis block
  12.         '''
  13.         timestamp = time.mktime(time.strptime('2022-06-11 00:00:00', '%Y-%m-%d %H:%M:%S'))
  14.         block = Block(timestamp, [], '')
  15.         return block

  16.     def get_latest_block(self):
  17.         '''
  18.         Get the last and latest block on the chain
  19.         :return:Last block
  20.         '''
  21.         return self.chain[-1]

  22.     def add_block(self, block):
  23.         '''
  24.         add block
  25.         :param block: Blocks to be added
  26.         :return:
  27.         '''
  28.         block.previous_hash = self.get_latest_block().hash
  29.         block.hash = block.calculate_hash()
  30.         self.chain.append(block)

  31.     def verify_blockchain(self):
  32.         '''
  33.         Verify whether the blockchain data is complete and tampered with
  34.         :return: Verification results
  35.         '''
  36.         for i in range(1, len(self.chain)):
  37.             current_block = self.chain[i]  # Currently traversed block
  38.             previous_block = self.chain[i - 1]  # Previous block of the current block
  39.             if current_block.hash != current_block.calculate_hash():
  40.                 # If the hash value of the current block is not equal to the calculated hash value, it indicates that the data has changed
  41.                 return False
  42.             if current_block.previous_hash != previous_block.calculate_hash():
  43.                 # If the hash value of the previous block recorded in the current block is not equal to the calculated hash value of the previous block, it indicates that the data of the previous block has changed or the hash value of the previous block recorded in the current block has been changed
  44.                 return False
  45.         return True


  46. if __name__ == '__main__':
  47.     # Test using blockchain
  48.     blockChain = BlockChain()
  49.     # Add Block
  50.     blockChain.add_block(Block(time.time(), {'amount': 100}))
  51.     blockChain.add_block(Block(time.time(), {'amount': 200}))
  52.     # Check the validity of blockchain, and the result is valid
  53.     print('Is the blockchain effective?', 'yes' if blockChain.verify_blockchain() else 'no')
  54.     # Trying to modify block data
  55.     blockChain.chain[1].data = {'amount': 10}
  56.     # Check the validity of blockchain, and the result is invalid
  57.     print('Is the blockchain effective?', 'yes' if blockChain.verify_blockchain() else 'no')



复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|4ameta

GMT+8, 2022-10-4 11:20 , Processed in 0.040852 second(s), 17 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表