
第2回: ブロックチェーンの詳細な動作解説と各部のコードの説明
こんにちは!前回の記事では、Pythonを使って簡単なブロックチェーンを作成する方法を紹介しました。
今回は、そのプログラムの詳細な動作を解説し、各部のコードが何をしているのかを説明します。
ブロックチェーンの仕組みをおさらい
ブロックチェーンは、データを保存するブロックが連鎖して形成されます。
各ブロックは、前のブロックのハッシュ値を持つことでチェーンのようにつながっており、データの改ざんが難しくなっています。
プログラムの全体構造
以下に、前回使用したプログラム全体を再掲します。
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def calculate_hash(index, previous_hash, timestamp, data):
return hashlib.sha256(f"{index}{previous_hash}{timestamp}{data}".encode('utf-8')).hexdigest()
def create_genesis_block():
return Block(0, "0", int(time.time()), "Genesis Block", calculate_hash(0, "0", int(time.time()), "Genesis Block"))
def create_new_block(previous_block, data):
index = previous_block.index + 1
timestamp = int(time.time())
hash = calculate_hash(index, previous_block.hash, timestamp, data)
return Block(index, previous_block.hash, timestamp, data, hash)
# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
# Add new blocks to the blockchain
num_blocks_to_add = 10
for i in range(1, num_blocks_to_add + 1):
new_block = create_new_block(previous_block, f"Block {i} Data")
blockchain.append(new_block)
previous_block = new_block
print(f"Block {new_block.index} has been added to the blockchain!")
print(f"Hash: {new_block.hash}\n")
# Display the blockchain contents
print("\nBlockchain contents:")
for block in blockchain:
print(f"Index: {block.index}")
print(f"Previous Hash: {block.previous_hash}")
print(f"Timestamp: {block.timestamp}")
print(f"Data: {block.data}")
print(f"Hash: {block.hash}")
print("-------------")1. 必要なライブラリのインポート
import hashlib
import timeこの部分では、プログラムで使用するライブラリをインポートしています。
`hashlib`はハッシュ値を計算するためのライブラリで、`time`はタイムスタンプを取得するために使用します。
2. ブロッククラスの定義
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash`Block`クラスは、ブロックの設計図です。
このクラスは、以下の属性を持つブロックを作成します:
`index`: ブロックの番号。
`previous_hash`: 前のブロックのハッシュ値。
`timestamp`: ブロックが作成された時刻。
`data`: ブロックに保存されるデータ。
`hash`: ブロックのハッシュ値。
3. ハッシュ値の計算
def calculate_hash(index, previous_hash, timestamp, data):
return hashlib.sha256(f"{index}{previous_hash}{timestamp}{data}".encode('utf-8')).hexdigest()`calculate_hash`関数は、ブロックの内容を基にハッシュ値を計算します。
このハッシュ値は、ブロックの内容が改ざんされていないことを確認するために使用されます。
4. ジェネシスブロックの作成
def create_genesis_block():
return Block(0, "0", int(time.time()), "Genesis Block", calculate_hash(0, "0", int(time.time()), "Genesis Block"))`create_genesis_block`関数は、ブロックチェーンの最初のブロック(ジェネシスブロック)を作成します。
ジェネシスブロックは特別で、前のブロックが存在しないため、`previous_hash`が"0"に設定されています。
5. 新しいブロックの作成
def create_new_block(previous_block, data):
index = previous_block.index + 1
timestamp = int(time.time())
hash = calculate_hash(index, previous_block.hash, timestamp, data)
return Block(index, previous_block.hash, timestamp, data, hash)`create_new_block`関数は、新しいブロックを作成します。新しいブロックは、前のブロックの情報を基にして作成され、チェーンのように連鎖します。
6. ブロックチェーンの作成とブロックの追加
# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
# Add new blocks to the blockchain
num_blocks_to_add = 10
for i in range(1, num_blocks_to_add + 1):
new_block = create_new_block(previous_block, f"Block {i} Data")
blockchain.append(new_block)
previous_block = new_block
print(f"Block {new_block.index} has been added to the blockchain!")
print(f"Hash: {new_block.hash}\n")この部分では、最初にジェネシスブロックを作成し、ブロックチェーンリストに追加します。
その後、新しいブロックを作成し、チェーンに追加します。各ブロックの情報がコンソールに出力されます。
7. ブロックチェーンの内容を表示
# Display the blockchain contents
print("\nBlockchain contents:")
for block in blockchain:
print(f"Index: {block.index}")
print(f"Previous Hash: {block.previous_hash}")
print(f"Timestamp: {block.timestamp}")
print(f"Data: {block.data}")
print(f"Hash: {block.hash}")
print("-------------")この部分では、ブロックチェーン内の各ブロックの内容を表示します。これにより、各ブロックがどのように連鎖しているかを確認できます。
まとめ
今回の記事では、前回紹介したプログラムの詳細な動作を解説しました。
各部のコードがどのように機能しているかを理解することで、ブロックチェーンの基本的な仕組みがより明確になったと思います。
次回は、ブロックチェーンの応用例やさらなる発展について解説します。
お楽しみに!