話題のブロックチェーンに関するメモ.元ネタは
Wei-Meng Lee, Beginning Ethereum Smart Contracts Programming With Examples in Python, Solidity and JavaScript, Apress, 2019, Chapter 2
ここではお金(コイン)の送受信機能のみをもつ,ごく簡単なブロックチェーンをpythonで作成する.署名やマークル木やスクリプトなどは扱わない.セグウィットももちろん扱わない.
コインの送受信に最低限必要な情報は,誰が誰にいくら送ったか(トランザクション)である.これを tx という辞書で
tx = { 'sender': 送り手の名前, 'recipient': 受け手の名前, 'amount': 金額 }
と表す.複数のトランザクションはリストでまとめて
tx_list = [tx1, tx2, ...]
とする.トランザクションはflaskを使ってHTTPリクエストによりポストする.
from flask import Flask, jsonify, request app = Flask(__name__) tx_list = [] # トランザクション生成 @app.route("/tx", methods=['POST']) def tx(): tx = request.get_json() fields = ['sender', 'recipient', 'amount'] if (not all(k in tx for k in fields)) or (tx['amount'] <= 0): message = 'Input Error' status_code = 400 else: tx_list.append(tx) message ='Tx added' status_code = 201 responce = {'message': message, 'tx_list': tx_list} return jsonify(responce), status_code if __name__ == "__main__": app.run()
トランザクションのチェックはsender, recipient, amountが存在するかどうかと,amountがマイナスでないことだけにした.
> curl -X POST -H "Content-Type: application/json" -d "{\"sender\": \"Kato\", \"recipient\": \"Yamada\", \"amount\": 17}" "http://localhost:5000/tx" | jq
結果
{ "message": "Tx added", "tx_list": [ { "amount": 23, "recipient": "Sato", "sender": "Yamada" } ] }
もう一度トランザクションを生成
> curl -X POST -H "Content-Type: application/json" -d "{\"sender\": \"Kato\", \"recipient\": \"Yamada\", \"amount\": 17}" "http://localhost:5000/tx" | jq
結果
{ "message": "Tx added", "tx_list": [ { "amount": 23, "recipient": "Sato", "sender": "Yamada" }, { "amount": 17, "recipient": "Yamada", "sender": "Kato" } ] }