diff --git a/crates/cli/examples/build_segments.rs b/crates/cli/examples/build_segments.rs index 94409c9..2f3b375 100644 --- a/crates/cli/examples/build_segments.rs +++ b/crates/cli/examples/build_segments.rs @@ -41,7 +41,12 @@ use std::sync::atomic::Ordering; use std::sync::Arc; use std::time::Instant; -const UNITRIE_FROM: u64 = 1_591_000; +/// Mainnet's RSKIP-126 height, below which headers declare Orchid roots. +/// +/// A default, not a constant of the protocol: on testnet `wasabi100` is at +/// height 0, so the Unitrie starts at genesis, there is no Orchid era and no +/// baseline is needed. `--network testnet` sets this to 0. +const UNITRIE_FROM_MAINNET: u64 = 1_591_000; const PROGRESS_EVERY: u64 = 200; /// Blocks between dropping the materialized trie tree and re-rooting from the /// hash. @@ -68,6 +73,38 @@ fn checkpoint_every() -> u64 { .unwrap_or(CHECKPOINT_EVERY) } + +/// Open the archival trie, in whichever format it happens to be. +/// +/// Rustock keeps trie nodes in a `trie_nodes` column family; rskj keeps the +/// same bytes in the default one. The import between them is a straight +/// key-to-value copy, so an rskj snapshot can serve as the archive directly -- +/// which for testnet is the difference between parallel range builds and a +/// single sequential pass from genesis, since ranges are independent only when +/// each can seed from an archival pre-state. +/// +/// Chosen by inspecting the column families rather than by a flag, because the +/// wrong flag here is silent: a default-family reader on a rustock store finds +/// nothing and reports every node absent, which is indistinguishable from a +/// pruned archive. +fn open_archive(path: &str) -> anyhow::Result> { + let probe = rocksdb::Options::default(); + let dir = { + let p = std::path::Path::new(path); + if p.join("unitrie").join("CURRENT").exists() { p.join("unitrie") } else { p.to_path_buf() } + }; + let rustock_format = rocksdb::DB::list_cf(&probe, &dir) + .map(|cfs| cfs.iter().any(|c| c == "trie_nodes")) + .unwrap_or(true); + if rustock_format { + println!("archive {}: rustock format", dir.display()); + Ok(Arc::new(RocksDbTrieStore::open_read_only(path)?)) + } else { + println!("archive {}: rskj format, read directly (no import)", dir.display()); + Ok(Arc::new(rustock_storage::rskj_trie_store::RskjTrieStore::open_read_only(&dir)?)) + } +} + fn write_progress(path: &str, fields: &[(&str, String)]) { let body: String = fields.iter().map(|(k, v)| format!("{k}={v}\n")).collect(); let tmp = format!("{path}.tmp"); @@ -135,13 +172,40 @@ fn reclaim_own(chunks: &std::path::Path, id: &str) { fn main() -> anyhow::Result<()> { let a: Vec = std::env::args().skip(1).collect(); if a.len() < 8 { - eprintln!("usage: build_segments "); + eprintln!( + "usage: build_segments \ + \n\ + \n\ + options:\n\ + \x20 --network mainnet|testnet consensus rules AND where the Unitrie starts\n\ + \x20 (testnet implies --unitrie-from 0, because\n\ + \x20 wasabi100 is at height 0 there)\n\ + \x20 --unitrie-from N override that height explicitly\n\ + \x20 --baseline FILE pre-RSKIP126 roots, needed only below\n\ + \x20 --unitrie-from\n\ + \n\ + The archive may be a rustock store or an rskj one; the format is detected\n\ + from its column families, not from a flag." + ); std::process::exit(2); } let (id, block_dir, archive, chunks_dir, out_root) = (&a[0], &a[1], &a[2], &a[3], &a[4]); let seal_mb: u64 = a[5].parse()?; let tables: usize = a[6].parse()?; let progress = a[7].clone(); + // Which chain's rules to execute under, and where its Unitrie starts. + let testnet = a.iter().any(|x| x == "testnet") + || a.windows(2).any(|w| w[0] == "--network" && w[1] == "testnet"); + let unitrie_from: u64 = a + .windows(2) + .find(|w| w[0] == "--unitrie-from") + .and_then(|w| w[1].parse().ok()) + .unwrap_or(if testnet { 0 } else { UNITRIE_FROM_MAINNET }); + println!( + "network: {} unitrie from #{unitrie_from}", + if testnet { "TESTNET" } else { "mainnet" } + ); + let chunks = std::path::PathBuf::from(chunks_dir); reclaim_own(&chunks, id); @@ -170,7 +234,7 @@ fn main() -> anyhow::Result<()> { }; let out_dir = format!("{out_root}/{stem}"); eprintln!("[w{id}] claimed {stem} (#{start}..#{end})"); - match run_chunk(id, block_dir, archive, &out_dir, start, end, seal_mb, tables, + match run_chunk(id, block_dir, archive, &out_dir, testnet, unitrie_from, start, end, seal_mb, tables, &progress, &t_all, &mut total_done, base.as_ref()) { Ok(n) => { let _ = std::fs::rename(chunks.join(format!("{stem}.run-{id}")), @@ -191,14 +255,14 @@ fn main() -> anyhow::Result<()> { #[allow(clippy::too_many_arguments)] fn run_chunk( - id: &str, block_dir: &str, archive: &str, out_dir: &str, + id: &str, block_dir: &str, archive: &str, out_dir: &str, testnet: bool, unitrie_from: u64, start: u64, end: u64, seal_mb: u64, tables: usize, progress: &str, t_all: &Instant, total_done: &mut u64, base: Option<&std::sync::Arc>, ) -> anyhow::Result { let store = Arc::new(BlockStore::open_read_only(block_dir)?); - let fallback: Arc = Arc::new(RocksDbTrieStore::open_read_only(archive)?); + let fallback: Arc = open_archive(archive)?; let window = Arc::new(WindowStore::new( WindowConfig { seal_bytes: seal_mb * 1024 * 1024, @@ -230,7 +294,7 @@ fn run_chunk( // Seed the starting state. let mut root = if let Some(r) = seeded_root { r } else if start <= 1 { - let config = ChainConfig::mainnet(); + let config = if testnet { ChainConfig::testnet() } else { ChainConfig::mainnet() }; let mut r = TrieNode::empty(); for e in &config.genesis_alloc() { let k = account_key(&e.address); @@ -240,7 +304,7 @@ fn run_chunk( eprintln!("[w{id}] genesis root {:?}", r.compute_hash(win.as_ref())); r } else if let Some(seed) = base.and_then(|b| { - if start - 1 < UNITRIE_FROM { b.root(start - 1) } else { None } + if start - 1 < unitrie_from { b.root(start - 1) } else { None } }) { // The parent header below the fork declares an Orchid root, which is // not a key in a Unitrie store, so the baseline is the only way to @@ -271,17 +335,24 @@ fn run_chunk( TrieNode::from_message(&data, fallback.as_ref()) }; - let processor = BlockProcessor::new(RskHardforkConfig::mainnet(), store.clone()); + // The network decides the consensus rules. Executing testnet blocks under + // mainnet rules would compute different state roots for every block that + // straddles an activation the two ladders place differently -- which is + // most of them, since testnet puts orchid and wasabi100 at height 0. + let processor = BlockProcessor::new( + if testnet { RskHardforkConfig::testnet() } else { RskHardforkConfig::mainnet() }, + store.clone(), + ); let ckpt_every = checkpoint_every(); let t0 = Instant::now(); let total = end - start + 1; let mut verified = 0u64; - if start < UNITRIE_FROM && base.is_none() { + if start < unitrie_from && base.is_none() { eprintln!( - "[w{id}] WARNING: #{start}..#{} lies below #{UNITRIE_FROM}, where headers carry \ + "[w{id}] WARNING: #{start}..#{} lies below #{unitrie_from}, where headers carry \ Orchid roots. Without --baseline these blocks are replayed but NOT verified, so \ this segment will be built out of state nothing has checked.", - end.min(UNITRIE_FROM - 1) + end.min(unitrie_from.saturating_sub(1)) ); } @@ -300,7 +371,7 @@ fn run_chunk( // header is Orchid-format, so the baseline is the only thing that can // check the block -- and with no baseline the range is replayed // unchecked, which the warning above the loop calls out. - let expected: Option> = if n >= UNITRIE_FROM { + let expected: Option> = if n >= unitrie_from { Some(header_root.as_slice().to_vec()) } else { base.and_then(|b| b.root(n)).map(|r| r.to_vec()) @@ -342,10 +413,21 @@ fn run_chunk( let el = t_all.elapsed().as_secs_f64(); let rate = (chunk_base + done) as f64 / el.max(0.001); let reads = window.reads.load(Ordering::Relaxed).max(1); + // Percent and ETA, so a reader does not have to divide two of the + // other fields to learn whether this will finish tonight. + let pct = (chunk_base + done) as f64 * 100.0 / (total.max(1)) as f64; + let remaining = total.saturating_sub(chunk_base + done) as f64; + let eta_s = if rate > 0.0 { remaining / rate } else { 0.0 }; + println!( + "[w{id}] #{n} {:.2}% {rate:.1} blk/s eta {:.1} h ({}/{} blocks, {:.0}m elapsed)", + pct, eta_s / 3600.0, chunk_base + done, total, el / 60.0 + ); + let _ = std::io::Write::flush(&mut std::io::stdout()); write_progress(progress, &[ ("id", id.to_string()), ("state", "running".into()), ("block", n.to_string()), ("start", start.to_string()), ("end", end.to_string()), ("done", (chunk_base + done).to_string()), ("total", total.to_string()), + ("pct", format!("{pct:.2}")), ("eta_s", format!("{eta_s:.0}")), ("elapsed_s", format!("{el:.0}")), ("rate", format!("{rate:.2}")), ("verified", verified.to_string()), ("segments", window.segment_count().to_string()), diff --git a/crates/cli/examples/repair_segments.rs b/crates/cli/examples/repair_segments.rs index 909cdab..bba8aed 100644 --- a/crates/cli/examples/repair_segments.rs +++ b/crates/cli/examples/repair_segments.rs @@ -41,7 +41,12 @@ use std::sync::Arc; /// ever captured. Only the explicit repair write happens. struct RepairStore { segment: RocksDbTrieStore, - full: RocksDbTrieStore, + /// Shared across every segment, and opened once. + /// + /// The archival trie is 131 GB and read-only, and opening it costs 15-21 + /// seconds. Opening it inside the per-segment loop spent about twenty + /// minutes of a thirty-minute run reopening the same database 77 times. + full: Arc, inserted: AtomicU64, served: AtomicU64, } @@ -137,6 +142,16 @@ fn main() -> anyhow::Result<()> { println!("work: {} segments, {blocks} blocks", work.len()); let store = Arc::new(BlockStore::open_read_only(&block_dir)?); + // Opened once, before the loop: see `RepairStore::full`. Skipped entirely + // under --verify-only, which never reads it. + let full: Arc = if verify_only { + Arc::new(RocksDbTrieStore::open_read_only(&full_dir)?) + } else { + let t = std::time::Instant::now(); + let f = Arc::new(RocksDbTrieStore::open_read_only(&full_dir)?); + println!("fallback trie opened in {:.1}s (once, shared by every segment)", t.elapsed().as_secs_f64()); + f + }; let mut total_inserted = 0u64; let mut failures = 0usize; @@ -151,7 +166,7 @@ fn main() -> anyhow::Result<()> { if !verify_only { let rs = Arc::new(RepairStore { segment: RocksDbTrieStore::open(&dir)?, - full: RocksDbTrieStore::open_read_only(&full_dir)?, + full: Arc::clone(&full), inserted: AtomicU64::new(0), served: AtomicU64::new(0), }); diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 996aedd..0cf2667 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -1,3 +1,4 @@ +pub mod rskj_trie_store; pub mod segment_reader; pub mod trie_store; pub mod cached_trie_store; diff --git a/crates/storage/src/rskj_trie_store.rs b/crates/storage/src/rskj_trie_store.rs new file mode 100644 index 0000000..43e10b9 --- /dev/null +++ b/crates/storage/src/rskj_trie_store.rs @@ -0,0 +1,179 @@ +//! Read an **rskj** unitrie directly, without importing it first. +//! +//! rskj keeps its flat unitrie in RocksDB's **default** column family, keyed by +//! node hash. Rustock keeps the same bytes in a `trie_nodes` column family. +//! The import between them is a straight key-to-value copy -- content-addressed +//! nodes, nothing transformed -- so the only real difference is which column +//! family the bytes live in. +//! +//! That makes an adapter cheap, and worth having: it lets a tool that wants an +//! archival trie use an rskj snapshot as-is. For testnet that is the difference +//! between parallel range builds and a single sequential pass from genesis, +//! because ranges are independent only when each can seed from an archival +//! pre-state. +//! +//! # The mistake this refuses to make +//! +//! Pointing a default-column-family reader at a rustock store finds nothing and +//! reports every hash absent -- which looks exactly like a pruned archive, and +//! has already been taken for a real result once (see `rskj_root_probe`). So +//! [`RskjTrieStore::open_read_only`] **refuses** a store that has a +//! `trie_nodes` column family, rather than opening it and answering `None` to +//! everything. +//! +//! Read-only: `put` is a no-op, because an rskj snapshot is a source, never a +//! destination. + +use anyhow::{bail, Context, Result}; +use rocksdb::{Options, DB}; +use rustock_trie::TrieStore; +use std::path::{Path, PathBuf}; + +pub struct RskjTrieStore { + db: DB, +} + +impl RskjTrieStore { + /// Open an rskj unitrie for random access. + /// + /// Accepts either the `unitrie` directory itself or the database directory + /// containing it, because both are natural things to have a path to. + pub fn open_read_only(path: impl AsRef) -> Result { + let given = path.as_ref(); + let dir: PathBuf = if given.join("unitrie").join("CURRENT").exists() { + given.join("unitrie") + } else { + given.to_path_buf() + }; + if !dir.join("CURRENT").exists() { + bail!("{} is not a RocksDB store (no CURRENT)", dir.display()); + } + + // Refuse a rustock-format store rather than answering None to every + // hash. See the module note. + let probe = Options::default(); + if let Ok(cfs) = DB::list_cf(&probe, &dir) { + if cfs.iter().any(|c| c == "trie_nodes") { + bail!( + "{} has a `trie_nodes` column family, so it is a rustock store, not an \ + rskj one. Opening it here would find nothing in the default column \ + family and report every node absent, which is indistinguishable from a \ + pruned archive. Use RocksDbTrieStore for a rustock store.", + dir.display() + ); + } + } + + // Tuned for scattered point lookups, as `rskj_import::open_source_random` + // is: keep every table open and give the index and filter blocks a real + // cache, because a point lookup consults those first. The opposite + // setting -- a bounded table cache, right for a sequential scan -- made + // a comparable random workload run at ~83 reads/s. + let mut opts = Options::default(); + opts.create_if_missing(false); + opts.set_max_open_files(-1); + let cache = rocksdb::Cache::new_lru_cache(512 * 1024 * 1024); + let mut bb = rocksdb::BlockBasedOptions::default(); + bb.set_block_cache(&cache); + bb.set_cache_index_and_filter_blocks(true); + bb.set_pin_l0_filter_and_index_blocks_in_cache(true); + opts.set_block_based_table_factory(&bb); + + let db = DB::open_for_read_only(&opts, &dir, false) + .with_context(|| format!("opening rskj unitrie at {}", dir.display()))?; + Ok(Self { db }) + } +} + +impl TrieStore for RskjTrieStore { + fn get(&self, key: &[u8]) -> Option> { + self.db.get(key).ok().flatten() + } + /// A no-op: an rskj snapshot is a source, never a destination. + fn put(&self, _key: &[u8], _value: &[u8]) {} + fn flush(&self) {} +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_a_node_from_the_default_column_family() { + let dir = tempfile::tempdir().unwrap(); + { + let mut o = Options::default(); + o.create_if_missing(true); + let db = DB::open(&o, dir.path()).unwrap(); + db.put(b"\xaa\xbb", b"node-bytes").unwrap(); + } + let s = RskjTrieStore::open_read_only(dir.path()).unwrap(); + assert_eq!(s.get(b"\xaa\xbb"), Some(b"node-bytes".to_vec())); + assert_eq!(s.get(b"\x01\x02"), None); + } + + /// The failure this type exists to prevent: a rustock store opened here + /// would report every node absent, which reads as a pruned archive. + #[test] + fn refuses_a_rustock_store_instead_of_reporting_everything_absent() { + let dir = tempfile::tempdir().unwrap(); + { + let mut o = Options::default(); + o.create_if_missing(true); + o.create_missing_column_families(true); + let _ = DB::open_cf(&o, dir.path(), vec!["default", "trie_nodes"]).unwrap(); + } + let e = match RskjTrieStore::open_read_only(dir.path()) { + Ok(_) => panic!("a rustock store was accepted"), + Err(e) => e.to_string(), + }; + assert!(e.contains("trie_nodes"), "{e}"); + assert!(e.contains("rustock store"), "{e}"); + } + + #[test] + fn a_directory_that_is_not_a_store_is_refused_clearly() { + let dir = tempfile::tempdir().unwrap(); + let e = match RskjTrieStore::open_read_only(dir.path()) { + Ok(_) => panic!("a non-store directory was accepted"), + Err(e) => e.to_string(), + }; + assert!(e.contains("not a RocksDB store"), "{e}"); + } +} + +#[cfg(test)] +mod real_store_tests { + use super::*; + + /// Against a real rskj snapshot, if one is pointed at. + /// + /// The unit tests above prove the plumbing on a synthetic store; this + /// proves the format assumption on a real one, which is the part that + /// would be embarrassing to get wrong. + /// + /// ```text + /// RSKJ_UNITRIE= RSKJ_ROOT=<0xhash> \ + /// cargo test -p rustock-storage --lib real_store -- --ignored --nocapture + /// ``` + #[test] + #[ignore = "requires RSKJ_UNITRIE and RSKJ_ROOT"] + fn a_real_rskj_snapshot_answers_a_real_state_root() { + let (Ok(dir), Ok(root)) = (std::env::var("RSKJ_UNITRIE"), std::env::var("RSKJ_ROOT")) else { + eprintln!("RSKJ_UNITRIE / RSKJ_ROOT not set; skipping"); + return; + }; + let key: Vec = (0..root.trim_start_matches("0x").len()) + .step_by(2) + .map(|i| u8::from_str_radix(&root.trim_start_matches("0x")[i..i + 2], 16).unwrap()) + .collect(); + let s = RskjTrieStore::open_read_only(&dir).expect("open"); + let got = s.get(&key); + println!("root {root} -> {:?} octets", got.as_ref().map(|v| v.len())); + assert!( + got.is_some(), + "the snapshot does not hold that state root: either it is pruned, or this is \ + not the chain it belongs to" + ); + } +}