LoginSignup
1
2

More than 5 years have passed since last update.

【Aidemy】ブロックチェーン基礎のコードの整理 ①

Last updated at Posted at 2018-09-08

ブロックチェーン基礎を学習している中で詰まってしまったので、
コードの内容の整理として記録

内容はブロックチェーン基礎 1.2.3 ジェネシスブロック


import time

class Blockchain:
    def __init__(self):
        self.chain = []
        self.current_transactions = []
        self.transaction_index = 0
        self.create_block(nonce="hoge", previous_hash="00000")

    # ジェネシスブロックを作成する関数を完成させてください
    def create_block(self, nonce, previous_hash):
        block = {
            'index' :  len(self.chain),
            'timestamp' : time.time(),
            'transactions' : self.current_transactions,
            'nonce' : nonce,
            'previous_hash' : previous_hash,
        }        
        # ブロックの追加をします
        self.chain.append(block)
        return block


blockchain = Blockchain()
print(blockchain.chain)

上から順番に整理していく

import time

timestampにて、ブロックが生成された時間を受け取る必要があるため必要なモジュール

blockchain = Blockchain()

この部分でクラスのインスタンスオブジェクトを生成しており、その内容が以下

class Blockchain:
    def __init__(self):
        self.chain = []
        self.current_transactions = []
        self.transaction_index = 0
        self.create_block(nonce="hoge", previous_hash="00000")

self.chain:リスト化
current_transactions:このブロック内での取引データ
transaction_index = 0:初期値を0と指定
self.create_block(nonce="hoge", previous_hash="00000"):この関数は別に定義

    def create_block(self, nonce, previous_hash):
        block = {
            'index' :  len(self.chain),
            'timestamp' : time.time(),
            'transactions' : self.current_transactions,
            'nonce' : nonce,
            'previous_hash' : previous_hash,
        }        
        self.chain.append(block)
        return block

関数create_block(nonce="hoge", previous_hash="00000")の詳細
blockの内部は辞書化されており、 
・'index' : len(self.chain) → 繰り返すことで要素が1ずつ増えていくので、index番号と一致
・'timestamp' : time.time(), → 作成された時間を受け取る
・'transactions' : self.current_transactions, →今回は定義なし
・'nonce' : nonce, →引数1の値が代入される
・'previous_hash' : previous_hash, → 引数2の値が代入される

self.chain.append(block) →リストであるchainの末尾に辞書であるblockが追加される
create_block(self, nonce, previous_hash)にblockを戻り値として返す
→なぜ?
→おそらく次章で使用するから?(一旦保留)

以下が出力結果

[{'index': 0, 
  'timestamp': 1536389268.5988321, 
  'transactions': [], 
  'nonce': 'hoge', 
  'previous_hash': '00000'}]

出力内容の整理
変数bloclchainの.chianなので、リストが出力される
・ジェネシスブロックなのでindexは0
・transactions': []なので、今回は取引されたデータはなし
・nonce値は「特に指定がない」という意(?)のhoge
・previous_hash': '00000'は、直前のブロックがないので00000としている(?)

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2