通过构建区块链来学习区块链2transactionminechain

5次阅读

共计 3934 个字符,预计需要花费 10 分钟才能阅读完成。

原文链接:https://medium.com/@vanflymen/learn-blockchains-by-building-one-117428612f46

  • 将区块链作为 API
  • 创建新的 Transaction
  • 挖块处理
  • 与区块链交互

步骤 2: 将区块链作为 API

我们将使用 Python Flask 框架。它是一个微型框架,可以方便地将端点映射到 Python 函数。这允许我们使用 HTTP 请求在 web 上与区块链通信。

我们将创建三个方法:

  • /transaction/new 创建一个块的新事务。
  • /mine 来告诉我们的服务器挖掘一个新的块。
  • /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()


@app.route('/mine', methods=['GET’])
def mine():
    return "We'll mine a new Block”@app.route('/transactions/new', methods=['POST’])
def new_transaction():
    return "We'll add a new transaction”@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)

简单解释一下我们在上面添加的内容:

  • 第 15 行: 实例化我们的节点。阅读更多关于 Flask。
  • 第 18 行: 为节点创建一个随机名称。
  • 第 21 行: 实例化我们的区块链类。
  • 第 24-26 行: 创建 /mine 端点,它是一个 GET 请求。
  • 第 28-30 行: 创建 /transactions/new 端点,这是一个 POST 请求,因为我们将向它发送数据。
  • 第 32-38 行: 创建 /chain 端点,它返回完整的区块链。
  • 第 40-41 行: 在端口 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
Mining 端点

我们的 Mining 端点就是奇迹发生的地方,而且很简单。它必须做三件事:

  • 计算工作量的证明
  • 奖励矿商 (我们) 通过增加一个交易给予我们 1 枚硬币
  • 把新的 Block 加到链上
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

注意,挖掘块的收件人是我们节点的地址。我们在这里做的大部分只是和区块链类上的方法交互。现在,我们已经完成了,可以开始与区块链进行交互了。

步骤 3: 与区块链交互

您可以使用普通的旧式 cURL 或 Postman 通过网络与我们的 API 进行交互。
启动服务器:

$ python blockchain.py

* Running on [http://127.0.0.1:5000/](http://127.0.0.1:5000/) (Press CTRL+C to quit)

让我们尝试通过向 http://localhost:5000/mine 发出 GET 请求来挖掘一个块:

让我们创建一个新的事务,通过发送 POST 请求到 http://localhost:5000/transactions/new,其主体包含我们的事务结构:

如果您不使用 Postman,那么您可以使用 cURL 发出相同的请求:

$ curl -X POST -H "Content-Type: application/json" -d‘{
"sender":“d4ee26eee15148ee92c6cd394edd974e”,
"recipient": "someone-other-address”,"amount": 5
}' "[http://localhost:5000/transactions/new](http://localhost:5000/transactions/new)”

我重新启动服务器,挖掘了两个块,总共得到 3 个。让我们通过请求 http://localhost:5000/chain 来检查整个链:

{
  "chain": [
    {
      "index": 1,
      "previous_hash": 1,
      "proof": 100,
      "timestamp": 1506280650.770839,
      "transactions": []},
    {
      "index": 2,
      "previous_hash": "c099bc...bfb7",
      "proof": 35293,
      "timestamp": 1506280664.717925,
      "transactions": [
        {
          "amount": 1,
          "recipient": "8bbcb347e0634905b0cac7955bae152b",
          "sender": "0"
        }
      ]
    },
    {
      "index": 3,
      "previous_hash": "eff91a...10f2",
      "proof": 35089,
      "timestamp": 1506280666.1086972,
      "transactions": [
        {
          "amount": 1,
          "recipient": "8bbcb347e0634905b0cac7955bae152b",
          "sender": "0"
        }
      ]
    }
  ],
  "length": 3
}

本文由 Rebase 社区的 River 进行翻译和整理,有问题请加微信 syuukawa,备注:区块链

正文完
 0