Skip to main content

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.BlockChain
    • useful_blockchain.signature.SignatureManager
    • useful_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: 直前ブロックのトランザクションハッシュ(先頭ブロックは config/default.yamlgenesis.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

P2P ネットワークの詳細は docs/p2p.md を参照してください。

設定ファイル

config/default.yaml で合意方式・ネットワーク・ジェネシスを設定します。環境変数 EASYBLOCKCHAIN_CONFIG でパスを上書きできます。

genesis.prev_hash は先頭ブロックの prev_hash および P2P の genesis_hash 識別子として使われます。同一ネットワーク内の全ノードで同じ値を設定してください。

ノード起動(PoW)

uv run easyblockchain-node --consensus pow --port 8765
uv run easyblockchain-node --consensus pow --port 8766 --bootstrap ws://127.0.0.1:8765

または:

uv run python examples/run_node.py --consensus pow --port 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

運用・デプロイ(v2.1)

  • 運用ドキュメント: docs/operations.md
  • 本番設定テンプレート: config/production.yaml
  • Docker 3 ノード例:
docker compose up --build
curl -f http://localhost:9090/healthz
  • ヘルスチェック: GET /healthz(liveness), GET /readyz(readiness)
  • メトリクス: GET /metricsuv sync --extra observability が必要)

注意事項

  • PoW/PoS/P2P は教育・試作向けの実装です。本番利用には追加のセキュリティ監査が必要です。
  • v1 互換: BlockChain() を合意なしで使うと従来どおり即時ブロック追加が可能です。

変更履歴

CHANGELOG.md を参照してください。


English Documentation

useful_blockchain Overview

  • Provided Classes:
    • useful_blockchain.blockchain.BlockChain
    • useful_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 1
    • block_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 elements
    • tran_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 docs/p2p.md for P2P networking details, plus 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.

PyPI リリース

リポジトリシークレット PYPI_API_TOKEN を設定したうえで、GitHub Actions から自動リリースできます。

  1. Actions → Release → Run workflowpatch / minor / major を選択
  2. バージョン更新・タグ作成・GitHub Release 作成が実行される
  3. Publish to PyPI ワークフローが Release イベントで起動し PyPI へアップロード

詳細は docs/operations.md を参照してください。

手動ビルド:

uv build

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

useful_blockchain-2.1.2.tar.gz (44.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

useful_blockchain-2.1.2-py3-none-any.whl (55.6 kB view details)

Uploaded Python 3

File details

Details for the file useful_blockchain-2.1.2.tar.gz.

File metadata

  • Download URL: useful_blockchain-2.1.2.tar.gz
  • Upload date:
  • Size: 44.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for useful_blockchain-2.1.2.tar.gz
Algorithm Hash digest
SHA256 a909a3508c961827e13e4ac1faec702a0c7fddc8372f6deac84c57d1f1991878
MD5 dfa0b95531637766cfb4d52dd8ead7cf
BLAKE2b-256 3dd00cde08aca27b7cc37311bf8f0f9815437a51c22b9bf161c5d54f43b79824

See more details on using hashes here.

File details

Details for the file useful_blockchain-2.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for useful_blockchain-2.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 de087b0c85a563ef27e08a19f015f35873b42a5c8d95c16b9de5afe34163cccd
MD5 5ee21ef8de4a8d4ba782e34c56eed721
BLAKE2b-256 790e6bdbfc027a26f509c0e71d8ffc642e3f1429f5c90fb1dc98f31042e6780d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page