美文网首页区块链
python BlockChain(四)共识机制,解决冲突

python BlockChain(四)共识机制,解决冲突

作者: ab64fd4eaee3 | 来源:发表于2018-07-02 08:16 被阅读3次

    开启两个服务器,两个节点

    pipenv run python blockchain.py -p 5001
    pipenv run python blockchain.py -p 5000

    节点一

    1.查看链条
    http://127.0.0.1:5000/chain
    2.创建交易
    http://127.0.0.1:5000/transanctions/new
    3.挖矿
    http://127.0.0.1:5000/mine

    节点二

    1.查看链条
    http://127.0.0.1:5001/chain
    4.节点二注册节点一

    image.png

    5.节点二解决冲突

    http://127.0.0.1:5001/node/resolve

        def valid_chain(self,chain)->bool:
    
            last_block=chain[0]
            current_index = 1
    
            while current_index <len(chain):
                block = chain[current_index]
    
                if block['previous_hash'] != self.hash(last_block):
                    return False
                if not  self.valid_proof(last_block['proof'],block['proof']):
                    return False
    
                last_block = block
                current_index +=1
            return True
    
    
    
        def resolve_conflicts(self) -> bool:
    
            neighbours = self.nodes
    
            max_length = len(self.chain)
            max_chain = None
    
            for node in neighbours:
                reponse = request.get(f'http://{node}/chain')
                if reponse.status_code == 200:
                    length = reponse.json()['length']
                    chain = reponse.json()["chain"]
    
                    if length > max_length and self.valid_chain(chain):
                        max_length = length
                        max_chain = chain
    
            if max_chain:
                self.chain = max_chain
                return True
    
            return False
    
    @app.route('/node/resolve',methods=["GET"])
    def consensus():
        replaced = blockchain.resolve_conflicts()
    
        if replaced:
            reponse = {
                'message': "Our chain was replaced ",
                'new_chain': blockchain.chain
            }
        else:
            reponse = {
                'message': "Our chain is authoritative ",
                'chain': blockchain.chain
            }
        return jsonify(reponse), 200
    
    
    if __name__ == '__main__':
        parse = ArgumentParser()
        parse.add_argument("-p","--port",default=5000,type=int,help="port add ")
        args = parse.parse_args()
        port = args.port
        app.run(host="0.0.0.0", port=port)
    

    相关文章

      网友评论

        本文标题:python BlockChain(四)共识机制,解决冲突

        本文链接:https://www.haomeiwen.com/subject/cducuftx.html