看了好几个从零开始建区块链的文章,

只有以下这几个URL实在,

于是,花了一晚上,

妥妥的自已手打一次,

感觉棒棒哒~~:)

https://www.jianshu.com/p/ecfb2a9040a3

https://www.jianshu.com/p/b39c361687c1

https://www.jianshu.com/p/1e247faf8a15

ChgBlockChain.py

# coding=utf-8import hashlib
import json
import datetimefrom typing import Optional, Dict, Any, List
from urllib.parse import urlparse
import requestsclass ComplexEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, datetime.datetime):return obj.strftime('%Y-%m-%d %H:%M:%S')else:return json.JSONEncoder.default(self, obj)class ChgBlockChain(object):def __init__(self):self.chain = []self.current_transactions = []self.nodes = set()self.new_block(proof=100, prev_hash=1)def new_block(self,proof: int,prev_hash: Optional[str])->Dict[str, Any]:block = {"index": len(self.chain) + 1,"timestamp": datetime.datetime.now(),"transactions": self.current_transactions,"proof": proof,"prev_hash": prev_hash or self.hash(self.chain[-1])}self.current_transactions = []self.chain.append(block)return blockdef new_transaction(self, sender: str, recipient: str, amount: int)->int:self.current_transactions.append({"sender": sender,"recipient": recipient,"amount": amount})return self.last_block["index"] + 1@staticmethoddef hash(block: Dict[str, Any])->str:block_str = json.dumps(block, sort_keys=True,  indent=4, cls=ComplexEncoder).encode("utf-8")return hashlib.sha256(block_str).hexdigest()@propertydef last_block(self)->Dict[str, Any]:return self.chain[-1]def proof_of_work(self, last_block)->int:last_proof = last_block["proof"]# last_hash = self.hash(last_block)proof = 0while self.valid_proof(last_proof, proof) is False:proof += 1return proof@staticmethoddef valid_proof(last_proof: int, proof: int)->bool:guess = f'{last_proof}{proof}'.encode("utf-8")guess_hash = hashlib.sha256(guess).hexdigest()return guess_hash[:4] == "0000"def register_node(self, addr: str)->None:parsed_url = urlparse(addr)if parsed_url.netloc:self.nodes.add(parsed_url.netloc)elif parsed_url.path:self.nodes.add(parsed_url.path)else:raise ValueError("url invalid!")def valid_chain(self, chain: List[Dict[str, Any]])->bool:last_block = chain[0]current_index = 1while current_index < len(chain):block = chain[current_index]if block["prev_hash"] != self.hash(last_block):return Falseif not self.valid_proof(last_block["proof"],block["proof"]):return Falselast_block = blockcurrent_index += 1return Truedef resolve_conflicts(self)->bool:neighbours = self.nodesnew_chain = Nonemax_length = len(self.chain)for node in neighbours:response = requests.get(f'http://{node}/chain')if response.status_code == 200:length = response.json()["length"]chain = response.json()["chain"]if length > max_length and self.valid_chain(chain):max_length = lengthnew_chain = chainif new_chain:return Trueelse:return False

ChgCoinBlockNode.py

# coding=utf-8from uuid import uuid4
from flask import Flask, jsonify, requestfrom ChgBlockChain import ChgBlockChainchgCoin = ChgBlockChain()
node_id = str(uuid4()).replace("-", "")
print("current node wallet address: ", node_id)app = Flask(__name__)
app.config['DEBUG'] = True
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True@app.route("/")
def index_page():return "welcome to ChgCoin..."@app.route("/chain")
def index_chain():response = {"chain": chgCoin.chain,"length": len(chgCoin.chain)}return jsonify(response), 200@app.route("/mine")
def index_mine():last_block = chgCoin.last_blockproof = chgCoin.proof_of_work(last_block)chgCoin.new_transaction(sender=0,recipient=node_id,amount=12.5)block = chgCoin.new_block(proof, chgCoin.hash(last_block))response = {"message": "new block created...","index": block["index"],"transactions": block["transactions"],"proof": block["proof"],"hash": chgCoin.hash(block),"prev_hash": block["prev_hash"]}return jsonify(response), 200@app.route("/new_transactions", methods=["POST"])
def index_new_transactions():values = request.get_json()required = ["sender", "recipient", "amount"]if not all(key in values for key in required):return "data is invalid", 400index = chgCoin.new_transaction(values["sender"],values["recipient"],values["amount"])response = {"message": f"transaction added to block{index}"}return jsonify(response), 201@app.route("/new_node", methods=["POST"])
def index_new_node():values = request.get_json()nodes = values.get("nodes")if nodes is None:return "It's empty node"for node in nodes:chgCoin.register_node(node)response = {"message": "new node added to block","nodes": list(chgCoin.nodes)}return jsonify(response), 201@app.route("/node_refresh")
def index_node_refresh():replaced = chgCoin.resolve_conflicts()print(replaced)if replaced:response = {"message": "block chain is replaced by longest chain","new chain": chgCoin.chain}else:response = {"message": "block chain is no need replaced ","chain": chgCoin.chain}return jsonify(response), 200if __name__ == '__main__':app.run("127.0.0.1", port=5005)

Flask 区域块简单原理实现相关推荐

  1. 四种比较简单的图像显著性区域特征提取方法原理及实现

    四种比较简单的图像显著性区域特征提取方法原理及实现-----> AC/HC/LC/FT. laviewpbt  2014.8.4 编辑 Email:laviewpbt@sina.com   QQ ...

  2. 中国北斗简单原理随笔

    中国北斗简单原理随笔         博主本科大二的时候负责一个海上浮漂的项目,我们移动网络基本距离岸边一般10海里也就完全没有信号了,所有海上目前最为常见的就是卫星通信.而我们使用的就是我们国家自主 ...

  3. 人工智能-阿尔法狗背后的简单原理:贝叶斯公式

    版权声明:本文为博主原创文章,未经博主允许不得转载. AlphaGo为代表的人工智能,彻底的战胜了人类的围棋大师,震撼了全世界,那么人工智能的背后,有着怎样的科技在支撑?本文要介绍的就是人工智能背后的 ...

  4. 修复版区域块源码,首发众车宝源码,共享汽车源码码支付接口搭建教程

    介绍: 修复版区域块源码,首发众车宝源码,共享汽车挂机赚钱合约控矿机器人系统/码支付接口搭建教程 ■产品介绍众车宝共享汽车是一款适用于市场各种场景下进行操作的共享平台,用户可以通过认领市场上的共享汽车 ...

  5. Es区域查找底层原理vsRedis Geo区域查找的实现区别

    es区域查找底层原理 Api如何调用 映射 PUT /test {"mappings":{"properties":{"name":{&qu ...

  6. 【Java面试题】21 Java中的异常处理机制的简单原理和应用。

    [Java面试题]21 Java中的异常处理机制的简单原理和应用. 参考文章: (1)[Java面试题]21 Java中的异常处理机制的简单原理和应用. (2)https://www.cnblogs. ...

  7. 关于单点登录的简单原理和实现步骤

    关于单点登录的简单原理和实现步骤 一.单系统登录机制 1.http无状态协议 web应用采用browser/server架构,http作为通信协议.http是无状态协议,浏览器的每一次请求,服务器会独 ...

  8. Python Flask框架-开发简单博客-认证蓝图

    作者:Eason_LYC 悲观者预言失败,十言九中. 乐观者创造奇迹,一次即可. 一个人的价值,在于他所拥有的.可以不学无术,但不能一无所有! 技术领域:WEB安全.网络攻防 关注WEB安全.网络攻防 ...

  9. C++ 智能指针的简单原理

    C++ 智能指针的简单原理 为什么会有智能指针的原因 delete引起的内存泄漏 智能指针的使用及其原理 RAII auto_ptr std::unique_ptr std::shared_ptr(线 ...

最新文章

  1. 活在未来,需要知道了解过去
  2. Ecplise SVN 配置和使用
  3. 使用WHERE子句将数组传递给查询
  4. little kernel中如何决定app目录下应该包含哪个app
  5. 判断输入的字符串总字节数是否超出限制
  6. SELECT的学习以及在socket中的应用
  7. 创建线程时,需要创建的内容
  8. 第五和第六单元练习题
  9. pantum打印机驱动安装m6506_奔图PantumM6506NW驱动官方版
  10. 电磁场仿真原理——5. 有限元法(FEM)
  11. 布客·ApacheCN 编程/大数据/数据科学/人工智能学习资源 2020.1
  12. js使用高德地图api实现定位,行政区域划分,点击事件,只显示某个省市或区,海量点标记
  13. win10锁屏壁纸文件夹位置
  14. 小丑改造计划之动态规划
  15. 2048游戏英雄榜java_2048游戏攻略 2048分数排行榜详解
  16. 自然数拆分 Lunatic版 TYVJ1172(完全背包)
  17. 5s换脸吴彦祖!爆红AI应用ZAO仍面临技术困境,你的“脸”被授权了吗?
  18. Android Studio 的ListView 的用法
  19. 成功解决Error running ‘Application‘: command line is too long
  20. 吴恩达机器学习训练秘籍整理三十三到三十五章(五)

热门文章

  1. ArcSegment对象
  2. Python学习手册之内部方法、操作符重载和对象生命周期
  3. 机器学习入门框架scikit-learn
  4. .net winform panel 不刷新_winform项目——仿QQ即时通讯程序04:登录界面补充
  5. python写入Excel时,将路径或链接以超链接的方式写入
  6. php和js搜索框,利用PHP+JS实现搜索自动提示(实例)_php技巧
  7. [Ext JS6]工作区-Workspace
  8. Base64 编码介绍
  9. linux中副规则_Linux中的命名规范
  10. Maven 多环境配置profile