Easy Blockchain: A simple blockchain with PoW/PoS consensus and P2P networking
Project description
easy_blockchain
you can use blockchain easily. please use for prototype
簡単にブロックチェーンを使うためのライブラリ. IoTに組み込んだりなど,簡易的なプロトタイプ作成に使ってください.
useful_blockchain 概要
- 提供クラス:
useful_blockchain.blockchain.BlockChainuseful_blockchain.signature.SignatureManageruseful_blockchain.network.node.Node(v2.0: P2P ノード)
- 目的: プロトタイプ・学習向けのブロックチェーン実装(PoW/PoS 合意 + P2P 対応)。
- 主なメソッド:
add_new_block(input_data, output_data): 新しいトランザクションを作成し,直前ブロックのハッシュと組み合わせて末尾にブロックを追加します(戻り値は追加されたブロックの辞書)。dump(block_index=0): チェーン全体または指定インデックスのブロックを簡易表示します。generate_key_pair(): デジタル署名用の鍵ペアを生成します(署名機能有効時のみ)。verify_block_signature(block_index): 指定ブロックの署名を検証します。
- ブロック構造(辞書):
block_index: 1始まりの連番block_item: 生成日時(YYYY-MM-DD HH:MM:SS)block_header.prev_hash: 直前ブロックのトランザクションハッシュ(先頭ブロックのみ乱数シードから生成)block_header.tran_hash:sha256(prev_hash + sha256(json(tran_body)))tran_counter: 入力と出力の要素数の合計tran_body.input_data/tran_body.output_data: 追加時に渡した値
- ハッシュ化:
sha256による簡易的な整合性保証(改ざん検知の学習・デモ用途)。
使い方(例)
基本的な使い方
from useful_blockchain.blockchain import BlockChain
bc = BlockChain()
bc.add_new_block(["a"], ["b"])
bc.add_new_block(["c"], ["d"])
print(bc.chain) # チェーン配列(各ブロックは dict)
署名機能付きブロックチェーン
from useful_blockchain.blockchain import BlockChain
# 署名機能を有効にしてブロックチェーンを作成
bc = BlockChain(enable_signature=True)
# 鍵ペアを生成
private_key, public_key = bc.generate_key_pair()
# 署名付きブロックを追加
bc.add_new_block(["sender_a"], ["receiver_b"])
bc.add_new_block(["sender_c"], ["receiver_d"])
# 署名を検証
print(bc.verify_block_signature(1)) # True(署名が正しい場合)
print(bc.verify_all_signatures()) # 全ブロックの検証結果
デジタル署名単体での使用
from useful_blockchain.signature import SignatureManager
sig_manager = SignatureManager()
private_key, public_key = sig_manager.generate_key_pair()
# データに署名
data = {"message": "Hello, Blockchain!"}
signature = sig_manager.sign_data(data)
# 署名を検証
is_valid = sig_manager.verify_signature(data, signature)
print(f"署名検証結果: {is_valid}")
デジタル署名機能について
- RSA暗号化を使用したデジタル署名機能を提供
- 各ブロックに署名を付与し、データの完全性と認証を保証
- 署名の生成・検証・鍵管理機能を含む
- PEM形式での公開鍵エクスポート/インポートに対応
v2.0: PoW / PoS 分散合意 + P2P
設定ファイル
config/default.yaml で合意方式・ネットワークを設定します。環境変数 EASYBLOCKCHAIN_CONFIG でパスを上書きできます。
ノード起動(PoW)
uv run python examples/run_node.py --consensus pow --port 8765
uv run python examples/run_node.py --consensus pow --port 8766 --bootstrap ws://127.0.0.1:8765
ノード起動(PoS)
uv run python examples/run_node.py --consensus pos --port 8770
Python API
import asyncio
from useful_blockchain.network.node import Node
async def main():
node = Node(overrides={"consensus": {"type": "pow", "pow": {"initial_difficulty": 2}}})
await node.start()
await node.add_block(["alice"], ["bob"])
await node.stop()
asyncio.run(main())
テスト
uv run pytest tests -v
uv run pytest tests/e2e -v -m slow
注意事項
- PoW/PoS/P2P は教育・試作向けの実装です。本番利用には追加のセキュリティ監査が必要です。
- v1 互換:
BlockChain()を合意なしで使うと従来どおり即時ブロック追加が可能です。
変更履歴
CHANGELOG.md を参照してください。
English Documentation
useful_blockchain Overview
- Provided Classes:
useful_blockchain.blockchain.BlockChainuseful_blockchain.signature.SignatureManager
- Purpose: Minimal blockchain implementation for prototyping and learning.
- Main Methods:
add_new_block(input_data, output_data): Creates a new transaction and adds a block to the end of the chain by combining it with the hash of the previous block (returns the dictionary of the added block).dump(block_index=0): Simple display of the entire chain or a block at the specified index.generate_key_pair(): Generates key pairs for digital signatures (only when signature feature is enabled).verify_block_signature(block_index): Verifies the signature of the specified block.
- Block Structure (dictionary):
block_index: Sequential number starting from 1block_item: Generation timestamp (YYYY-MM-DD HH:MM:SS)block_header.prev_hash: Transaction hash of the previous block (generated from random seed only for the first block)block_header.tran_hash:sha256(prev_hash + sha256(json(tran_body)))tran_counter: Total number of input and output elementstran_body.input_data/tran_body.output_data: Values passed during addition
- Hashing: Simple integrity assurance by
sha256(for learning and demonstration purposes of tampering detection).
Usage Examples
Basic Usage
from useful_blockchain.blockchain import BlockChain
bc = BlockChain()
bc.add_new_block(["a"], ["b"])
bc.add_new_block(["c"], ["d"])
print(bc.chain) # Chain array (each block is a dict)
Blockchain with Signature Feature
from useful_blockchain.blockchain import BlockChain
# Create blockchain with signature feature enabled
bc = BlockChain(enable_signature=True)
# Generate key pair
private_key, public_key = bc.generate_key_pair()
# Add signed blocks
bc.add_new_block(["sender_a"], ["receiver_b"])
bc.add_new_block(["sender_c"], ["receiver_d"])
# Verify signatures
print(bc.verify_block_signature(1)) # True (if signature is correct)
print(bc.verify_all_signatures()) # Verification results for all blocks
Standalone Digital Signature Usage
from useful_blockchain.signature import SignatureManager
sig_manager = SignatureManager()
private_key, public_key = sig_manager.generate_key_pair()
# Sign data
data = {"message": "Hello, Blockchain!"}
signature = sig_manager.sign_data(data)
# Verify signature
is_valid = sig_manager.verify_signature(data, signature)
print(f"Signature verification result: {is_valid}")
About Digital Signature Feature
- Provides digital signature functionality using RSA encryption
- Adds signatures to each block to ensure data integrity and authentication
- Includes signature generation, verification, and key management functions
- Supports public key export/import in PEM format
v2.0: PoW / PoS Consensus + P2P
See config/default.yaml, examples/run_node.py, and CHANGELOG.md.
Important Notes
- PoW/PoS/P2P are educational implementations; production use requires additional security review.
- v1 compatibility:
BlockChain()without consensus retains legacy instant-add behavior.
commands for me
python3 setup.py bdist_wheel sdist
twine upload -r pypi dist/*
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file useful_blockchain-2.0.0.tar.gz.
File metadata
- Download URL: useful_blockchain-2.0.0.tar.gz
- Upload date:
- Size: 23.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
24c9705563b6b6acf0345fb3174085b0fe7ebbd1552286e4ded41521bed023c8
|
|
| MD5 |
e9e00224662c7d66e8cc8bfae4973736
|
|
| BLAKE2b-256 |
7697fa6555fb26b460e73a23c9d7949493b7d419aa8a6b49a7b4454e61c93e3a
|
File details
Details for the file useful_blockchain-2.0.0-py3-none-any.whl.
File metadata
- Download URL: useful_blockchain-2.0.0-py3-none-any.whl
- Upload date:
- Size: 27.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
84a0a28e64d20ac878bb84d8d7a79cb4d4391638de3a00834ca5637ce0724e5f
|
|
| MD5 |
d2f4ec5a797f92b42d90af52993113ac
|
|
| BLAKE2b-256 |
49c667ebbc46c0ef3b4107a4277cc627430f72d6077361c8bdbb66a4e61a4103
|