• <option id="cacee"><noscript id="cacee"></noscript></option>
  • <table id="cacee"><noscript id="cacee"></noscript></table>
  • <td id="cacee"></td>
  • <option id="cacee"></option>
  • <table id="cacee"></table>
  • <option id="cacee"><option id="cacee"></option></option>
  • <table id="cacee"><source id="cacee"></source></table><td id="cacee"><rt id="cacee"></rt></td>
    <option id="cacee"><option id="cacee"></option></option>
     找回密碼
     立即注冊

    掃一掃,登錄網站

    首頁 百科 查看內容
    • 1840
    • 0
    • 分享到

    【編程技術】將區塊鏈作為API使用起來的代碼

    2020-4-1 08:50

    區塊鏈作為API使用起來

    使用Python的Flask框架。它是一個微型框架,它可以很容易地將端點映射到Python函數。這讓我們使用HTTP請求在web上與 Blockchain 進行交互。

    我們將創建三個方法:

    1. /transactions/new   創建一個新的交易到一個區塊。
    2. /mine   告訴我們的服務器去挖掘一個新的區塊。
    3. /chain 返回完整的 Blockchain 。

    設置Flask

    我們的“服務器”將在 Blockchain 網絡中形成單獨節點,創建一些樣板代碼如下所示:

    1.             import hashlib

    2.             import json

    3.             from textwrap import dedent

    4.             from time import time

    5.             from uuid import uuid4

    6.

    7.             from flask import Flask

    8.

    9.

    10.          class Blockchain(object):

    11.               …

    12.

    13.

    14.          # Instantiate our Node

    15.          app = Flask(__name__)

    16.

    17.          # Generate a globally unique address for this node

    18.          node_identifier = str(uuid4()).replace(‘-‘, ”)

    19.

    20.          # Instantiate the Blockchain

    21.          blockchain = Blockchain()

    22.

    23.

    24.          @app.route(‘/mine’, methods=[‘GET’])

    25.          def mine():

    26.              return “We’ll mine a new Block”

    27.

    28.          @app.route(‘/transactions/new’, methods=[‘POST’])

    29.          def new_transaction():

    30.              return “We’ll add a new transaction”

    31.

    32.          @app.route(‘/chain’, methods=[‘GET’])

    33.          def full_chain():

    34.              response = {

    35.                  ‘chain’: blockchain.chain,

    36.                  ‘length’: len(blockchain.chain),

    37.              }

    38.              return jsonify(response), 200

    39.

    40.          if __name__ == ‘__main__’:

    41.              app.run(host=’0.0.0.0′, port=5000)

    關于在上面代碼中添加的內容的簡要說明如下:

    • Line 15: 實例化節點。
    • Line 18: 為我們的節點創建一個隨機名稱。
    • Line 21: 實例化我們的Blockchain類。
    • Line 24–26: 創建/mine 端點,這是一個GET請求。
    • Line 28–30: 創建 /transactions/new 端點,這是一個POST 請求,因為我們將向它發送數據。
    • Line 32–38: 創建/chain端點,它返回完整的 Blockchain 。
    • Line 40–41: 在端口5000上運行服務器。

    交易端點

    這就是交易請求的樣子。這是用戶發送給服務器的內容:

    1.             {

    2.              “sender”: “my address”,

    3.              “recipient”: “someone else’s address”,

    4.              “amount”: 5

    5.             }

    由于已經有了將交易添加到區塊的類的方法,其余的都很簡單。讓我們編寫添加交易的函數:

    1.             import hashlib

    2.             import json

    3.             from textwrap import dedent

    4.             from time import time

    5.             from uuid import uuid4

    6.

    7.             from flask import Flask, jsonify, request

    8.

    9.             …

    10.

    11.           @app.route(‘/transactions/new’, methods=[‘POST’])

    12.          def new_transaction():

    13.              values = request.get_json()

    14.

    15.              # Check that the required fields are in the POST’ed data

    16.              required = [‘sender’, ‘recipient’, ‘amount’]

    17.              if not all(k in values for k in required):

    18.                  return ‘Missing values’, 400

    19.

    20.              # Create a new Transaction

    21.              index = blockchain.new_transaction(values[‘sender’], values[‘recipient’], values[‘amount’])

    22.

    23.              response = {‘message’: f’Transaction will be added to Block {index}’}

    24.              return jsonify(response), 201

    Amethod for creating Transactions

    挖礦端點

    挖礦端點必須做三件事:

    (1)計算工作量證明。

    (2)通過增加一筆交易,獎賞給礦工(也就是我們自己)一定量的數字貨幣

    (3)通過將新區塊添加到鏈中來鍛造區塊。

    1.             import hashlib

    2.             import json

    3.

    4.             from time import time

    5.             from uuid import uuid4

    6.

    7.             from flask import Flask, jsonify, request

    8.

    9.             …

    10.

    11.           @app.route(‘/mine’, methods=[‘GET’])

    12.          def mine():

    13.              # We run the proof of work algorithm to get the next proof…

    14.              last_block = blockchain.last_block

    15.              last_proof = last_block[‘proof’]

    16.              proof = blockchain.proof_of_work(last_proof)

    17.

    18.              # We must receive a reward for finding the proof.

    19.              # The sender is “0” to signify that this node has mined a new coin.

    20.              blockchain.new_transaction(

    21.                  sender=”0″,

    22.                  recipient=node_identifier,

    23.                  amount=1,

    24.              )

    25.

    26.              # Forge the new Block by adding it to the chain

    27.              previous_hash = blockchain.hash(last_block)

    28.              block = blockchain.new_block(proof, previous_hash)

    29.

    30.              response = {

    31.                  ‘message’: “New Block Forged”,

    32.                  ‘index’: block[‘index’],

    33.                  ‘transactions’: block[‘transactions’],

    34.                  ‘proof’: block[‘proof’],

    35.                  ‘previous_hash’: block[‘previous_hash’],

    36.              }

    37.              return jsonify(response), 200

    被挖掘出來的區塊的接收者是我們節點的地址。在這里所做的大部分工作只是與Blockchain class中的方法進行交互。在這一點上,我們已經完成了,并且可以開始與我們的 Blockchain 進行交互了。

    版權申明:本內容來自于互聯網,屬第三方匯集推薦平臺。本文的版權歸原作者所有,文章言論不代表鏈門戶的觀點,鏈門戶不承擔任何法律責任。如有侵權請聯系QQ:3341927519進行反饋。
    相關新聞
    發表評論

    請先 注冊/登錄 后參與評論

      回頂部
    • <option id="cacee"><noscript id="cacee"></noscript></option>
    • <table id="cacee"><noscript id="cacee"></noscript></table>
    • <td id="cacee"></td>
    • <option id="cacee"></option>
    • <table id="cacee"></table>
    • <option id="cacee"><option id="cacee"></option></option>
    • <table id="cacee"><source id="cacee"></source></table><td id="cacee"><rt id="cacee"></rt></td>
      <option id="cacee"><option id="cacee"></option></option>
      妖精视频