1. 确定区块结构
一个区块包括区块的索引、时间戳、交易信息和上一个交易的 hash 值以及工作量证明:
block = {
'index': 0,
'timestamp': '时间戳',
'transations': [
{
'sender': '发送者',
'recipient': '接收者',
'amount': 0,
}
],
'proof': '',
'previous_hash': '',
}
2. 实现区块类结构
由确定好的区块结构可以在类中简单实现:
class BlocakChain(object):
def __init__(self):
self.chain = []
self.current_transaction = []
def new_transaction(self):
"""
添加交易信息
"""
pass
def new_block(self):
"""
添加区块
"""
pass
@staticmethod
def hash(self):
"""
计算区块的hash值
"""
pass
@property
def last_block(self):
"""
获取区块链中最后一个区块
"""
pass
3. 实现添加交易信息
class BlocakChain(object):
def __init__(self):
self.chain = []
self.current_transaction = []
def new_transaction(self, sender, recipient, amount) -> int:
'''
添加交易信息
:param sender:发送者
:param recipient:接收者
:param amount:交易金额
:return:区块的索引
'''
self.current_transaction.append(
{
'sender': sender,
'recipient': recipient,
'amount': amount,
}
)
return self.last_block['index'] + 1
def new_block(self):
"""
添加区块
"""
pass
@staticmethod
def hash(self):
"""
计算区块的hash值
"""
pass
@property
def last_block(self):
'''
获取区块链中最后一个区块
:return:最后一个区块
'''
return self.chain[-1]
4. 实现创建区块
import hashlib
import json
from time import time
class BlocakChain(object):
def __init__(self):
self.chain = []
self.current_transaction = []
self.new_block(proof=100, previous_hash=1)
def new_transaction(self, sender, recipient, amount) -> int:
'''
添加交易信息
:param sender:发送者
:param recipient:接收者
:param amount:交易金额
:return:区块的索引
'''
self.current_transaction.append(
{
'sender': sender,
'recipient': recipient,
'amount': amount,
}
)
return self.last_block['index'] + 1
def new_block(self, proof, previous_hash=None):
'''
创建区块
:param proof:工作量证明
:param previous_hash:上一个区块的hash值
:return:None
'''
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transaction,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.last_block),
}
self.current_transaction = []
self.chain.append(block)
@staticmethod
def hash(self, block):
'''
计算区块的hash值
:param block:区块
:return:
'''
block_str = json.dumps(block, sort_keys=True).encode('utf-8')
return hashlib.sha256(block_str).hexdigest()
@property
def last_block(self):
'''
获取区块链中最后一个区块
:return:最后一个区块
'''
return self.chain[-1]
5. 实现工作量证明
import hashlib
import json
from time import time
class BlocakChain(object):
def __init__(self):
self.chain = []
self.current_transaction = []
self.new_block(proof=100, previous_hash=1)
def new_transaction(self, sender, recipient, amount) -> int:
'''
添加交易信息
:param sender:发送者
:param recipient:接收者
:param amount:交易金额
:return:区块的索引
'''
self.current_transaction.append(
{
'sender': sender,
'recipient': recipient,
'amount': amount,
}
)
return self.last_block['index'] + 1
def new_block(self, proof, previous_hash=None):
'''
创建区块
:param proof:工作量证明
:param previous_hash:上一个区块的hash值
:return:None
'''
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transaction,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.last_block),
}
self.current_transaction = []
self.chain.append(block)
@staticmethod
def hash(self, block):
'''
计算区块的hash值
:param block:区块
:return:区块的hash值
'''
block_str = json.dumps(block, sort_keys=True).encode('utf-8')
return hashlib.sha256(block_str).hexdigest()
@property
def last_block(self):
'''
获取区块链中最后一个区块
:return:最后一个区块
'''
return self.chain[-1]
def proof_of_work(self, last_proof: int) -> int:
'''
实现工作量证明:这里做个简化版,对两个值(上一个hash值last_proof和交易记录集proof)进行hash看是否能得到5个0开头hash值
:param last_proof:上一个区块的Hash值
:return:满足hash是5个0开头的那个值
'''
proof = 0
init_time = time()
while self.verify_proof(last_proof, proof) is False:
proof += 1
print(proof)
use_time = time() - init_time
print('耗时:{:.2f}秒'.format(use_time))
return proof
def verify_proof(self, last_proof, proof: int) -> bool:
"""
验证
:param last_proof: 上一个区块的Hash值
:param proof:
:return:
"""
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
print(guess_hash)
return guess_hash[0:5] == '00000'
bc = BlocakChain()
bc.proof_of_work(10000)
耗时2.87秒,最终找到了5个0开头的 hash 值:
6. 添加节点通信功能
7. 交易接口实现
8. 挖矿接口实现
9. 实现注册节点
10. 实现共识机制
|