Skip to main content

Chaincraft

Python 3.9+ Python Unit Tests License: MIT Blockchain ECDSA Schnorr Project Status PyPI version PyPI Downloads

A platform for blockchain research and prototyping

Chaincraft is a Python-based framework for building and experimenting with blockchain protocols. It provides the fundamental components needed to create distributed networks, implement consensus mechanisms, and prototype blockchain applications.

Key Features

  • Modular blockchain (0.6.0): Pluggable ledger, fee market, mempool, consensus, and fork choice via BlockchainConfig
  • BIP-340 Schnorr (0.7.0): x-only secp256k1 signatures for Nostr-style digests; pure-Python by default, optional coincurve
  • NAT traversal (0.8.0): STUN, UDP hole punching, and relay coordination via node.nat (nat_traversal=True)
  • Decentralized protocols: Configurable ChatGroup, pub/sub, and CRDT key-value store
  • Consensus catalog: Gossip, PoW, BFT, and DAG engines selectable by name
  • Decentralized Network: Built-in peer discovery, connection management, and message propagation
  • Shared Objects: Extensible framework for maintaining distributed state across nodes
  • Cryptographic Primitives: Implementation of essential blockchain cryptography
  • Persistence: Optional persistent storage for nodes and messages
  • Data Validation: Type checking and schema validation for messages
  • Merklelized Storage: Support for efficient state synchronization

Installation

Install from PyPI

The easiest way to install Chaincraft is via pip:

pip install chaincraft

Install from Source

For development or to get the latest features:

git clone https://github.com/jio-gl/chaincraft.git
cd chaincraft
pip install -e .

Development Installation

To install with development dependencies:

git clone https://github.com/jio-gl/chaincraft.git
cd chaincraft
pip install -e ".[dev]"

Requirements

  • Python 3.9 or higher
  • cryptography>=50.0.0
  • Optional: coincurve>=21.0.0 for faster BIP-340 Schnorr (pip install chaincraft[schnorr])

Code quality (pre-commit hooks)

After cloning, run ./scripts/setup-hooks.sh to enable black and flake8 checks on commit.

Import Guide

After installing chaincraft, you can import its components using the package namespace:

# Main node component
from chaincraft import ChaincraftNode

# Core components
from chaincraft.shared_object import SharedObject
from chaincraft.shared_message import SharedMessage

# Exceptions
from chaincraft.shared_object import SharedObjectException

# Cryptographic primitives
from chaincraft.crypto_primitives.pow import ProofOfWorkPrimitive
from chaincraft.crypto_primitives.sign import ECDSASignaturePrimitive
from chaincraft.crypto_primitives.schnorr import SchnorrSignaturePrimitive

BIP-340 Schnorr uses a pure-Python backend by default (no native deps). For production / Nostr performance, install the optional backend: pip install chaincraft[schnorr] (selects coincurve at import time).

prim = SchnorrSignaturePrimitive()
prim.generate_key()
sig = prim.sign(event_id_32_bytes)  # 64-byte Schnorr sig
prim.verify(event_id_32_bytes, sig, prim.pubkey_hex)

Quick Start

Command Line Interface

After installation, you can use the chaincraft-cli command:

# Start a node with default settings
chaincraft-cli

# Start a node on a specific port
chaincraft-cli -p 8000

# Start a node and connect to a seed peer
chaincraft-cli -s 127.0.0.1:21000

# Enable debugging and use memory storage
chaincraft-cli -d -m

Python API

import chaincraft

# Create and start a node
node = chaincraft.ChaincraftNode()
node.start()

# Connect to another node
node.connect_to_peer("127.0.0.1", 21000)

# Create and broadcast a message
node.create_shared_message("Hello, Chaincraft!")

Architecture

Chaincraft is built on several core components:

  • ChaincraftNode: Handles networking, peer discovery, and message gossip
  • SharedMessage: Wraps and serializes data for network transmission
  • SharedObject: Abstract base class for implementing distributed data structures
  • Cryptographic primitives: PoW, VDF, ECDSA, BIP-340 Schnorr, and VRF implementations

Usage

Basic Node Setup

from chaincraft import ChaincraftNode

# Create a node with default settings
node = ChaincraftNode()
node.start()

# Connect to another node
node.connect_to_peer("127.0.0.1", 21000)

# Create and broadcast a message
node.create_shared_message("Hello, Chaincraft!")

Creating a Custom Shared Object

from chaincraft.shared_object import SharedObject
from chaincraft.shared_message import SharedMessage
import hashlib
import json

class MySharedState(SharedObject):
    def __init__(self):
        self.state = {}
        self.chain = []  # For merklelized sync
    
    def is_valid(self, message: SharedMessage) -> bool:
        # Validate incoming messages
        return isinstance(message.data, dict) and "key" in message.data
        
    def add_message(self, message: SharedMessage) -> None:
        # Update state based on message
        self.state[message.data["key"]] = message.data["value"]
        self.chain.append(message.data)
        
    def is_merkelized(self) -> bool:
        return True
        
    def get_latest_digest(self) -> str:
        # Return latest state digest for sync
        return hashlib.sha256(json.dumps(self.chain).encode()).hexdigest()
    
    # Additional required methods...

Using Cryptographic Primitives

from chaincraft.crypto_primitives.pow import ProofOfWorkPrimitive

# Create a Proof of Work challenge
pow_primitive = ProofOfWorkPrimitive(difficulty_bits=16)
challenge = "block_data_here"
nonce, hash_hex = pow_primitive.create_proof(challenge)

# Verify the proof
is_valid = pow_primitive.verify_proof(challenge, nonce, hash_hex)

Blockchain Prototyping

Chaincraft provides the building blocks for implementing various blockchain designs:

  • Proof of Work Blockchains: Using the PoW primitive
  • State-Based Applications: Using SharedObjects for consensus
  • Transaction Validation: Using the message validation framework
  • Custom Consensus Mechanisms: By extending SharedObjects with validation rules

Examples

The project includes various examples:

  • Simple Blockchain: A basic blockchain with PoW consensus
  • Message Chain: A merklelized append-only log of messages
  • ECDSA Transactions: Signed transactions with balance tracking
  • Chatroom: A real-time chat example with auto-accept membership

Running Tests

Install the test dependencies first (only needed once, or after pulling changes):

pip install -e ".[dev]"

Run all tests (this is what CI runs):

pytest tests

Run a specific test file:

pytest tests/test_blockchain_example.py

Run a specific test:

pytest tests/test_local_discovery.py -v -k test_local_discovery_enabled

Some tests are marked stress — heavy, long-running tests (storage/memory/ indexing at scale). They are excluded by default via addopts in pyproject.toml (so a plain pytest tests / CI run skips them).

To run only the stress suite:

pip install -e ".[dev,stress]"
pytest tests -m stress

Design Principles

Chaincraft is designed to help explore blockchain tradeoffs:

  • Blockchain Trilemma:
    • Security vs. Scalability vs. Decentralization
  • Time Synchronization:
    • Asynchronous vs. Time-Bounded vs. Synchronized
  • Identity Models:
    • Anonymous vs. Resource-Based vs. Identity-Based

Contributing

Contributions to Chaincraft are welcome! This is an educational project aimed at helping developers understand blockchain concepts through hands-on implementation.

Current Status (Roadmap)

0.8.0 (this release)

  • ✅ NAT traversal (NatTraversal / node.nat): STUN, hole punch, relay — PR #72
  • ✅ Protocol control messages no longer strike SharedObject peers (sync flake fix)

0.7.0

  • ✅ BIP-340 Schnorr (SchnorrSignaturePrimitive): x-only pubkeys, pure-Python default, optional coincurve — closes #102

Roadmap to version 1.0.0

  • ✅ Gossip Protocol: Sharing JSON messages between nodes
  • ✅ Persistent Storage: Key-value storage for messages
  • ✅ Peer Discovery: Global and local node discovery
  • ✅ Message Validation: Field and type validation with peer banning
  • ✅ Shared Objects: State synchronization between nodes
  • ✅ Merklelized Storage: Efficient state synchronization
  • ✅ Additional Cryptographic Primitives (ECDSA, VRF, PoW, VDF, BIP-340 Schnorr)
  • ✅ Indexing (Validated Message Type can have some indexed fields)
  • ✅ Consensus Mechanisms
  • ✅ Proof of Work
  • ✅ Practical Byzantine Fault Tolerance (PBFT) or Tenderming (simpler)
  • ⬜ Transaction Validation for Ledgers (Balance-based and UTXO-based)
  • ⬜ Proof of Stake
  • ⬜ Proof of Authority
  • ⬜ Proof of Elapsed Time
  • ⬜ Smart Contracts
  • ⬜ State Machine Replication
  • ⬜ Sharding

Ideas for version 2.0.0

  • Configurable Building Blocks:
    • choose consensys protocol (PoS, PoW, PoA, etc)
    • choose ledger type (UTXO, Account Balances, etc)
    • choose gas auction (Lower Price First, Median Price, etc)

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chaincraft-0.8.0.tar.gz (195.0 kB view details)

Uploaded Source

Built Distribution

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

chaincraft-0.8.0-py3-none-any.whl (160.2 kB view details)

Uploaded Python 3

File details

Details for the file chaincraft-0.8.0.tar.gz.

File metadata

  • Download URL: chaincraft-0.8.0.tar.gz
  • Upload date:
  • Size: 195.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for chaincraft-0.8.0.tar.gz
Algorithm Hash digest
SHA256 f44953c0c9a92684dff06bedab98b3c2d21a922593e79b0839a9b3dcc2f24afb
MD5 60c55cba9f0164b43fff59f3596210a8
BLAKE2b-256 e9c5fdffc37b53c1c89f3f31512f12cee50b6967949a76a6da301f0a0981382a

See more details on using hashes here.

Provenance

The following attestation bundles were made for chaincraft-0.8.0.tar.gz:

Publisher: publish-to-pypi.yml on jose-compu/chaincraft

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chaincraft-0.8.0-py3-none-any.whl.

File metadata

  • Download URL: chaincraft-0.8.0-py3-none-any.whl
  • Upload date:
  • Size: 160.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for chaincraft-0.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ab79cda65417dd8327f664e2886ebe1d3d63315366d7ddaf8e20c1a1415087d0
MD5 549db8bdd3479c116bc7c44bb052bf95
BLAKE2b-256 d6d4817212e27f9c8bae4cbef0760139ebae3015d6a0a9d50ca60bd4e854bd11

See more details on using hashes here.

Provenance

The following attestation bundles were made for chaincraft-0.8.0-py3-none-any.whl:

Publisher: publish-to-pypi.yml on jose-compu/chaincraft

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 files

0.7.0

2 files

0.6.3

2 files

0.6.2

2 files

0.6.0

2 files

0.5.2

2 files

0.5.1

2 files

0.5.0

2 files

0.4.7

2 files

0.4.6

2 files

0.4.5

2 files

0.4.3

2 files

0.4.2

2 files

0.4.1

2 files

0.4.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page