我正在尝试使用python创建自己的区块链。
我拿了this source code,然后尝试对其进行调整以适合我的需要。 我的代码:
import datetime
import hashlib
class Block:
def __init__(
self,
previous_block_hash,
data,
timestamp,
sender,
):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
self.hash = self.get_hash()
self.sender = self.get_sender()
@staticmethod
def create_genesis_block():
return Block('0', '0', datetime.datetime.now(), '')
def get_sender(self):
self.sender = input('Enter senders ID number: ')
return self.sender
def get_hash(self):
header_bin = str(self.previous_block_hash) + str(self.data) \
+ str(self.timestamp) + str(self.sender)
inner_hash = \
hashlib.sha256(header_bin.encode()).hexdigest().encode()
outer_hash = hashlib.sha256(inner_hash).hexdigest()
return outer_hash
blockchain = [Block.create_genesis_block()]
length_of_blockchain = len(blockchain)
print ('The genesis block has been created.')
print ('Hash: %s' % blockchain[0].hash)
blockchain.append(Block(blockchain[length_of_blockchain - 1].hash,
'Blockchain Number: '[length_of_blockchain - 1],
datetime.datetime.now(), Block.get_sender()))
我想向该块添加一个发送者和接收者。因此,我首先开始是发送者。我不断收到此错误here,但不确定如何解决。一切都在本地进行测试,以确保一切都签出,然后我将对其添加本机反应。希望有人可以帮助我
答案 0 :(得分:0)
您正在尝试访问self.sender
,然后再对其进行初始化。重新排序初始化可能对我们有帮助。
import datetime
import hashlib
class Block:
def __init__(
self,
previous_block_hash,
data,
timestamp,
sender,
):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
#reordering self.hash and self.sender as self.get_sender() references to self.sender
self.sender = self.get_sender()
self.hash = self.get_hash()
@staticmethod
def create_genesis_block():
return Block('0', '0', datetime.datetime.now(), '')
def get_sender(self):
self.sender = input('Enter senders ID number: ')
return self.sender
def get_hash(self):
header_bin = str(self.previous_block_hash) + str(self.data) \
+ str(self.timestamp) + str(self.sender)
inner_hash = \
hashlib.sha256(header_bin.encode()).hexdigest().encode()
outer_hash = hashlib.sha256(inner_hash).hexdigest()
return outer_hash
希望这会有所帮助