def add_block(self, data): if self.blocks.get('l'): # there we should mark last block hash to create a new block. # in the redis the l is the last block hash value key. last_hash = self.blocks.get('l').decode() b = Block() new_block = b.new_block(data, last_hash) pow = ProofOfWork(new_block, new_block["Nonce"]) if pow.validate(): # self.blocks.append(new_block) self.blocks.set(new_block["Hash"], new_block) self.blocks.set("l", new_block["Hash"]) else: b = Block() new_block = b.new_block(data) pow = ProofOfWork(new_block, new_block["Nonce"]) if pow.validate(): # self.blocks.append(new_block) self.blocks.set(new_block["Hash"], new_block) self.blocks.set("l", new_block["Hash"])
def mine_block(self, transactions): """ 根据链上的最后一个区块的hash值,生成一个新的block :param transactions: :return: """ lash_hash = self.blocks.get("l").decode() height = self.get_height() b = Block() new_block = b.new_block(transactions, lash_hash, height + 1) return new_block
def test_create_bc(): bc = BlockChain() # 创世区块 coinbase = new_coinbase_tx("7AgP8z7XYyZ2sdnVJ6HCiE5X2reJDf") genesis_block = new_genesis_block(coinbase) bc.add_block(genesis_block) b = Block() # 自定义几个block for i in range(5): transactions = [b'Node1', b"Node2", b"Node3", b"Node4"] last_hash = bc.blocks.get("l").decode() height = bc.get_height() new_block = b.new_block(transactions, last_hash, height + 1) bc.add_block(new_block)
#!/usr/bin/env python # -*- coding:utf-8 -*- """ This Document is Created by At 2018/7/9 """ from consensus.proof_of_work import ProofOfWork from core.blockchain.block import Block if __name__ == '__main__': b = Block() genesis_block = b.new_block("Magic test", "") pow = ProofOfWork(genesis_block) pow.run()
def add_block(): b = Block() b.new_block("Magic", "") block = b.block return json.dumps(block)