用python搭建简单的区块链

以下是使用Python编写简单的区块链的步骤:

  1. 安装需要的库
pip install hashlib
pip install flask

  1. 创建区块链的类
import hashlib
import json
from time import time

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

        # 创建创世块
        self.new_block(previous_hash=1, proof=100)

    def new_block(self, proof, previous_hash=None):
        """
        创建新的区块
        :param proof:  工作量证明算法提供的证明
        :param previous_hash: (Optional)  前一个区块的 hash 值
        :return:  新的区块
        """

        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }

        # 重置当前交易列表
        self.current_transactions = []

        self.chain.append(block)
        return block

  1. 创建创世块和区块的添加方法
class Blockchain:
    ...
    
    def new_block(self, proof, previous_hash=None):
        ...
        
    def new_transaction(self, sender, recipient, amount):
        """
        创建新的交易信息,将交易信息添加到当前交易列表
        :param sender:  发送者地址
        :param recipient:  接收者地址
        :param amount:  金额
        :return:  保存这个交易信息的区块的索引
        """
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })

        return self.last_block['index'] + 1

    @staticmethod
    def hash(block):
        """
        给一个区块生成 SHA-256 值
        :param block:  区块
        :return: 
        """

        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

    @property
    def last_block(self):
        return self.chain[-1]
    
    def proof_of_work(self, last_proof):
        """
        简单的工作量证明算法:
         - 查找一个 p' 使得 hash(pp') 以4个0开头
         - p 是上一个区块的证明, p' 是当前的证明
        :param last_proof: 
        :return: 
        """

        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:  Previous Proof
        :param proof:  Current Proof
        :return:  True if correct, False if not.
        """

        guess = f'{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

  1. 创建Flask Web应用程序
from uuid import uuid4

from flask import Flask, jsonify, request

# 创建一个节点名称
node_identifier = str(uuid4()).replace('-', '')

# 实例化flask
app = Flask(__name__)

# 实例化区块链
blockchain = Blockchain()


@app.route('/mine', methods=['GET'])
def mine():
    # 挖掘新的区块
    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,
    )

    # 添加新的区块到区块链中
    previous_hash = blockchain.hash(last_block)
    block = blockchain.new_block(proof, previous_hash)

    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('/transactions/new', methods=['POST'])
def new_transaction():
    values = request.get_json()

    # 检查请求中的必需字段是否在POST中
    required = ['sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # 创建一个新的交易
    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('/chain', methods=['GET'])
def full_chain():
    response = {
        'chain': blockchain.chain,
        'length': len(blockchain.chain),
    }
    return jsonify(response), 200


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

  1. 运行应用程序并测试

运行应用程序:

$ python blockchain.py

使用POST请求创建新的交易:

import requests

url = "http://localhost:5000/transactions/new"
values = {
    "sender": "my address",
    "recipient": "someone else's address",
    "amount": 5
}

response = requests.post(url, json=values)
print(response)

使用GET请求获取完整的区块链:

import requests

url = "http://localhost:5000/chain"

response = requests.get(url)
print(response.json())

使用GET请求挖掘新的区块:

import requests

url = "http://localhost:5000/mine"

response = requests.get(url)
print(response.json())

以上就是使用Python编写简单的区块链的过程。当然,这只是一个简单的示例,实际上实现一个真正有用的区块链需要更多的工作和细节。

你可能感兴趣的:(python源代码,python,区块链,开发语言)