6.区块链节点信息同步

区块链节点信息需要同步,本节主要讲一下选取最长的链做为基准链。

NiuCoinBlockChainOne.py

# -*- coding: utf-8 -*-
from typing import Any,Dict,List,Optional
import time
import hashlib
from uuid import uuid4
import json
from flask import Flask
from flask import jsonify
from urllib.parse import urlparse
from flask import request
import requests

class NiuCoinBlockChainOne:

    # 构造器
    def __init__(self):
        self.current_transcations=[]#缓存交易列表,在没有新区块前放在这里,产生新区块后,会被加入到新区块
        self.chain=[]#区块链管理多个区块
        self.nodes=set()#保存网络中的其它节点
        self.new_block(pre_hash="1",proof=100)#创世区块

    #新增一个新区块
    def new_block(self,pre_hash:Optional[str],proof:int)->Dict[str,Any]:
        block = {
            "index":len(self.chain)+1, #索引
            "timestamp":time.time(),
            "transcations":self.current_transcations,#将临时缓存的交易放在区块中
            "proof":proof,#工作量要记下来,校验区块时需要这个证明
            "pre_hash":pre_hash or self.chain[-1]["hash"]
        }
        block["hash"] = self.hash(block)
        self.current_transcations=[]#交易被打包成区块后,要清空
        self.chain.append(block)

    #新增一个新的交易
    def new_transcations(self,sender:str,recer:str,amount:int)->int:
        self.current_transcations.append({
            "sender":sender,
            "recer":recer,
            "amount":amount,
        })
        return self.last_block()["index"]+1

    # 获得最后一个区块
    def last_block(self)->Dict[str,Any]:
        return self.chain[-1]

    # 整个区块hash
    @staticmethod
    def hash(block:Dict[str,Any])->str:
        blockstring = json.dumps(block,sort_keys=True).encode()
        return hashlib.sha256(blockstring).hexdigest()

    # 不断修改值,进行hash碰撞,起到算出结果为止(即拿到证明)
    def proof_of_work(self,last_proof:int)->int:
        proof = 0
        while self.do_proof(last_proof,proof) is False:
            proof+=1
        return proof

    # 进行hash碰撞
    @staticmethod
    def do_proof(last_proof:int,proof:int)->bool:
        guess = f'{last_proof*proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4]=="0000"#难度可调

    # 校验整个链是否正确
    def valid_chain(self,chain:List[Dict[str,Any]]):
        #用当前区块与前一个区块进行校验,循环至最后一个
        pre_block = chain[0]
        current_index = 1
        while current_index<len(chain):
            block = chain[current_index]
            if block["pre_hash"]!=self.hash(pre_block): #校验是否被篡改,hash要能对上
                return False
            if not self.valid_proof(pre_block["proof"],block["proof"]):#校验工作量正确
                return False
            pre_block = block
            current_index+=1
        return True

    # 节点注册,追加节点
    def register_node(self,addr:str)->None:
        now_url=urlparse(addr)#将addr转成对象,能取出schame或port等
        self.nodes.add(now_url.netloc)#netloc='www.cwi.nl:80'

    #节点同步:查找所有的节点,如果附近的节点比自己多,将邻居节点的链赋值给自己节点
    def resolve_conflicts(self)->bool:
        neighbours=self.nodes
        new_chain=None
        max_length=len(self.chain)
        for node in neighbours:#从邻居中取最长的链,赋值给new_chain
            response = requests.get(f"http://{node}/chain") #node的域名与端口都不一样
            if response.status_code==200:
                length = response.json()["length"]
                chain = response.json()["chain"]
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain
        if new_chain:
            self.chain = new_chain#将最长的链赋值给自己
            return True
        return False

niucoin = NiuCoinBlockChainOne()
node_id = str(uuid4()).replace("-","")
print("当前节点钱包地址:",node_id)

app = Flask(__name__)
@app.route("/")
def index_page():
    return "欢迎呵呵"

@app.route("/chain")
def chain():#输出区块链
    response={
        "chain":niucoin.chain,
        "length":len(niucoin.chain),
    }
    return jsonify(response),200

@app.route("/mine")#挖矿,系统奖励比特币
def index_mine():
    last_block = niucoin.last_block()
    last_proof = last_block["proof"]
    proof = niucoin.proof_of_work(last_proof) #挖矿,挖到矿才往下走

    niucoin.new_transcations("0",node_id,200) #获得奖励

    niucoin.new_block(None,proof)
    response={
        "message":"新的区块产生",
        "index":niucoin.last_block()["index"],
        "transcations":niucoin.last_block()["transcations"],
        "proof":niucoin.last_block()["proof"],
        "pre_hash":niucoin.last_block()["pre_hash"]
    }

    return jsonify(response),200

@app.route("/new_transcations",methods=["POST"])#交易
def new_transcations():
    values = request.get_json()
    required = ["payer","recer","amount"]
    if not all(key in values for key in required):
        return "数据不完整",400
    index = niucoin.new_transcations(values["payer"],values["recer"],values["amount"])
    response = {
        "message":f"交易加入到区块{index}"
    }
    return jsonify(response),200

@app.route("/new_node",methods=["POST"])#新增一个节点
def new_node():
    values = request.get_json()
    nodes = values.get("nodes")#获得所有节点
    if nodes is None:
        return "数据有问题",400
    for node in nodes:
        niucoin.register_node(node) #加入节点
    response = {
        "message":f"节点已经追加",
        "node":list(niucoin.nodes)
    }
    return jsonify(response),200

@app.route("/node_synchronize")#节点信息同步
def node_refresh():
    replaced = niucoin.resolve_conflicts() #最长的链
    if replaced:
        response={
            "message":"区块链查新为最长区块链",
            "new_chain":niucoin.chain
        }
    else:
        response = {
            "message": "区块链已经是最长的,无需替换",
            "new_chain": niucoin.chain
        }
    return jsonify(response), 200

if __name__ == "__main__":
    app.run("127.0.0.1",port=65531)

NiuCoinBlockChainTwo.py

# -*- coding: utf-8 -*-
from typing import Any,Dict,List,Optional
import time
import hashlib
from uuid import uuid4
import json
from flask import Flask
from flask import jsonify
from urllib.parse import urlparse
from flask import request
import requests

class NiuCoinBlockChainTwo:

    #构造器
    def __init__(self):
        self.current_transcations=[]#缓存交易列表,在没有新区块前放在这里,产生新区块后,会被加入到新区块
        self.chain=[]#区块链管理多个区块
        self.nodes=set()#保存网络中的其它节点
        self.new_block(pre_hash="1",proof=100)#创世区块

    #新增一个新区块
    def new_block(self,pre_hash:Optional[str],proof:int)->Dict[str,Any]:
        block = {
            "index":len(self.chain)+1, #索引
            "timestamp":time.time(),
            "transcations":self.current_transcations,#将临时缓存的交易放在区块中
            "proof":proof,#工作量要记下来,校验区块时需要这个证明
            "pre_hash":pre_hash or self.chain[-1]["hash"]
        }
        block["hash"] = self.hash(block)
        self.current_transcations=[]#交易被打包成区块后,要清空
        self.chain.append(block)

    #新增一个新的交易
    def new_transcations(self,sender:str,recer:str,amount:int)->int:
        self.current_transcations.append({
            "sender":sender,
            "recer":recer,
            "amount":amount,
        })
        return self.last_block()["index"]+1

    # 获得最后一个区块
    def last_block(self)->Dict[str,Any]:
        return self.chain[-1]

    # 整个区块hash
    @staticmethod
    def hash(block:Dict[str,Any])->str:
        blockstring = json.dumps(block,sort_keys=True).encode()
        return hashlib.sha256(blockstring).hexdigest()

    # 不断修改值,进行hash碰撞,起到算出结果为止(即拿到证明)
    def proof_of_work(self,last_proof:int)->int:
        proof = 0
        while self.do_proof(last_proof,proof) is False:
            proof+=1
        return proof

    # 进行hash碰撞
    @staticmethod
    def do_proof(last_proof:int,proof:int)->bool:
        guess=f'{last_proof*proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4]=="0000"#难度可调

    # 校验整个链是否正确
    def valid_chain(self,chain:List[Dict[str,Any]]):
        #用当前区块与前一个区块进行校验,循环至最后一个
        pre_block = chain[0]
        current_index = 1
        while current_index<len(chain):
            block = chain[current_index]
            if block["pre_hash"]!=self.hash(pre_block): #校验是否被篡改,hash要能对上
                return False
            if not self.valid_proof(pre_block["proof"],block["proof"]):#校验工作量正确
                return False
            pre_block = block
            current_index+=1
        return True

    # 节点注册,追加节点
    def register_node(self,addr:str)->None:
        now_url=urlparse(addr)#将addr转成对象,能取出schame或port等
        self.nodes.add(now_url.path)#netloc='www.cwi.nl:80'

    #节点同步:查找所有的节点,如果附近的节点比自己多,将邻居节点的链赋值给自己节点
    def resolve_conflicts(self)->bool:
        neighbours=self.nodes
        new_chain=None
        max_length=len(self.chain)
        for node in neighbours:#从邻居中取最长的链,赋值给new_chain
            response = requests.get(f"http://{node}/chain") #node的域名与端口都不一样
            if response.status_code==200:
                length = response.json()["length"]
                chain = response.json()["chain"]
                if length > max_length :#and self.valid_chain(chain)
                    max_length = length
                    new_chain = chain
        if new_chain:
            self.chain = new_chain#将最长的链赋值给自己
            return True
        return False

niucoin = NiuCoinBlockChainTwo()
node_id = str(uuid4()).replace("-","")
print("当前节点钱包地址:",node_id)

app = Flask(__name__)
@app.route("/")
def index_page():
    return "欢迎呵呵"

@app.route("/chain")
def chain():#输出区块链
    response={
        "chain":niucoin.chain,
        "length":len(niucoin.chain),
    }
    return jsonify(response),200

@app.route("/mine")#挖矿,系统奖励比特币
def index_mine():
    last_block = niucoin.last_block()
    last_proof = last_block["proof"]
    proof = niucoin.proof_of_work(last_proof) #挖矿,挖到矿才往下走

    niucoin.new_transcations("0",node_id,200) #获得奖励

    niucoin.new_block(None,proof)
    response={
        "message":"新的区块产生",
        "index":niucoin.last_block()["index"],
        "transcations":niucoin.last_block()["transcations"],
        "proof":niucoin.last_block()["proof"],
        "pre_hash":niucoin.last_block()["pre_hash"]
    }

    return jsonify(response),200

@app.route("/new_transcations",methods=["POST"])#交易
def new_transcations():
    values = request.get_json()
    required = ["payer","recer","amount"]
    if not all(key in values for key in required):
        return "数据不完整",400
    index = niucoin.new_transcations(values["payer"],values["recer"],values["amount"])
    response = {
        "message":f"交易加入到区块{index}"
    }
    return jsonify(response),200

@app.route("/new_node",methods=["POST"])
def new_node():
    values = request.get_json()
    nodes = values.get("nodes")#获得所有节点
    if nodes is None:
        return "数据有问题",400
    for node in nodes:
        niucoin.register_node(node) #加入节点
    response = {
        "message":f"节点已经追加",
        "node":list(niucoin.nodes)
    }
    return jsonify(response),200

@app.route("/node_refresh")
def node_refresh():
    replaced = niucoin.resolve_conflicts() #最长的链
    if replaced:
        response={
            "message":"区块链查新为最长区块链",
            "new_chain":niucoin.chain
        }
    else:
        response = {
            "message": "区块链已经是最长的,无需替换",
            "new_chain": niucoin.chain
        }
    return jsonify(response), 200

if __name__ == "__main__":
    app.run("127.0.0.1",port=65532)

NiuCoinBlockChainThree.py

# -*- coding: utf-8 -*-
from typing import Any,Dict,List,Optional
import time
import hashlib
from uuid import uuid4
import json
from flask import Flask
from flask import jsonify
from urllib.parse import urlparse
from flask import request
import requests

class NiuCoinBlockChainThree:

    #构造器
    def __init__(self):
        self.current_transcations=[]#缓存交易列表,在没有新区块前放在这里,产生新区块后,会被加入到新区块
        self.chain=[]#区块链管理多个区块
        self.nodes=set()#保存网络中的其它节点
        self.new_block(pre_hash="1",proof=100)#创世区块

    #新增一个新区块
    def new_block(self,pre_hash:Optional[str],proof:int)->Dict[str,Any]:
        block = {
            "index":len(self.chain)+1, #索引
            "timestamp":time.time(),
            "transcations":self.current_transcations,#将临时缓存的交易放在区块中
            "proof":proof,#工作量要记下来,校验区块时需要这个证明
            "pre_hash":pre_hash or self.chain[-1]["hash"]
        }
        block["hash"] = self.hash(block)
        self.current_transcations=[]#交易被打包成区块后,要清空
        self.chain.append(block)

    #新增一个新的交易
    def new_transcations(self,sender:str,recer:str,amount:int)->int:
        self.current_transcations.append({
            "sender":sender,
            "recer":recer,
            "amount":amount,
        })
        return self.last_block()["index"]+1

    # 获得最后一个区块
    def last_block(self)->Dict[str,Any]:
        return self.chain[-1]

    # 整个区块hash
    @staticmethod
    def hash(block:Dict[str,Any])->str:
        blockstring = json.dumps(block,sort_keys=True).encode()
        return hashlib.sha256(blockstring).hexdigest()

    # 不断修改值,进行hash碰撞,起到算出结果为止(即拿到证明)
    def proof_of_work(self,last_proof:int)->int:
        proof = 0
        while self.do_proof(last_proof,proof) is False:
            proof+=1
        return proof

    # 进行hash碰撞
    @staticmethod
    def do_proof(last_proof:int,proof:int)->bool:
        guess=f'{last_proof*proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4]=="0000"#难度可调

    # 校验整个链是否正确
    def valid_chain(self,chain:List[Dict[str,Any]]):
        #用当前区块与前一个区块进行校验,循环至最后一个
        pre_block = chain[0]
        current_index = 1
        while current_index<len(chain):
            block = chain[current_index]
            if block["pre_hash"]!=self.hash(pre_block): #校验是否被篡改,hash要能对上
                return False
            if not self.valid_proof(pre_block["proof"],block["proof"]):#校验工作量正确
                return False
            pre_block = block
            current_index+=1
        return True

    # 节点注册,追加节点
    def register_node(self,addr:str)->None:
        now_url=urlparse(addr)#将addr转成对象,能取出schame或port等
        self.nodes.add(now_url.netloc)#netloc='www.cwi.nl:80'

    #节点同步:查找所有的节点,如果附近的节点比自己多,将邻居节点的链赋值给自己节点
    def resolve_conflicts(self)->bool:
        neighbours=self.nodes
        new_chain=None
        max_length=len(self.chain)
        for node in neighbours:#从邻居中取最长的链,赋值给new_chain
            response = requests.get(f"http://{node}/chain") #node的域名与端口都不一样
            if response.status_code==200:
                length = response.json()["length"]
                chain = response.json()["chain"]
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain
        if new_chain:
            self.chain = new_chain#将最长的链赋值给自己
            return True
        return False

niucoin = NiuCoinBlockChainTwo()
node_id = str(uuid4()).replace("-","")
print("当前节点钱包地址:",node_id)

app = Flask(__name__)
@app.route("/")
def index_page():
    return "欢迎呵呵"

@app.route("/chain")
def chain():#输出区块链
    response={
        "chain":niucoin.chain,
        "length":len(niucoin.chain),
    }
    return jsonify(response),200

@app.route("/mine")#挖矿,系统奖励比特币
def index_mine():
    last_block = niucoin.last_block()
    last_proof = last_block["proof"]
    proof = niucoin.proof_of_work(last_proof) #挖矿,挖到矿才往下走

    niucoin.new_transcations("0",node_id,200) #获得奖励

    niucoin.new_block(None,proof)
    response={
        "message":"新的区块产生",
        "index":niucoin.last_block()["index"],
        "transcations":niucoin.last_block()["transcations"],
        "proof":niucoin.last_block()["proof"],
        "pre_hash":niucoin.last_block()["pre_hash"]
    }

    return jsonify(response),200

@app.route("/new_transcations",methods=["POST"])#交易
def new_transcations():
    values = request.get_json()
    required = ["payer","recer","amount"]
    if not all(key in values for key in required):
        return "数据不完整",400
    index = niucoin.new_transcations(values["payer"],values["recer"],values["amount"])
    response = {
        "message":f"交易加入到区块{index}"
    }
    return jsonify(response),200

@app.route("/new_node",methods=["POST"])
def new_node():
    values = request.get_json()
    nodes = values.get("nodes")#获得所有节点
    if nodes is None:
        return "数据有问题",400
    for node in nodes:
        niucoin.register_node(node) #加入节点
    response = {
        "message":f"节点已经追加",
        "node":list(niucoin.nodes)
    }
    return jsonify(response),200

@app.route("/node_refresh")
def node_refresh():
    replaced = niucoin.resolve_conflicts() #最长的链
    if replaced:
        response={
            "message":"区块链查新为最长区块链",
            "new_chain":niucoin.chain
        }
    else:
        response = {
            "message": "区块链已经是最长的,无需替换",
            "new_chain": niucoin.chain
        }
    return jsonify(response), 200

if __name__ == "__main__":
    app.run("127.0.0.1",port=65533)

以上用到的库(import),百度一下安装即可;
端口要用5位,我这里四位不行,比如6000;
运行时不要run flask,要配置python的运行环境(在pycharm在右上角可配置flask还是python环境);
代码比较长,先大概理解下代码,跑完程序就理解所有代码了;
有三个节点类,可以模拟三个节点信息同步,为了简单我仅演示两个。

1.准备最长链,节点1

访问『http://127.0.0.1:65531/mine』,执行10次,制造最长链;
访问『http://127.0.0.1:65531/chain』,可以显示有11个区块。

2.准备短链,节点2

访问『http://127.0.0.1:65532/mine』,执行2次,制造最短链;
访问『http://127.0.0.1:65532/chain』,可以显示有3个区块。

3.将所有节点注册

用postman执行『http://127.0.0.1:65532/new_node』,POST方式,内容为『{"nodes":["127.0.0.1:65531","127.0.0.1:65533"]}』,加入节点1与节点3至节点2,这里仅是模拟,不要加入自己(节点2),否则会卡住线程。

4.同步信息,将短的替换为长的

访问『http://127.0.0.1:65532/node_refresh』,同步最长链至当前节点;
至此就完成了简单的节点间信息同步。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • 一、快速术语检索 比特币地址:(例如:1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV)由一串...
    不如假如阅读 15,770评论 4 88
  • 不要再祈求那些一帆风顺的机会了 给你了,抓得住吗 就算再来一次, 结果也不会变 配不上的终究会失去 你,还是你 嘿...
    小艾11号阅读 228评论 0 0
  • 1做到了划掉,只有一项没做到,时间来不及,等下花点时间做到, 2.有哪些我觉得满意的?自律,积极的完成态度,注意力...
    Hi_张阅读 143评论 0 0
  • 这个月商场有活动,一元嗨购50元现金券,名额有限只有2000张,每人限购2张,可以叠加使用,使用时间3月17日开始...
    镇江吾悦DDM徐冰阅读 508评论 0 0
  • 大家做功能,遇到任务完成提醒的功能点时,在界面显示或者事件回调的地方调用下这个方法就可以,提示显示的逻辑、控件的创...
    小母鸡他哥阅读 1,048评论 0 1