{"from": "network", "to": miner_address, "amount": 1}
# 接受WEB请求 @node.route('/txion', methods=['POST']) def transaction(): # 每一次新的 POST 请求, # 我们要的传输data new_txion = request.get_json() # 把传输任务添加都列表中 this_nodes_transactions.append(new_txion) # 传输成功,把信息打到控制台 print ("New transaction") print ("FROM: {}".format(new_txion['from'].encode('ascii', 'replace'))) print ("TO: {}".format(new_txion['to'].encode('ascii', 'replace'))) print ("AMOUNT: {}\n".format(new_txion['amount'])) # 让客户端知道成功了 return "Transaction submission successful\n"
@node.route('/mine', methods=['GET']) def mine(): # 获取最近的POW last_block = blockchain[len(blockchain) - 1] last_proof = last_block.data['proof-of-work'] # 找到最新块的工作量证明 # Note: 这个程序会一直挂到最新块被挖出来 proof = proof_of_work(last_proof) # 一旦我们找到有效的工作量证明 # 当我们知道挖到块 我们就在交易中奖励矿工 this_nodes_transactions.append( {"from": "network", "to": miner_address, "amount": 1} ) # 现在我们能收集需要创造新块的数据 new_block_data = { "proof-of-work": proof, "transactions": list(this_nodes_transactions) } new_block_index = last_block.index + 1 new_block_timestamp = this_timestamp = date.datetime.now() last_block_hash = last_block.hash # 空的交易列表 this_nodes_transactions[:] = [] # 建新块 mined_block = Block( new_block_index, new_block_timestamp, new_block_data, last_block_hash ) blockchain.append(mined_block) # 让客户端知道挖到矿 #json结构 return json.dumps({ "index": new_block_index, "timestamp": str(new_block_timestamp), "data": new_block_data, "hash": last_block_hash }) + "\n"
from hashlib import sha256 x = 5 y = 0 # We don't know what y should be yet... while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0": y += 1 print(f'The solution is y = {y}')
hash(5 * 21) = 1253e9373e...5e3600155e860
def proof_of_work(last_proof): # 产生一个我们能找到写一个工作量证明的变量 incrementor = last_proof + 1 # 知道有一个数能被9整除 # 同时 这个工作量证明包含前一个区块 while not (incrementor % 9 == 0 and incrementor % last_proof == 0): incrementor += 1 # 一旦数字被找到,返回POW return incrementor
现在,我们能控制一定时间周期内挖掘的区块数量了,并且我们能在网络上发行CCHCoin给人们,使他们能互相发送了。但正如我们所说,我们只在一台电脑上做到了这些。如果区块链是去中心化的,我们如何能够确定每一个节点中的链是一样的呢?为了做到这一点,我们让每一个节点广播它的链的版本给其他节点,并且允许他们接受其他节点的链。这之后,每一个节点必须核实其他节点的链,所以每一个网络中的节点都与产生的区块链看起来一致了。这被称为共识(consensus)算法。