Block ChainPython

【Python】ブロックチェーンの実装方法_3 トランザクションの定義

Block Chain

どうも、月見(@Suzuka14144156)です。

私は、ブロックチェーンに関する研究をしており、本ブログでは仮想通貨/暗号資産の情報を整理して発信しています。

今回は、Pythonでブロックチェーンを実際に実装していきたいと思います。

参考にした講座は以下のUdemyの講座です。

【教育・学習】資格・学習
総合情報サイト「コレダ!」がお届けする教育・学習における資格・学習の総合情報サイトです。

こちらの講座は、Pythonでスクラッチでブロックチェーンを実装するというものです。

Pythonの中級者以上の向けの講座となっています。

ブロックチェーンだけでなく、クラスを使ったコーディングを覚えたい方にもオススメの講座だと思います。

前回までの私の記事は、こちらです。

今回は、前回からの続きですので、お読みでない方は、ぜひ参考にしてみてください。

今回は、トランザクションの実装です。

トランザクションとは?

ノート, 日記, 論文, 空欄, 支配, マーカー, ブックマーク, 主催者, 個人的, カレンダー, 仕事
  • トランザクションとは、誰が誰にいくら送金したかの履歴

この情報をブロック上に保持することで、全取引履歴を分散したノード同士でその信頼性を担保します。

つまり、暗号資産をハッキングして、取引履歴を改ざん使用とすると、全ノードをハッキング(ビットコインでは51%攻撃が有名な例)し、書き換えなければなりません。

現実的には、そのようなことは不可能なので、ビットコインなどの暗号資産は信頼性を担保しています。

トランザクションの実装

では、実際にトランザクションを実装していきます。

トランザクションの中身は、以下3つとします。

  • 送信者
  • 受信者
  • 送金額

トランザクションのコード

    def add_transaction(self, sender_blockchain_address,
                        recipient_blockchain_address, value):
        transaction = utils.sorted_dict_by_key({
            'sender_blockchain_address': sender_blockchain_address,
            'recipient_blockchain_address': recipient_blockchain_address,
            'value': float(value)
        })
        self.transaction_pool.append(transaction)
        return True

トランザクションは、class BlockChain(object):のメソッドとして定義します。

add_transactionがコールされると以下3つがディクショナリー型で格納されます。

  • sender_blockchain_address’: sender_blockchain_address,
  • ‘recipient_blockchain_address’: recipient_blockchain_address,
  • ‘value’: float(value)

utils.py

import collections


def sorted_dict_by_key(unsorted_dict):
    return collections.OrderedDict(
        sorted(unsorted_dict.items(), key=lambda d: d[0]))

ディクショナリーのitemの順序を整列かさせるための関数です。

詳細は、以下の記事を参考にしてみてください。

blockchains.py

import hashlib
import json
import logging
import sys
import time

import utils

logging.basicConfig(level=logging.INFO, stream=sys.stdout)


class BlockChain(object):

    def __init__(self):
        self.transaction_pool = []
        self.chain = []
        self.create_block(0, self.hash({}))

    def create_block(self, nonce, previous_hash):
        block = utils.sorted_dict_by_key({
            'timestamp': time.time(),
            'transactions': self.transaction_pool,
            'nonce': nonce,
            'previous_hash': previous_hash
        })
        self.chain.append(block)
        self.transaction_pool = []
        return block

    def hash(self, block):
        sorted_block = json.dumps(block, sort_keys=True)
        return hashlib.sha256(sorted_block.encode()).hexdigest()

    def add_transaction(self, sender_blockchain_address,
                        recipient_blockchain_address, value):
        transaction = utils.sorted_dict_by_key({
            'sender_blockchain_address': sender_blockchain_address,
            'recipient_blockchain_address': recipient_blockchain_address,
            'value': float(value)
        })
        self.transaction_pool.append(transaction)
        return True


def pprint(chains):
    for i, chain in enumerate(chains):
        print(f'{"="*25} Chain {i} {"="*25}')
        for k, v in chain.items():
            if k == 'transactions':
                print(k)
                for d in v:
                    print(f'{"-"*40}')
                    for kk, vv in d.items():
                        print(f' {kk:30}{vv}')
            else:
                print(f'{k:15}{v}')
    print(f'{"*"*25}')


if __name__ == '__main__':
    block_chain = BlockChain()
    pprint(block_chain.chain)

    block_chain.add_transaction('A','B', 1.0)
    previous_hash = block_chain.hash(block_chain.chain[-1])
    block_chain.create_block(5, previous_hash)
    pprint(block_chain.chain)

    block_chain.add_transaction('C','D', 2.0)
    block_chain.add_transaction('X','Y', 3.0)
    previous_hash = block_chain.hash(block_chain.chain[-1])
    block_chain.create_block(2, previous_hash)
    pprint(block_chain.chain)

実行結果は、以下です。

トランザクションの中身に以下3つか含まれていることがわかります。

  • 送信者
  • 受信者
  • 送金額
========================= Chain 0 =========================
nonce          0
previous_hash  44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a
timestamp      1630801628.132861
transactions
*************************
========================= Chain 0 =========================
nonce          0
previous_hash  44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a
timestamp      1630801628.132861
transactions
========================= Chain 1 =========================
nonce          5
previous_hash  28c80497533fb426ddba60f6af6d3d3f057c7dc4b266845c408483040c9c9c1b
timestamp      1630801628.1350038
transactions
----------------------------------------
 recipient_blockchain_address  B
 sender_blockchain_address     A
 value                         1.0
*************************
========================= Chain 0 =========================
nonce          0
previous_hash  44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a
timestamp      1630801628.132861
transactions
========================= Chain 1 =========================
nonce          5
previous_hash  28c80497533fb426ddba60f6af6d3d3f057c7dc4b266845c408483040c9c9c1b
timestamp      1630801628.1350038
transactions
----------------------------------------
 recipient_blockchain_address  B
 sender_blockchain_address     A
 value                         1.0
========================= Chain 2 =========================
nonce          2
previous_hash  9f0be24aa3a723f04e4ccbaabc9967f16a995d791dee2bbc74abaed22a9b999d
timestamp      1630801628.138853
transactions
----------------------------------------
 recipient_blockchain_address  D
 sender_blockchain_address     C
 value                         2.0
----------------------------------------
 recipient_blockchain_address  Y
 sender_blockchain_address     X
 value                         3.0
*************************

今回の記事は、以上です。

最後までお読みいただきありがとうございました。

コメント

タイトルとURLをコピーしました