美文网首页区块链大学区块链研习社
通过构建区块链来学习区块链-2-transaction|mine

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

作者: 空乱木 | 来源:发表于2019-09-15 14:38 被阅读0次

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

    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
    }
    

    相关文章

      网友评论

        本文标题:通过构建区块链来学习区块链-2-transaction|mine

        本文链接:https://www.haomeiwen.com/subject/xsazyctx.html