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.
- β¨ Features
- π Quick Start
- π¦ Installation
- π Examples
- ποΈ Architecture
- π§ Advanced Usage
- π Performance
- π Security
- π€ Contributing
- π License
- β° 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
Add this to your Cargo.toml:
[dependencies]
chrono-merkle = "1.1"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 | β |
default:serde,std,blake3-hashserde: Serialization support withserdestd: Standard library support (enabled by default)blake3-hash: Blake3 hasher (enabled by default)sha2-hash: SHA-256 hasherclockhash: ClockHash integration for trace compressionparallel: Parallel tree operations with Rayonstorage: Storage backend supportfile-storage: File-based storagememory-storage: In-memory storage (enabled withstorage)postgres-storage: PostgreSQL storage backendredis-storage: Redis storage backendno-std: Embedded/no-std supportwasm: WebAssembly supportvisualization: ASCII/DOT/JSON visualization
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(())
}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
- π± 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
# 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# ClockHash integration for trace compression (requires clockhash feature)
cargo run --example clockhash_integration --features clockhash# Test all examples
cargo run --example basic_usage
cargo run --example blockchain_example
cargo run --example programmable_nodes
cargo run --example clockhash_integration --features clockhashChronoMerkle is built around a modular, cryptographically secure architecture designed for high-performance temporal data integrity.
| 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 |
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.
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)?;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)?;ChronoMerkle implements multiple layers of 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
- 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
- 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
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());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());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())?;
}ChronoMerkle is optimized for high-throughput, time-sensitive applications with enterprise-scale datasets.
| 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 |
# 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- π 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
- 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 + Syncguarantees
- β 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
- Initial release with core time-aware Merkle tree functionality
- Basic proof generation and verification
- Memory and file storage backends
We welcome contributions from developers, security researchers, and the broader Rust community!
| 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 |
-
Fork & Clone
git clone https://github.com/your-username/chrono-merkle.git cd chrono-merkle -
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
-
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
-
Submit Pull Request
- Ensure all tests pass
- Update documentation if needed
- Add tests for new functionality
- Follow code style guidelines
- 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
- 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.
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
- clock-rand - High-performance random number generation for Rust with blockchain-aware RNGs
- Blake3 - Fast, secure cryptographic hash function
- RustCrypto - Comprehensive cryptography library ecosystem
- Merkle Trees - Fundamental cryptographic data structure
- rs-merkletree - Basic Merkle tree implementation
- merkle - Another Rust Merkle tree library
- sparse-merkle-tree - Sparse Merkle tree implementation
- π API Documentation - Comprehensive Rust docs
- π Issue Tracker - Bug reports and feature requests
- π¬ Discussions - Community questions and ideas
- π Security Issues: Email
security@clockin.networkfor private disclosure - π Security Audit: Independent third-party security review completed
- π‘οΈ Responsible Disclosure: 90-day disclosure policy for vulnerabilities
- π’ Enterprise Support: Commercial licensing and support available
- π§ Contact:
contact@clockin.networkfor 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