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

4Ameta

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

write a blockchain in Python【1】create a block class

[复制链接]

8

主题

8

帖子

47

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
47
发表于 2022-9-2 07:27:24 | 显示全部楼层 |阅读模式
##1.1 create a block
first, we create a block class to represent each block on the blockchain, and create a new ` block.py`


  1. import hashlib


  2. class Block:

  3.     def __init__(self, timestamp, data, previous_hash=''):
  4.         '''
  5. block init
  6.         :param timestamp: create time
  7.         :param data: data in this block
  8.         :param previous_hash: last block hash
  9.        :param hash: this block hash
  10.         '''
  11.         self.previous_hash = previous_hash
  12.         self.timestamp = timestamp
  13.         self.data = data
  14.         self.hash = self.calculate_hash()

  15.     def calculate_hash(self):
  16.         '''
  17.         Calculate the required hash value
  18.         :return:
  19.         '''
  20.         # Concatenate the block information and generate the hash value of sha256
  21.         raw_str = self.previous_hash + str(self.timestamp) + json.dumps(self.data, ensure_ascii=False)
  22.         sha256 = hashlib.sha256()
  23.         sha256.update(raw_str.encode('utf-8'))
  24.         hash = sha256.hexdigest()
  25.         return hash

复制代码



The 'hashlib' module is introduced to calculate the hash value,
It's block's`__ init__` In the method, we perform basic initialization on the block,
Each block contains the hash value of the previous block,
Used to verify data integrity.
`Data ` stores the data of this block,
If it is a cryptocurrency, such as bitcoin, this data is the transaction of the transaction.
`calculate_ The hash ` method is used to calculate the hash value of the current block.







Tip: the hash algorithm is simply a function that compresses messages of arbitrary length into a message digest of a fixed length.
Sha256 is a hash algorithm in the Sha cryptographic hash function family.
Different input hash values have different output values.
A little change in input will lead to completely different hash values.
So the hash algorithm can be used to check whether the data is changed.

next lesson>>>>

回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2022-10-4 12:35 , Processed in 0.036891 second(s), 17 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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