参考链接:https://hackernoon.com/learn-blockchains-by-building-one-117428612f46
参考链接:https://xiaozhuanlan.com/topic/1547608293
1区块链数据结构(BlockChain.py)
一个区块主要结构如下:
block = {
'index' : len(self.chain) + 1,
'timestamp' : time(),
'transactions' : self.currentTransaction,
'proof' : proof,
'previousHash' : previousHash or self.hash(self.chain[-1])
}
具体说也就是当前区块的索引。
创建区块时间戳
区块里面包含的交易
知识证明
前一个区块的hash值
1.1 区块链初始化:
def __init__(self):
self.chain = []
self.currentTransaction = []
#Create the genesis block
self.newBlock(proof=100, previousHash=1)
有一个区块链的数组
以及需要区块链里面的交易的数组
一个一个创世区块
1.2. 创建新区块
def newBlock(self, proof, previousHash = None):
# Creates a new Block and adds it to the chain
"""
生成新块
:param proof: <int> The proof given by the Proof of Work algorithm
:param previous_hash: (Optional) <str> Hash of previous Block
:return: <dict> New Block
"""
block = {
'index' : len(self.chain) + 1,
'timestamp' : time(),
'transactions' : self.currentTransaction,
'proof' : proof,
'previousHash' : previousHash or self.hash(self.chain[-1])
}
# Reset the current list of transactions
self.currentTransaction = []
self.chain.append(block)
return block
前面的交易需要加入到新生成的区块中
因此新生成的区块包含前面的交易,生成之后,当前交易数组清空,最后返回当前区块
1.3. 创建新的交易
def newTransaction(self, sender, recipient, amount):
# Adds a new transaction to the list of transactions
"""
生成新交易信息,信息将加入到下一个待挖的区块中
:param sender: <str> Address of the Sender
:param recipient: <str> Address of the Recipient
:param amount: <int> Amount
:return: <int> The index of the Block that will hold this transaction
"""
self.currentTransaction.append({
'sender' : sender,
'recipient' : recipient,
'amount' : amount,
})
#下一个待挖的区块中
return self.lastBlock['index'] + 1
交易有三个属性
- 发送方
- 接收方
- 数量
返回值的意思是,需要将交易记录在下一个区块中