python - Add creator name to a block
问题描述
I am practicing Blockchain and need to record timestamps of when a block is created and the block creator's name.
Link of source code. https://github.com/howCodeORG/Simple-Python-Blockchain
I have modified a few lines
import getpass # Added by me
class Block:
blockNo = 0
data = None
next = None
hash = None
nonce = 0
previous_hash = 0x0
timestamp = datetime.datetime.now()
creator = getpass.getuser() # Added by me
def __init__(self, data):
self.data = data
def hash(self):
h = hashlib.sha256()
h.update(
str(self.nonce).encode('utf-8') +
str(self.data).encode('utf-8') +
str(self.previous_hash).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.creator).encode('utf-8') + # Added by me
str(self.blockNo).encode('utf-8')
)
return h.hexdigest()
def __str__(self):
return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nBlock Creator: " + str(self.creator) + "\nHashes: " + str(self.nonce) + "\n--------------"
Output:
Block Hash: 50339796dd060db74766426b02c57f58b591ddad6331a75e72b61081bf97ade0
BlockNo: 1
Block Data: Block 1
Block Creator: anku
Hashes: 1036355
--------------
Block Hash: 5c1d8eac7b95f4c2410681c0d2cb61eb754ff222d926778c4e1da332133107f1
BlockNo: 2
Block Data: Block 2
Block Creator: anku
Hashes: 3015159
--------------
Block Hash: ad14237eadc3be6ea1a1318fd25dc33e40216c0d37ea0bde14b8d05adf2501b9
BlockNo: 0
Block Data: Genesis
Block Creator: anku
Hashes: 0
--------------
Block Hash: 50339796dd060db74766426b02c57f58b591ddad6331a75e72b61081bf97ade0
BlockNo: 1
Block Data: Block 1
Block Creator: anku
Hashes: 1036355
--------------
Block Hash: 5c1d8eac7b95f4c2410681c0d2cb61eb754ff222d926778c4e1da332133107f1
BlockNo: 2
Block Data: Block 2
Block Creator: anku
Hashes: 3015159
--------------
Issue: The Genesis block must be the first one to be executed but it is executed in between. Can someone guide me where I am doing it wrong?
解决方案
如果你看一下这个mine
函数,它会打印出它挖掘的块。这就是创世块之前的块的来源。尝试删除print
inmine
函数。
推荐阅读
- database - 唯一键约束问题 - MySQL、SQL Server、Oracle、Postgres
- unity3d - 如何在统一 VR 中检测到特定区域的传送
- sql - 值为 NULL 的列会影响 Microsoft SQL Server 的性能吗?
- flutter - 如何使用 Flutter AnimationController 和 Transform 旋转图像?
- mysql - 从一个表中获取列内容并使用它从另一个表中获取 id
- azure-sql-database - Azure SQL 数据库 100% DTU,而查询 DTU 使用率低
- java - 借助 Java 中的批处理脚本启动 tomcat 服务
- c++ - 将存储在 int 中的内存地址分配给 int
- mysql - 如何使用 laravel 备份数据库中的所有存储数据并保存在文件夹中的文件
- javascript - 在 jQuery dailog 上编辑数据网格的模板出现错误