Metadata-Version: 2.4
Name: useful_blockchain
Version: 2.1.1
Summary: Easy Blockchain: A simple blockchain with PoW/PoS consensus and P2P networking
Home-page: https://github.com/T3pp31/easyblockchain
Download-URL: https://github.com/T3pp31/easyblockchain
Author: Teppei Fukutomi
Author-email: Teppei Fukutomi <ttyn4519@outlook.jp>
Maintainer: Teppei Fukutomi
Maintainer-email: ttyn4519@outlook.jp
License: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=3.0.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: websockets>=12.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-timeout>=2.2; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: types-PyYAML>=6.0; extra == "dev"
Provides-Extra: observability
Requires-Dist: prometheus-client>=0.20; extra == "observability"
Provides-Extra: mdns
Requires-Dist: zeroconf>=0.131; extra == "mdns"
Dynamic: author
Dynamic: download-url
Dynamic: home-page
Dynamic: license-file
Dynamic: maintainer
Dynamic: maintainer-email
Dynamic: requires-python

# 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.yaml` の `genesis.prev_hash` で固定）
  - `block_header.tran_hash`: `sha256(prev_hash + sha256(json(tran_body)))`
  - `tran_counter`: 入力と出力の要素数の合計
  - `tran_body.input_data` / `tran_body.output_data`: 追加時に渡した値
- ハッシュ化: `sha256` による簡易的な整合性保証（改ざん検知の学習・デモ用途）。

### 使い方（例）

#### 基本的な使い方

```python
from useful_blockchain.blockchain import BlockChain

bc = BlockChain()
bc.add_new_block(["a"], ["b"])
bc.add_new_block(["c"], ["d"])
print(bc.chain)  # チェーン配列（各ブロックは dict）
```

#### 署名機能付きブロックチェーン

```python
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())    # 全ブロックの検証結果
```

#### デジタル署名単体での使用

```python
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](docs/p2p.md) を参照してください。

#### 設定ファイル

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

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

#### ノード起動（PoW）

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

または:

```bash
uv run python examples/run_node.py --consensus pow --port 8765
```

#### ノード起動（PoS）

```bash
uv run python examples/run_node.py --consensus pos --port 8770
```

#### Python API

```python
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())
```

#### テスト

```bash
uv run pytest tests -v
uv run pytest tests/e2e -v -m slow
```

#### 運用・デプロイ（v2.1）

- 運用ドキュメント: [docs/operations.md](docs/operations.md)
- 本番設定テンプレート: `config/production.yaml`
- Docker 3 ノード例:

```bash
docker compose up --build
curl -f http://localhost:9090/healthz
```

- ヘルスチェック: `GET /healthz`（liveness）, `GET /readyz`（readiness）
- メトリクス: `GET /metrics`（`uv sync --extra observability` が必要）

### 注意事項

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

# 変更履歴

[CHANGELOG.md](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

```python
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

```python
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

```python
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](docs/p2p.md) for P2P networking details, plus `config/default.yaml`, `examples/run_node.py`, and [CHANGELOG.md](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 リリース

GitHub Release を公開すると `.github/workflows/publish.yml` が PyPI へ自動公開します（Trusted Publishing）。

手動ビルド:

```bash
uv build
```
