You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
use dig_blockstore::{BlockStore,BlockStoreConfig,ChainTip,L2Block,L2BlockHeader,Bytes32,BlockStatus,// re-exported from dig-block / chia-protocol};// Open or create a storelet config = BlockStoreConfig{path:"data/my-blockstore".into(),
..Default::default()};let store = BlockStore::open(config)?;// Initialize genesis
store.init_genesis(&genesis_block)?;// Extend the canonical chain
store.extend_chain(&block)?;// Query by hash or heightlet block = store.get_block(&hash)?;let header = store.get_header_by_height(42)?;let tip = store.tip();// Option<ChainTip>
Public API Reference
BlockStore — Constructors
Method
Input
Output
Description
open(config)
BlockStoreConfig
Result<BlockStore>
Open or create a store at config.path. Creates all column families, loads tip from metadata, optionally warms caches.
open_readonly(path)
impl AsRef<Path>
Result<BlockStore>
Open existing database read-only. All mutation methods return ERR_MUTATION_READ_ONLY. Path must exist.
BlockStore — Genesis & Chain Tip
Method
Input
Output
Description
init_genesis(&self, block)
&L2Block
Result<()>
Initialize an empty store with the genesis block. Atomic WriteBatch writes block + header + canonical index + tip + genesis hash. Fails if already initialized.
tip(&self)
—
Option<ChainTip>
Current canonical chain tip (hash + height). None before genesis. Lock-free read from RwLock.
height(&self)
—
Option<u64>
Shorthand for tip().map(|t| t.height).
set_tip(&self, tip)
ChainTip
Result<()>
Persist a new chain tip to CF_METADATA/META_TIP (40 bytes: hash || height LE). Updates in-memory cache.
BlockStore — Block Storage (Write)
Method
Input
Output
Description
put_block(&self, block, canonical)
&L2Block, bool
Result<bool>
Store a block. Returns true if novel, false if duplicate (idempotent). When canonical=true, also writes height→hash to CF_CANONICAL. Triggers dictionary training when block count reaches 1000.
put(&self, block, canonical)
&L2Block, bool
Result<bool>
Alias for put_block.
extend_chain(&self, block)
&L2Block
Result<bool>
Primary ingestion API: put(block, true) + set_tip. Returns false for duplicates. Does NOT validate parent-hash linkage (caller's responsibility).
put_pipelined(&self, block, canonical)
L2Block, bool
Result<Receiver<Result<bool>>>
Async batched write. Enqueues into bounded channel; background task flushes via single WriteBatch. Returns oneshot receiver for per-block ack. Requires tokio runtime.
from_bytes(&[u8]) -> Result<Self> — Decode from exactly 40 bytes
BlockRecord
In-memory block metadata. Never persisted to RocksDB. Derived from headers via from_header.
pubstructBlockRecord{pubhash:Bytes32,pubheight:u64,pubepoch:u64,pubparent_hash:Bytes32,pubin_canonical_chain:bool,// from BlockStatus::is_canonical()pubstatus:BlockStatus,// Validated | SoftFinalized | HardFinalized | Orphaned | Rejected | Pendingpubtimestamp:u64,pubproposer_index:u32,pubspend_bundle_count:u32,pubtotal_cost:u64,pubtotal_fees:u64,pubadditions_count:u32,pubremovals_count:u32,pubblock_size:u64,// 0 until filled by future APIpubl1_height:u32,publ1_hash:Bytes32,pubstate_root:Bytes32,}
StorageStats
pubstructStorageStats{pubblock_count:u64,// all blocks including forkspubcanonical_block_count:u64,// main chain onlypubheader_count:u64,pubcheckpoint_count:u64,pubattested_count:u64,pubtip_height:Option<u64>,pubmin_height:Option<u64>,// pruning floorpubtotal_size_bytes:u64,// approximate disk footprint}
ReorgResult
pubstructReorgResult{pubreverted:Vec<Bytes32>,// removed from canonical (descending height)pubapplied:Vec<Bytes32>,// added to canonical (ascending height)pubnew_tip:ChainTip,}
pubstructSnapshotManifest{pubversion:u32,// current: 1pubstart_height:u64,pubend_height:u64,pubblock_count:u64,// must equal end_height - start_height + 1pubstate_root:Bytes32,pubchecksum:Bytes32,// SHA-256 of all block data}
Error Types
pubenumBlockStoreError{RocksDb(rocksdb::Error),// RocksDB operation failedSerialization(String),// bincode/structural failureCompression(String),// zstd compress/decompress failureBlockNotFound(Bytes32),// hash not in CF_BLOCKSCheckpointNotFound(u64),// no checkpoint at epochBlockNotInStore(Bytes32),// hash not in store (chain operation)RollbackBelowMin{target:u64,min:u64},// target < min_retained_heightRollbackAboveTip{target:u64,tip:u64},// target > current tipNoTip,// no chain tip setSchemaMismatch{expected:u32,found:u32},// on-disk version mismatchNotInitialized,// store has no genesisEmptyReorgChain,// apply_reorg with empty hashesPipelineClosed,// async channel closed}
Configuration
All fields of BlockStoreConfig with defaults:
Field
Type
Default
Description
path
PathBuf
"data/blockstore"
RocksDB directory
block_cache_capacity
usize
1000
Max blocks in sharded LRU
header_cache_capacity
usize
2000
Max headers in sharded LRU
cache_shards
usize
16
Shard count (power of 2)
warm_cache_on_open
bool
true
Preload recent blocks on open
warm_cache_depth
u64
64
Heights to warm from tip
write_buffer_size
usize
67_108_864
RocksDB memtable (64 MiB)
block_cache_size
usize
134_217_728
RocksDB block cache (128 MiB)
max_open_files
i32
1000
File descriptor budget
enable_blob_db
bool
true
BlobDB for large block values
compress_blocks
bool
true
Application-level zstd
compression_level
i32
3
Zstd level
use_compression_dict
bool
true
Trained dictionary after 1000 blocks
max_decompressed_block_bytes
usize
134_217_728
Decompression bomb cap (128 MiB)
zstd_dictionary_override
Option<Vec<u8>>
None
Inject dictionary for tests
write_pipeline_batch_size
usize
64
Max blocks per WriteBatch flush
write_pipeline_flush_ms
u64
100
Partial batch flush timer
write_pipeline_channel_capacity
usize
256
Bounded async channel depth
sync_writes
bool
false
WAL sync per write
readahead_size
usize
2_097_152
Sequential readahead hint (2 MiB)
canonical_height_cache_capacity
usize
10_000
Height→hash BTreeMap entries
hash_to_height_cache_capacity
usize
10_000
Hash→height reverse LRU entries
enable_compaction_pruning
bool
false
Register compaction filter
min_retained_height
Option<u64>
None
Pruning floor (config override)
Column Families
Name
Key
Value
Purpose
blocks
hash (32 bytes)
zstd-compressed bincode L2Block
Full block bodies
headers
hash (32 bytes)
bincode L2BlockHeader
Block headers (no compression)
canonical
height (8 bytes BE)
hash (32 bytes)
Canonical chain height→hash index
metadata
UTF-8 string
varies
Tip, genesis hash, schema version, zstd dict, min height
checkpoints
epoch (8 bytes BE)
bincode StoredCheckpoint
Consensus checkpoints by epoch
attested
hash (32 bytes)
bincode AttestedBlock
Attested block data
Key Encoding Functions
Function
Input
Output
Description
hash_key(hash)
&Bytes32
&[u8; 32]
Raw 32-byte hash for CF_BLOCKS/CF_HEADERS/CF_ATTESTED keys
height_key(height)
u64
[u8; 8]
Big-endian 8-byte key for CF_CANONICAL (preserves sort order)
decode_height_key(key)
&[u8; 8]
u64
Decode big-endian height key
epoch_key(epoch)
u64
[u8; 8]
Big-endian 8-byte key for CF_CHECKPOINTS
decode_epoch_key(key)
&[u8; 8]
u64
Decode big-endian epoch key
metadata_key(name)
&str
&[u8]
UTF-8 bytes for CF_METADATA keys
Wire Format (Chia Streamable)
Function
Input
Output
Description
block_to_wire_bytes(block)
&L2Block
Result<Vec<u8>>
Chia Streamable encoding (big-endian, length-prefixed lists). NOT bincode.
The checksum covers all bytes from the start of the manifest through the last block (exclusive of the trailing 32-byte checksum itself). Computed via chia_sha2::Sha256.