我的实例没有在while循环中更新

2024-10-02 22:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过将nonce改为1来重新计算散列。但是self.hash文件没有改变。你知道吗

我不是那么有经验,不知道如何解决这些类型的问题

import hashlib

class Block:

  def __init__(self, timestamp, transaction, previousHash = ''):
    self.timestamp = timestamp
    self.transaction = transaction
    self.nonce = 0
    self.previousHash = previousHash
    self.hash = self.calculateHash()

  def mineBlock(self):
    checkIfTrue = str(self.hash).startswith('0')
    while checkIfTrue != True:
        self.nonce += 1
        self.hash = self.calculateHash()
        print(self.hash)

    print("block mined")

  def calculateHash(self):
    h = hashlib.sha256((str(self.timestamp) + str(self.transaction) + str(self.previousHash) + str(self.nonce)).encode('utf-8'))
    return h.hexdigest()

Tags: 文件self类型defhash经验timestampnonce
2条回答

您没有在循环内更新checkIfTrue。你知道吗

实际上不需要这个变量,只需在while语句中进行哈希检查。你知道吗

while not str(self.hash).startswith('0'):
    self.nonce += 1
    self.hash = self.calculateHash()
    print(self.hash)

我试过你的代码对我来说很好,self.hash文件变化。但是由于条件“while checkIfTrue!=True:“在循环内不会改变。一旦你更新了self.hash文件,您需要退出循环并执行“checkIfTrue=str”(self.hash文件).startswith('0')”再次。你知道吗

相关问题 更多 >