我正在构建一个简单的区块链/加密货币,以了解python和区块链编程。
我遇到了有关将交易对象附加到我的Block对象中的列表变量'transactions'的问题。
无论出于何种原因,将交易添加到区块时,都会将其添加到链上的每个区块。
我已将代码上传到github存储库: 该项目包含3个类文件:Blockchain.py,Block.py和Transaction.py 我也有一个测试文件'test1.py',它再现了错误。
https://github.com/swooperior/blockchain-py
我怀疑问题出在Block类文件中
#Not intended behaviour. addTransaction seems to add to every block in self.chain
from datetime import datetime
import hashlib
class Block:
hash = ''
txIndex = 0
transactions = []
timeStamp = ''
previous_hash = ''
nonce = 0
def calculateHash(self):
self.hash = str(hashlib.sha256(repr([self.transactions,self.previous_hash,self.nonce]).encode('utf-8')).hexdigest())
def getHash(self):
return self.hash
def addTransaction(self,tx):
#Validate transaction, then pass to transactions list
tx.id = self.txIndex
self.transactions.append(tx)
self.txIndex += 1
def printDetails(self):
print('Block Hash: '+self.getHash())
print('Nonce: '+str(self.nonce))
print('Created: '+ str(datetime.fromtimestamp(self.timeStamp)))
print('Prev_hash: '+self.previous_hash)
print('Transactions ('+str(len(self.transactions))+'):')
self.printTransactions()
def printTransactions(self):
c = 1
for tx in self.transactions:
print('Transaction:'+ str(c))
tx.printDetails()
c += 1
def __init__(self,txlist=[],prev_hash=''):
self.txIndex = 0
self.previous_hash = prev_hash
for tx in txlist:
self.addTransaction(tx)
self.timeStamp = datetime.timestamp(datetime.now())
self.nonce = 1
self.calculateHash()
#print(self.printDetails())
答案 0 :(得分:0)
transactions
属性是该类的所有实例的类属性。实例化类时,应改为创建一个实例变量。您也不应使用可变的默认参数。
class Block:
...
def __init__(self, txlist=None, prev_hash=''):
self.transactions = []
txlist = txlist or []
self.previous_hash = prev_hash
for tx in txlist:
self.addTransaction(tx)
self.timeStamp = datetime.timestamp(datetime.now())
self.nonce = 1
self.calculateHash()
函数默认值仅被评估一次,因此每个实例都使用相同的默认参数,除非您给它另一个参数。这仅发生在可变对象上,因为重新分配它们不会复制它们。