Skip to content

clockinchain/chrono-merkle

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

23 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ChronoMerkle

Crates.io Documentation License Rust Tests

Time-aware Merkle trees for blockchain, audit trails, and secure data verification

ChronoMerkle provides a production-ready, cryptographically secure implementation of time-aware Merkle trees with delta-based updates, programmable validation nodes, and sparse timestamp indexing. Perfect for blockchain applications, compliance logging, audit trails, and time-series data integrity verification.

Table of Contents

✨ Features

  • ⏰ Time-aware leaves: Every data entry includes a timestamp for chronological queries
  • πŸ”„ Delta-based updates: Efficient incremental updates without full tree rebuilds
  • πŸŽ›οΈ Programmable validation: Custom business logic and security rules at tree nodes
  • πŸ“Š Sparse timestamp indexing: O(log n) time-based lookups and range queries
  • πŸ”§ Cryptographically flexible: Support for any hash function (Blake3, SHA-256, etc.)
  • πŸ” Zero-knowledge proofs: Cryptographic inclusion proofs with delta chain verification
  • βͺ Time-based rollback: Roll back to any historical state
  • πŸ’Ύ Enterprise storage: Multiple backends (Memory, File, PostgreSQL, Redis)
  • πŸš€ High performance: Parallel operations, optimized for large-scale datasets
  • πŸ›‘οΈ Security-first: Constant-time operations, input validation, audit logging

πŸ“¦ Installation

Add this to your Cargo.toml:

[dependencies]
chrono-merkle = "1.1"

Feature Flags

ChronoMerkle uses feature flags to keep your binary size small. The default feature set includes essential functionality:

Feature Description Default
serde Serialization/deserialization support βœ…
std Standard library support βœ…
blake3-hash Blake3 cryptographic hasher βœ…
sha2-hash SHA-256 cryptographic hasher ❌
clockhash ClockHash trace compression integration ❌
parallel Parallel tree operations with Rayon ❌
storage Storage backend support ❌
memory-storage In-memory storage backend ❌
file-storage File-based persistent storage ❌
postgres-storage PostgreSQL database backend ❌
redis-storage Redis cache backend ❌
no-std Embedded/no_std compatibility ❌
wasm WebAssembly support ❌
visualization ASCII/DOT/JSON tree visualization ❌
security-logging Enhanced security event logging ❌

Feature Flags

  • default: serde, std, blake3-hash
  • serde: Serialization support with serde
  • std: Standard library support (enabled by default)
  • blake3-hash: Blake3 hasher (enabled by default)
  • sha2-hash: SHA-256 hasher
  • clockhash: ClockHash integration for trace compression
  • parallel: Parallel tree operations with Rayon
  • storage: Storage backend support
  • file-storage: File-based storage
  • memory-storage: In-memory storage (enabled with storage)
  • postgres-storage: PostgreSQL storage backend
  • redis-storage: Redis storage backend
  • no-std: Embedded/no-std support
  • wasm: WebAssembly support
  • visualization: ASCII/DOT/JSON visualization

πŸš€ Quick Start

use chrono_merkle::{ChronoMerkleTree, Blake3Hasher};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new ChronoMerkle tree with Blake3 hashing
    let mut tree = ChronoMerkleTree::new(Blake3Hasher::default());

    // Insert data with timestamps (Unix timestamps)
    tree.insert(b"Hello World", 1000)?;
    tree.insert(b"ChronoMerkle", 1001)?;
    tree.insert(b"Time-aware", 1002)?;

    // Generate cryptographic proof for data inclusion
    let proof = tree.generate_proof(0)?;
    let is_valid = tree.verify_proof(&proof)?;

    assert!(is_valid);
    println!("βœ… Proof verified successfully!");

    // Time-based range queries
    let results = tree.find_range(1000, 1002);
    println!("Found {} entries in time range", results.len());

    // Rollback to previous state
    tree.rollback_to_timestamp(1001)?;
    println!("Rolled back to timestamp 1001, tree now has {} leaves", tree.leaf_count());

    Ok(())
}

🎯 Why ChronoMerkle?

Traditional Merkle trees provide data integrity but lack temporal awareness. ChronoMerkle bridges this gap by combining:

  • Chronological integrity: Every data entry is timestamped and cryptographically linked
  • Temporal queries: Efficient range queries and historical state reconstruction
  • Delta efficiency: Incremental updates without expensive full rebuilds
  • Programmable validation: Business rules and security policies embedded in the tree structure
  • Enterprise storage: Production-ready persistence with multiple database backends

Use Cases

  • πŸ“± Blockchain applications: Time-ordered transaction validation and state proofs
  • πŸ“Š Audit trails: Tamper-proof chronological logging with rollback capabilities
  • 🏒 Compliance systems: Regulatory reporting with cryptographic integrity guarantees
  • πŸ” Data provenance: Track data changes over time with verifiable history
  • ⏱️ Time-series verification: Ensure data integrity in temporal datasets

πŸ“š Examples

Core Functionality

# Basic tree operations and proof generation
cargo run --example basic_usage

# Blockchain-style operations with transaction validation
cargo run --example blockchain_example

# Custom validation rules and programmable nodes
cargo run --example programmable_nodes

Advanced Features

# ClockHash integration for trace compression (requires clockhash feature)
cargo run --example clockhash_integration --features clockhash

Running All Examples

# Test all examples
cargo run --example basic_usage
cargo run --example blockchain_example
cargo run --example programmable_nodes
cargo run --example clockhash_integration --features clockhash

πŸ—οΈ Architecture

ChronoMerkle is built around a modular, cryptographically secure architecture designed for high-performance temporal data integrity.

Core Components

Component Purpose
ChronoMerkleTree Main tree structure with time-aware operations and delta updates
SparseIndex Efficient timestamp-based indexing for O(log n) temporal queries
ChronoProof Cryptographic inclusion proofs with delta chain verification
Node Types Leaf (data), Internal (hashes), Delta (changes), Programmable (validation)
Storage Backends Pluggable persistence: Memory, File, PostgreSQL, Redis
Security Logger Audit trail and security event logging

Key Concepts

πŸ”„ Delta-Based Updates

Traditional Merkle trees rebuild entire branches on updates. ChronoMerkle uses delta nodes to track changes incrementally:

// Instead of rebuilding the entire tree...
tree.insert(data, timestamp)?;

// ...only affected branches are updated with delta tracking
let delta = tree.compute_delta(old_root, new_root)?;
tree.apply_delta(delta)?;

Benefits: 10-100x faster updates for large trees, minimal memory overhead.

πŸ“Š Sparse Timestamp Indexing

Time-based queries are optimized through configurable sparse indexing:

// Configurable sparsity (e.g., every 10th timestamp)
let config = TreeConfig {
    sparse_index_sparsity: 10,
    ..Default::default()
};

// Enables O(log n) range queries
let results = tree.find_range(start_timestamp, end_timestamp)?;

πŸŽ›οΈ Programmable Validation Nodes

Embed business logic directly into tree structure:

// Custom validation at tree nodes
let validator = |node: &Node, proof: &ChronoProof| -> Result<bool> {
    // Your business rules here
    match node.node_type() {
        NodeType::Programmable => validate_business_rules(node, proof),
        _ => Ok(true)
    }
};

tree.add_programmable_node(validator)?;

πŸ”’ Security

ChronoMerkle implements multiple layers of cryptographic security:

Cryptographic Security

  • Zero-knowledge proofs: Cryptographic verification without revealing data
  • Constant-time operations: Timing attack resistance for hash comparisons
  • Delta chain verification: Ensures update integrity across time
  • Timestamp validation: Prevents temporal manipulation attacks

Input Validation & Sanitization

  • Data size limits: Prevents resource exhaustion attacks
  • Timestamp bounds: Reasonable temporal constraints (no future/past dates)
  • Type safety: Rust's type system prevents memory corruption
  • SQL injection prevention: Parameterized queries in storage backends

Audit & Compliance

  • Security event logging: Comprehensive audit trails
  • Immutable history: Cryptographic guarantees of temporal integrity
  • Rollback verification: Secure state restoration with proof validation
  • Access control: Programmable nodes for authorization rules

πŸ”§ Advanced Usage

Custom Hash Functions

use chrono_merkle::{ChronoMerkleTree, HashFunction};

// Implement your own hasher
#[derive(Clone, Default)]
struct MyHasher;

impl HashFunction for MyHasher {
    type Output = [u8; 32];

    fn hash(&self, data: &[u8]) -> Self::Output {
        // Your hashing logic here
        [0; 32] // Placeholder
    }

    fn hash_pair(&self, left: &Self::Output, right: &Self::Output) -> Self::Output {
        // Hash combination logic
        [0; 32] // Placeholder
    }
}

let tree = ChronoMerkleTree::new(MyHasher::default());

Programmable Validation

use chrono_merkle::{ChronoMerkleTree, Blake3Hasher};

let mut tree = ChronoMerkleTree::new(Blake3Hasher::default());

// Add data that should pass your validation rules
tree.insert(b"valid_data", 1000)?;

// Tree maintains validation state
assert!(tree.is_valid());

Storage Persistence

use chrono_merkle::{ChronoMerkleTree, Blake3Hasher, MemoryStorage};

#[cfg(feature = "storage")]
{
    let mut tree = ChronoMerkleTree::new(Blake3Hasher::default());
    tree.insert(b"persistent_data", 1000)?;

    // Save to storage
    let storage = MemoryStorage::new();
    tree.save_state(&storage, "my_tree")?;

    // Load from storage
    let loaded_tree = ChronoMerkleTree::load_state(&storage, "my_tree", Blake3Hasher::default())?;
}

πŸ“Š Performance

ChronoMerkle is optimized for high-throughput, time-sensitive applications with enterprise-scale datasets.

Key Performance Characteristics

Operation Complexity Typical Performance Notes
Tree Construction O(1) ~5ns empty tree Minimal overhead
Data Insertion O(log n) ~50ΞΌs for 1000 entries Delta-based updates
Proof Generation O(log n) ~25ΞΌs for 1000 entries Cryptographic security
Proof Verification O(log n) ~15ΞΌs for 1000 entries Constant-time
Time Range Queries O(log n) ~10ΞΌs for 10K entries Sparse index optimized
Rollback Operations O(log n) ~30ΞΌs for 1000 entries Delta chain replay

Benchmark Results

# Run comprehensive benchmarks
cargo bench

# Key benchmark results (typical performance on modern hardware):

tree_construction/create_empty_tree    time:   ~5.5 ns
tree_construction/insert_1000_leaves   time:   ~45 ΞΌs
proof_operations/generate_proof        time:   ~25 ΞΌs
proof_operations/verify_proof          time:   ~15 ΞΌs
query_operations/range_query_10000     time:   ~10 ΞΌs

Performance Optimizations

  • πŸš€ Parallel Processing: Rayon-based parallel tree construction and validation
  • πŸ’Ύ Memory Efficiency: Sparse indexing reduces memory footprint by configurable factors
  • ⚑ SIMD Operations: Optimized hash computations using platform-specific acceleration
  • πŸ”„ Incremental Updates: Delta-based changes minimize recomputation overhead
  • πŸ“Š Query Optimization: Time-based indexing enables sub-linear query performance

Enterprise Features

  • Horizontal Scaling: Stateless design supports distributed deployments
  • Storage Backend Optimization: Database-specific query optimization
  • Memory Management: Configurable memory limits and garbage collection
  • Concurrent Access: Thread-safe operations with Send + Sync guarantees

πŸ“‹ Changelog

Version 1.0.0 (Latest)

  • βœ… Production Ready: Complete security audit and performance optimization
  • βœ… 48 Comprehensive Tests: Unit, integration, and security test coverage
  • βœ… Enterprise Storage: PostgreSQL, Redis, and file-based backends
  • βœ… Programmable Nodes: Custom validation logic at tree nodes
  • βœ… Delta-Based Updates: Efficient incremental tree modifications
  • βœ… Sparse Indexing: Optimized time-based queries and range operations
  • βœ… Cryptographic Security: Zero-knowledge proofs and constant-time operations

Version 0.1.x (Legacy)

  • Initial release with core time-aware Merkle tree functionality
  • Basic proof generation and verification
  • Memory and file storage backends

🀝 Contributing

We welcome contributions from developers, security researchers, and the broader Rust community!

Ways to Contribute

Type Impact Getting Started
πŸ› Bug Reports High Check existing issues, provide reproduction steps
πŸ”’ Security Issues Critical Email security@clockin.network privately
✨ Features High Open RFC in Discussions, implement if approved
πŸ“– Documentation Medium Improve README, add examples, fix typos
πŸ§ͺ Testing Medium Add property-based tests, improve coverage
πŸ”§ Code High Fix bugs, optimize performance, add features

Development Workflow

  1. Fork & Clone

    git clone https://github.com/your-username/chrono-merkle.git
    cd chrono-merkle
  2. Setup Development Environment

    # Install Rust 1.85+
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
    # Run full test suite
    cargo test
    cargo test --release
    cargo bench
    
    # Check code quality
    cargo fmt --check
    cargo clippy -- -D warnings
  3. Make Changes

    # Create feature branch
    git checkout -b feature/your-feature-name
    
    # Follow conventional commits
    # feat: add new feature
    # fix: resolve bug
    # docs: update documentation
    # test: add tests
  4. Submit Pull Request

    • Ensure all tests pass
    • Update documentation if needed
    • Add tests for new functionality
    • Follow code style guidelines

Code Quality Standards

  • Rust Edition 2021 with latest stable features
  • Zero unsafe code for memory safety guarantees
  • Comprehensive error handling with custom error types
  • Constant-time cryptographic operations for timing attack resistance
  • Full test coverage with integration and property-based testing
  • Performance benchmarks for all critical paths

Security Considerations

  • Cryptographic review required for crypto-related changes
  • Timing attack analysis for performance-critical code
  • Input validation for all public APIs
  • Audit logging for security events

For detailed contribution guidelines, see CONTRIBUTING.md.

πŸ“„ License

Licensed under either of:

at your option.

πŸ”— Ecosystem & Related Projects

ClockinChain Ecosystem

  • clock-rand - High-performance random number generation for Rust with blockchain-aware RNGs

Cryptographic Foundations

  • Blake3 - Fast, secure cryptographic hash function
  • RustCrypto - Comprehensive cryptography library ecosystem
  • Merkle Trees - Fundamental cryptographic data structure

Similar Projects

πŸ“ž Support & Community

Documentation & Help

Security

  • πŸ”’ Security Issues: Email security@clockin.network for private disclosure
  • πŸ“‹ Security Audit: Independent third-party security review completed
  • πŸ›‘οΈ Responsible Disclosure: 90-day disclosure policy for vulnerabilities

Commercial Support

  • 🏒 Enterprise Support: Commercial licensing and support available
  • πŸ“§ Contact: contact@clockin.network for business inquiries

ChronoMerkle - Time-aware cryptographic data structures for the next generation of blockchain and distributed systems.

Built with ❀️ by ClockinChain β€’ Licensed under MIT OR Apache-2.0