构建区块链 python(二)

步骤2:将我们的区块链作为API

我们将使用Python Flask框架。这是一个微框架,可以轻松将端点映射到Python函数。这使我们可以使用HTTP请求通过Web与我们的区块链进行对话。

我们将创建三种方法:

  1. /transactions/new 创建一个新的交易块
  2. /mine 告诉我们的服务器挖掘一个新块。
  3. /chain 返回完整的区块链

设置Flask
我们的“服务器”将在我们的区块链网络中形成单个节点。让我们创建一些样板代码:

import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4

from flask import Flask


class Blockchain(object):
    ...


# Instantiate our Node
app = Flask(__name__)

# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')

# Instantiate the Blockchain
blockchain = Blockchain()

#创建/mine 端点,这是一个 GET 请求。
@app.route('/mine', methods=['GET'])
def mine():
    return "We'll mine a new Block"

#创建/transactions/new 端点,这是一个 POST 请求,因为我们将向它发送数据。
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    return "We'll add a new transaction"#创建/chain 端点,返回完整的区块链
@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)

交易端点

这就是交易请求的样子。这是用户发送到服务器的内容:

{
 "sender": "my address",
 "recipient": "someone else's address",
 "amount": 5
}

由于我们已经有了用于将事务添加到块中的类方法,因此其余操作很容易。让我们编写添加事务的函数:

import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4

from flask import Flask, jsonify, request

...

@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

(一种创建事务的方法)

采矿终点

我们的挖掘终点是魔术发生的地方,这很容易。它必须做三件事:

  1. 计算工作量证明
  2. 通过添加授予我们1个硬币的交易来奖励矿工(us)
  3. 通过将新块添加到链中来伪造
import hashlib
import json

from time import time
from uuid import uuid4

from flask import Flask, jsonify, request

...

@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)

    # We must receive a reward for finding the proof.
    # The sender is "0" to signify that this node has mined a new coin.
    blockchain.new_transaction(
        sender="0",
        recipient=node_identifier,
        amount=1,
    )

    # Forge the new Block by adding it to the chain
    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

注意,已开采区块的收件人是我们节点的地址。而且,我们在这里所做的大部分工作只是与Blockchain类上的方法进行交互。至此,我们完成了,可以开始与我们的区块链进行交互了。

发布了77 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39682037/article/details/105461495
今日推荐