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

这篇具有很好参考价值的文章主要介绍了从构建区块链理解区块链概念。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

import hashlib
import json
from datetime import time
from urllib.parse import urlparse
from uuid import uuid4

import requests
from flask import Flask, jsonify, request


class Blockchain(object):
    def __init__(self):
        # 当前交易的列表
        self.current_transactions = []
        # 区块的链
        self.chain = []
        # 共识机制的节点set
        self.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 = 1

        while 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 correct
            if block["previous_hash"] != self.hash(last_block):
                return False

            # Check that the Proof of Work is correct
            if not self.valid_proof(last_block["proof"], block["proof"]):
                return False

            last_block = block
            current_index += 1

        return True

    def resolve_conflicts(self):
        """
        共识算法解决冲突
        使用网络中最长的链.
        :return: <bool> True 如果链被取代, 否则为False
        """

        neighbours = self.nodes
        new_chain = None

        # We're only looking for chains longer than ours
        max_length = len(self.chain)

        # Grab and verify the chains from all the nodes in our network
        for 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 valid
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain

        # Replace our chain if we discovered a new, valid chain longer than ours
        if new_chain:
            self.chain = new_chain
            return True

        return False

    def 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 block

    def 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

    @property
    def last_block(self):
        return self.chain[-1]

    @staticmethod
    def 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 hashes
        block_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 = 0
        while self.valid_proof(last_proof, proof) is False:
            proof += 1

        return proof

    @staticmethod
    def 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 data
    required = ["sender", "recipient", "amount"]
    if not all(k in values for k in required):
        return "Missing values", 400

    # Create a new Transaction
    index = 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_block
    last_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 chain
    block = 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", 400

    for 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), 200


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

文章来源地址https://www.toymoban.com/news/detail-517555.html

到了这里,关于从构建区块链理解区块链概念的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 用Python实现概率矩阵分解(PMF)算法在MovieLens ml-100k数据集上构建精确的推荐系统:深入理解GroupLens数据的操作

    第一部分:推荐系统的重要性以及概率矩阵分解的介绍 在如今的数字化时代,推荐系统在我们的日常生活中起着重要的作用。无论我们在哪个电商网站上购物,哪个音乐平台听歌,或者在哪个电影网站看电影,都会看到推荐系统的身影。它们根据我们的喜好和行为,向我们推

    2024年02月15日
    浏览(29)
  • 区块链技术与应用-----区块链概念

    一,智能社会与区块链技术 当前我们进入智能化社会发展时期,新兴的5G,量子计算,云计算,物联网,人工智能,区块链等新兴IT技术,将支撑人类迈入智能化社会。区块链作为智能化社会的关键技术之一,其核心价值是实现社会关系运行的智能化。 二,区块链的概念与体

    2024年02月07日
    浏览(36)
  • 【概念】区块链中账本是什么?通用区块链平台账本概念介绍,一个谁都能看懂的账本概念

    目录 前言 举个例子 账本在不同链中担任什么角色 联盟链 公有链 私有链 随着区块链的发展,目前国内也掀起了一阵区块链的热潮,无论是金融、信任、交易、溯源等领域都是非常受欢迎,慢慢的我们也将成为第一个吃螃蟹的人,本篇文章主要是与大家一起聊聊什么是区块链

    2023年04月10日
    浏览(29)
  • 《区块链原理与技术》学习笔记(一)——区块链概念和区块链共识机制

    《区块链原理与技术》专业课学习笔记 第一部分 一、概论 1.什么是区块链 2.区块链与比特币的关系 2.1 区块链是比特币的底层技术,是比特币的核心基础与架构 2.2 区块链不止是比特币 3 区块链的特点 3.1去中心化 3.2 透明性 3.3 不可篡改性 3.4 多方共识 4 区块链的分类 二、区

    2024年02月04日
    浏览(34)
  • 区块链基础概念

    为了解决网络应用中过分依赖服务端的状况,出现了点对点( Peer to Peer, P2P )应用 在这类应用中并不存在对网络完全控制的中心节点 其中部分节点挂掉,并不影响整个 P2P 络的运行,这类应用就称为去中心化应用(Decentralized Application, DApp )。 在DApp中并没有中心服务器来协

    2024年02月03日
    浏览(28)
  • 区块链 技术 基本概念

    1.区块链 区块链(Blockchain) 最早在 2008 年被提出,本质上是一 个去中心化的分布式账本(Distributed Ledger)技术。 交易(Transaction) :指使区块链分布式账本状态改变的一次操作,如添加一条记录或者是一笔在两个账户之间的转账操 作。 区块(Block) :用于记录一段时间内

    2024年01月17日
    浏览(33)
  • 【区块链基本概念】

    工作需求对于区块链的简单理解 可以理解为去中心化(比如淘宝)的分布式账本数据库,这里的去中心化,可以先暂时理解为去的是技术中心,管理中心可以不去掉,比特币区块链是两个中心都去掉了 账本中的每一条记录在网络的世界里需要一定的形式进行存储,那在区块

    2024年01月18日
    浏览(31)
  • 区块链相关概念

    区块链是什么,就算是做计算机技术开发的程序员,100个当中都没有几个能把这个概念理解明白,更不要说讲清楚了。那对于普通人来说,就更扯了。 除了“挖矿”表面意思似乎比较好理解外,其他的基础概念真TMD绕。 去中心化、共识机制、NFT、智能合约、Gas 等基础概念随

    2024年04月28日
    浏览(19)
  • 区块链概念集合

    一个区块包含了一组有序的交易。他们以加密的方式与前一个区块相连,并且他们也会跟后续的区块相连。在这个链条中的第一个区块被称为  创世区块 。区块是由排序服务创建的,并且由 Peer 节点进行验证和提交。后一区块存储着前一区块的hash值。 B0是创世区块,区块

    2023年04月09日
    浏览(20)
  • 区块链入门二:概念篇

    区块链技术是由多方共同记录和维护的一个分布式数据库,通过哈希索引形成一种链状结构,数据的记录和定义 维护通过密码学技术来保护其完整性,使得任何一方难以篡改、抵赖、造假。 关键技术:分布式存储 加密算法 点对点传输 共识机制 特性:分布式、可共享、隐私

    2024年02月02日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包