我正在尝试制作自己的加密货币和区块链。进行了一些编辑,现在不进行散列了吗?
具有hashlib知识的人可以帮助我吗?
# -*- coding: utf-8 -*-
from hashlib import sha256
def updatehash(*args):
hashing_text = ""; h = sha256()
for arg in args:
hashing_text += str(args)
h.update(hashing_text.encode("utf-8"))
return h.hexdigest()
class Block():
data = None
hash = None
nonce = 0
previous_hash = "0" * 64
def __init__(self, data, number=0):
self.data = data
self.number = number
def hash(self):
return updatehash(
self.number,
self.previous_hash,
self.data,
self.nonce,
)
def __str__(self):
return str("Block#: %s\nHash: %s\nPrevious: %s\nData: %s\nNonce: %s\n" %(
self.number,
self.hash,
self.previous_hash,
self.data,
self.nonce
)
)
class Blockchain():
difficulty = 4
def __init__(self, chain=[]):
self.chain = chain
def add(self, block):
self.chain.append(block)
def remove(self, block):
self.chain.remove(block)
def mine(self, block):
try: block.previous_hash = self.chain[-1].hash()
except IndexError: pass
while True:
if block.hash()[:self.difficulty] == "0" * self.difficulty:
self.add(block); break
else:
block.nonce += 1
def main():
blockchain = Blockchain()
database = ["hello", "goodbye", "test", "DATA here"]
num = 0
for data in database:
num += 1
blockchain.mine(Block(data, num))
for block in blockchain.chain:
print(block)
if __name__ == '__main__':
main()
这是第一个块的外观。哈希没有显示,只是在说main.Block对象位于0x032C9AA8 >> ...
Hash: <bound method Block.hash of <__main__.Block object at 0x032C9AA8>>
Previous: 0000000000000000000000000000000000000000000000000000000000000000
Data: hello
Nonce: 78787
我需要帮助以使Hash重新工作...
def hash(self):
哈希是一个函数。您忘记了()
以获得结果:
def __str__(self):
return str("Block#: %s\nHash: %s\nPrevious: %s\nData: %s\nNonce: %s\n" %(
self.number,
self.hash(),
self.previous_hash,
self.data,
self.nonce
)
)