用不到50行的Python代码构建最小的区块链

yizhihongxing

下面是“用不到50行的Python代码构建最小的区块链”的完整攻略。

1. 准备工作

我们需要在本地安装Python3和Flask框架。

2. 创建一个最小的区块链

我们需要定义一些模块,包括区块、链和挖矿。具体代码如下:

import datetime
import hashlib
import json
from flask import Flask, jsonify

class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        block_string = json.dumps(self.__dict__, sort_keys=True)
        return hashlib.sha256(block_string.encode()).hexdigest()

class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]

    def create_genesis_block(self):
        return Block(0, datetime.datetime.now(), "Genesis Block", "0")

    def get_latest_block(self):
        return self.chain[-1]

    def add_block(self, new_block):
        new_block.previous_hash = self.get_latest_block().hash
        new_block.hash = new_block.calculate_hash()
        self.chain.append(new_block)

    def is_valid_chain(self):
        for i in range(1, len(self.chain)):
            current_block = self.chain[i]
            previous_block = self.chain[i-1]
            if current_block.hash != current_block.calculate_hash():
                return False
            if current_block.previous_hash != previous_block.hash:
                return False
        return True

    def __str__(self):
        return json.dumps([block.__dict__ for block in self.chain], indent=2)

blockchain = Blockchain()

class Mining:
    @staticmethod
    def mine_block(data):
        new_block = Block(len(blockchain.chain), datetime.datetime.now(), data, blockchain.get_latest_block().hash)
        blockchain.add_block(new_block)

app = Flask(__name__)

@app.route('/')
def index():
    return "Welcome to the blockchain!"

@app.route('/blockchain', methods=['GET'])
def get_blockchain():
    return blockchain.__str__()

@app.route('/mine_block/<data>', methods=['GET'])
def mine_block(data):
    Mining.mine_block(data)
    return "Block mined and added to the blockchain!"

if __name__ == '__main__':
    app.run(debug=True, port=5000)

3. 运行应用程序

运行上述代码后,在浏览器中访问http://localhost:5000/,即可看到“Welcome to the blockchain!”的欢迎信息。

此时,我们已经成功创建了一个最小的区块链,并可以通过访问http://localhost:5000/blockchain获取到区块链的详细信息。

4. 挖掘新块

我们可以通过访问http://localhost:5000/mine_block/<data>来挖掘一个新块,并将其添加到区块链中。

例如,我们访问http://localhost:5000/mine_block/Hello%20World!即可挖掘一个包含“Hello World!”数据的新块。

5. 示例说明

下面是两个关于如何使用该区块链的示例说明:

示例1

我们可以用这个区块链来记录一些重要事件的发生时间,如下所示:

@app.route('/event/<event_name>', methods=['POST'])
def add_event(event_name):
    event_time = datetime.datetime.now()
    Mining.mine_block(f"{event_name} occurred at {event_time}.")
    return "Event added to the blockchain!"

这个路由可以将一个事件的名称作为URL参数传递,然后在区块链上创建一个包含事件名称和发生时间的新块。

示例2

我们可以用这个区块链来记录一些重要的交易,如下所示:

class Transaction:
    def __init__(self, sender, receiver, amount):
        self.sender = sender
        self.receiver = receiver
        self.amount = amount

transactions = []

@app.route('/transaction', methods=['POST'])
def add_transaction():
    data = request.get_json()
    new_transaction = Transaction(data['sender'], data['receiver'], data['amount'])
    transactions.append(new_transaction)
    return "Transaction added to the pending transactions!"

@app.route('/mine_transactions', methods=['GET'])
def mine_transactions():
    Mining.mine_block(json.dumps([transaction.__dict__ for transaction in transactions]))
    transactions.clear()
    return "Transactions mined and added to the blockchain!"

@app.route('/pending_transactions', methods=['GET'])
def get_pending_transactions():
    return json.dumps([transaction.__dict__ for transaction in transactions])

这些路由允许我们添加新的交易到待处理的交易列表中,在适当的时候挖掘这些交易,并将它们添加到区块链中。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:用不到50行的Python代码构建最小的区块链 - Python技术站

(0)
上一篇 2023年6月2日
下一篇 2023年6月2日

相关文章

  • python 正则表达式如何实现重叠匹配

    Python正则表达式中的重叠匹配是指一个字符串中有多个子字符串都能匹配同一个正则表达式,但是这些子字符串之间可能存在重叠的部分。下面是实现重叠匹配的两个示例: 示例一 当我们需要匹配一个长字符串中可能出现的重叠子字符串时,我们可以使用正则表达式中的“|”(或运算符)以及“(?=(regex))”(正则表达式中的前瞻)结合使用。具体的步骤如下: 假设需要匹配…

    python 2023年6月3日
    00
  • 编写每5分钟执行一次的python脚本

    【问题标题】:write python script that is executed every 5 minutes编写每5分钟执行一次的python脚本 【发布时间】:2023-04-04 06:10:01 【问题描述】: 我需要编写一个在启动时自动启动并在树莓派上每 5 分钟执行一次的 Python 脚本。如何才能做到这一点?特别是,我怎样才能避免让脚…

    Python开发 2023年4月6日
    00
  • Python常见文件操作的函数示例代码

    下面是Python常见文件操作的函数示例代码的完整攻略。 1. 打开文件 使用Python打开文件可以使用open()函数,它需要传入两个参数:文件名和文件打开模式。 file = open(‘example.txt’, ‘r’) 上面的代码打开了一个名为”example.txt”的文件,并将其赋值给变量file。这里的打开模式是r,表示读取文件。除了读取文…

    python 2023年5月31日
    00
  • Python 3 到 2 等效代码

    【问题标题】:Python 3 to 2 equivalent codePython 3 到 2 等效代码 【发布时间】:2023-04-05 16:15:01 【问题描述】: 这是来自 Ken Lambert 的书,基于 Python 3。 print(‘The median is’, end=” “) Python 2 中的等价物是什么?我认为是 ‘en…

    Python开发 2023年4月5日
    00
  • python3获取当前文件的上一级目录实例

    要获取当前文件的上一级目录,可以使用Python的标准库os中的path模块。 具体的步骤如下: 1.导入Python中的os模块 import os 2.使用os.path模块中的dirname()方法获取当前文件的绝对路径 current_dir = os.path.abspath(__file__) 其中__file__表示当前文件的路径,os.pat…

    python 2023年6月2日
    00
  • python中time tzset()函数实例用法

    当我们使用 Python 进行时间计算时,时区始终是一个关键的问题。Python 的 time 模块提供了一个 tzset() 函数,用于设置当前系统的本地时区信息。本篇文章将详细讲解 Python 中 time tzset() 函数的用法。 函数参数 此函数不接受参数。 示例1 以下示例展示了如何在 Python 中使用 tzset() 函数设置本地时区信…

    python 2023年6月3日
    00
  • 几种常见的Python数据结构

    摘要:本文主要为大家讲解在Python开发中常见的几种数据结构。 本文分享自华为云社区《Python的常见数据结构》,作者: timerring 。 数据结构和序列 元组 元组是一个固定长度,不可改变的Python序列对象。创建元组的最简单方式,是用逗号分隔一列值: In [1]: tup = 4, 5, 6 当用复杂的表达式定义元组,最好将值放到圆括号内,…

    python 2023年5月8日
    00
  • python中嵌套函数的实操步骤

    下面是关于Python中嵌套函数(Nested Function)的实操步骤的完整攻略。 1. 什么是Python中的嵌套函数? 在Python中,嵌套函数是定义在函数中的函数。即在函数内部定义一个函数,这个内部函数就是一个嵌套函数。这样,外部的函数就成为了嵌套函数的容器。 嵌套函数的好处在于可以封装、隐藏子函数的实现细节,不会与全局变量等产生命名冲突,并且…

    python 2023年6月5日
    00
合作推广
合作推广
分享本页
返回顶部