Я действительно застрял на этой проблеме в течение последнего дня. Кто-нибудь может мне помочь? Ниже приведен код:
import base64
import os
import datetime
import ast
from time import time
import hashlib, binascii
class BlockChain:
def __init__(self, chain=[], difficulty=2):
self.difficulty = difficulty
self.chain = [self.createGenesis()]
def createGenesis(self):
return Block("sometext", datetime.datetime.now().timestamp(), 0)
def latestblock(self):
return self.chain[len(self.chain) - 1]
def addblock(self, newblock):
previouschain = self.chain
rollbackchain = {}
for i in previouschain:
this = {i.index: {"data": i.data, "hash": i.hash,"previoushash": i.previoushash, "timestamp": i.timestamp, "index": i.index, "nonce": i.nonce}}
rollbackchain.update(this)
open("previousChain.txt", "w+").write(str(rollbackchain))
newblock.hash = newblock.mine(self.difficulty)
newblock.previoushash = self.latestblock().hash
self.chain.append(newblock)
def verify(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i - 1]
if current.hash != current.calculatehash():
print(current.hash + "<!=!!>" + current.calculatehash(True))
print( Exception("current hash error"))
#self.rollback()
return False
if current.previoushash != previous.calculatehash(True):
print(current.previoushash + "<!=!!>" + previous.calculatehash(True))
print(Exception("previous hash error"))
#self.rollback()
return False
return True
def rollback(self):
n = 0
prechain = ast.literal_eval(open("previousChain.txt", "r").read())
for i in prechain:
thisdata = prechain[i]
self.chain[n] = Block(thisdata["data"], thisdata["timestamp"], thisdata["index"], thisdata["previoushash"])
n += 1
class Block(BlockChain):
def __init__(self, data, timestamp, index, previoushash="", nonce=0):
self.data = data
self.timestamp = timestamp
self.index = index
self.previoushash = previoushash
self.nonce = nonce
self.hash = self.calculatehash(True)
def calculatehash(self, debbuger=False):
byte = bytes(str(self.data) + str(self.timestamp) + str(self.index) + str(self.nonce) + str(self.previoushash), "utf-8")
hashsha = hashlib.pbkdf2_hmac("sha512", byte, b'\xfe\x8f\x8d\xea\x8diM1u\xde\xe8)\xad<{\xe7\x83\xdcD\xa5\xb6\xf1\x98m\xf1\xea\xa8J\xb6j~w', 1, dklen=None).hex()
if debugger:
print("nonce",self.nonce)
print("prehash",self.previoushash)
print("index",self.index)
print("time",self.timestamp)
print("data",self.data)
print("hash",hashsha == self.calculatehash())
print("byte",byte)
return hashsha
def mine(self, difficulty):
st = time()
thishash = self.calculatehash()
while not str(thishash).find("0" * difficulty) == 0:
self.nonce += 1
thishash = self.calculatehash()
#print(self.nonce, end="\r")
print("time took:", time() - st)
return thishash #self.hash? self.hash = thishash?
chain = BlockChain(difficulty=2)
st = time()
print("mining block1...")
poopchain.addblock(Block("some transaction data", datetime.datetime.now().timestamp(), len(poopchain.chain)))
#print("overall time:", time() - st)
print("verifying")
print("ver",chain.verify())
for i in range(len(chain.chain)):
print(poopchain.chain[i].__dict__)
Вот результат:
mining block1...
time took: 0.0009968280792236328
verifying
nonce 32
prehash ec1ee715f088b2b467605f71d90018589ede6c15c956e1ee78a1aec254d52dd9d4a6e9092947d30abd906377f24467aec19ebac5766f2ba0e6ff67b36b2b763d
index 1
time 1594741787.585748
data some transaction data
hash True
byte b'some transaction data1594741787.585748132ec1ee715f088b2b467605f71d90018589ede6c15c956e1ee78a1aec254d52dd9d4a6e9092947d30abd906377f24467aec19ebac5766f2ba0e6ff67b36b2b763d'
00f2c60c3016a16e2442185b35e9f86d510bf60bbbf75cc806863a2ffd7ec00e65621c0bf005914058f04b0f48b88b108f4a6042db258fdf1d6df09ea95555b7<!=!!>1fc5b85591b5398d214a4d843f90f6653a6495f6a45f2263f9ea0421c13b10d12857030db28d47e78e98cef1c4912a18f27849ddc6575780310cb36e76181b51
current hash error
ver False
{'data': 'sometext', 'timestamp': 1594741787.585748, 'index': 0, 'previoushash': '', 'nonce': 0, 'hash': 'ec1ee715f088b2b467605f71d90018589ede6c15c956e1ee78a1aec254d52dd9d4a6e9092947d30abd906377f24467aec19ebac5766f2ba0e6ff67b36b2b763d'}
{'data': 'some transaction data', 'timestamp': 1594741787.585748, 'index': 1, 'previoushash': 'ec1ee715f088b2b467605f71d90018589ede6c15c956e1ee78a1aec254d52dd9d4a6e9092947d30abd906377f24467aec19ebac5766f2ba0e6ff67b36b2b763d', 'nonce': 32, 'hash': '00f2c60c3016a16e2442185b35e9f86d510bf60bbbf75cc806863a2ffd7ec00e65621c0bf005914058f04b0f48b88b108f4a6042db258fdf1d6df09ea95555b7'}
ha sh не то же самое, хотя байты такие. Я проверил ha sh, находятся ли они в одной и той же функции, и это так. Извините за длинный код, это для проекта цепочки блоков. Я использую hashlib binascii. Эти хэши не имеют к этому отношения, просто они не похожи. исследованы везде. спасибо, если помогаете!