tenzro-storage
State storage layer for Tenzro Network. Provides persistent storage for Tenzro Ledger (the L1 settlement layer).
Overview
The tenzro-storage crate provides a comprehensive storage infrastructure for the Tenzro Network blockchain, including efficient key-value storage, Merkle Patricia Trie state commitment, block indexing, account management, and state snapshots.
Features
- RocksDB Integration: High-performance persistent storage with 30 column families
KvStoretrait:get,put,delete,get_keys_with_prefix,write_batch,write_batch_sync— used by upper-layer registries for write-through persistence and startup hydration- Merkle Patricia Trie: Efficient state commitment and cryptographic proof generation
- Block Storage: Fast indexing and retrieval of blocks by hash and height
- Account Storage: Comprehensive account state management with balance and nonce tracking
- State Snapshots: Point-in-time state snapshots with automatic pruning and compression
- In-Memory Storage: Testing-friendly in-memory storage implementation
- Durability Guarantees: Explicit fsync via
write_batch_sync()for finalized blocks - Async/Await Support: Full async interface for all storage operations
Architecture
Column Families (28 total)
The storage layer uses RocksDB with the following column families:
blocks- Block data indexed by hash and heightstate- Merkle Patricia Trie state dataaccounts- Account state and metadatatransactions- Transaction storage and indexingmetadata- System metadata and configurationsnapshots- State snapshots at specific heightsidentities- TDIP identity registrydelegations- Identity delegation recordscredentials- Verifiable credentialschannels- Micropayment channelsagents- AI agent registry and statemodels- Model catalog and metadataproviders- Provider registrationstasks- Task marketplace dataagent_templates- Agent template definitionsskills- Skill registrytools- Tool definitionstokens- Token registry (ERC-20, SPL, CIP-56)settlements- Settlement receipts and historymodel_services- Served model endpointsnfts- NFT metadata and ownershipevents- Event store for event sourcingwebhooks- Webhook subscriptionscompliance- Compliance and audit logstraining_runs- Tenzro Train run metadatatraining_receipts- Tenzro Train commitment receiptsaudit- Audit log recordsapprovals- Approval state for multi-step flows
Data Availability Primitives (da module)
High-volume receipts (inference, agent message, channel updates) ship a commitment + pointer instead of the full payload; sensitive low-volume receipts (kill-switch, governance, escrow, lifecycle) stay inline.
ReceiptEnvelope { kind, storage_mode, inline_summary, inline_payload, da_pointer, commitment, mandate_ref }- Receipts either embed the payload (Inline) or record a pointer to an external DA layer (OffloadedDA).commitmentis alwaysSHA-256(canonical_payload)regardless of mode. The optionalmandate_refties the receipt to a signed off-chain mandate (AP2 cart, x402 challenge, MPP session, Stripe SPT, Visa TAP, Mastercard Agent Pay, Capital Intent, Workflow step) closing the audit loop from intent → settlementMandateRef { protocol, mandate_hash, issuer_did, mandate_uri?, expires_at }- Reference to a signed off-chain mandate authorizing the receipt; convenience constructorsMandateRef::ap2_cart(hash, did)andMandateRef::x402(hash, did); attach viaReceiptEnvelope::with_mandate(mandate_ref)ReceiptKind-SettlementEscrow | SettlementChannel | Inference | AgentMessage | KillSwitch | Lifecycle | Governancewith per-kinddefault_mode()DaPointer { backend, namespace, locator, commitment_kzg, attestation_root }- Reference to an external DA layer (IrohBlobs / EigenDA / Celestia / Avail)DaBackendId,DaBackendStatus#[async_trait] DaBackendtrait -submit/fetch/verify_availabilityInlineFallbackBackend- Safe default; refuses offload until external backends are wired behind feature flagscompute_commitment(payload) -> Hash- Canonical SHA-256 commitment
Merkle Patricia Trie
The Merkle Patricia Trie implementation provides:
- Efficient Storage: Path compression using extension nodes
- Cryptographic Commitment: SHA-256 based state root computation
- Proof Generation: Generate and verify Merkle proofs for state inclusion
- Node Types: Branch (16-way), Extension (path compression), and Leaf nodes
Usage
Basic Storage Setup
use ;
use Arc;
use PathBuf;
// Create storage configuration
let config = new
.with_cache_size // 512 MB cache
.with_compression;
// Open RocksDB store
let kv_store = new;
// Create block and account stores
let block_store = new?;
let account_store = new;
Block Storage
use BlockStore;
use ;
// Store a block
block_store.put_block.await?;
// Retrieve by hash
let block = block_store.get_block.await?;
// Retrieve by height
let block = block_store.get_block_by_height.await?;
// Get latest block
let latest = block_store.latest_block.await?;
// Get block range
let blocks = block_store
.blocks_by_height_range
.await?;
Account Storage
use AccountStore;
use ;
// Store an account
account_store.put_account.await?;
// Retrieve an account
let account = account_store.get_account.await?;
// Get balance
let balance = account_store.get_balance.await?;
// Update nonce
account_store.update_nonce.await?;
// Delete account
account_store.delete_account.await?;
Merkle Patricia Trie
use MerklePatriciaTrie;
let mut trie = new;
// Insert key-value pairs
trie.insert?;
trie.insert?;
// Commit changes and get state root
let state_root = trie.commit?;
// Get values
let value = trie.get?;
// Generate Merkle proof
let proof = trie.generate_proof?;
// Verify proof (reconstructs root hash from proof and verifies match)
let is_valid = verify_proof?;
// Delete a key
trie.delete?;
trie.commit?;
State Snapshots
use ;
use ;
// Create snapshot manager
let snapshot_manager = new;
// Create a snapshot
let snapshot = snapshot_manager
.create_snapshot
.await?;
// Load a snapshot
let snapshot = snapshot_manager.load_snapshot.await?;
// List all snapshots
let snapshots = snapshot_manager.list_snapshots.await?;
// Get latest snapshot
let latest = snapshot_manager.latest_snapshot.await?;
// Restore from snapshot
use SnapshotRestorer;
let restored = restore_from_snapshot.await?;
Durability and Persistence
use WriteOp;
// Buffered write (may be lost on power failure)
kv_store.write_batch?;
// Durable write with fsync (survives power failure)
kv_store.write_batch_sync?;
In-Memory Storage (Testing)
use MemoryStore;
// Create in-memory store for testing
let kv_store = new;
// Use exactly like RocksDB store
let account_store = new;
Configuration
StorageConfig Options
db_path: Path to the database directorycache_size: LRU cache size in bytes (default: 512 MB, max: 1 GB)compression: Enable/disable compression (default: true)max_open_files: Maximum number of open files (default: 1000)write_buffer_size: Write buffer size in bytes (default: 64 MB)max_write_buffer_number: Maximum write buffer count (default: 3)target_file_size_base: Target SST file size (default: 64 MB)enable_statistics: Enable RocksDB statistics (default: false)snapshot_retention: Number of snapshots to retain (default: 100)enable_wal: Enable Write-Ahead Log (default: true)
Storage Traits
StateStore
Generic state storage interface:
get(key) -> valueput(key, value)delete(key)state_root() -> Hashcommit() -> Hashrollback()
BlockStore
Block storage interface:
get_block(hash) -> Blockget_block_by_height(height) -> Blockput_block(block)latest_block() -> Blockblocks_by_height_range(start, end) -> Vec<Block>
AccountStore
Account storage interface:
get_account(address) -> Accountput_account(account)delete_account(address)get_balance(address) -> u64update_nonce(address, nonce)get_nonce(address) -> Nonce
Dependencies
rocksdb- Persistent key-value storagesha2- SHA-256 hashing for Merkle trieserde,serde_json,bincode- Serializationtokio- Async runtimeparking_lot- High-performance locksasync-trait- Async trait supportflate2- LZ4 compression for snapshots
Test Coverage
24 unit tests + 1 doc test covering:
- RocksDB store operations (get, put, delete, batch writes)
- Merkle Patricia Trie insertion, deletion, proof generation/verification
- Block storage indexing (by hash and height)
- Account storage operations
- Snapshot creation, compression, and restoration
- State root computation and commitment
- Genesis block persistence
- Durability guarantees (
write_batch_syncwith fsync)
Constants
STORAGE_VERSION: 1MAX_CACHE_SIZE: 1 GB (1,073,741,824 bytes)DEFAULT_SNAPSHOT_RETENTION: 100 snapshots
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License (http://opensource.org/licenses/MIT)
at your option.