簡単なブロックチェーンをつくる(その4 ブロックチェーンのクラス化)

 ブロックチェーンのクラスをつくって前回のプログラムを少し整理する.

import hashlib, json

from time import time
from flask import Flask, jsonify, request

app = Flask(__name__)

class Blockchain():

    def __init__(self):
        # ブロックチェーン本体
        self.blockchain = []
        # 1ブロックのトランザクションリスト
        self.tx_list = []
        # ジェネシスブロックの"前ブロック"のハッシュ値
        self.prev_block_hash = hashlib.sha256("genesis".encode()).hexdigest()

# ブロックチェーンインスタンス
bc = Blockchain()

# ブロック生成
@app.route("/block", methods=["GET"])
def block():
    nonce = 0
    block = {
        'index': len(bc.blockchain),
        'tiemstamp': time(),
        'tx_list': bc.tx_list,
        'nonce': nonce,
        'prev_block_hash': bc.prev_block_hash
    }

    # 次のブロック用に現在のブロックのハッシュを計算しておく
    bc.prev_block_hash = hashlib.sha256(json.dumps(block, sort_keys=True).encode()).hexdigest()

    # トランザクションリストをブロックに入れたのでクリア
    bc.tx_list = []

    # ブロックチェーンにブロックを追加
    bc.blockchain.append(block)

    return jsonify(bc.blockchain), 200

# トランザクション生成
@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:
        bc.tx_list.append(tx)
        message ='Tx added'
        status_code = 201

    responce = {'message': message}
    return jsonify(responce), status_code

if __name__ == "__main__":
    app.run()

出力は前回と同じなので省略.