python实现分布式区块链
import hashlib
import json
from time import time
from urllib.parse import urlparse
from uuid import uuid4
import requests
from flask import Flask, jsonify, request
import math
class Blockchain(object):
def __init__(self):
self.current_transactions = []
self.chain = []
self.nodes = set()
# 创建“创世块”
self.new_block(previous_hash=1, proof=100)
def register_node(self, address):
"""
增加一个新的网络节点到set集合
"""
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
def valid_chain(self, chain):
"""
检查给定的链是否是有效的
:param chain: <list> 区块链
:return: <bool>
"""
last_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
print(f'{last_block}')
print(f'{block}')
# 检验当前block的previous_hash值和前面block的hash值是否相等
if block['previous_hash'] != self.hash(last_block):
return False
# 验证前面block的工作量证明和当前block的工作量证明拼接起来的字符串的hash是否以'abc'为开头
if not self.valid_proof(last_block['proof'], block['proof']):
return False
last_block = block
current_index += 1
# 验证通过,返回True
return True
def resolve_conflicts(self):
"""
共识算法解决冲突
使用网络中最长的链.
:return: <bool> True 如果链被取代, 否则为False
"""
# 所有的邻居节点
neighbours = self.nodes
new_chain = None
# 在所有邻居中查找比自己链更长的
max_length = len(self.chain)
# 遍历并且验证