从构建区块链理解区块链概念

import hashlib
import json
from datetime import time
from urllib.parse import urlparse
from uuid import uuid4import requests
from flask import Flask, jsonify, requestclass Blockchain(object):def __init__(self):# 当前交易的列表self.current_transactions = []# 区块的链self.chain = []# 共识机制的节点setself.nodes = set()# Create the genesis block# 创建创世区块self.new_block(previous_hash=1, proof=100)def register_node(self, address):"""Add a new node to the list of nodesresolve_conflicts:param address: <str> Address of node. Eg. 'http://192.168.0.5:5000':return: None"""parsed_url = urlparse(address)self.nodes.add(parsed_url.netloc)def valid_chain(self, chain):"""Determine if a given blockchain is valid:param chain: <list> A blockchain:return: <bool> 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):"""共识算法解决冲突使用网络中最长的链.:return: <bool> 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, previous_hash=None):"""生成新块:param proof: <int> The proof given by the Proof of Work algorithm:param previous_hash: (Optional) <str> Hash of previous Block:return: <dict> 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 transactions# 重置交易列表self.current_transactions = []# 将区块放入链中self.chain.append(block)return blockdef new_transaction(self, sender, recipient, amount):"""生成新交易信息,信息将加入到下一个待挖的区块中:param sender: <str> Address of the Sender:param recipient: <str> Address of the Recipient:param amount: <int> Amount:return: <int> 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):return self.chain[-1]@staticmethoddef hash(block):"""生成块的 SHA-256 hash值:param block: <dict> Block:return: <str>"""# 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):"""简单的工作量证明:- 查找一个 p' 使得 hash(pp') 以4个0开头- p 是上一个块的证明,  p' 是当前的证明:param last_proof: <int>:return: <int>"""proof = 0while self.valid_proof(last_proof, proof) is False:proof += 1return proof@staticmethoddef valid_proof(last_proof, proof):"""验证证明: 是否hash(last_proof, proof)以4个0开头?:param last_proof: <int> Previous Proof:param proof: <int> Current Proof:return: <bool> True if correct, False if not."""guess = f"{last_proof}{proof}".encode()guess_hash = hashlib.sha256(guess).hexdigest()return guess_hash[:4] == "0000"# Instantiate our Node
app = Flask(__name__)# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace("-", "")# Instantiate the Blockchain
blockchain = Blockchain()@app.route("/chain", methods=["GET"])
def full_chain():response = {"chain": blockchain.chain,"length": len(blockchain.chain),}return jsonify(response), 200@app.route("/transactions/new", methods=["POST"])
def new_transaction():values = request.get_json()# Check that the required fields are in the POST'ed datarequired = ["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("/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)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("/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__":app.run(host="0.0.0.0", port=5000)

从构建区块链理解区块链概念相关推荐

  1. 初识区块链——用JS构建你自己的区块链

    初识区块链--用JS构建你自己的区块链 区块链太复杂,那我们就讲点简单的.用JS来构建你自己的区块链系统,寥寥几行代码就可以说明区块链的底层数据结构.POW挖矿思想和交易过程等.当然了,真实的场景远远 ...

  2. 由浅入深理解区块链技术

    一.区块链技术概述 区块链技术的核心思想与密码朋克组织的渊源很深,这个组织由一批致力于个人隐私保护的密码学爱好者组成,他们认为在互联网环境下想要保护个人隐私,应该使用基于技术的而非其他组织背书的加密方 ...

  3. 理解区块链背后的Merkle Tree

    你可以在Github上获取最新的源代码(C#) 目录 简介 本文中的术语 Merkle Tree被应用在哪里? 数字货币 全球供应链 保健行业 资本市场 Git 和 Mercurial 为什么使用Me ...

  4. 吴军:AI应该变成通识教育,区块链不是炒概念

    来源:大数据文摘 作者:魏子敏.龙牧雪 本文共4100字,建议阅读6分钟. 本文为你分享吴军老师对AI相关话题的思考和见地. 2006年,当时的谷歌成立还不足10年.时任智能搜索部科学家的吴军,将其在 ...

  5. 吴军北京来信:人工智能应该变成通识教育,区块链不是炒概念

    大数据文摘作品 作者:魏子敏.龙牧雪 就像今天在每一所理工院校的图书馆,都能找到几台正在播放吴恩达深度学习课程的电脑,10年前,在每一栋理工院校的宿舍楼里,都能看到几本被放在枕边的<数学之美&g ...

  6. 区块链学习 | 区块链的核心概念

    想要学习区块链的相关知识,区块链的核心概念--区块.哈希算法.公钥和私钥.时间戳等是必须要弄懂的.区块链由多个相连的区块构成,所以我们先从了解区块的概念开始! 一.区块 区块的结构图 先看上面的区块的 ...

  7. 区块链中的基本概念整理

    区块链中的基本概念整理 区块链本身是由多种技术集合而成,涉及了多方面的内容,而在其组合应用的过程中,同时也产生了很多新的概念.对于这些概念的整理和理解,有助于更加深刻的理解区块链的本质,也可以指导我们 ...

  8. 第6讲 | 理解区块链之前,先上手体验一把数字货币

    初次接触到区块链的你,肯定是一头雾水:"区块链是什么,这玩意到底怎么回事". 其实对于区块链的原理,你大可不必着急,咱们可以直接上手体验一下目前区块链的第一大应用:数字货币. 本篇 ...

  9. 元宇宙之经济(01)理解区块链

    1 解读区块链 1.1 为啥要有区块链 @1 技术起源 区块链起源于比特币,2008年11月1日,一位自称 中本聪(Satoshi Nakamoto)的人发表了<比特币:一种点对点的电子现金系统 ...

最新文章

  1. 在linux下创建自定义service服务
  2. Product description search in opportunity line item
  3. IAR STM32工程报错Error[Pe020]: identifier “GPIO_Pin_0”is undefined D:\STM32F103_Demo\App\main.c
  4. pat09-散列3. Hashing - Hard Version (30)
  5. pythonios脚本语言-iOS开发Swift篇—(一)简单介绍
  6. 虚拟机中安装vmware tools 到 Debian 时出现 找不到kernel headers的提示
  7. socket 源码分析
  8. 客车网上订票系统项目--在线预约、个人中心我的订单
  9. 在vs中怎样一次性的添加一个文件夹到解决方案里
  10. 数据采集及预处理——针对“数据”“采集”“预处理”的理解与解析
  11. 两步使用Ubuntu 创建自己的网站
  12. Win10 VC++运行库集合|VC++ 2005 2008 2010 2012 2015
  13. 贵有恒,何必三更起五更眠;最无益,只怕一日曝十日寒
  14. webuploader-上传图片到服务器
  15. 软考高级系统架构设计师系列论文七:论基于构件的软件开发
  16. JS小知识,如何将 CSV 转换为 JSON 字符串
  17. android乐视视频直播技术,乐视网进军android平台开发领域
  18. 如何用java实现发邮件功能
  19. 记录 支付宝口碑--商户会员卡 开发历程
  20. JQ动画和特效轮播图

热门文章

  1. 基于三相VSR的SVPWM调制
  2. 晶振与晶体的参数详细介绍
  3. HCNP——RIPv1和RIPv2概况
  4. 主Module(app)直接跳转到子Module,子Module跳转到主Module(app)要借助Router
  5. Python自学指南-你好啊!Python
  6. 《Python编程快速上手——让繁琐的工作自动化》读书笔记4
  7. Java解析Excel 获取文本和图片信息
  8. 制造业数字孪生四大典型应用展示
  9. 计算机组成原理 总线与微命令实验
  10. 棒球·飞盘·MLB棒球创造营