2019独角兽企业重金招聘Python工程师标准>>>

import hashlib
import json
from time import time
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
from uuid import uuid4import requests
from flask import Flask, jsonify, requestclass Blockchain:def __init__(self):self.current_transactions = []self.chain = []self.nodes = set()# 创建创世块self.new_block(previous_hash='1', proof=100)def register_node(self, address: str) -> None:"""Add a new node to the list of nodes:param address: Address of node. Eg. 'http://192.168.0.5:5000'"""parsed_url = urlparse(address)self.nodes.add(parsed_url.netloc)def valid_chain(self, chain: List[Dict[str, Any]]) -> bool:"""Determine if a given blockchain is valid:param chain: A blockchain:return: True if valid, False if not"""last_block = chain[0]current_index = 1while current_index < len(chain):block = chain[current_index]print(f'{last_block}')print(f'{block}')print("\n-----------\n")# Check that the hash of the block is correctif block['previous_hash'] != self.hash(last_block):return False# Check that the Proof of Work is correctif not self.valid_proof(last_block['proof'], block['proof']):return Falselast_block = blockcurrent_index += 1return Truedef resolve_conflicts(self) -> bool:"""共识算法解决冲突使用网络中最长的链.:return:  如果链被取代返回 True, 否则为False"""neighbours = self.nodesnew_chain = None# We're only looking for chains longer than oursmax_length = len(self.chain)# Grab and verify the chains from all the nodes in our networkfor node in neighbours:response = requests.get(f'http://{node}/chain')if response.status_code == 200:length = response.json()['length']chain = response.json()['chain']# Check if the length is longer and the chain is validif length > max_length and self.valid_chain(chain):max_length = lengthnew_chain = chain# Replace our chain if we discovered a new, valid chain longer than oursif new_chain:self.chain = new_chainreturn Truereturn Falsedef new_block(self, proof: int, previous_hash: Optional[str]) -> Dict[str, Any]:"""生成新块:param proof: The proof given by the Proof of Work algorithm:param previous_hash: Hash of previous Block:return: New Block"""block = {'index': len(self.chain) + 1,'timestamp': time(),'transactions': self.current_transactions,'proof': proof,'previous_hash': previous_hash or self.hash(self.chain[-1]),}# Reset the current list of transactionsself.current_transactions = []self.chain.append(block)return blockdef new_transaction(self, sender: str, recipient: str, amount: int) -> int:"""生成新交易信息,信息将加入到下一个待挖的区块中:param sender: Address of the Sender:param recipient: Address of the Recipient:param amount: Amount:return: The index of the Block that will hold this transaction"""self.current_transactions.append({'sender': sender,'recipient': recipient,'amount': amount,})return self.last_block['index'] + 1@propertydef last_block(self) -> Dict[str, Any]:return self.chain[-1]@staticmethoddef hash(block: Dict[str, Any]) -> str:"""生成块的 SHA-256 hash值:param block: Block"""# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashesblock_string = json.dumps(block, sort_keys=True).encode()return hashlib.sha256(block_string).hexdigest()def proof_of_work(self, last_proof: int) -> int:"""简单的工作量证明:- 查找一个 p' 使得 hash(pp') 以4个0开头- p 是上一个块的证明,  p' 是当前的证明"""proof = 0while self.valid_proof(last_proof, proof) is False:proof += 1return proof@staticmethoddef valid_proof(last_proof: int, proof: int) -> bool:"""验证证明: 是否hash(last_proof, proof)以4个0开头:param last_proof: Previous Proof:param proof: Current Proof:return: True if correct, False if not."""guess = f'{last_proof}{proof}'.encode()guess_hash = hashlib.sha256(guess).hexdigest()return guess_hash[:4] == "0000"# Instantiate the Node
app = Flask(__name__)# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')# Instantiate the Blockchain
blockchain = Blockchain()@app.route('/mine', methods=['GET'])
def mine():# We run the proof of work algorithm to get the next proof...last_block = blockchain.last_blocklast_proof = last_block['proof']proof = blockchain.proof_of_work(last_proof)# 给工作量证明的节点提供奖励.# 发送者为 "0" 表明是新挖出的币blockchain.new_transaction(sender="0",recipient=node_identifier,amount=1,)# Forge the new Block by adding it to the chainblock = blockchain.new_block(proof, None)response = {'message': "New Block Forged",'index': block['index'],'transactions': block['transactions'],'proof': block['proof'],'previous_hash': block['previous_hash'],}return jsonify(response), 200@app.route('/transactions/new', methods=['POST'])
def new_transaction():values = request.get_json()# 检查POST数据required = ['sender', 'recipient', 'amount']if not all(k in values for k in required):return 'Missing values', 400# Create a new Transactionindex = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])response = {'message': f'Transaction will be added to Block {index}'}return jsonify(response), 201@app.route('/chain', methods=['GET'])
def full_chain():response = {'chain': blockchain.chain,'length': len(blockchain.chain),}return jsonify(response), 200@app.route('/nodes/register', methods=['POST'])
def register_nodes():values = request.get_json()nodes = values.get('nodes')if nodes is None:return "Error: Please supply a valid list of nodes", 400for node in nodes:blockchain.register_node(node)response = {'message': 'New nodes have been added','total_nodes': list(blockchain.nodes),}return jsonify(response), 201@app.route('/nodes/resolve', methods=['GET'])
def consensus():replaced = blockchain.resolve_conflicts()if replaced:response = {'message': 'Our chain was replaced','new_chain': blockchain.chain}else:response = {'message': 'Our chain is authoritative','chain': blockchain.chain}return jsonify(response), 200if __name__ == '__main__':from argparse import ArgumentParserparser = ArgumentParser()parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')args = parser.parse_args()port = args.portapp.run(host='127.0.0.1', port=port)

转载于:https://my.oschina.net/corleone/blog/1815666

block chain相关推荐

  1. 关于医疗区块链(Medical Block Chain)的杂谈,以及其他

    前段时间收到了<时代观察>寄来的名为"区块链技术和央行数字货币"的杂志,开头正好讲的是有关医疗的话题.(并不是蹭热点) Medical Block Chain ,中文译 ...

  2. 区块链(Block Chain)结构解析

    定义 狭隘定义:区块链是一个公共账本(Public ledger),一个按照时间顺序排序的交易记录 广义定义:区块链是分布式数据存储.点对点传输.共识机制.加密算法等计算机技术的新型应用模式.所谓共识 ...

  3. geth同步 retrieved hash chain is invalid 错误

    错误信息: ########## BAD BLOCK ######### Chain config: {ChainID: 1 Homestead: 1150000 DAO: 1920000 DAOSu ...

  4. 【北邮国院大三下】Logistics and Supply Chain Management 物流与供应链管理 Week1

    北邮国院大三电商在读,随课程进行整理知识点.仅整理PPT中相对重要的知识点,内容驳杂并不做期末突击复习用.个人认为相对不重要的细小的知识点不列在其中.如有错误请指出.转载请注明出处,祝您学习愉快. 编 ...

  5. 区块链概况:什么是区块链

    链客,专为开发者而生,有问必答! 此文章来自区块链技术社区,未经允许拒绝转载. 区块链技术自身仍然在飞速发展中,目前还缺乏统一的规范和标准. wikipedia 给出的定义为: A blockchai ...

  6. 用Python从零开始创建区块链

    链客,专为开发者而生,有问必答! 此文章来自区块链技术社区,未经允许拒绝转载. 前言 如果你还没有听说过 3 点钟区块链群,说明你还不是链圈的人:如果你还没有加入 3 点钟区块链群,说明你还不是链圈的 ...

  7. 比特币挖矿——区块链技术

    链客,专为开发者而生,有问必答! 此文章来自区块链技术社区,未经允许拒绝转载. 说明 区块链具有数据运行公开.不可篡改.可溯源.跨国际.去中心化的特点.因此越来越多地被应用在各个领域.区块链主要技术包 ...

  8. 92年的小哥,985的特聘教授:3年博士期间发表40篇SCI

    来源:知乎.个人主页等 转自:新智元(AI_era) 参考链接地址:https://www.zhihu.com/question/356327912 "90后"教授.博导越来越多, ...

  9. 以太坊C++客户端Aleth源码分析,转账交易和智能合约的入口代码

    本文主要记录以太坊C++客户端Aleth的源码分析和相关实验过程和结果.本文将讲解两部分的内容,一是转账交易和智能合约的入口代码在哪里?二是通过实验验证转账交易和智能合约交易这两种不同交易所对应的不同 ...

最新文章

  1. 图解ZooKeeper!小学生也能看懂!
  2. JAVA遇见HTML——JSP篇(JSP内置对象上)
  3. python网页优化公司_使用python优化scipy.optimize.minimize公司
  4. 6.win03安全策略
  5. PandasGUI:使用图形用户界面分析 Pandas 数据帧
  6. MYSQL处理数据重复值
  7. java 写一个计算器_java编写一个计算器类
  8. 紫金计算机网络,江苏省计算机网络技术重点实验室
  9. C++11 新特性整理(2)
  10. MySQL深入02-DML之Select查询
  11. mysql数据的表分区二
  12. JAVA基础知识|进程与线程
  13. CrazyWing:Python自动化运维开发实战 七、Python数据类型之数字
  14. Spring Boot
  15. 人工智能十大流行算法,通俗易懂讲明白
  16. RSS简述 及 Java构造RSS接口
  17. 如何拍出优秀风景摄影作品
  18. 基于劈窗算法的地表温度反演算法
  19. 【大顶堆】最小的k个数
  20. 基于语义分割实现人脸图像的皱纹检测定位与分割

热门文章

  1. java 运行时异常 处理_如何在Java中处理运行时异常?
  2. 字符变量赋值规则_第四章 变量
  3. 20200909:链表类题目集合下
  4. 安卓选择多张图片上传_微信7.0.5更新!安卓客户端领先ios发布,新增多项实用功能...
  5. python的抽象类详解_第7.19节 Python中的抽象类详解:abstractmethod、abc与真实子类...
  6. CentOS二进制安装Kubernetes
  7. 评审系统:查看互评信息实现及优化显示
  8. 自考那些事儿(四):软件开发工具(理论篇)
  9. 50秒开门,3分钟开走,特斯拉Model S就这样不翼而飞
  10. NVIDIA DGX低至7.5折限时抢购,全球首款深度学习超级计算机组合