使用了Python语言和Flask框架。创建一个区块链网络,允许用户通过HTTP请求进行交互,如包括创建区块链、挖矿、验证区块链等功能。(持续更新)

embedded/2024/9/22 16:42:29/

目录

大概来说:

二、代码注释

1.添加交易方法(add_transaction函数)

2.添加新的节点(add_node 函数)

3、替换链的方法(replace_chain函数)

总结


大概来说:

  1. 定义了一个名为Blockchain的类,用于构建区块链
  2. 在Blockchain类中,定义了创建区块、获取上一个区块、工作量证明、哈希计算、验证区块链等方法。
  3. 使用Flask框架创建了一个Web应用,提供了挖矿、获取整个区块链和验证区块链的API接口。
  4. 运行Web应用,监听5000端口。

一、代码展示

# Module 1 - Create a Cryptocurrency
# To be installed:
# Flask==0.12.2: pip install Flask==0.12.2
# Postman HTrp Client: https://www.getpostman.com
# requests==2.18.4: pip install requests==2.18.4

# 时间戳
import datetime
import hashlib
import json

# Flask可以定义Web应用的路由(URL到Python函数的映射),并处理HTTP请求和响应。
# jsonify是一个函数,用于将Python对象转换为JSON格式的响应。
# 当你在Flask路由函数中返回一个jsonify对象时,Flask会自动将该对象对应的数据转换为JSON格式,
# 并设置合适的HTTP响应头,以便客户端可以正确解析响应内容。
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse

# 1******Building a Blockchain

class Blockchain:
    # 初始化区块链
    def __init__(self):
        self.transactions = []  # 存储交易信息
        self.chain = []  # 存储区块链
        self.create_block(proof=1, previous_hash='0')  # 创建创世区块
        self.nodes = set()  # 存储网络节点

    # 创建一个新的区块
    def create_block(self, proof, previous_hash):
        block = {
            'index': len(self.chain) + 1,
            'timestamp': str(datetime.datetime.now()),
            'proof': proof,
            'previous_hash': previous_hash,
            'transactions': self.transactions
        }
        self.transactions = []  # 清空交易列表
        self.chain.append(block)  # 将新区块添加到链中
        return block  # 返回创建的区块

    # 获取链中最后一个区块
    def get_previous_block(self):
        return self.chain[-1]

    # 工作量证明(Proof of Work)
    def proof_of_work(self, previous_proof):
        new_proof = 1
        check_proof = False
        while check_proof is False:
            hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
            if hash_operation[:4] == '0000':
                check_proof = True
            else:
                new_proof += 1
        return new_proof

    # 哈希函数,用于计算区块的哈希值
    def hash(self, block):
        encode_block = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(encode_block).hexdigest()

    # 验证区块链的有效性
    def is_chain_valid(self, chain):
        previous_block = chain[0]
        block_index = 1
        while block_index < len(chain):
            block = chain[block_index]
            if block['previous_hash'] != self.hash(previous_block):
                return False
            previous_proof = previous_block['proof']
            proof = block['proof']
            hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
            if hash_operation[:4] != '0000':
                return False
            previous_block = block
            block_index += 1
        return True

    # 添加交易
    def add_transaction(self, sender, receiver, amount):
        self.transactions.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        previous_block = self.get_previous_block()
        return previous_block['index'] + 1

    # 添加网络节点
    def add_node(self, address):
        parsed_url = urlparse(address)
        self.nodes.add(parsed_url.netloc)

    # 替换链,如果找到更长的链则替换当前链
   def replace_chain(self):
        network = self.nodes
        longest_chain = None
        max_length = len(self.chain)
    
        for node in network:
            try:
                response = requests.get(f'http://{node}/get_chain')
                response.raise_for_status()  # 这将抛出异常,如果请求失败
            except requests.exceptions.RequestException as e:
                print(f"Failed to get the chain from {node}. Exception: {e}")
                continue
    
            if response.status_code == 200:
                length = response.json()['length']
                chain = response.json()['chain']
                if length > max_length and self.is_chain_valid(chain):
                    max_length = length
                    longest_chain = chain
    
        if longest_chain:
            self.chain = longest_chain
            return True
        return False

# Part 2 - Mining our Blockchain

# Creating a Web App
app = Flask(__name__)

# Creating a Blockchain
blockchain = Blockchain()

# Mining a new block
@app.route('/mine_block', methods=['GET'])
def mine_block():
    previous_block = blockchain.get_previous_block()
    previous_proof = previous_block['proof']
    proof = blockchain.proof_of_work(previous_proof)
    previous_hash = blockchain.hash(previous_block)
    block = blockchain.create_block(proof, previous_hash)
    response = {
        'message': 'Congratulation, you just mined a block',
        'index': block['index'],
        'timestamp': block['timestamp'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash']
    }
    return jsonify(response), 200

# Getting the full Blockchain
@app.route('/get_chain', methods=['GET'])
def get_chain():
    response = {
        'chain': blockchain.chain,
        'length': len(blockchain.chain)
    }
    return jsonify(response), 200

# Checking if the Blockchain
@app.route('/is_valid', methods=['GET'])
def get_valid():
    is_valid = blockchain.is_chain_valid(blockchain.chain)
    if is_valid:
        response = {'message': 'All good. The Blockchain is valid.'}
    else:
        response = {'message': 'Houston, we have a problem. The Blockchain is not valid.'}
    return jsonify(response), 200

# 运行Flask应用
app.run(host='0.0.0.0', port=5000)

二、代码注释

注:下面对三个函数进行讲解,其他函数的详解在我的另外一篇我的文章里“创建一个简单的区块链,并使用 Flask 框架提供一个简单的 Web 接口来与区块链交互。-CSDN博客”add_transaction 函数、add_node 函数、replace_chain 函数

1.添加交易方法(add_transaction函数)

这个函数用于向区块链中添加交易记录。它接受三个参数:发送者(sender)、接收者(receiver)和交易金额(amount)。该函数将交易信息以字典的形式添加到当前区块的交易列表中,并返回下一个区块的索引值。

  # 添加交易
#创建一个字典,包含发送者、接收者和金额信息,然后将这个字典添加到self.transactions
列表中。def add_transaction(self, sender, receiver, amount):self.transactions.append({'sender': sender,'receiver': receiver,'amount': amount})
#获取当前区块链的最后一个区块,并返回它的索引加1,这个索引加1将是下一个区块的索引。        previous_block = self.get_previous_block()return previous_block['index'] + 1

2.添加新的节点(add_node 函数)

这个函数用于向网络中添加新的节点。它接受一个参数:节点地址(address)。该函数使用 urlparse 函数解析地址,并将解析后的主机名(netloc)添加到节点集合中。

# 添加网络节点

def add_node(self, address):

# 使用urlparse函数解析提供的地址,这个函数是Python内置的url解析模块urllib.parse中的一个函数
        parsed_url = urlparse(address)

# 通过urlparse得到的parsed_url对象中,netloc属性包含了解析后的网络位置,通常是主机名(有时也包括端口号)

# 例如,如果提供的地址是 'http://localhost:5000',那么parsed_url.netloc将会是 'localhost:5000'

# 将解析得到的网络位置添加到self.nodes集合中 # self.nodes是一个集合(set),它自动去除了重复的元素,并且保持了添加的顺序无关性
        self.nodes.add(parsed_url.netloc)

3、替换链的方法(replace_chain函数)

这个函数函数用于替换当前的区块链。它首先获取网络中的所有节点,然后遍历每个节点,通过发送 HTTP 请求获取其区块链信息。如果收到有效的响应,并且该链的长度大于当前链的长度且有效,则将最长链替换为当前链。最后,根据是否成功替换链,返回相应的布尔值。

def replace_chain(self):
    # 获取当前区块链网络中所有节点的集合
    network = self.nodes
    
    # 初始化最长链为 None,表示我们尚未找到比当前链更长的链
    longest_chain = None
    
    # 获取当前链的长度,用于比较
    max_length = len(self.chain)
    
    # 遍历网络中的每个节点
    for node in network:
        try:
            # 尝试从每个节点获取区块链信息
            response = requests.get(f'http://{node}/get_chain')
            # 如果请求成功,但没有返回成功的状态码(如200),将抛出异常
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            # 如果请求失败(例如,节点不可达或网络问题),打印错误并继续下一个节点
            print(f"Failed to get the chain from {node}. Exception: {e}")
            continue
    
        # 如果请求成功且状态码为200
        if response.status_code == 200:
            # 从响应中获取区块链的长度和链数据
            length = response.json()['length']
            chain = response.json()['chain']
            
            # 如果获取的链比当前已知的最长链还长,并且验证该链是有效的
            if length > max_length and self.is_chain_valid(chain):
                # 更新最长链和最大长度
                max_length = length
                longest_chain = chain
    
    # 在检查完所有节点后,如果找到了更长的链,就用它替换当前链
    if longest_chain:
        self.chain = longest_chain
        return True  # 返回 True 表示链已被替换
    else:
        return False  # 如果没有找到更长的链,返回 False 表示链没有被替换


总结

这段代码定义了一个Blockchain类,它包含了创建区块、验证工作量证明、添加交易、添加网络节点、替换链等方法。然后,使用Flask框架创建了一个Web应用,通过定义路由来处理不同的HTTP请求,如挖掘新区块、获取区块链信息、验证区块链的有效性等。最后,启动了Flask应用,使其在端口5000上监听请求。


http://www.ppmy.cn/embedded/17294.html

相关文章

springboot+java海洋馆门票预订网上商城线上销售系统

有代码视频讲解参考,对项目进行黑盒测试和白盒测试,搭建开发环境、编写相关文档、搭建对象、数据库设计、编写功能代码、设计网页、用例测试&#xff0c;代码的整合打包&#xff0c;完成服务器的相关配置&#xff0c;最后得到项目成品。 ,软件开发源码包部署调试,包修改标题和时…

【26考研】考研备考计划4.22开始

A海海: 408:重中之重&#xff0c;和数学同等地位&#xff01;越早开始越好&#xff01;前期直接跟着王道视频课学习&#xff0c;教材直接用王道四本书&#xff0c;顺序结构的话按照数据结构-计算机组成原理-操作系统-计算机网络的顺序来学习。刚开始学会感觉很吃力很难&#xf…

jmeter安装和简单使用

jmeter安装和简单使用 1. 安装 jmeter是基于Java开发的测试应用&#xff0c;其运行依赖于java环境&#xff0c;所以在下载运行jmeter前&#xff0c;先确保本机已经安装jdk或者jre&#xff0c;安装jdk步骤此处不描述。 下载jmeter&#xff1a; jmeter是Apache旗下的产品&…

mysql的约束和表关系

根据查询的结果&#xff0c;复制出一个新表 create table newTable AS select * from oldTable; create table newPeople AS select * from day2_test.people; 约束 引入&#xff1a;如果某一列如id列&#xff0c;有重复的数据&#xff0c;无法准确定位&#xff0c;有的列有空…

手机在网时长查询API接口的业务场景

手机号在网时长接口&#xff0c;作为一项高效实用的数据服务工具&#xff0c;能够全面支持中国移动、中国电信和中国联通三大运营商的手机号码查询&#xff0c;实时获取并精确计算用户的手机号在网使用时长&#xff0c;并以时间区间的形式进行反馈。这一功能不仅有助于企业实现…

Chrome插件开发的教程,附属详细的案例

Chrome插件开发是一个相对复杂的过程&#xff0c;涉及多个步骤和组件。以下是一个详细的Chrome插件开发教程&#xff0c;包括一个具体的案例&#xff0c;帮助你理解整个开发流程。 1. 了解Chrome插件的基本结构 Chrome插件主要由几个关键部分组成&#xff1a; manifest.json…

leetcode多个测试用例之间相互影响导致提交失败

背景 在做一道easy题&#xff0c;二叉树的中序遍历&#xff0c;我提交的代码如下 from typing import (Optional,List )# Definition for a binary tree node. class TreeNode:def __init__(self, val0, leftNone, rightNone):self.val valself.left leftself.right right…

docker 简单使用

docker 简单使用 docker基础命令 在Docker Hub上搜索镜像 docker search <镜像名> 拉取镜像 docker pull <镜像名> 查看全部镜像 docker images 查看指定镜像 docker images <镜像名> 查看容器日志 docker logs <容器名或容器ID> 列出容器…