区块链大学区块链研习社

通过构建区块链来学习区块链-2-transaction|mine

2019-09-15  本文已影响0人  空乱木

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

步骤2:将区块链作为API

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

我们将创建三个方法:

设置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)

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

交易的端点

这就是事务请求的样子。它是用户发送给服务器的:

{
 "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端点就是奇迹发生的地方,而且很简单。它必须做三件事:

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请求来挖掘一个块:

image.png

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

image.png

如果您不使用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
}
上一篇下一篇

猜你喜欢

热点阅读