From 47a699cc3cf7341aecffa1409e59be74a92aecc2 Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 19:58:42 +0100 Subject: [PATCH 1/9] feat(finalized-chunks,get-block): add finalized ledger chunks, catalog, streaming compactor, and getBlock serving --- Cargo.toml | 2 + blockzilla/get-block/resolver/Cargo.lock | 93 +- blockzilla/get-block/resolver/Cargo.toml | 2 + .../get-block/resolver/src/chunk_archive.rs | 371 +++++ .../get-block/resolver/src/finalized.rs | 81 +- .../get-block/resolver/src/http_tests.rs | 136 ++ blockzilla/get-block/resolver/src/lib.rs | 1 + blockzilla/get-block/resolver/src/recent.rs | 24 +- .../get-block/resolver/src/recent_tests.rs | 1 + blockzilla/get-block/src/worker.rs | 26 + .../get-block/src/worker/foundation_first.rs | 104 +- .../src/worker/foundation_first/finalized.rs | 110 +- blockzilla/get-block/src/worker/resolution.rs | 2 +- .../src/archive.rs | 572 ++++++++ .../src/lib.rs | 147 +- .../src/tests.rs | 232 +++ crates/blockzilla-account-client/src/lib.rs | 75 +- crates/blockzilla-account-client/src/tests.rs | 182 +++ crates/blockzilla-finalized-chunks/Cargo.lock | 1126 ++++++++++++++ crates/blockzilla-finalized-chunks/Cargo.toml | 36 + crates/blockzilla-finalized-chunks/README.md | 17 + .../src/builder.rs | 391 +++++ .../src/catalog.rs | 411 ++++++ .../blockzilla-finalized-chunks/src/check.rs | 135 ++ .../src/compact.rs | 1290 +++++++++++++++++ .../blockzilla-finalized-chunks/src/format.rs | 647 +++++++++ crates/blockzilla-finalized-chunks/src/lib.rs | 34 + .../src/payload.rs | 597 ++++++++ .../blockzilla-finalized-chunks/src/tests.rs | 1267 ++++++++++++++++ .../src/v2/wire_rewrite.rs | 147 +- 30 files changed, 8231 insertions(+), 28 deletions(-) create mode 100644 blockzilla/get-block/resolver/src/chunk_archive.rs create mode 100644 crates/blockzilla-account-bridge-protocol/src/archive.rs create mode 100644 crates/blockzilla-finalized-chunks/Cargo.lock create mode 100644 crates/blockzilla-finalized-chunks/Cargo.toml create mode 100644 crates/blockzilla-finalized-chunks/README.md create mode 100644 crates/blockzilla-finalized-chunks/src/builder.rs create mode 100644 crates/blockzilla-finalized-chunks/src/catalog.rs create mode 100644 crates/blockzilla-finalized-chunks/src/check.rs create mode 100644 crates/blockzilla-finalized-chunks/src/compact.rs create mode 100644 crates/blockzilla-finalized-chunks/src/format.rs create mode 100644 crates/blockzilla-finalized-chunks/src/lib.rs create mode 100644 crates/blockzilla-finalized-chunks/src/payload.rs create mode 100644 crates/blockzilla-finalized-chunks/src/tests.rs diff --git a/Cargo.toml b/Cargo.toml index 78c437e5..9b241d5c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,12 +24,14 @@ members = [ ] exclude = [ "blockzilla/builder", + "blockzilla/finalized-ledger", "blockzilla/ledger-archive", "blockzilla/get-block/resolver", "crates/blockzilla-account-bridge-protocol", "crates/blockzilla-account-client", "crates/blockzilla-bank-client", "crates/blockzilla-bank-stream-v2", + "crates/blockzilla-finalized-chunks", "zillastream/capture-core", "zillastream/geyser-plugin", "zillastream/relay", diff --git a/blockzilla/get-block/resolver/Cargo.lock b/blockzilla/get-block/resolver/Cargo.lock index 85a8f6dc..a8ac04f3 100644 --- a/blockzilla/get-block/resolver/Cargo.lock +++ b/blockzilla/get-block/resolver/Cargo.lock @@ -167,6 +167,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" @@ -203,6 +209,16 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "blockzilla-account-bridge-protocol" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "bs58", + "serde", + "serde_json", +] + [[package]] name = "blockzilla-archive-v2" version = "0.3.0" @@ -241,15 +257,39 @@ dependencies = [ "blockzilla-solana-wire", "data-encoding", "heapless", + "prost", "serde", "wincode", ] +[[package]] +name = "blockzilla-finalized-chunks" +version = "0.1.0" +dependencies = [ + "anyhow", + "blockzilla-account-bridge-protocol", + "blockzilla-archive-v2", + "blockzilla-compact", + "blockzilla-primitives", + "blockzilla-registry", + "blockzilla-solana-wire", + "bs58", + "hex", + "prost", + "rusqlite", + "serde", + "serde_json", + "sha2", + "tempfile", + "wincode", + "zstd", +] + [[package]] name = "blockzilla-get-block" version = "0.3.0" dependencies = [ - "base64", + "base64 0.23.1", "blockzilla-archive-v2", "blockzilla-compact", "blockzilla-primitives", @@ -304,9 +344,11 @@ version = "0.1.0" dependencies = [ "anyhow", "axum", - "base64", + "base64 0.23.1", + "blockzilla-account-bridge-protocol", "blockzilla-archive-v2", "blockzilla-bank-stream-v2", + "blockzilla-finalized-chunks", "blockzilla-get-block", "blockzilla-primitives", "clap", @@ -333,6 +375,8 @@ name = "blockzilla-solana-wire" version = "0.3.0" dependencies = [ "minicbor", + "prost", + "quick-protobuf", "serde", "wincode", ] @@ -1003,7 +1047,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", @@ -1153,6 +1197,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" @@ -1389,6 +1442,38 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quick-protobuf" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d6da84cc204722a989e01ba2f6e1e276e190f22263d0cb6ce8526fcdb0d2e1f" +dependencies = [ + "byteorder", +] + [[package]] name = "quinn" version = "0.11.12" @@ -1513,7 +1598,7 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-core", "futures-util", diff --git a/blockzilla/get-block/resolver/Cargo.toml b/blockzilla/get-block/resolver/Cargo.toml index cb486fe5..4fc2885d 100644 --- a/blockzilla/get-block/resolver/Cargo.toml +++ b/blockzilla/get-block/resolver/Cargo.toml @@ -19,6 +19,7 @@ blockzilla-get-block = { path = "..", default-features = false } blockzilla-archive-v2 = { path = "../../../crates/compact-v2/blockzilla-archive-v2", default-features = false, features = ["known-program-logs"] } blockzilla-primitives = { path = "../../../crates/blockzilla-primitives", default-features = false } blockzilla-bank-stream-v2 = { path = "../../../crates/blockzilla-bank-stream-v2" } +blockzilla-finalized-chunks = { path = "../../../crates/blockzilla-finalized-chunks" } clap = { version = "4.6.6", features = ["derive", "env"] } hex = "0.4.3" libc = "0.2.190" @@ -33,6 +34,7 @@ wincode = "=0.6.1" zstd = "0.14.0" [dev-dependencies] +blockzilla-account-bridge-protocol = { path = "../../../crates/blockzilla-account-bridge-protocol" } blockzilla-bank-stream-v2 = { path = "../../../crates/blockzilla-bank-stream-v2", features = ["test-fixtures"] } http-body-util = "0.1.5" tempfile = "3.27.0" diff --git a/blockzilla/get-block/resolver/src/chunk_archive.rs b/blockzilla/get-block/resolver/src/chunk_archive.rs new file mode 100644 index 00000000..eaa7e62a --- /dev/null +++ b/blockzilla/get-block/resolver/src/chunk_archive.rs @@ -0,0 +1,371 @@ +//! Read-only finalized chunk lookup for current-epoch `getBlock`. +//! +//! Queries the sealed SQLite chunk catalog written by `finalized-ledger`. +//! - In `R2` mode, returns a small verified byte-range locator (`ChunkBundleLocatorV1`) +//! so the Cloudflare Worker performs a single R2 Range GET of `chunk.bundles.bin`. +//! - In `Local` mode, reads the exact verified byte range via `pread` and returns +//! the `BlockzillaGetBlockBundleV1` directly without spawning a subprocess. +//! - For proven skipped slots and abandoned forks, returns `ChunkOutcome::Skipped` +//! immediately with zero storage or RocksDB reads. + +use std::fs::File; +use std::os::unix::fs::FileExt; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, ensure}; +use axum::body::Bytes; +use blockzilla_bank_stream_v2 as v2; +use blockzilla_finalized_chunks::{ + ChunkCatalogBinding, ChunkCatalogLookup, ChunkCatalogReader, ChunkStorageMode, +}; +use blockzilla_get_block::slot_resolution::ResolutionHotRow; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::ledger_compact::{Block, MAX_BUNDLE, Metadata}; +use crate::recent::encode_hash; + +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub catalog: PathBuf, + pub generation: String, + pub prefix: String, + #[serde(default)] + pub minimum_slot: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ChunkBundleObjectV1 { + pub key: String, + pub etag: String, + pub object_length: u64, + pub object_sha256: String, + pub offset: u64, + pub length: u64, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ChunkBundleLocatorV1 { + pub version: u16, + pub generation: String, + pub object: ChunkBundleObjectV1, + pub metadata: Metadata, +} + +pub enum ChunkOutcome { + R2Bundle(ChunkBundleLocatorV1), + LocalBundle(Block), + Skipped, +} + +pub struct Client { + config: Config, +} + +impl Client { + pub fn new(config: Config) -> Result { + ensure!( + config.catalog.is_absolute() && config.minimum_slot <= v2::SAFE, + "invalid_chunk_archive_config" + ); + ChunkCatalogBinding { + version: 1, + generation: config.generation.clone(), + prefix: config.prefix.clone(), + } + .validate() + .context("invalid_chunk_archive_binding")?; + Ok(Self { config }) + } + + pub fn generation(&self) -> &str { + &self.config.generation + } + + pub fn read(&self, slot: u64) -> Result> { + ensure!(slot <= v2::SAFE, "invalid_request"); + if slot < self.config.minimum_slot { + return Ok(None); + } + let Some(lookup) = ChunkCatalogReader::lookup( + &self.config.catalog, + &self.config.generation, + &self.config.prefix, + slot, + )? + else { + return Ok(None); + }; + match lookup { + ChunkCatalogLookup::Skipped { .. } => Ok(Some(ChunkOutcome::Skipped)), + ChunkCatalogLookup::ProducedBlock { + storage_mode, + bundles_location, + bundles_etag, + bundles_length, + bundles_sha256, + entry, + .. + } => { + let bundle_len = entry.bundle_len as usize; + ensure!( + (1..=MAX_BUNDLE).contains(&bundle_len), + "chunk_bundle_exceeds_bound" + ); + let sha256 = hex::encode(entry.bundle_sha256); + let metadata = Metadata { + version: 1, + slot, + parent_slot: entry.parent_slot, + blockhash: encode_hash(&entry.blockhash), + previous_blockhash: encode_hash(&entry.previous_blockhash), + tx_count: entry.tx_count, + hot: ResolutionHotRow { + block_id: 1, + slot, + compressed_offset: 0, + compressed_len: entry.compressed_len, + uncompressed_len: entry.uncompressed_len, + tx_count: entry.tx_count, + first_tx_ordinal: 0, + first_signature_ordinal: 0, + signature_count: entry.signature_count, + }, + sha256, + length: u64::from(entry.bundle_len), + message_schema: 0, + metadata_schema: 0, + rooted: true, + metadata_complete: true, + }; + match storage_mode { + ChunkStorageMode::R2 => { + let etag = bundles_etag.context("chunk_r2_etag_missing")?; + Ok(Some(ChunkOutcome::R2Bundle(ChunkBundleLocatorV1 { + version: 1, + generation: self.config.generation.clone(), + object: ChunkBundleObjectV1 { + key: bundles_location, + etag, + object_length: bundles_length, + object_sha256: bundles_sha256, + offset: entry.bundle_offset, + length: u64::from(entry.bundle_len), + }, + metadata, + }))) + } + ChunkStorageMode::Local => { + let path = Path::new(&bundles_location); + ensure!( + path.is_absolute() + && std::fs::symlink_metadata(path)?.is_file() + && path.canonicalize()? == path, + "chunk_local_bundles_unavailable" + ); + let file = File::open(path)?; + let file_len = file.metadata()?.len(); + let end = entry + .bundle_offset + .checked_add(u64::from(entry.bundle_len)) + .context("chunk_bundle_range_overflow")?; + ensure!( + file_len == bundles_length && end <= file_len, + "chunk_local_bundles_size_changed" + ); + let mut body = vec![0u8; bundle_len]; + file.read_exact_at(&mut body, entry.bundle_offset)?; + let digest: [u8; 32] = Sha256::digest(&body).into(); + ensure!( + digest == entry.bundle_sha256, + "chunk_local_bundle_digest_mismatch" + ); + let metadata_bytes = Bytes::from(serde_json::to_vec(&metadata)?); + ensure!(metadata_bytes.len() <= 4096, "chunk_metadata_too_large"); + Ok(Some(ChunkOutcome::LocalBundle(Block { + body: Bytes::from(body), + metadata, + metadata_bytes, + generation: self.config.generation.clone(), + }))) + } + } + } + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use blockzilla_account_bridge_protocol::{ + ArchiveBlockPayloadV1, ArchiveEntry, ArchiveShredGroup, + }; + use blockzilla_finalized_chunks::{ + CHUNK_BUNDLES_FILE, ChunkBuilder, ChunkCatalogWriter, SLOTS_PER_EPOCH, chunk_dir_name, + encode_archive_payload, + }; + + pub(crate) fn fixture_dir() -> tempfile::TempDir { + tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap() + } + + pub(crate) fn seed_catalog( + root: &Path, + mode: ChunkStorageMode, + generation: &str, + prefix: &str, + ) -> (PathBuf, u64, Vec) { + let chunks_root = root.join("chunks"); + let catalog_path = root.join("chunk_catalog.sqlite"); + let slot = SLOTS_PER_EPOCH; + let payload = ArchiveBlockPayloadV1 { + slot, + parent_slot: slot - 1, + blockhash: [0x22; 32], + previous_blockhash: [0x11; 32], + block_time: Some(1_700_000_000), + block_height: Some(100), + consensus_block_id: [0x33; 32], + markers: vec![], + rewards_proto: vec![], + entries: vec![ArchiveEntry { + num_hashes: 1, + hash: [0x22; 32], + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }; + let encoded = encode_archive_payload(&payload, 1).unwrap(); + let mut builder = ChunkBuilder::create_default(&chunks_root, slot, slot + 2).unwrap(); + builder.add_block(&encoded).unwrap(); + builder.add_skip(slot + 1).unwrap(); + builder.add_abandoned_fork(slot + 2).unwrap(); + let sealed = builder.finish().unwrap(); + + let binding = ChunkCatalogBinding { + version: 1, + generation: generation.to_owned(), + prefix: prefix.to_owned(), + }; + let mut writer = ChunkCatalogWriter::open_or_create(&catalog_path, binding).unwrap(); + match mode { + ChunkStorageMode::R2 => { + let key = format!( + "{prefix}/epoch-1/{}/{CHUNK_BUNDLES_FILE}", + chunk_dir_name(slot, slot + 2) + ); + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + ChunkStorageMode::R2, + &key, + Some("\"chunk-etag-v1\""), + ) + .unwrap(); + } + ChunkStorageMode::Local => { + let local_path = sealed.dir.join(CHUNK_BUNDLES_FILE).canonicalize().unwrap(); + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + ChunkStorageMode::Local, + local_path.to_str().unwrap(), + None, + ) + .unwrap(); + } + } + (catalog_path.canonicalize().unwrap(), slot, encoded.bundle_bytes) + } + + #[test] + fn r2_chunk_catalog_returns_verified_range_locator_and_skips() { + let dir = fixture_dir(); + let (catalog, slot, bundle_bytes) = seed_catalog( + dir.path(), + ChunkStorageMode::R2, + "chunk-gen-1", + "finalized-chunks/mainnet", + ); + let client = Client::new(Config { + catalog, + generation: "chunk-gen-1".into(), + prefix: "finalized-chunks/mainnet".into(), + minimum_slot: 0, + }) + .unwrap(); + + match client.read(slot).unwrap().unwrap() { + ChunkOutcome::R2Bundle(locator) => { + assert_eq!(locator.version, 1); + assert_eq!(locator.generation, "chunk-gen-1"); + assert_eq!(locator.object.offset, 0); + assert_eq!(locator.object.length, bundle_bytes.len() as u64); + assert_eq!(locator.object.etag, "\"chunk-etag-v1\""); + assert_eq!(locator.metadata.slot, slot); + assert_eq!(locator.metadata.sha256, hex::encode(Sha256::digest(&bundle_bytes))); + } + _ => panic!("expected R2Bundle"), + } + assert!(matches!( + client.read(slot + 1).unwrap(), + Some(ChunkOutcome::Skipped) + )); + assert!(matches!( + client.read(slot + 2).unwrap(), + Some(ChunkOutcome::Skipped) + )); + assert!(client.read(slot + 3).unwrap().is_none()); + } + + #[test] + fn local_chunk_catalog_preads_and_verifies_bundle_sha256() { + let dir = fixture_dir(); + let (catalog, slot, bundle_bytes) = seed_catalog( + dir.path(), + ChunkStorageMode::Local, + "chunk-gen-local", + "finalized-chunks/mainnet", + ); + let client = Client::new(Config { + catalog, + generation: "chunk-gen-local".into(), + prefix: "finalized-chunks/mainnet".into(), + minimum_slot: 0, + }) + .unwrap(); + + match client.read(slot).unwrap().unwrap() { + ChunkOutcome::LocalBundle(block) => { + assert_eq!(block.body.as_ref(), bundle_bytes.as_slice()); + assert_eq!(block.generation, "chunk-gen-local"); + assert_eq!(block.metadata.slot, slot); + } + _ => panic!("expected LocalBundle"), + } + + // Tampering with local bundle bytes must fail closed! + let bundles_file = dir + .path() + .join("chunks/epoch-1") + .join(chunk_dir_name(slot, slot + 2)) + .join(CHUNK_BUNDLES_FILE); + let mut tampered = std::fs::read(&bundles_file).unwrap(); + tampered[0] ^= 0xff; + std::fs::write(&bundles_file, tampered).unwrap(); + assert!(client.read(slot).is_err()); + } +} diff --git a/blockzilla/get-block/resolver/src/finalized.rs b/blockzilla/get-block/resolver/src/finalized.rs index eef3b66d..4fba48ed 100644 --- a/blockzilla/get-block/resolver/src/finalized.rs +++ b/blockzilla/get-block/resolver/src/finalized.rs @@ -88,7 +88,16 @@ pub(super) async fn block( } else { None }; - let ledger = if archive.as_ref().is_some_and(|(source, _)| source.is_none()) { + let chunk = if archive.as_ref().is_some_and(|(source, _)| source.is_none()) { + recent + .chunk_archive(slot) + .map_err(|_| anyhow::anyhow!("chunk_archive_unavailable"))? + } else { + None + }; + let ledger = if archive.as_ref().is_some_and(|(source, _)| source.is_none()) + && chunk.is_none() + { recent.ledger_compact(slot).map_err(|error| { if error.to_string() == "ledger_not_rooted" { error @@ -99,13 +108,17 @@ pub(super) async fn block( } else { None }; - if native_unavailable && ledger.is_none() && matches!(archive, Some((None, None))) { + if native_unavailable + && chunk.is_none() + && ledger.is_none() + && matches!(archive, Some((None, None))) + { // The checked feed reported failed health, and the independently // available local readers supplied no block. The archive is // still a possible source. Errors above never enter this path. return Err(ArchiveLookupRequired.into()); } - Ok((found, native_archive, archive, ledger)) + Ok((found, native_archive, archive, chunk, ledger)) })(); Ok((result, clock.finish()?)) }) @@ -125,7 +138,7 @@ pub(super) async fn block( _ => (Err(anyhow::anyhow!("finalized task failed")), None), }; let mut reply = match result { - Ok((Some(found), None, _, None)) => { + Ok((Some(found), None, _, None, None)) => { let metadata = serde_json::to_vec(&found.metadata).expect("finalized metadata JSON"); if metadata.len() > 4096 || found.root.wire.len() > 4096 { state.counters.recent_errors.fetch_add(1, Ordering::Relaxed); @@ -165,7 +178,7 @@ pub(super) async fn block( } reply } - Ok((None, Some(native_archive), None, None)) => { + Ok((None, Some(native_archive), None, None, None)) => { state.counters.recent_misses.fetch_add(1, Ordering::Relaxed); let raw=Bytes::from(serde_json::to_vec(&json!({"version":1,"slot":slot,"reason":"not_cached","source":null,"native_archive":native_archive})).expect("native archive miss JSON")); if raw.len() > 16384 { @@ -191,7 +204,51 @@ pub(super) async fn block( .insert("x-bz-foundation-cache", "BYPASS".parse().unwrap()); reply } - Ok((None, None, _, Some(ledger))) => { + Ok((None, None, _, Some(crate::chunk_archive::ChunkOutcome::R2Bundle(chunk_bundle)), None)) => { + state.counters.recent_misses.fetch_add(1, Ordering::Relaxed); + let raw = Bytes::from( + serde_json::to_vec(&json!({ + "version": 1, + "slot": slot, + "reason": "not_cached", + "source": null, + "chunk_bundle": chunk_bundle + })) + .expect("chunk bundle locator JSON"), + ); + if raw.len() > 16384 { + return unavailable( + &state, + slot, + StatusCode::SERVICE_UNAVAILABLE, + "chunk_archive_metadata_unavailable", + None, + ); + } + let sha = hex::encode(Sha256::digest(&raw)); + let mut reply = response( + &state, + StatusCode::NOT_FOUND, + "not_cached", + "application/json", + raw, + &sha, + ); + reply + .headers_mut() + .insert("x-bz-foundation-cache", "BYPASS".parse().unwrap()); + reply + } + Ok((None, None, _, Some(crate::chunk_archive::ChunkOutcome::Skipped), None)) => { + state.counters.recent_misses.fetch_add(1, Ordering::Relaxed); + let mut reply = unavailable(&state, slot, StatusCode::NOT_FOUND, "unavailable", None); + reply + .headers_mut() + .insert("x-bz-foundation-cache", "BYPASS".parse().unwrap()); + reply + } + Ok((None, None, _, Some(crate::chunk_archive::ChunkOutcome::LocalBundle(ledger)), None)) + | Ok((None, None, _, None, Some(ledger))) => { state.counters.recent_hits.fetch_add(1, Ordering::Relaxed); let mut reply = response( &state, @@ -216,7 +273,7 @@ pub(super) async fn block( } reply } - Ok((None, None, Some((source, hash)), None)) => { + Ok((None, None, Some((source, hash)), None, None)) => { state.counters.recent_misses.fetch_add(1, Ordering::Relaxed); if source.is_none() { state.enqueue_archive_miss(slot); @@ -276,6 +333,16 @@ pub(super) async fn block( None, ) } + Err(error) if error.to_string() == "chunk_archive_unavailable" => { + state.counters.recent_errors.fetch_add(1, Ordering::Relaxed); + unavailable( + &state, + slot, + StatusCode::SERVICE_UNAVAILABLE, + "chunk_archive_unavailable", + None, + ) + } Err(error) if error.to_string() == "ledger_compact_unavailable" => { state.counters.recent_errors.fetch_add(1, Ordering::Relaxed); unavailable( diff --git a/blockzilla/get-block/resolver/src/http_tests.rs b/blockzilla/get-block/resolver/src/http_tests.rs index e5c188d3..005a79cd 100644 --- a/blockzilla/get-block/resolver/src/http_tests.rs +++ b/blockzilla/get-block/resolver/src/http_tests.rs @@ -455,6 +455,7 @@ async fn finalized_slot_http_returns_verified_native_locator_after_local_retirem source: f.frame.source.clone(), producer_generation: "a".repeat(64), native_archive_catalog: Some(directory.path().join("archive.sqlite")), + chunk_archive: None, ledger_compact: None, }) .unwrap(); @@ -515,6 +516,7 @@ fn ledger_app( source: f.frame.source.clone(), producer_generation: "a".repeat(64), native_archive_catalog: None, + chunk_archive: None, ledger_compact: Some(config.clone()), }) .unwrap(); @@ -1337,3 +1339,137 @@ fn a_nonzero_result_cache_budget_is_rejected() { }); assert!(router(catalog, TOKEN, 1, 1).is_err()); } + +#[tokio::test] +async fn finalized_slot_http_serves_r2_chunk_locator_local_chunk_bundle_and_proven_skips() { + use blockzilla_finalized_chunks::ChunkStorageMode; + + // 1. R2 mode: returns 404 not_cached JSON carrying verified chunk_bundle locator, + // and returns instant 404 unavailable for proven skip / abandoned fork. + { + let dir = crate::chunk_archive::tests::fixture_dir(); + let (catalog_path, slot, bundle_bytes) = crate::chunk_archive::tests::seed_catalog( + dir.path(), + ChunkStorageMode::R2, + "chunk-gen-http-r2", + "finalized-chunks/mainnet", + ); + let f = crate::recent::tests::fixture(); + f.db.execute("DELETE FROM banks", []).unwrap(); + f.db.execute("DELETE FROM feed_events", []).unwrap(); + let recent = RecentClient::new(crate::recent::RecentConfig { + bank_source_root: f.root.path().canonicalize().unwrap(), + payload_root: f.root.path().join("processed").canonicalize().unwrap(), + source: f.frame.source.clone(), + producer_generation: "a".repeat(64), + native_archive_catalog: None, + chunk_archive: Some(crate::chunk_archive::Config { + catalog: catalog_path, + generation: "chunk-gen-http-r2".into(), + prefix: "finalized-chunks/mainnet".into(), + minimum_slot: 0, + }), + ledger_compact: None, + }) + .unwrap(); + let app = router_with_recent( + Arc::new(MockCatalog { + calls: AtomicUsize::new(0), + }), + TOKEN, + 0, + 2, + Some(Arc::new(recent)), + ) + .unwrap(); + + // Produced block -> R2 range locator JSON + let response = app + .clone() + .oneshot(get_request(&format!("/v1/finalized/{slot}"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!(response.headers()["x-bz-foundation-result"], "not_cached"); + let body = bytes(response).await; + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["version"], 1); + assert_eq!(json["slot"], slot); + assert_eq!(json["chunk_bundle"]["generation"], "chunk-gen-http-r2"); + assert_eq!(json["chunk_bundle"]["object"]["offset"], 0); + assert_eq!( + json["chunk_bundle"]["object"]["length"], + bundle_bytes.len() as u64 + ); + assert_eq!(json["chunk_bundle"]["object"]["etag"], "\"chunk-etag-v1\""); + + // ProvenSkip -> instant 404 unavailable + let skip_response = app + .clone() + .oneshot(get_request(&format!("/v1/finalized/{}", slot + 1))) + .await + .unwrap(); + assert_eq!(skip_response.status(), StatusCode::NOT_FOUND); + assert_eq!( + skip_response.headers()["x-bz-foundation-result"], + "unavailable" + ); + let skip_json: serde_json::Value = + serde_json::from_slice(&bytes(skip_response).await).unwrap(); + assert_eq!(skip_json["reason"], "unavailable"); + } + + // 2. Local mode: preads verified bundle bytes and returns 200 OK ledger_compact directly. + { + let dir = crate::chunk_archive::tests::fixture_dir(); + let (catalog_path, slot, bundle_bytes) = crate::chunk_archive::tests::seed_catalog( + dir.path(), + ChunkStorageMode::Local, + "chunk-gen-http-local", + "finalized-chunks/mainnet", + ); + let f = crate::recent::tests::fixture(); + f.db.execute("DELETE FROM banks", []).unwrap(); + f.db.execute("DELETE FROM feed_events", []).unwrap(); + let recent = RecentClient::new(crate::recent::RecentConfig { + bank_source_root: f.root.path().canonicalize().unwrap(), + payload_root: f.root.path().join("processed").canonicalize().unwrap(), + source: f.frame.source.clone(), + producer_generation: "a".repeat(64), + native_archive_catalog: None, + chunk_archive: Some(crate::chunk_archive::Config { + catalog: catalog_path, + generation: "chunk-gen-http-local".into(), + prefix: "finalized-chunks/mainnet".into(), + minimum_slot: 0, + }), + ledger_compact: None, + }) + .unwrap(); + let app = router_with_recent( + Arc::new(MockCatalog { + calls: AtomicUsize::new(0), + }), + TOKEN, + 0, + 2, + Some(Arc::new(recent)), + ) + .unwrap(); + + let response = app + .oneshot(get_request(&format!("/v1/finalized/{slot}"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers()["x-bz-foundation-result"], + "ledger_compact" + ); + assert_eq!( + response.headers()["x-bz-ledger-generation"], + "chunk-gen-http-local" + ); + assert_eq!(bytes(response).await, bundle_bytes); + } +} diff --git a/blockzilla/get-block/resolver/src/lib.rs b/blockzilla/get-block/resolver/src/lib.rs index 75b80b55..bba14aa6 100644 --- a/blockzilla/get-block/resolver/src/lib.rs +++ b/blockzilla/get-block/resolver/src/lib.rs @@ -1,6 +1,7 @@ //! A read-only ID broker. No block-resolution result cache is used. pub mod cache; pub mod catalog; +pub mod chunk_archive; pub mod direct; pub mod http; pub mod ledger_compact; diff --git a/blockzilla/get-block/resolver/src/recent.rs b/blockzilla/get-block/resolver/src/recent.rs index 68e91d35..7acf5d14 100644 --- a/blockzilla/get-block/resolver/src/recent.rs +++ b/blockzilla/get-block/resolver/src/recent.rs @@ -23,11 +23,14 @@ pub struct RecentConfig { #[serde(default)] pub native_archive_catalog: Option, #[serde(default)] + pub chunk_archive: Option, + #[serde(default)] pub ledger_compact: Option, } pub struct RecentClient { config: RecentConfig, + chunk_archive: Option, ledger: Option, } @@ -144,14 +147,25 @@ impl RecentClient { "recent_source_requires_real_absolute_directory" ); } + let chunk_archive = config + .chunk_archive + .clone() + .map(crate::chunk_archive::Client::new) + .transpose()?; let ledger = config .ledger_compact .clone() .map(crate::ledger_compact::Client::new) .transpose()?; - let client = Self { config, ledger }; + let client = Self { + config, + chunk_archive, + ledger, + }; ensure!( - client.open_checked()?.is_some() || client.ledger.is_some(), + client.open_checked()?.is_some() + || client.chunk_archive.is_some() + || client.ledger.is_some(), "recent_source_failed" ); Ok(client) @@ -182,6 +196,12 @@ impl RecentClient { }) } + pub fn chunk_archive(&self, slot: u64) -> Result> { + self.chunk_archive + .as_ref() + .map_or(Ok(None), |client| client.read(slot)) + } + pub fn ledger_compact(&self, slot: u64) -> Result> { self.ledger .as_ref() diff --git a/blockzilla/get-block/resolver/src/recent_tests.rs b/blockzilla/get-block/resolver/src/recent_tests.rs index a2894f80..94b2be5b 100644 --- a/blockzilla/get-block/resolver/src/recent_tests.rs +++ b/blockzilla/get-block/resolver/src/recent_tests.rs @@ -92,6 +92,7 @@ pub(crate) fn fixture() -> Fixture { source: frame.source.clone(), producer_generation: generation, native_archive_catalog: None, + chunk_archive: None, ledger_compact: None, }) .unwrap(); diff --git a/blockzilla/get-block/src/worker.rs b/blockzilla/get-block/src/worker.rs index 2e4bcee4..cee028f6 100644 --- a/blockzilla/get-block/src/worker.rs +++ b/blockzilla/get-block/src/worker.rs @@ -1373,6 +1373,10 @@ async fn handle_authenticated_direct_block( foundation_status = "NATIVE_ARCHIVE"; source.foundation_prepared.borrow_mut().replace(result); } + Ok(result @ foundation_first::Outcome::ChunkBundle { .. }) => { + foundation_status = "CHUNK_BUNDLE"; + source.foundation_prepared.borrow_mut().replace(result); + } Ok(result @ foundation_first::Outcome::LedgerCompact { .. }) => { foundation_status = "LEDGER_COMPACT"; source.foundation_prepared.borrow_mut().replace(result); @@ -1507,6 +1511,7 @@ async fn handle_authenticated_direct_block( Ok( foundation_first::Outcome::Native { .. } | foundation_first::Outcome::NativeArchive { .. } + | foundation_first::Outcome::ChunkBundle { .. } | foundation_first::Outcome::NativeUnavailable { .. } | foundation_first::Outcome::LedgerCompact { .. }, ) => { @@ -3479,6 +3484,27 @@ async fn fetch_direct_json_block( foundation_first::read_complete_verified(response, length, digest).await?; bundle_object::decode_ledger_bundle(source, slot, &bytes, &metadata)? } + foundation_first::Outcome::ChunkBundle { locator } => { + let length = usize::try_from(locator.object.length) + .map_err(|_| "chunk bundle exceeds runtime bounds")?; + let expected_digest = foundation_first::decode_digest(&locator.metadata.sha256)?; + let identity = crate::slot_resolution::SourceObjectIdentity { + etag: locator.object.etag.clone(), + length: locator.object.object_length, + }; + let response = resolution::pinned_origin_response( + source, + &locator.object.key, + locator.object.offset, + length, + &identity, + ) + .await?; + let bytes = + foundation_first::read_complete_verified(response, length, expected_digest) + .await?; + bundle_object::decode_ledger_bundle(source, slot, &bytes, &locator.metadata)? + } foundation_first::Outcome::Native { response, metadata, diff --git a/blockzilla/get-block/src/worker/foundation_first.rs b/blockzilla/get-block/src/worker/foundation_first.rs index 4f2b6c15..b9f4b616 100644 --- a/blockzilla/get-block/src/worker/foundation_first.rs +++ b/blockzilla/get-block/src/worker/foundation_first.rs @@ -17,7 +17,9 @@ use wasm_bindgen::prelude::wasm_bindgen; use worker::{ResponseBody, web_sys}; mod finalized; mod recent; -pub(super) use finalized::{LedgerCompactMetadata, NativeArchiveV1, read_native_frame}; +pub(super) use finalized::{ + ChunkBundleLocatorV1, LedgerCompactMetadata, NativeArchiveV1, decode_digest, read_native_frame, +}; pub(super) use recent::{RecentMetadata, RecentOutcome, RecentRequest, RecentSource}; const PROTOCOL: &str = "1"; @@ -48,6 +50,8 @@ pub(super) struct Config { native_producer_generation: Option, native_archive_prefix: Option, ledger_generation: Option, + chunk_generation: Option, + chunk_prefix: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -67,6 +71,9 @@ pub(super) enum Outcome { NativeArchive { record: NativeArchiveV1, }, + ChunkBundle { + locator: ChunkBundleLocatorV1, + }, NativeUnavailable { status: u16, reason: String, @@ -319,6 +326,8 @@ impl Config { native_producer_generation: None, native_archive_prefix: None, ledger_generation: None, + chunk_generation: None, + chunk_prefix: None, }) } @@ -401,6 +410,7 @@ impl Config { | Outcome::Complete { .. } | Outcome::Native { .. } | Outcome::NativeArchive { .. } + | Outcome::ChunkBundle { .. } | Outcome::NativeUnavailable { .. } | Outcome::LedgerCompact { .. } => { Err("Foundation ID resolution returned an invalid result type".into()) @@ -451,6 +461,7 @@ impl Config { | Outcome::Complete { .. } | Outcome::Native { .. } | Outcome::NativeArchive { .. } + | Outcome::ChunkBundle { .. } | Outcome::NativeUnavailable { .. } | Outcome::LedgerCompact { .. } => { Err("Foundation raw-block resolution returned an invalid result type".into()) @@ -1711,4 +1722,95 @@ mod tests { ); } } + + #[test] + fn chunk_bundle_locator_validates_prefix_generation_etag_bounds_and_metadata() { + let mut cfg = config(); + cfg.chunk_generation = Some("chunk-gen-1".into()); + cfg.chunk_prefix = Some("finalized-chunks/mainnet".into()); + + let bh = five8::encode_32(&[0x22; 32], &mut [0u8; 44]); + let mut bh_buf = [0u8; 44]; + let bh_len = five8::encode_32(&[0x22; 32], &mut bh_buf) as usize; + let _ = bh; + let bh_str = std::str::from_utf8(&bh_buf[..bh_len]).unwrap().to_owned(); + let mut prev_buf = [0u8; 44]; + let prev_len = five8::encode_32(&[0x11; 32], &mut prev_buf) as usize; + let prev_str = std::str::from_utf8(&prev_buf[..prev_len]).unwrap().to_owned(); + + let valid = ChunkBundleLocatorV1 { + version: 1, + generation: "chunk-gen-1".into(), + object: finalized::ChunkBundleObjectV1 { + key: "finalized-chunks/mainnet/epoch-1/chunk-000000432000-000000436095/chunk.bundles.bin".into(), + etag: "\"chunk-etag-v1\"".into(), + object_length: 10_000, + object_sha256: "a".repeat(64), + offset: 128, + length: 512, + }, + metadata: LedgerCompactMetadata { + version: 1, + slot: 432_000, + parent_slot: 431_999, + blockhash: bh_str, + previous_blockhash: prev_str, + tx_count: 1, + hot: crate::slot_resolution::ResolutionHotRow { + block_id: 1, + slot: 432_000, + compressed_offset: 0, + compressed_len: 200, + uncompressed_len: 400, + tx_count: 1, + first_tx_ordinal: 0, + first_signature_ordinal: 0, + signature_count: 1, + }, + sha256: "b".repeat(64), + length: 512, + message_schema: 0, + metadata_schema: 0, + rooted: true, + metadata_complete: true, + }, + }; + assert!(valid.validate(&cfg, 432_000).is_ok()); + + // Disabled config rejects + let mut disabled = cfg.clone(); + disabled.chunk_prefix = None; + assert!(valid.validate(&disabled, 432_000).is_err()); + + // Wrong generation + let mut bad = valid.clone(); + bad.generation = "other".into(); + assert!(bad.validate(&cfg, 432_000).is_err()); + + // Wrong prefix & path traversal + let mut bad = valid.clone(); + bad.object.key = "other/epoch-1/chunk.bundles.bin".into(); + assert!(bad.validate(&cfg, 432_000).is_err()); + let mut bad = valid.clone(); + bad.object.key = "finalized-chunks/mainnet/../secret.bin".into(); + assert!(bad.validate(&cfg, 432_000).is_err()); + + // Invalid ETag + let mut bad = valid.clone(); + bad.object.etag = "unquoted".into(); + assert!(bad.validate(&cfg, 432_000).is_err()); + + // Range out of object bounds + let mut bad = valid.clone(); + bad.object.offset = 9_600; + assert!(bad.validate(&cfg, 432_000).is_err()); + + // Metadata length disagrees with object slice length + let mut bad = valid.clone(); + bad.metadata.length = 513; + assert!(bad.validate(&cfg, 432_000).is_err()); + + // Wrong slot + assert!(valid.validate(&cfg, 432_001).is_err()); + } } diff --git a/blockzilla/get-block/src/worker/foundation_first/finalized.rs b/blockzilla/get-block/src/worker/foundation_first/finalized.rs index a7f0b8f0..359edc55 100644 --- a/blockzilla/get-block/src/worker/foundation_first/finalized.rs +++ b/blockzilla/get-block/src/worker/foundation_first/finalized.rs @@ -138,6 +138,63 @@ impl NativeArchiveV1 { } } +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChunkBundleObjectV1 { + pub(crate) key: String, + pub(crate) etag: String, + pub(crate) object_length: u64, + pub(crate) object_sha256: String, + pub(crate) offset: u64, + pub(crate) length: u64, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChunkBundleLocatorV1 { + pub(crate) version: u16, + pub(crate) generation: String, + pub(crate) object: ChunkBundleObjectV1, + pub(crate) metadata: LedgerCompactMetadata, +} + +impl ChunkBundleLocatorV1 { + pub(crate) fn validate(&self, config: &Config, slot: u64) -> std::result::Result<(), String> { + let prefix = config + .chunk_prefix + .as_ref() + .ok_or("chunk archive is disabled")?; + let prefix_slash = format!("{prefix}/"); + let etag = self.object.etag.as_bytes(); + let valid_etag = (3..=258).contains(&etag.len()) + && etag[0] == b'"' + && etag[etag.len() - 1] == b'"' + && etag[1..etag.len() - 1] + .iter() + .all(|b| b.is_ascii_graphic() && *b != b'"' && *b != b'\\'); + if self.version != 1 + || config.chunk_generation.as_deref() != Some(self.generation.as_str()) + || !self.object.key.starts_with(&prefix_slash) + || self.object.key.contains("..") + || !self.object.key.bytes().all(|b| b.is_ascii_graphic()) + || !valid_etag + || self.object.length == 0 + || self.object.length > MAX_BUNDLE_BYTES as u64 + || self + .object + .offset + .checked_add(self.object.length) + .is_none_or(|end| end > self.object.object_length) + || self.metadata.length != self.object.length + { + return Err("chunk bundle locator differs from its configured source".into()); + } + decode_digest(&self.object.object_sha256)?; + self.metadata.validate(slot)?; + Ok(()) + } +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Miss { @@ -148,9 +205,11 @@ struct Miss { source: Option, #[serde(default)] native_archive: Option, + #[serde(default)] + chunk_bundle: Option, } -fn decode_digest(value: &str) -> std::result::Result<[u8; 32], String> { +pub(crate) fn decode_digest(value: &str) -> std::result::Result<[u8; 32], String> { if value.len() != 64 || !value .bytes() @@ -267,6 +326,37 @@ impl Config { { return Err("invalid ledger compact generation".into()); } + let chunk_generation = optional_var(env, "BZ_FOUNDATION_CHUNK_GENERATION"); + let chunk_prefix = optional_var(env, "BZ_FOUNDATION_CHUNK_PREFIX"); + match (chunk_generation, chunk_prefix) { + (None, None) => {} + (Some(generation), Some(prefix)) => { + if generation.is_empty() + || generation.len() > 128 + || !generation + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) + { + return Err("invalid finalized chunk generation".into()); + } + if prefix.is_empty() + || prefix.len() > 512 + || prefix + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") + { + return Err("invalid finalized chunk prefix".into()); + } + self.chunk_generation = Some(generation); + self.chunk_prefix = Some(prefix); + } + _ => { + return Err( + "BZ_FOUNDATION_CHUNK_GENERATION and BZ_FOUNDATION_CHUNK_PREFIX are required together" + .into(), + ); + } + } Ok(()) } @@ -365,9 +455,12 @@ impl Config { let sha = decode_digest(&header("X-BZ-Foundation-SHA256")?)?; let result = header("X-BZ-Foundation-Result")?; if status == 200 && result == "ledger_compact" && header("Content-Type")? == BUNDLE_TYPE { + let delivered_generation = header("X-BZ-Ledger-Generation")?; + let generation_matches = self.ledger_generation.as_deref() + == Some(delivered_generation.as_str()) + || self.chunk_generation.as_deref() == Some(delivered_generation.as_str()); if !(1..=MAX_BUNDLE_BYTES).contains(&length) - || self.ledger_generation.as_deref() - != Some(header("X-BZ-Ledger-Generation")?.as_str()) + || !generation_matches || self.native_producer_generation.as_deref() != Some(header("X-BZ-Finalized-Producer-Generation")?.as_str()) { @@ -451,10 +544,13 @@ impl Config { if status == 404 && result == "not_cached" { let miss: Miss = serde_json::from_slice(&bytes).map_err(|_| "invalid finalized miss body")?; + let present_routes = usize::from(miss.source.is_some()) + + usize::from(miss.native_archive.is_some()) + + usize::from(miss.chunk_bundle.is_some()); if miss.version != 1 || miss.slot != slot || miss.reason != "not_cached" - || miss.source.is_some() && miss.native_archive.is_some() + || present_routes > 1 { return Err("finalized miss identity differs".into()); } @@ -462,6 +558,10 @@ impl Config { record.validate(self, slot)?; return Ok(Outcome::NativeArchive { record }); } + if let Some(locator) = miss.chunk_bundle { + locator.validate(self, slot)?; + return Ok(Outcome::ChunkBundle { locator }); + } // The legacy validator rejects unknown fields. Keep its wire // contract unchanged when this endpoint has no native record. let legacy = serde_json::to_vec(&json!({ @@ -489,6 +589,8 @@ impl Config { | "recent_capacity_unavailable" | "recent_metadata_unavailable" | "native_archive_metadata_unavailable" + | "chunk_archive_unavailable" + | "chunk_archive_metadata_unavailable" | "archive_metadata_unavailable" | "ledger_compact_unavailable" | ARCHIVE_LOOKUP_REQUIRED diff --git a/blockzilla/get-block/src/worker/resolution.rs b/blockzilla/get-block/src/worker/resolution.rs index a971b5b7..94be3533 100644 --- a/blockzilla/get-block/src/worker/resolution.rs +++ b/blockzilla/get-block/src/worker/resolution.rs @@ -1183,7 +1183,7 @@ fn record_origin_completion( }); } -async fn pinned_origin_response( +pub(super) async fn pinned_origin_response( source: &WorkerSource, path: &str, offset: u64, diff --git a/crates/blockzilla-account-bridge-protocol/src/archive.rs b/crates/blockzilla-account-bridge-protocol/src/archive.rs new file mode 100644 index 00000000..b2433d68 --- /dev/null +++ b/crates/blockzilla-account-bridge-protocol/src/archive.rs @@ -0,0 +1,572 @@ +//! Archive-grade finalized ledger bridge types and deterministic binary payload codec. +//! +//! These additive v1 operations allow a sidecar to drain finalized rooted blocks, +//! skip/fork proofs, and ancestor blockhash tails from the validator's live +//! `Blockstore` over the private Unix socket without opening a second RocksDB. + +use crate::{ + Error, MAX_BLOCK_TRANSACTIONS, MAX_LEGACY_TRANSACTION_BYTES, MAX_TRANSACTION_BYTES, Result, + V1_TRANSACTION_PREFIX, key, required_option, +}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use serde::{Deserialize, Serialize}; + +pub const MAX_SLOT_STATES_RANGE: u64 = 4_096; +pub const MAX_ANCESTOR_BLOCKHASHES: u32 = 300; +pub const MAX_ARCHIVE_MARKERS: usize = 64; +pub const MAX_ARCHIVE_MARKER_BYTES: usize = 64 * 1024; +pub const MAX_ARCHIVE_ENTRIES: usize = 256 * 1024; +pub const MAX_ARCHIVE_SHREDDING: usize = 256 * 1024; +pub const MAX_ARCHIVE_REWARDS_PROTO_BYTES: usize = 8 * 1024 * 1024; +pub const MAX_ARCHIVE_TX_STATUS_PROTO_BYTES: usize = 4 * 1024 * 1024; +pub const MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES: usize = 64 * 1024 * 1024; +pub const MAX_ARCHIVE_PAYLOAD_COMPRESSED_BYTES: usize = 16 * 1024 * 1024; + +pub const ARCHIVE_PAYLOAD_MAGIC: [u8; 8] = *b"BZARC01!"; +pub const ARCHIVE_PAYLOAD_VERSION: u16 = 1; + +fn is_sha256_hex(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn validate_canonical_base64(value: &str, max_decoded: usize, field: &'static str) -> Result { + if value.len() > max_decoded.div_ceil(3) * 4 { + return Err(Error::Invalid(field)); + } + let decoded = STANDARD.decode(value).map_err(|_| Error::Invalid(field))?; + if decoded.len() > max_decoded || STANDARD.encode(&decoded) != value { + return Err(Error::Invalid(field)); + } + Ok(decoded.len()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LedgerStatus { + pub lowest_slot: u64, + pub lowest_cleanup_slot: u64, + pub max_root: u64, + #[serde(deserialize_with = "required_option")] + pub highest_slot: Option, +} + +impl LedgerStatus { + pub fn validate(&self) -> Result<()> { + if let Some(highest) = self.highest_slot + && highest < self.max_root + { + return Err(Error::Invalid("ledger status")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SlotStateCode { + RootedFull, + RootedIncomplete, + NonRoot, + Absent, + Pruned, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SlotStates { + pub start_slot: u64, + pub end_slot: u64, + pub states: Vec, +} + +impl SlotStates { + pub fn validate(&self) -> Result<()> { + if self.end_slot < self.start_slot { + return Err(Error::Invalid("slot state range")); + } + let expected = self + .end_slot + .checked_sub(self.start_slot) + .and_then(|d| d.checked_add(1)) + .ok_or(Error::Invalid("slot state range"))?; + if expected > MAX_SLOT_STATES_RANGE || self.states.len() as u64 != expected { + return Err(Error::Invalid("slot states length")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum SlotChainRelation { + JumpsOver { next_root: u64 }, + DescendsFrom { next_root: u64 }, + NextRootIncomplete { next_root: u64 }, +} + +impl SlotChainRelation { + fn validate_for_slot(&self, slot: u64) -> Result<()> { + let next_root = match *self { + Self::JumpsOver { next_root } + | Self::DescendsFrom { next_root } + | Self::NextRootIncomplete { next_root } => next_root, + }; + if next_root <= slot { + return Err(Error::Invalid("slot chain relation")); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SlotInspection { + pub slot: u64, + pub state: SlotStateCode, + #[serde(deserialize_with = "required_option")] + pub parent_slot: Option, + #[serde(deserialize_with = "required_option")] + pub blockhash: Option, + #[serde(deserialize_with = "required_option")] + pub markers_base64: Option>, + #[serde(deserialize_with = "required_option")] + pub chain_relation: Option, +} + +impl SlotInspection { + pub fn validate(&self) -> Result<()> { + if let Some(parent) = self.parent_slot + && (parent > self.slot || (self.slot != 0 && parent == self.slot)) + { + return Err(Error::Invalid("slot inspection parent")); + } + if let Some(hash) = &self.blockhash + && !key(hash) + { + return Err(Error::Invalid("slot inspection blockhash")); + } + if let Some(markers) = &self.markers_base64 { + if markers.len() > MAX_ARCHIVE_MARKERS { + return Err(Error::Invalid("slot inspection marker count")); + } + for marker in markers { + validate_canonical_base64( + marker, + MAX_ARCHIVE_MARKER_BYTES, + "slot inspection marker base64", + )?; + } + } + if let Some(relation) = &self.chain_relation { + relation.validate_for_slot(self.slot)?; + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SlotBlockhash { + pub slot: u64, + pub blockhash: String, +} + +impl SlotBlockhash { + pub fn validate(&self) -> Result<()> { + if !key(&self.blockhash) { + return Err(Error::Invalid("ancestor blockhash")); + } + Ok(()) + } +} + +/// Wire envelope for one complete rooted archive block. +/// +/// `payload_zstd_base64` carries a zstd-compressed [`ArchiveBlockPayloadV1`]. +/// `payload_sha256` commits to the uncompressed canonical payload bytes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArchiveBlockEnvelope { + pub slot: u64, + pub parent_slot: u64, + pub blockhash: String, + pub previous_blockhash: String, + pub consensus_block_id: String, + pub payload_uncompressed_len: u32, + pub payload_sha256: String, + pub payload_zstd_base64: String, +} + +impl ArchiveBlockEnvelope { + pub fn validate(&self) -> Result<()> { + if !key(&self.blockhash) + || !key(&self.previous_blockhash) + || !key(&self.consensus_block_id) + || self.parent_slot > self.slot + || (self.slot != 0 && self.parent_slot == self.slot) + || self.payload_uncompressed_len == 0 + || self.payload_uncompressed_len as usize > MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES + || !is_sha256_hex(&self.payload_sha256) + || self.payload_zstd_base64.is_empty() + { + return Err(Error::Invalid("archive block envelope")); + } + let decoded = validate_canonical_base64( + &self.payload_zstd_base64, + MAX_ARCHIVE_PAYLOAD_COMPRESSED_BYTES, + "archive block payload base64", + )?; + if decoded == 0 { + return Err(Error::Invalid("archive block payload base64")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ArchiveEntry { + pub num_hashes: u64, + pub hash: [u8; 32], + pub tx_count: u32, + pub signature_count: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ArchiveShredGroup { + pub entry_end_idx: i64, + pub shred_end_idx: i64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ArchiveTransaction { + /// Raw Agave wincode `VersionedTransaction` bytes (legacy, V0, or V1). + pub wire_bytes: Vec, + /// Raw Agave protobuf `TransactionStatusMeta` bytes from `transaction_status_cf`. + pub status_proto: Vec, +} + +/// Complete binary payload for one rooted block, preserving all archive fields +/// (entries, shredding, block markers, consensus block ID, wire transactions, +/// and raw protobuf execution metadata and rewards). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ArchiveBlockPayloadV1 { + pub slot: u64, + pub parent_slot: u64, + pub blockhash: [u8; 32], + pub previous_blockhash: [u8; 32], + pub consensus_block_id: [u8; 32], + pub block_time: Option, + pub block_height: Option, + /// Raw Agave protobuf `Rewards` bytes from `rewards_cf`. + pub rewards_proto: Vec, + /// Raw Agave wincode `VersionedBlockMarker` bytes in shred order. + pub markers: Vec>, + pub entries: Vec, + pub shredding: Vec, + pub transactions: Vec, +} + +impl ArchiveBlockPayloadV1 { + pub fn validate(&self) -> Result<()> { + if self.parent_slot > self.slot || (self.slot != 0 && self.parent_slot == self.slot) { + return Err(Error::Invalid("archive payload parent slot")); + } + if self.rewards_proto.len() > MAX_ARCHIVE_REWARDS_PROTO_BYTES { + return Err(Error::Invalid("archive payload rewards size")); + } + if self.markers.len() > MAX_ARCHIVE_MARKERS { + return Err(Error::Invalid("archive payload marker count")); + } + for marker in &self.markers { + if marker.is_empty() || marker.len() > MAX_ARCHIVE_MARKER_BYTES { + return Err(Error::Invalid("archive payload marker size")); + } + } + if self.entries.len() > MAX_ARCHIVE_ENTRIES { + return Err(Error::Invalid("archive payload entry count")); + } + if self.shredding.len() > MAX_ARCHIVE_SHREDDING { + return Err(Error::Invalid("archive payload shredding count")); + } + if self.transactions.len() > MAX_BLOCK_TRANSACTIONS { + return Err(Error::Invalid("archive payload transaction count")); + } + let mut entry_tx_total = 0u64; + for entry in &self.entries { + entry_tx_total = entry_tx_total + .checked_add(u64::from(entry.tx_count)) + .ok_or(Error::Invalid("archive payload entry tx overflow"))?; + } + if entry_tx_total != self.transactions.len() as u64 { + return Err(Error::Invalid("archive payload entry tx mismatch")); + } + for tx in &self.transactions { + let tx_limit = if tx.wire_bytes.first() == Some(&V1_TRANSACTION_PREFIX) { + MAX_TRANSACTION_BYTES + } else { + MAX_LEGACY_TRANSACTION_BYTES + }; + if tx.wire_bytes.is_empty() + || tx.wire_bytes.len() > tx_limit + || tx.status_proto.len() > MAX_ARCHIVE_TX_STATUS_PROTO_BYTES + { + return Err(Error::Invalid("archive payload transaction bounds")); + } + } + Ok(()) + } + + pub fn encode(&self) -> Result> { + self.validate()?; + let mut out = Vec::with_capacity( + 128 + self.rewards_proto.len() + + self.entries.len() * 48 + + self.shredding.len() * 16 + + self.transactions.len() * 256, + ); + out.extend_from_slice(&ARCHIVE_PAYLOAD_MAGIC); + out.extend_from_slice(&ARCHIVE_PAYLOAD_VERSION.to_le_bytes()); + out.extend_from_slice(&self.slot.to_le_bytes()); + out.extend_from_slice(&self.parent_slot.to_le_bytes()); + out.extend_from_slice(&self.blockhash); + out.extend_from_slice(&self.previous_blockhash); + out.extend_from_slice(&self.consensus_block_id); + let mut flags = 0u8; + if self.block_time.is_some() { + flags |= 1 << 0; + } + if self.block_height.is_some() { + flags |= 1 << 1; + } + out.push(flags); + if let Some(block_time) = self.block_time { + out.extend_from_slice(&block_time.to_le_bytes()); + } + if let Some(block_height) = self.block_height { + out.extend_from_slice(&block_height.to_le_bytes()); + } + push_bytes(&mut out, &self.rewards_proto)?; + push_len(&mut out, self.markers.len())?; + for marker in &self.markers { + push_bytes(&mut out, marker)?; + } + push_len(&mut out, self.entries.len())?; + for entry in &self.entries { + out.extend_from_slice(&entry.num_hashes.to_le_bytes()); + out.extend_from_slice(&entry.hash); + out.extend_from_slice(&entry.tx_count.to_le_bytes()); + out.extend_from_slice(&entry.signature_count.to_le_bytes()); + } + push_len(&mut out, self.shredding.len())?; + for group in &self.shredding { + out.extend_from_slice(&group.entry_end_idx.to_le_bytes()); + out.extend_from_slice(&group.shred_end_idx.to_le_bytes()); + } + push_len(&mut out, self.transactions.len())?; + for tx in &self.transactions { + push_bytes(&mut out, &tx.wire_bytes)?; + push_bytes(&mut out, &tx.status_proto)?; + } + if out.len() > MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES { + return Err(Error::FrameTooLarge { + bytes: out.len(), + limit: MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, + }); + } + Ok(out) + } + + pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES { + return Err(Error::FrameTooLarge { + bytes: bytes.len(), + limit: MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, + }); + } + let mut cursor = SliceCursor::new(bytes); + let magic = cursor.read_array::<8>()?; + if magic != ARCHIVE_PAYLOAD_MAGIC { + return Err(Error::Invalid("archive payload magic")); + } + let version = cursor.read_u16()?; + if version != ARCHIVE_PAYLOAD_VERSION { + return Err(Error::Invalid("archive payload version")); + } + let slot = cursor.read_u64()?; + let parent_slot = cursor.read_u64()?; + let blockhash = cursor.read_array::<32>()?; + let previous_blockhash = cursor.read_array::<32>()?; + let consensus_block_id = cursor.read_array::<32>()?; + let flags = cursor.read_u8()?; + if flags & !0b11 != 0 { + return Err(Error::Invalid("archive payload flags")); + } + let block_time = if flags & (1 << 0) != 0 { + Some(cursor.read_i64()?) + } else { + None + }; + let block_height = if flags & (1 << 1) != 0 { + Some(cursor.read_u64()?) + } else { + None + }; + let rewards_proto = cursor.read_vec(MAX_ARCHIVE_REWARDS_PROTO_BYTES)?; + let marker_count = cursor.read_count(MAX_ARCHIVE_MARKERS)?; + let mut markers = Vec::with_capacity(marker_count); + for _ in 0..marker_count { + markers.push(cursor.read_vec(MAX_ARCHIVE_MARKER_BYTES)?); + } + let entry_count = cursor.read_count(MAX_ARCHIVE_ENTRIES)?; + if entry_count.saturating_mul(48) > cursor.remaining() { + return Err(Error::Invalid("archive payload truncated entries")); + } + let mut entries = Vec::with_capacity(entry_count); + for _ in 0..entry_count { + entries.push(ArchiveEntry { + num_hashes: cursor.read_u64()?, + hash: cursor.read_array::<32>()?, + tx_count: cursor.read_u32()?, + signature_count: cursor.read_u32()?, + }); + } + let shredding_count = cursor.read_count(MAX_ARCHIVE_SHREDDING)?; + if shredding_count.saturating_mul(16) > cursor.remaining() { + return Err(Error::Invalid("archive payload truncated shredding")); + } + let mut shredding = Vec::with_capacity(shredding_count); + for _ in 0..shredding_count { + shredding.push(ArchiveShredGroup { + entry_end_idx: cursor.read_i64()?, + shred_end_idx: cursor.read_i64()?, + }); + } + let tx_count = cursor.read_count(MAX_BLOCK_TRANSACTIONS)?; + if tx_count.saturating_mul(8) > cursor.remaining() { + return Err(Error::Invalid("archive payload truncated transactions")); + } + let mut transactions = Vec::with_capacity(tx_count); + for _ in 0..tx_count { + let wire_bytes = cursor.read_vec(MAX_TRANSACTION_BYTES)?; + let status_proto = cursor.read_vec(MAX_ARCHIVE_TX_STATUS_PROTO_BYTES)?; + transactions.push(ArchiveTransaction { + wire_bytes, + status_proto, + }); + } + if cursor.remaining() != 0 { + return Err(Error::Invalid("archive payload trailing bytes")); + } + let payload = Self { + slot, + parent_slot, + blockhash, + previous_blockhash, + consensus_block_id, + block_time, + block_height, + rewards_proto, + markers, + entries, + shredding, + transactions, + }; + payload.validate()?; + Ok(payload) + } + + pub fn validate_against_envelope(&self, envelope: &ArchiveBlockEnvelope) -> Result<()> { + if self.slot != envelope.slot + || self.parent_slot != envelope.parent_slot + || bs58::encode(self.blockhash).into_string() != envelope.blockhash + || bs58::encode(self.previous_blockhash).into_string() != envelope.previous_blockhash + || bs58::encode(self.consensus_block_id).into_string() != envelope.consensus_block_id + { + return Err(Error::BlockMismatch); + } + Ok(()) + } +} + +fn push_len(out: &mut Vec, len: usize) -> Result<()> { + let len = u32::try_from(len).map_err(|_| Error::Invalid("archive payload length"))?; + out.extend_from_slice(&len.to_le_bytes()); + Ok(()) +} + +fn push_bytes(out: &mut Vec, bytes: &[u8]) -> Result<()> { + push_len(out, bytes.len())?; + out.extend_from_slice(bytes); + Ok(()) +} + +struct SliceCursor<'a> { + bytes: &'a [u8], + offset: usize, +} + +impl<'a> SliceCursor<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, offset: 0 } + } + + fn remaining(&self) -> usize { + self.bytes.len().saturating_sub(self.offset) + } + + fn read_slice(&mut self, len: usize) -> Result<&'a [u8]> { + let end = self + .offset + .checked_add(len) + .ok_or(Error::Invalid("archive payload truncated"))?; + if end > self.bytes.len() { + return Err(Error::Invalid("archive payload truncated")); + } + let slice = &self.bytes[self.offset..end]; + self.offset = end; + Ok(slice) + } + + fn read_array(&mut self) -> Result<[u8; N]> { + let slice = self.read_slice(N)?; + let mut out = [0u8; N]; + out.copy_from_slice(slice); + Ok(out) + } + + fn read_u8(&mut self) -> Result { + Ok(self.read_array::<1>()?[0]) + } + + fn read_u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.read_array::<2>()?)) + } + + fn read_u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.read_array::<4>()?)) + } + + fn read_u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.read_array::<8>()?)) + } + + fn read_i64(&mut self) -> Result { + Ok(i64::from_le_bytes(self.read_array::<8>()?)) + } + + fn read_count(&mut self, max: usize) -> Result { + let count = self.read_u32()? as usize; + if count > max { + return Err(Error::Invalid("archive payload count exceeds limit")); + } + Ok(count) + } + + fn read_vec(&mut self, max: usize) -> Result> { + let len = self.read_count(max)?; + Ok(self.read_slice(len)?.to_vec()) + } +} diff --git a/crates/blockzilla-account-bridge-protocol/src/lib.rs b/crates/blockzilla-account-bridge-protocol/src/lib.rs index b0b74434..fdfc4361 100644 --- a/crates/blockzilla-account-bridge-protocol/src/lib.rs +++ b/crates/blockzilla-account-bridge-protocol/src/lib.rs @@ -4,6 +4,17 @@ //! A requested Bank is exact: neither the server nor the client may substitute //! a newer Bank. Account values contain no inferred historical write metadata. +pub mod archive; +pub use archive::{ + ARCHIVE_PAYLOAD_MAGIC, ARCHIVE_PAYLOAD_VERSION, ArchiveBlockEnvelope, ArchiveBlockPayloadV1, + ArchiveEntry, ArchiveShredGroup, ArchiveTransaction, LedgerStatus, MAX_ANCESTOR_BLOCKHASHES, + MAX_ARCHIVE_ENTRIES, MAX_ARCHIVE_MARKER_BYTES, MAX_ARCHIVE_MARKERS, + MAX_ARCHIVE_PAYLOAD_COMPRESSED_BYTES, MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, + MAX_ARCHIVE_REWARDS_PROTO_BYTES, MAX_ARCHIVE_SHREDDING, MAX_ARCHIVE_TX_STATUS_PROTO_BYTES, + MAX_SLOT_STATES_RANGE, SlotBlockhash, SlotChainRelation, SlotInspection, SlotStateCode, + SlotStates, +}; + use base64::{Engine, engine::general_purpose::STANDARD}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use std::{ @@ -198,11 +209,34 @@ pub enum Operation { #[serde(deserialize_with = "required_option")] expected_blockhash: Option, }, + /// Query current ledger retention and root watermarks. + GetLedgerStatus, + /// Query compact slot states over an inclusive window (at most 4096 slots). + GetSlotStates { + start_slot: u64, + end_slot: u64, + }, + /// Inspect one slot's finalized state, optional carrier markers, and parent-chain relation. + InspectSlot { + slot: u64, + include_markers: bool, + }, + /// Walk up to 300 rooted ancestors before `before_slot` (oldest first). + GetAncestorBlockhashes { + before_slot: u64, + max_count: u32, + }, + /// Read one complete rooted block in compact zstd binary archive format. + GetArchiveBlock { + slot: u64, + #[serde(deserialize_with = "required_option")] + expected_blockhash: Option, + }, } impl Operation { pub fn validate(&self) -> Result<()> { match self { - Self::Describe => Ok(()), + Self::Describe | Self::GetLedgerStatus => Ok(()), Self::GetAccount { bank, pubkey } => { bank.validate()?; if !key(pubkey) { @@ -222,12 +256,35 @@ impl Operation { } Self::GetBlock { expected_blockhash, .. + } + | Self::GetArchiveBlock { + expected_blockhash, .. } => { if expected_blockhash.as_deref().is_some_and(|hash| !key(hash)) { return Err(Error::Invalid("expected blockhash")); } Ok(()) } + Self::GetSlotStates { + start_slot, + end_slot, + } => { + let count = end_slot + .checked_sub(*start_slot) + .and_then(|d| d.checked_add(1)) + .ok_or(Error::Invalid("slot state range"))?; + if count > MAX_SLOT_STATES_RANGE { + return Err(Error::Invalid("slot state range")); + } + Ok(()) + } + Self::InspectSlot { .. } => Ok(()), + Self::GetAncestorBlockhashes { max_count, .. } => { + if *max_count == 0 || *max_count > MAX_ANCESTOR_BLOCKHASHES { + return Err(Error::Invalid("ancestor blockhash count")); + } + Ok(()) + } } } } @@ -513,6 +570,21 @@ pub enum ResponseData { GetBlock { block: LedgerBlock, }, + GetLedgerStatus { + status: LedgerStatus, + }, + GetSlotStates { + states: SlotStates, + }, + InspectSlot { + inspection: SlotInspection, + }, + GetAncestorBlockhashes { + ancestors: Vec, + }, + GetArchiveBlock { + block: ArchiveBlockEnvelope, + }, } impl ResponseData { fn validate(&self) -> Result<()> { @@ -541,6 +613,22 @@ impl ResponseData { Ok(()) } Self::GetBlock { block } => block.validate(), + Self::GetLedgerStatus { status } => status.validate(), + Self::GetSlotStates { states } => states.validate(), + Self::InspectSlot { inspection } => inspection.validate(), + Self::GetAncestorBlockhashes { ancestors } => { + if ancestors.len() > MAX_ANCESTOR_BLOCKHASHES as usize { + return Err(Error::Invalid("ancestor blockhash count")); + } + for (index, item) in ancestors.iter().enumerate() { + item.validate()?; + if index > 0 && item.slot <= ancestors[index - 1].slot { + return Err(Error::Invalid("ancestor blockhash order")); + } + } + Ok(()) + } + Self::GetArchiveBlock { block } => block.validate(), } } } @@ -660,6 +748,63 @@ impl Response { } Ok(()) } + (Operation::GetLedgerStatus, ResponseData::GetLedgerStatus { .. }) => Ok(()), + ( + Operation::GetSlotStates { + start_slot, + end_slot, + }, + ResponseData::GetSlotStates { states }, + ) => { + if states.start_slot != *start_slot || states.end_slot != *end_slot { + return Err(Error::BlockMismatch); + } + Ok(()) + } + ( + Operation::InspectSlot { + slot, + include_markers, + }, + ResponseData::InspectSlot { inspection }, + ) => { + if inspection.slot != *slot + || (!*include_markers && inspection.markers_base64.is_some()) + { + return Err(Error::BlockMismatch); + } + Ok(()) + } + ( + Operation::GetAncestorBlockhashes { + before_slot, + max_count, + }, + ResponseData::GetAncestorBlockhashes { ancestors }, + ) => { + if ancestors.len() > *max_count as usize + || ancestors.iter().any(|item| item.slot >= *before_slot) + { + return Err(Error::BlockMismatch); + } + Ok(()) + } + ( + Operation::GetArchiveBlock { + slot, + expected_blockhash, + }, + ResponseData::GetArchiveBlock { block }, + ) => { + if *slot != block.slot + || expected_blockhash + .as_ref() + .is_some_and(|hash| hash != &block.blockhash) + { + return Err(Error::BlockMismatch); + } + Ok(()) + } _ => Err(Error::OperationMismatch), } } diff --git a/crates/blockzilla-account-bridge-protocol/src/tests.rs b/crates/blockzilla-account-bridge-protocol/src/tests.rs index be3a5a3d..fd903efc 100644 --- a/crates/blockzilla-account-bridge-protocol/src/tests.rs +++ b/crates/blockzilla-account-bridge-protocol/src/tests.rs @@ -498,3 +498,235 @@ fn ledger_block_accepts_extended_v1_transactions_without_relaxing_legacy_or_v0() block.transactions[0].transaction_base64 = STANDARD.encode(bytes); assert!(block.validate().is_err()); } + +#[test] +fn archive_payload_binary_codec_round_trips_and_rejects_corruption() { + let mut v1_tx = vec![0u8; MAX_LEGACY_TRANSACTION_BYTES + 64]; + v1_tx[0] = V1_TRANSACTION_PREFIX; + let payload = ArchiveBlockPayloadV1 { + slot: 420_000, + parent_slot: 419_999, + blockhash: [11; 32], + previous_blockhash: [10; 32], + consensus_block_id: [12; 32], + block_time: Some(1_760_000_000), + block_height: Some(390_000), + rewards_proto: vec![1, 2, 3, 4], + markers: vec![vec![0xaa, 0xbb, 0xcc]], + entries: vec![ + ArchiveEntry { + num_hashes: 64, + hash: [21; 32], + tx_count: 1, + signature_count: 1, + }, + ArchiveEntry { + num_hashes: 1, + hash: [11; 32], + tx_count: 1, + signature_count: 2, + }, + ], + shredding: vec![ + ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 31, + }, + ArchiveShredGroup { + entry_end_idx: 2, + shred_end_idx: 63, + }, + ], + transactions: vec![ + ArchiveTransaction { + wire_bytes: vec![1, 2, 3, 4, 5], + status_proto: vec![9, 8, 7], + }, + ArchiveTransaction { + wire_bytes: v1_tx, + status_proto: vec![], + }, + ], + }; + let encoded = payload.encode().unwrap(); + let decoded = ArchiveBlockPayloadV1::decode(&encoded).unwrap(); + assert_eq!(decoded, payload); + + // Trailing byte must fail. + let mut trailing = encoded.clone(); + trailing.push(0); + assert!(ArchiveBlockPayloadV1::decode(&trailing).is_err()); + + // Truncated payload must fail. + assert!(ArchiveBlockPayloadV1::decode(&encoded[..encoded.len() - 1]).is_err()); + + // Bad magic must fail. + let mut bad_magic = encoded.clone(); + bad_magic[0] = b'X'; + assert!(ArchiveBlockPayloadV1::decode(&bad_magic).is_err()); + + // Mismatched entry tx sum must fail. + let mut mismatch = payload.clone(); + mismatch.entries[0].tx_count += 1; + assert!(mismatch.validate().is_err()); +} + +#[test] +fn archive_operations_validate_ranges_order_and_envelopes() { + let status_req = Request::new(10, source(), Operation::GetLedgerStatus); + let status_resp = Response::ok( + &status_req, + source(), + ResponseData::GetLedgerStatus { + status: LedgerStatus { + lowest_slot: 100, + lowest_cleanup_slot: 99, + max_root: 200, + highest_slot: Some(205), + }, + }, + ); + decode_response(&encode_response(&status_resp).unwrap()) + .unwrap() + .validate_for(&status_req) + .unwrap(); + + let states_req = Request::new( + 11, + source(), + Operation::GetSlotStates { + start_slot: 10, + end_slot: 12, + }, + ); + let states_resp = Response::ok( + &states_req, + source(), + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: 10, + end_slot: 12, + states: vec![ + SlotStateCode::RootedFull, + SlotStateCode::Absent, + SlotStateCode::NonRoot, + ], + }, + }, + ); + decode_response(&encode_response(&states_resp).unwrap()) + .unwrap() + .validate_for(&states_req) + .unwrap(); + + // Oversized slot state range rejected before wire send. + let too_wide = Request::new( + 12, + source(), + Operation::GetSlotStates { + start_slot: 0, + end_slot: MAX_SLOT_STATES_RANGE, + }, + ); + assert!(too_wide.validate().is_err()); + + let inspect_req = Request::new( + 13, + source(), + Operation::InspectSlot { + slot: 11, + include_markers: true, + }, + ); + let inspect_resp = Response::ok( + &inspect_req, + source(), + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: 11, + state: SlotStateCode::Absent, + parent_slot: None, + blockhash: None, + markers_base64: Some(vec![STANDARD.encode([1, 2, 3])]), + chain_relation: Some(SlotChainRelation::JumpsOver { next_root: 14 }), + }, + }, + ); + decode_response(&encode_response(&inspect_resp).unwrap()) + .unwrap() + .validate_for(&inspect_req) + .unwrap(); + + let ancestors_req = Request::new( + 14, + source(), + Operation::GetAncestorBlockhashes { + before_slot: 100, + max_count: 2, + }, + ); + let ancestors_resp = Response::ok( + &ancestors_req, + source(), + ResponseData::GetAncestorBlockhashes { + ancestors: vec![ + SlotBlockhash { + slot: 98, + blockhash: hash(98), + }, + SlotBlockhash { + slot: 99, + blockhash: hash(99), + }, + ], + }, + ); + decode_response(&encode_response(&ancestors_resp).unwrap()) + .unwrap() + .validate_for(&ancestors_req) + .unwrap(); + + // Ancestor >= before_slot must fail admission. + let bad_ancestors = Response::ok( + &ancestors_req, + source(), + ResponseData::GetAncestorBlockhashes { + ancestors: vec![SlotBlockhash { + slot: 100, + blockhash: hash(100), + }], + }, + ); + assert!(matches!( + bad_ancestors.validate_for(&ancestors_req), + Err(Error::BlockMismatch) + )); + + let archive_req = Request::new( + 15, + source(), + Operation::GetArchiveBlock { + slot: 50, + expected_blockhash: Some(hash(50)), + }, + ); + let envelope = ArchiveBlockEnvelope { + slot: 50, + parent_slot: 49, + blockhash: hash(50), + previous_blockhash: hash(49), + consensus_block_id: hash(51), + payload_uncompressed_len: 128, + payload_sha256: "a".repeat(64), + payload_zstd_base64: STANDARD.encode([0x28, 0xb5, 0x2f, 0xfd]), + }; + let archive_resp = Response::ok( + &archive_req, + source(), + ResponseData::GetArchiveBlock { block: envelope }, + ); + decode_response(&encode_response(&archive_resp).unwrap()) + .unwrap() + .validate_for(&archive_req) + .unwrap(); +} diff --git a/crates/blockzilla-account-client/src/lib.rs b/crates/blockzilla-account-client/src/lib.rs index 574a1193..f99f4d01 100644 --- a/crates/blockzilla-account-client/src/lib.rs +++ b/crates/blockzilla-account-client/src/lib.rs @@ -9,9 +9,11 @@ compile_error!("blockzilla-account-client requires Unix domain sockets"); use blockzilla_account_bridge_protocol::{self as protocol, Outcome, Request, ResponseData}; pub use blockzilla_account_bridge_protocol::{ - Account, AccountEntry, BankContext, BridgeError, BridgeErrorCode, ExecutionMetadata, - LedgerBlock, LedgerTransaction, LoadedAddresses, Operation, ProtocolLimits, ReturnData, - SourceIdentity, + Account, AccountEntry, ArchiveBlockEnvelope, ArchiveBlockPayloadV1, ArchiveEntry, + ArchiveShredGroup, ArchiveTransaction, BankContext, BridgeError, BridgeErrorCode, + ExecutionMetadata, LedgerBlock, LedgerStatus, LedgerTransaction, LoadedAddresses, Operation, + ProtocolLimits, ReturnData, SlotBlockhash, SlotChainRelation, SlotInspection, SlotStateCode, + SlotStates, SourceIdentity, }; use std::{ fmt, io, @@ -180,6 +182,73 @@ impl AccountClient { _ => unreachable!("response operation was admitted"), } } + /// Query current ledger retention and root watermarks. + pub async fn get_ledger_status(&self) -> Result { + match self.execute(Operation::GetLedgerStatus).await? { + ResponseData::GetLedgerStatus { status } => Ok(status), + _ => unreachable!("response operation was admitted"), + } + } + /// Query compact slot states over an inclusive window (at most 4096 slots). + pub async fn get_slot_states(&self, start_slot: u64, end_slot: u64) -> Result { + match self + .execute(Operation::GetSlotStates { + start_slot, + end_slot, + }) + .await? + { + ResponseData::GetSlotStates { states } => Ok(states), + _ => unreachable!("response operation was admitted"), + } + } + /// Inspect one slot's state, optional carrier markers, and parent-chain relation. + pub async fn inspect_slot(&self, slot: u64, include_markers: bool) -> Result { + match self + .execute(Operation::InspectSlot { + slot, + include_markers, + }) + .await? + { + ResponseData::InspectSlot { inspection } => Ok(inspection), + _ => unreachable!("response operation was admitted"), + } + } + /// Walk up to 300 rooted ancestor blockhashes before `before_slot` (oldest first). + pub async fn get_ancestor_blockhashes( + &self, + before_slot: u64, + max_count: u32, + ) -> Result> { + match self + .execute(Operation::GetAncestorBlockhashes { + before_slot, + max_count, + }) + .await? + { + ResponseData::GetAncestorBlockhashes { ancestors } => Ok(ancestors), + _ => unreachable!("response operation was admitted"), + } + } + /// Return one complete finalized block in compact zstd binary archive format. + pub async fn get_archive_block( + &self, + slot: u64, + expected_blockhash: Option<&str>, + ) -> Result { + match self + .execute(Operation::GetArchiveBlock { + slot, + expected_blockhash: expected_blockhash.map(str::to_owned), + }) + .await? + { + ResponseData::GetArchiveBlock { block } => Ok(block), + _ => unreachable!("response operation was admitted"), + } + } pub async fn execute(&self, operation: Operation) -> Result { let request_id = REQUEST_ID .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) diff --git a/crates/blockzilla-account-client/src/tests.rs b/crates/blockzilla-account-client/src/tests.rs index 3a0b21a1..2d6c75bb 100644 --- a/crates/blockzilla-account-client/src/tests.rs +++ b/crates/blockzilla-account-client/src/tests.rs @@ -628,3 +628,185 @@ fn constructor_requires_an_operator_pin_and_finite_bounds() { invalid.instance_id.clear(); assert!(AccountClient::new("/private/bridge.sock", invalid, ClientOptions::default()).is_err()); } + +#[tokio::test] +async fn archive_operations_round_trip_and_check_source_and_slot_bindings() { + use protocol::{ + ArchiveBlockEnvelope, LedgerStatus, SlotBlockhash, SlotChainRelation, SlotInspection, + SlotStateCode, SlotStates, + }; + + // 1. GetLedgerStatus + { + let (_dir, path, server) = mock(|request, socket| { + assert_eq!(request.operation, Operation::GetLedgerStatus); + write_response( + socket, + &Response::ok( + &request, + source(), + ResponseData::GetLedgerStatus { + status: LedgerStatus { + lowest_slot: 100, + lowest_cleanup_slot: 90, + max_root: 200, + highest_slot: Some(210), + }, + }, + ), + ) + .unwrap(); + }); + let status = client(path).get_ledger_status().await.unwrap(); + assert_eq!(status.lowest_slot, 100); + assert_eq!(status.max_root, 200); + server.join().unwrap(); + } + + // 2. GetSlotStates + { + let (_dir, path, server) = mock(|request, socket| { + assert_eq!( + request.operation, + Operation::GetSlotStates { + start_slot: 10, + end_slot: 12 + } + ); + write_response( + socket, + &Response::ok( + &request, + source(), + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: 10, + end_slot: 12, + states: vec![ + SlotStateCode::RootedFull, + SlotStateCode::Absent, + SlotStateCode::NonRoot, + ], + }, + }, + ), + ) + .unwrap(); + }); + let states = client(path).get_slot_states(10, 12).await.unwrap(); + assert_eq!(states.states.len(), 3); + assert_eq!(states.states[1], SlotStateCode::Absent); + server.join().unwrap(); + } + + // 3. InspectSlot + { + let (_dir, path, server) = mock(|request, socket| { + assert_eq!( + request.operation, + Operation::InspectSlot { + slot: 11, + include_markers: true, + } + ); + write_response( + socket, + &Response::ok( + &request, + source(), + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: 11, + state: SlotStateCode::Absent, + parent_slot: None, + blockhash: None, + chain_relation: Some(SlotChainRelation::JumpsOver { next_root: 12 }), + markers_base64: Some(vec![]), + }, + }, + ), + ) + .unwrap(); + }); + let inspected = client(path).inspect_slot(11, true).await.unwrap(); + assert_eq!( + inspected.chain_relation, + Some(SlotChainRelation::JumpsOver { next_root: 12 }) + ); + server.join().unwrap(); + } + + // 4. GetAncestorBlockhashes + { + let (_dir, path, server) = mock(|request, socket| { + assert_eq!( + request.operation, + Operation::GetAncestorBlockhashes { + before_slot: 100, + max_count: 2 + } + ); + write_response( + socket, + &Response::ok( + &request, + source(), + ResponseData::GetAncestorBlockhashes { + ancestors: vec![ + SlotBlockhash { + slot: 98, + blockhash: hash(98), + }, + SlotBlockhash { + slot: 99, + blockhash: hash(99), + }, + ], + }, + ), + ) + .unwrap(); + }); + let ancestors = client(path).get_ancestor_blockhashes(100, 2).await.unwrap(); + assert_eq!(ancestors.len(), 2); + assert_eq!(ancestors[0].slot, 98); + server.join().unwrap(); + } + + // 5. GetArchiveBlock + { + let (_dir, path, server) = mock(|request, socket| { + assert_eq!( + request.operation, + Operation::GetArchiveBlock { + slot: 55, + expected_blockhash: None + } + ); + write_response( + socket, + &Response::ok( + &request, + source(), + ResponseData::GetArchiveBlock { + block: ArchiveBlockEnvelope { + slot: 55, + parent_slot: 54, + blockhash: hash(55), + previous_blockhash: hash(54), + consensus_block_id: hash(56), + payload_uncompressed_len: 128, + payload_sha256: "a".repeat(64), + payload_zstd_base64: "AAAA".into(), + }, + }, + ), + ) + .unwrap(); + }); + let block = client(path).get_archive_block(55, None).await.unwrap(); + assert_eq!(block.slot, 55); + assert_eq!(block.parent_slot, 54); + server.join().unwrap(); + } +} diff --git a/crates/blockzilla-finalized-chunks/Cargo.lock b/crates/blockzilla-finalized-chunks/Cargo.lock new file mode 100644 index 00000000..0fcc8552 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/Cargo.lock @@ -0,0 +1,1126 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "arrayvec" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "binout" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff5fa7be63dbf62cca511b0e64e4b869ebc68f2b99d65fb1aa127771c5b7cd0d" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitm" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31468ea4a856000d83cb61960dfdc2980ecd96b15b61321c8c76cc96aea6e688" +dependencies = [ + "dyn_size_of", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "blockzilla-account-bridge-protocol" +version = "0.1.0" +dependencies = [ + "base64", + "bs58", + "serde", + "serde_json", +] + +[[package]] +name = "blockzilla-archive-v2" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-compact", + "blockzilla-primitives", + "blockzilla-program-logs", + "blockzilla-solana-wire", + "serde", + "sha2", + "wincode", +] + +[[package]] +name = "blockzilla-compact" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-log-parser", + "blockzilla-primitives", + "blockzilla-program-logs", + "blockzilla-registry", + "blockzilla-solana-wire", + "data-encoding", + "heapless", + "prost", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-compact-v2-reader" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-archive-v2", + "blockzilla-compact", + "blockzilla-model", + "blockzilla-primitives", + "blockzilla-program-logs", + "blockzilla-registry", + "blockzilla-source", + "blockzilla-source-local", + "ed25519-dalek", + "rayon", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "wincode", + "zstd", +] + +[[package]] +name = "blockzilla-finalized-chunks" +version = "0.1.0" +dependencies = [ + "anyhow", + "blockzilla-account-bridge-protocol", + "blockzilla-archive-v2", + "blockzilla-compact", + "blockzilla-compact-v2-reader", + "blockzilla-primitives", + "blockzilla-registry", + "blockzilla-solana-wire", + "bs58", + "hex", + "prost", + "rusqlite", + "serde", + "serde_json", + "sha2", + "tempfile", + "wincode", + "zstd", +] + +[[package]] +name = "blockzilla-log-parser" +version = "0.3.0" + +[[package]] +name = "blockzilla-model" +version = "0.3.0" +dependencies = [ + "serde", + "sha2", + "thiserror", +] + +[[package]] +name = "blockzilla-primitives" +version = "0.3.0" +dependencies = [ + "anyhow", + "five8", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-program-logs" +version = "0.3.0" +dependencies = [ + "blockzilla-primitives", + "data-encoding", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-registry" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-primitives", + "gxhash", + "memmap2", + "ph", +] + +[[package]] +name = "blockzilla-solana-wire" +version = "0.3.0" +dependencies = [ + "minicbor", + "prost", + "quick-protobuf", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-source" +version = "0.3.0" +dependencies = [ + "thiserror", +] + +[[package]] +name = "blockzilla-source-local" +version = "0.3.0" +dependencies = [ + "blockzilla-source", + "rustix", + "serde", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "byteorder" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "curve25519-dalek" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "dyn_size_of" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a742b95783b1f45b900129082cbc47717b6a77ee8d17eea70a8ea62462f5de3" + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2", + "subtle", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "five8" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f76610e969fa1784327ded240f1e28a3fd9520c9cec93b636fcf62dd37f772" +dependencies = [ + "five8_core", +] + +[[package]] +name = "five8_core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "059c31d7d36c43fe39d89e55711858b4da8be7eb6dabac23c7289b1a19489406" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "gxhash" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ce1bab7aa741d4e7042b2aae415b78741f267a98a7271ea226cd5ba6c43d7d" +dependencies = [ + "rustversion", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.2", +] + +[[package]] +name = "heapless" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411fdef4df93751117bd9ef8caa0e7f99c65dafec5bd84313eb8e2fdd75e32f2" +dependencies = [ + "hash32", + "serde_core", + "stable_deref_trait", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "minicbor" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7244eafd1e09e7c4e33043881997aa6ab6dffff3ed2cee3395a278980481d6e" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "ph" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a447f203c7254ebb06aa4f111480e821debb361e80fb4d760554a8460f236550" +dependencies = [ + "arrayvec", + "binout", + "bitm", + "dyn_size_of", + "rayon", + "seedable_hash", + "voracious_radix_sort", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quick-protobuf" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d6da84cc204722a989e01ba2f6e1e276e190f22263d0cb6ce8526fcdb0d2e1f" +dependencies = [ + "byteorder", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.40.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "seedable_hash" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba2a159211665e29bbf5a2fbb42da50dd6eadff23eef7a6a7ae4a9b0a7cd0152" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "voracious_radix_sort" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a26840011ddd3172ced523e372fc18d141e68f3b72a17312e51c5fb80b13fe78" +dependencies = [ + "rayon", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wincode" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfc6339f1ba427bf7ad7c42403b28e524832ba2ddb5eef1bb2cc3b85db6b7b75" +dependencies = [ + "pastey", + "proc-macro2", + "quote", + "smallvec", + "thiserror", + "wincode-derive", +] + +[[package]] +name = "wincode-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d582d9fc9d813264407a9e16bfa16846ccf15ef032f9bbcd700741bdc00255" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/crates/blockzilla-finalized-chunks/Cargo.toml b/crates/blockzilla-finalized-chunks/Cargo.toml new file mode 100644 index 00000000..8f5ac5f6 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "blockzilla-finalized-chunks" +version = "0.1.0" +edition = "2024" +rust-version = "1.98" +license = "MIT" +publish = false +description = "Immutable finalized ledger chunk format, catalog, and streaming Compact V2 epoch compactor" + +[workspace] + +[features] +default = ["catalog"] +catalog = ["dep:rusqlite"] + +[dependencies] +anyhow = "1.0.104" +blockzilla-account-bridge-protocol = { path = "../blockzilla-account-bridge-protocol" } +blockzilla-archive-v2 = { path = "../compact-v2/blockzilla-archive-v2", default-features = false } +blockzilla-compact = { path = "../compact-v2/blockzilla-compact", default-features = false, features = ["protobuf"] } +blockzilla-primitives = { path = "../blockzilla-primitives", default-features = false } +blockzilla-registry = { path = "../compact-v2/blockzilla-registry" } +blockzilla-solana-wire = { path = "../blockzilla-solana-wire", default-features = false, features = ["protobuf"] } +bs58 = "0.5.1" +hex = "0.4.3" +prost = "0.14.4" +rusqlite = { version = "=0.40.2", features = ["bundled", "fallible_uint"], optional = true } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +sha2 = "0.11.0" +tempfile = "3.27.0" +wincode = { version = "=0.6.1", features = ["derive"] } +zstd = "0.14.0" + +[dev-dependencies] +blockzilla-compact-v2-reader = { path = "../compact-v2/blockzilla-compact-v2-reader" } diff --git a/crates/blockzilla-finalized-chunks/README.md b/crates/blockzilla-finalized-chunks/README.md new file mode 100644 index 00000000..016bcb60 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/README.md @@ -0,0 +1,17 @@ +# Finalized ledger chunks + +Immutable, slot-ordered chunks for an in-progress Solana epoch. Each chunk +packs rooted blocks as seekable `BlockzillaGetBlockBundleV1` frames so +`getBlock` can serve any sealed slot in the current epoch with one R2 byte-range +GET, while epoch-end compaction streams the chunks in one pass without keeping a +full epoch inside RocksDB. + +## Chunk layout (`chunk--/`) + +| File | Purpose | +| --- | --- | +| `chunk.bundles.bin` | Concatenated `BlockzillaGetBlockBundleV1` frames for produced rooted blocks. | +| `chunk.index.bin` | Dense fixed-width slot table (`BZCHK01!`) mapping every slot in `[start..=end]` to a byte range + SHA-256 or a proven skip / abandoned fork. | +| `chunk.extras.zst` | zstd-compressed PoH and shredding sidecar records for epoch compaction. | +| `chunk.counts.zst` | zstd-compressed per-chunk registry-eligible pubkey counts so epoch compaction skips Pass 1 over block bodies. | +| `chunk.manifest.json` | Sealed manifest with boundary hashes, optional epoch-start ancestor tail, and file sizes/SHA-256s/ETags. | diff --git a/crates/blockzilla-finalized-chunks/src/builder.rs b/crates/blockzilla-finalized-chunks/src/builder.rs new file mode 100644 index 00000000..120c7148 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/builder.rs @@ -0,0 +1,391 @@ +//! Atomic writer for one immutable finalized ledger chunk directory. + +use std::collections::HashMap; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail, ensure}; +use sha2::{Digest, Sha256}; + +use crate::format::{ + CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, + CHUNK_MANIFEST_FILE, ChunkIndexV1, ChunkManifestV1, ChunkObjectMeta, ChunkObjects, + ChunkSlotEntry, ChunkSlotKind, TailBlockhash, chunk_dir_name, epoch_for_slot, + write_extras_header, write_extras_record, write_pubkey_counts_zstd, +}; +use crate::payload::{DEFAULT_ZSTD_LEVEL, EncodedChunkBlock, PubkeyCounts}; + +#[derive(Clone, Debug)] +pub struct SealedChunk { + pub dir: PathBuf, + pub manifest: ChunkManifestV1, + pub index_bytes: Vec, +} + +struct HashingWriter { + inner: W, + hasher: Sha256, + written: u64, +} + +impl HashingWriter { + fn new(inner: W) -> Self { + Self { + inner, + hasher: Sha256::new(), + written: 0, + } + } + + fn finish(mut self) -> Result<(W, u64, [u8; 32])> { + self.inner.flush()?; + let digest: [u8; 32] = self.hasher.finalize().into(); + Ok((self.inner, self.written, digest)) + } +} + +impl Write for HashingWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let n = self.inner.write(buf)?; + self.hasher.update(&buf[..n]); + self.written += n as u64; + Ok(n) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +/// Streams finalized blocks, proven skips, and abandoned forks for one +/// contiguous slot window `[start_slot..=end_slot]` into an atomic temporary +/// directory, then installs `parent/epoch-N/chunk--/`. +pub struct ChunkBuilder { + epoch: u64, + start_slot: u64, + end_slot: u64, + next_slot: u64, + zstd_level: i32, + epoch_dir: PathBuf, + temp_dir: tempfile::TempDir, + bundles: HashingWriter>, + extras: zstd::stream::write::Encoder<'static, HashingWriter>>, + entries: Vec, + counts: PubkeyCounts, + block_count: u64, + skip_count: u64, + fork_count: u64, + first_block_slot: Option, + last_block_slot: Option, + first_parent_slot: Option, + boundary_previous_blockhash: Option<[u8; 32]>, + last_blockhash: Option<[u8; 32]>, + previous_tail: Option>, + degraded_source: Option, +} + +impl ChunkBuilder { + pub fn create( + root_dir: &Path, + start_slot: u64, + end_slot: u64, + zstd_level: i32, + ) -> Result { + ensure!(end_slot >= start_slot, "chunk end_slot < start_slot"); + let epoch = epoch_for_slot(start_slot); + ensure!( + epoch_for_slot(end_slot) == epoch, + "chunk {start_slot}..={end_slot} crosses epoch boundary" + ); + let epoch_dir = root_dir.join(format!("epoch-{epoch}")); + fs::create_dir_all(&epoch_dir) + .with_context(|| format!("create {}", epoch_dir.display()))?; + let final_dir = epoch_dir.join(chunk_dir_name(start_slot, end_slot)); + ensure!( + !final_dir.exists(), + "chunk directory {} already exists", + final_dir.display() + ); + let temp_dir = tempfile::Builder::new() + .prefix(".chunk-tmp-") + .tempdir_in(&epoch_dir) + .context("create temp chunk dir")?; + + let bundles_file = File::create(temp_dir.path().join(CHUNK_BUNDLES_FILE)) + .context("create chunk.bundles.bin")?; + let extras_file = File::create(temp_dir.path().join(CHUNK_EXTRAS_FILE)) + .context("create chunk.extras.zst")?; + let mut extras = zstd::stream::write::Encoder::new( + HashingWriter::new(BufWriter::new(extras_file)), + zstd_level, + ) + .context("create zstd encoder for chunk.extras.zst")?; + write_extras_header(&mut extras)?; + + let capacity = usize::try_from(end_slot - start_slot + 1).context("chunk slot count")?; + Ok(Self { + epoch, + start_slot, + end_slot, + next_slot: start_slot, + zstd_level, + epoch_dir, + temp_dir, + bundles: HashingWriter::new(BufWriter::new(bundles_file)), + extras, + entries: Vec::with_capacity(capacity), + counts: HashMap::new(), + block_count: 0, + skip_count: 0, + fork_count: 0, + first_block_slot: None, + last_block_slot: None, + first_parent_slot: None, + boundary_previous_blockhash: None, + last_blockhash: None, + previous_tail: None, + degraded_source: None, + }) + } + + pub fn create_default(root_dir: &Path, start_slot: u64, end_slot: u64) -> Result { + Self::create(root_dir, start_slot, end_slot, DEFAULT_ZSTD_LEVEL) + } + + /// Attach the ≤300 ancestor blockhashes preceding this chunk (used on the + /// first chunk of an epoch to seed `prev_blockhash_tail.bin`). + pub fn set_previous_tail(&mut self, tail: Vec) { + self.previous_tail = Some(tail); + } + + /// Tag this chunk as built from a degraded fallback source (such as + /// [`crate::DEGRADED_SOURCE_RPC_ONLY`]). RPC-only chunks can serve temporary + /// `getBlock` traffic while epoch compaction refuses them until CAR + /// replacement arrives. + pub fn set_degraded_source(&mut self, source: impl Into) { + self.degraded_source = Some(source.into()); + } + + pub fn add_block(&mut self, block: &EncodedChunkBlock) -> Result<()> { + ensure!( + block.slot == self.next_slot && block.slot <= self.end_slot, + "expected slot {}, got block at slot {}", + self.next_slot, + block.slot + ); + ensure!( + block.parent_slot < block.slot, + "slot {} parent {} is not earlier", + block.slot, + block.parent_slot + ); + if let Some(prev_slot) = self.last_block_slot { + ensure!( + block.parent_slot == prev_slot + && Some(block.previous_blockhash) == self.last_blockhash, + "slot {} parent ({}, {}) does not chain to previous block ({prev_slot})", + block.slot, + block.parent_slot, + bs58::encode(block.previous_blockhash).into_string() + ); + } else { + ensure!( + block.parent_slot < self.start_slot, + "first block slot {} has parent {} inside chunk without an earlier block", + block.slot, + block.parent_slot + ); + self.first_block_slot = Some(block.slot); + self.first_parent_slot = Some(block.parent_slot); + self.boundary_previous_blockhash = Some(block.previous_blockhash); + } + + let offset = self.bundles.written; + let bundle_len = + u32::try_from(block.bundle_bytes.len()).context("bundle length exceeds u32")?; + self.bundles + .write_all(&block.bundle_bytes) + .with_context(|| format!("write bundle for slot {}", block.slot))?; + write_extras_record(&mut self.extras, &block.extras) + .with_context(|| format!("write extras for slot {}", block.slot))?; + + for (&key, &freq) in &block.pubkey_counts { + let entry = self.counts.entry(key).or_insert(0); + *entry = entry.saturating_add(freq); + } + + self.entries.push(ChunkSlotEntry { + kind: ChunkSlotKind::ProducedBlock, + bundle_offset: offset, + bundle_len, + bundle_sha256: block.bundle_sha256, + parent_slot: block.parent_slot, + blockhash: block.blockhash, + previous_blockhash: block.previous_blockhash, + compressed_len: block.hot.compressed_len, + uncompressed_len: block.hot.uncompressed_len, + tx_count: block.hot.tx_count, + signature_count: block.hot.signature_count, + block_time: block.block_time, + block_height: block.block_height, + }); + self.last_block_slot = Some(block.slot); + self.last_blockhash = Some(block.blockhash); + self.block_count += 1; + self.next_slot += 1; + Ok(()) + } + + pub fn add_skip(&mut self, slot: u64) -> Result<()> { + ensure!( + slot == self.next_slot && slot <= self.end_slot, + "expected slot {}, got skip at slot {slot}", + self.next_slot + ); + self.entries.push(ChunkSlotEntry::skipped(ChunkSlotKind::ProvenSkip)); + self.skip_count += 1; + self.next_slot += 1; + Ok(()) + } + + pub fn add_abandoned_fork(&mut self, slot: u64) -> Result<()> { + ensure!( + slot == self.next_slot && slot <= self.end_slot, + "expected slot {}, got abandoned fork at slot {slot}", + self.next_slot + ); + self.entries + .push(ChunkSlotEntry::skipped(ChunkSlotKind::AbandonedFork)); + self.fork_count += 1; + self.next_slot += 1; + Ok(()) + } + + pub fn finish(self) -> Result { + let expected_next = self + .end_slot + .checked_add(1) + .context("chunk end_slot + 1 overflows")?; + if self.next_slot != expected_next { + bail!( + "chunk {}..={} is incomplete: next expected slot is {}", + self.start_slot, + self.end_slot, + self.next_slot + ); + } + + let (bundles_buf, bundles_len, bundles_sha256) = self.bundles.finish()?; + let bundles_file = bundles_buf + .into_inner() + .map_err(|err| anyhow::anyhow!("flush chunk.bundles.bin: {err}"))?; + bundles_file.sync_all()?; + + let extras_hashing = self.extras.finish().context("finish chunk.extras.zst")?; + let (extras_buf, extras_len, extras_sha256) = extras_hashing.finish()?; + let extras_file = extras_buf + .into_inner() + .map_err(|err| anyhow::anyhow!("flush chunk.extras.zst: {err}"))?; + extras_file.sync_all()?; + + let counts_bytes = write_pubkey_counts_zstd(&self.counts, self.zstd_level)?; + let counts_sha256: [u8; 32] = Sha256::digest(&counts_bytes).into(); + write_and_sync(&self.temp_dir.path().join(CHUNK_COUNTS_FILE), &counts_bytes)?; + + let index = ChunkIndexV1 { + epoch: self.epoch, + start_slot: self.start_slot, + end_slot: self.end_slot, + bundles_len, + bundles_sha256, + first_block_slot: self.first_block_slot, + last_block_slot: self.last_block_slot, + first_parent_slot: self.first_parent_slot, + boundary_previous_blockhash: self.boundary_previous_blockhash, + last_blockhash: self.last_blockhash, + entries: self.entries, + }; + let index_bytes = index.encode()?; + let index_sha256: [u8; 32] = Sha256::digest(&index_bytes).into(); + write_and_sync(&self.temp_dir.path().join(CHUNK_INDEX_FILE), &index_bytes)?; + + let manifest = ChunkManifestV1 { + version: 1, + epoch: self.epoch, + start_slot: self.start_slot, + end_slot: self.end_slot, + block_count: self.block_count, + skip_count: self.skip_count, + fork_count: self.fork_count, + first_block_slot: self.first_block_slot, + last_block_slot: self.last_block_slot, + first_parent_slot: self.first_parent_slot, + boundary_previous_blockhash: self + .boundary_previous_blockhash + .map(|h| bs58::encode(h).into_string()), + last_blockhash: self.last_blockhash.map(|h| bs58::encode(h).into_string()), + previous_tail: self.previous_tail, + degraded_source: self.degraded_source, + objects: ChunkObjects { + bundles: ChunkObjectMeta { + path: CHUNK_BUNDLES_FILE.into(), + length: bundles_len, + sha256: hex::encode(bundles_sha256), + etag: None, + }, + index: ChunkObjectMeta { + path: CHUNK_INDEX_FILE.into(), + length: index_bytes.len() as u64, + sha256: hex::encode(index_sha256), + etag: None, + }, + extras: ChunkObjectMeta { + path: CHUNK_EXTRAS_FILE.into(), + length: extras_len, + sha256: hex::encode(extras_sha256), + etag: None, + }, + counts: ChunkObjectMeta { + path: CHUNK_COUNTS_FILE.into(), + length: counts_bytes.len() as u64, + sha256: hex::encode(counts_sha256), + etag: None, + }, + }, + }; + manifest.validate()?; + let manifest_bytes = + serde_json::to_vec_pretty(&manifest).context("serialize chunk.manifest.json")?; + write_and_sync( + &self.temp_dir.path().join(CHUNK_MANIFEST_FILE), + &manifest_bytes, + )?; + + let final_dir = self + .epoch_dir + .join(chunk_dir_name(self.start_slot, self.end_slot)); + let temp_path = self.temp_dir.keep(); + if let Err(err) = fs::rename(&temp_path, &final_dir) { + let _ = fs::remove_dir_all(&temp_path); + return Err(err).with_context(|| format!("install chunk {}", final_dir.display())); + } + if let Ok(dir_file) = File::open(&self.epoch_dir) { + let _ = dir_file.sync_all(); + } + Ok(SealedChunk { + dir: final_dir, + manifest, + index_bytes, + }) + } +} + +fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> { + let mut file = File::create(path).with_context(|| format!("create {}", path.display()))?; + file.write_all(bytes) + .with_context(|| format!("write {}", path.display()))?; + file.sync_all() + .with_context(|| format!("sync {}", path.display()))?; + Ok(()) +} diff --git a/crates/blockzilla-finalized-chunks/src/catalog.rs b/crates/blockzilla-finalized-chunks/src/catalog.rs new file mode 100644 index 00000000..b1b1672a --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/catalog.rs @@ -0,0 +1,411 @@ +//! Shared SQLite chunk catalog written by the finalized-ledger daemon and +//! queried read-only by `get-block/resolver`. + +use std::fs; +use std::path::Path; + +use anyhow::{Context, Result, bail, ensure}; +use rusqlite::{Connection, OpenFlags, params}; +use serde::{Deserialize, Serialize}; + +use crate::format::{ChunkIndexV1, ChunkManifestV1, ChunkSlotEntry, ChunkSlotKind, epoch_for_slot}; + +const MAX_BINDING_BYTES: usize = 16 * 1024; +const MAX_INDEX_BLOB_BYTES: usize = 16 * 1024 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ChunkStorageMode { + R2, + Local, +} + +impl ChunkStorageMode { + fn as_str(self) -> &'static str { + match self { + Self::R2 => "r2", + Self::Local => "local", + } + } + + fn parse(value: &str) -> Result { + match value { + "r2" => Ok(Self::R2), + "local" => Ok(Self::Local), + other => bail!("invalid chunk storage mode '{other}'"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChunkCatalogBinding { + pub version: u16, + pub generation: String, + pub prefix: String, +} + +impl ChunkCatalogBinding { + pub fn validate(&self) -> Result<()> { + ensure!(self.version == 1, "unsupported chunk catalog version"); + ensure!( + !self.generation.is_empty() + && self.generation.len() <= 128 + && self + .generation + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)), + "invalid chunk catalog generation" + ); + ensure!( + !self.prefix.is_empty() + && self.prefix.len() <= 512 + && !self + .prefix + .split('/') + .any(|part| part.is_empty() || part == "." || part == ".."), + "invalid chunk catalog prefix" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ChunkCatalogLookup { + ProducedBlock { + epoch: u64, + start_slot: u64, + end_slot: u64, + storage_mode: ChunkStorageMode, + bundles_location: String, + bundles_etag: Option, + bundles_length: u64, + bundles_sha256: String, + entry: ChunkSlotEntry, + }, + Skipped { + epoch: u64, + kind: ChunkSlotKind, + }, +} + +pub struct ChunkCatalogWriter { + db: Connection, + binding: ChunkCatalogBinding, +} + +impl ChunkCatalogWriter { + pub fn open_or_create(path: &Path, binding: ChunkCatalogBinding) -> Result { + binding.validate()?; + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("create catalog dir {}", parent.display()))?; + } + let db = Connection::open(path) + .with_context(|| format!("open chunk catalog {}", path.display()))?; + db.execute_batch( + "PRAGMA journal_mode=WAL; + PRAGMA synchronous=FULL; + PRAGMA trusted_schema=OFF; + CREATE TABLE IF NOT EXISTS meta ( + id INTEGER PRIMARY KEY CHECK (id = 1), + record TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS chunks ( + start_slot INTEGER PRIMARY KEY, + end_slot INTEGER NOT NULL UNIQUE, + epoch INTEGER NOT NULL, + storage_mode TEXT NOT NULL, + bundles_location TEXT NOT NULL, + bundles_etag TEXT, + bundles_length INTEGER NOT NULL, + bundles_sha256 TEXT NOT NULL, + index_blob BLOB NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_chunks_epoch ON chunks(epoch, start_slot); + CREATE INDEX IF NOT EXISTS idx_chunks_end_slot ON chunks(end_slot);", + )?; + + let existing: Option = { + let mut stmt = db.prepare("SELECT record FROM meta WHERE id = 1")?; + let mut rows = stmt.query([])?; + rows.next()?.map(|row| row.get(0)).transpose()? + }; + if let Some(raw) = existing { + let stored: ChunkCatalogBinding = + serde_json::from_str(&raw).context("parse stored chunk catalog binding")?; + ensure!( + stored == binding, + "chunk catalog binding differs from existing database" + ); + } else { + let encoded = serde_json::to_string(&binding)?; + db.execute("INSERT INTO meta(id, record) VALUES(1, ?1)", [encoded])?; + } + Ok(Self { db, binding }) + } + + pub fn binding(&self) -> &ChunkCatalogBinding { + &self.binding + } + + /// Atomically register one verified sealed chunk into the catalog. + /// Rejects overlapping slot ranges with different content. + pub fn register_chunk( + &mut self, + manifest: &ChunkManifestV1, + index_bytes: &[u8], + storage_mode: ChunkStorageMode, + bundles_location: &str, + bundles_etag: Option<&str>, + ) -> Result<()> { + manifest.validate()?; + let parsed = ChunkIndexV1::decode(index_bytes)?; + ensure!( + parsed.epoch == manifest.epoch + && parsed.start_slot == manifest.start_slot + && parsed.end_slot == manifest.end_slot + && parsed.bundles_len == manifest.objects.bundles.length + && hex::encode(parsed.bundles_sha256) == manifest.objects.bundles.sha256, + "chunk index bytes disagree with chunk manifest" + ); + ensure!( + index_bytes.len() <= MAX_INDEX_BLOB_BYTES, + "chunk index exceeds catalog blob limit" + ); + validate_location(storage_mode, &self.binding.prefix, bundles_location, bundles_etag)?; + + let tx = self.db.transaction()?; + let overlap: Option<(u64, u64, String)> = { + let mut stmt = tx.prepare( + "SELECT start_slot, end_slot, bundles_sha256 + FROM chunks + WHERE start_slot <= ?2 AND end_slot >= ?1 + LIMIT 1", + )?; + let mut rows = stmt.query(params![manifest.start_slot, manifest.end_slot])?; + rows.next()? + .map(|row| Ok::<_, rusqlite::Error>((row.get(0)?, row.get(1)?, row.get(2)?))) + .transpose()? + }; + if let Some((start, end, sha)) = overlap { + if start == manifest.start_slot + && end == manifest.end_slot + && sha == manifest.objects.bundles.sha256 + { + // Idempotent re-registration of the exact same verified chunk. + tx.execute( + "UPDATE chunks + SET storage_mode = ?2, bundles_location = ?3, bundles_etag = ?4 + WHERE start_slot = ?1", + params![ + manifest.start_slot, + storage_mode.as_str(), + bundles_location, + bundles_etag + ], + )?; + tx.commit()?; + return Ok(()); + } + bail!( + "chunk {}..={} overlaps existing catalog chunk {start}..={end}", + manifest.start_slot, + manifest.end_slot + ); + } + tx.execute( + "INSERT INTO chunks( + start_slot, end_slot, epoch, storage_mode, bundles_location, + bundles_etag, bundles_length, bundles_sha256, index_blob + ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + params![ + manifest.start_slot, + manifest.end_slot, + manifest.epoch, + storage_mode.as_str(), + bundles_location, + bundles_etag, + manifest.objects.bundles.length, + manifest.objects.bundles.sha256, + index_bytes, + ], + )?; + tx.commit()?; + Ok(()) + } + + pub fn highest_sealed_slot(&self) -> Result> { + let mut stmt = self.db.prepare("SELECT MAX(end_slot) FROM chunks")?; + let mut rows = stmt.query([])?; + Ok(rows.next()?.and_then(|row| row.get::<_, Option>(0).ok()).flatten()) + } + + pub fn remove_epoch(&mut self, epoch: u64) -> Result { + let deleted = self + .db + .execute("DELETE FROM chunks WHERE epoch = ?1", [epoch])?; + Ok(deleted) + } +} + +pub struct ChunkCatalogReader; + +impl ChunkCatalogReader { + /// Read one slot from a pinned read-only SQLite snapshot. Never mutates the + /// database and fails closed if the catalog binding changed. + pub fn lookup( + path: &Path, + expected_generation: &str, + expected_prefix: &str, + slot: u64, + ) -> Result> { + ensure!( + path.is_absolute() + && fs::symlink_metadata(path)?.is_file() + && path.canonicalize()? == path, + "chunk_catalog_unavailable" + ); + let db = Connection::open_with_flags( + path, + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, + )?; + db.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN;")?; + let binding_raw: String = { + let mut stmt = db.prepare("SELECT length(CAST(record AS BLOB)), record FROM meta WHERE id = 1")?; + let mut rows = stmt.query([])?; + let Some(row) = rows.next()? else { + bail!("chunk_catalog_binding_unavailable"); + }; + let len: u64 = row.get(0)?; + ensure!(len <= MAX_BINDING_BYTES as u64, "chunk_catalog_binding_too_large"); + let raw: String = row.get(1)?; + ensure!(rows.next()?.is_none(), "chunk_catalog_binding_ambiguous"); + raw + }; + let binding: ChunkCatalogBinding = serde_json::from_str(&binding_raw)?; + binding.validate()?; + ensure!( + binding.generation == expected_generation && binding.prefix == expected_prefix, + "chunk_catalog_binding_changed" + ); + + let mut stmt = db.prepare( + "SELECT start_slot, end_slot, epoch, storage_mode, bundles_location, + bundles_etag, bundles_length, bundles_sha256, + length(index_blob), index_blob + FROM chunks + WHERE start_slot <= ?1 AND end_slot >= ?1", + )?; + let mut rows = stmt.query([slot])?; + let Some(row) = rows.next()? else { + return Ok(None); + }; + let start_slot: u64 = row.get(0)?; + let end_slot: u64 = row.get(1)?; + let epoch: u64 = row.get(2)?; + let storage_mode = ChunkStorageMode::parse(&row.get::<_, String>(3)?)?; + let bundles_location: String = row.get(4)?; + let bundles_etag: Option = row.get(5)?; + let bundles_length: u64 = row.get(6)?; + let bundles_sha256: String = row.get(7)?; + let blob_len: u64 = row.get(8)?; + ensure!( + blob_len <= MAX_INDEX_BLOB_BYTES as u64, + "chunk_index_blob_too_large" + ); + let index_blob: Vec = row.get(9)?; + ensure!(rows.next()?.is_none(), "chunk_catalog_slot_ambiguous"); + + ensure!( + epoch == epoch_for_slot(slot) + && slot >= start_slot + && slot <= end_slot + && is_sha256_hex(&bundles_sha256), + "chunk_catalog_row_invalid" + ); + validate_location( + storage_mode, + expected_prefix, + &bundles_location, + bundles_etag.as_deref(), + )?; + + let Some((index_epoch, entry)) = ChunkIndexV1::lookup_in_bytes(&index_blob, slot)? else { + bail!("chunk_index_slot_missing"); + }; + ensure!(index_epoch == epoch, "chunk_index_epoch_mismatch"); + + match entry.kind { + ChunkSlotKind::ProducedBlock => { + let end = entry + .bundle_offset + .checked_add(u64::from(entry.bundle_len)) + .context("chunk_bundle_range_overflow")?; + ensure!( + entry.bundle_len > 0 && end <= bundles_length, + "chunk_bundle_range_out_of_bounds" + ); + Ok(Some(ChunkCatalogLookup::ProducedBlock { + epoch, + start_slot, + end_slot, + storage_mode, + bundles_location, + bundles_etag, + bundles_length, + bundles_sha256, + entry, + })) + } + ChunkSlotKind::ProvenSkip | ChunkSlotKind::AbandonedFork => { + Ok(Some(ChunkCatalogLookup::Skipped { + epoch, + kind: entry.kind, + })) + } + } + } +} + +fn is_sha256_hex(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn validate_location( + mode: ChunkStorageMode, + expected_prefix: &str, + location: &str, + etag: Option<&str>, +) -> Result<()> { + match mode { + ChunkStorageMode::R2 => { + let prefix_slash = format!("{expected_prefix}/"); + ensure!( + location.starts_with(&prefix_slash) + && !location.contains("..") + && location.bytes().all(|b| b.is_ascii_graphic()), + "chunk_r2_key_invalid" + ); + let etag = etag.context("chunk_r2_etag_missing")?; + let bytes = etag.as_bytes(); + ensure!( + (3..=258).contains(&bytes.len()) + && bytes[0] == b'"' + && bytes[bytes.len() - 1] == b'"' + && bytes[1..bytes.len() - 1] + .iter() + .all(|b| b.is_ascii_graphic() && *b != b'"' && *b != b'\\'), + "chunk_r2_etag_invalid" + ); + } + ChunkStorageMode::Local => { + let path = Path::new(location); + ensure!(path.is_absolute(), "chunk_local_path_not_absolute"); + } + } + Ok(()) +} diff --git a/crates/blockzilla-finalized-chunks/src/check.rs b/crates/blockzilla-finalized-chunks/src/check.rs new file mode 100644 index 00000000..4954c4af --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/check.rs @@ -0,0 +1,135 @@ +//! Alpenglow N+8 skip/notarization certificate and abandoned-fork checks. +//! +//! Mirrors the exact coverage rules of `hivezilla-ledger-archive` so finalized +//! chunks preserve identical skip/fork classification. + +use anyhow::{Context, Result, bail}; +use blockzilla_account_bridge_protocol::SlotChainRelation; +use blockzilla_solana_wire::blockmarker::{self, Marker}; + +/// Agave `NUM_SLOTS_FOR_REWARD`: a skip or notarization reward for slot `N` is +/// carried by the footer of slot `N + 8`. +pub const REWARD_SLOT_DISTANCE: u64 = 8; + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct RewardNames { + pub skips: Vec, + pub notars: Vec, +} + +/// Skip and notarization reward slots named by the footers of one carrier slot. +pub fn reward_names(markers: &[Vec]) -> Result { + let mut names = RewardNames::default(); + for marker in markers { + let parsed = blockmarker::parse(marker).context("block marker does not parse")?; + let Marker::Footer(footer) = parsed else { + continue; + }; + let certificates = blockmarker::decode_footer_certificates(&footer.certificates) + .context("footer certificates do not parse")?; + if let Some(skip) = certificates.skip_reward { + names.skips.push(skip.slot); + } + if let Some(notar) = certificates.notar_reward { + names.notars.push(notar.slot); + } + } + Ok(names) +} + +/// A hole walks parents when slot `N + 8` has no readable footer, and when that +/// footer carries both a skip reward and a notarization reward for `slot`. +pub fn hole_uses_parent_chain(slot: u64, markers: Option<&[Vec]>) -> Result { + let Some(markers) = markers else { + return Ok(true); + }; + let carrier = slot + .checked_add(REWARD_SLOT_DISTANCE) + .context("slot + 8 overflows")?; + let names = reward_names(markers) + .with_context(|| format!("slot {carrier} footer cannot prove slot {slot}"))?; + Ok(names.skips.contains(&slot) && names.notars.contains(&slot)) +} + +/// Verify a non-root slot may be omitted as an abandoned fork. +pub fn classify_abandoned_fork( + slot: u64, + chain: SlotChainRelation, + carrier_markers: Option<&[Vec]>, +) -> Result<()> { + match chain { + SlotChainRelation::DescendsFrom { next_root } => { + bail!( + "slot {slot} has data and is not rooted, and slot {next_root} descends from it" + ); + } + SlotChainRelation::NextRootIncomplete { next_root } => { + bail!("slot {next_root} is rooted and is not full"); + } + SlotChainRelation::JumpsOver { .. } => {} + } + let carrier = slot + .checked_add(REWARD_SLOT_DISTANCE) + .context("slot + 8 overflows")?; + let Some(markers) = carrier_markers else { + return Ok(()); + }; + let names = reward_names(markers) + .with_context(|| format!("slot {carrier} footer cannot prove slot {slot}"))?; + if names.skips.contains(&slot) { + return Ok(()); + } + bail!("slot {slot} has data and is not rooted, and slot {carrier} does not prove a skip"); +} + +/// Verify an absent slot may be omitted as a proven skip. +pub fn classify_hole( + slot: u64, + carrier_markers: Option<&[Vec]>, + chain: Option, +) -> Result<()> { + let carrier = slot + .checked_add(REWARD_SLOT_DISTANCE) + .context("slot + 8 overflows")?; + let Some(markers) = carrier_markers else { + return classify_hole_by_parent(slot, carrier, chain); + }; + let names = reward_names(markers) + .with_context(|| format!("slot {carrier} footer cannot prove slot {slot}"))?; + if names.skips.contains(&slot) && names.notars.contains(&slot) { + return match chain { + Some(SlotChainRelation::JumpsOver { .. }) => Ok(()), + Some(SlotChainRelation::DescendsFrom { next_root }) => { + bail!("slot {slot} has no SlotMeta and slot {next_root} descends from it") + } + Some(SlotChainRelation::NextRootIncomplete { next_root }) => { + bail!("slot {next_root} is rooted and is not full") + } + None => bail!("slot {slot} has no SlotMeta and no rooted slot follows it"), + }; + } + if names.notars.contains(&slot) { + bail!("slot {slot} is missing and slot {carrier} has a notarization reward for it"); + } + if names.skips.contains(&slot) { + return Ok(()); + } + bail!("slot {slot} has no SlotMeta and slot {carrier} does not prove a skip"); +} + +fn classify_hole_by_parent( + slot: u64, + carrier: u64, + chain: Option, +) -> Result<()> { + match chain { + Some(SlotChainRelation::JumpsOver { .. }) => Ok(()), + Some(SlotChainRelation::DescendsFrom { next_root }) => { + bail!("slot {slot} has no SlotMeta and slot {next_root} descends from it") + } + Some(SlotChainRelation::NextRootIncomplete { next_root }) => { + bail!("slot {next_root} is rooted and is not full") + } + None => bail!("slot {slot} has no SlotMeta and slot {carrier} has no footer proof"), + } +} diff --git a/crates/blockzilla-finalized-chunks/src/compact.rs b/crates/blockzilla-finalized-chunks/src/compact.rs new file mode 100644 index 00000000..4f4912d1 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/compact.rs @@ -0,0 +1,1290 @@ +//! Single-pass streaming Compact V2 epoch compactor from sealed finalized chunks. +//! +//! Eliminates Pass 1 over block payloads by merging tiny `chunk.counts.zst` +//! files first, then streams `chunk.bundles.bin` and `chunk.extras.zst` +//! sequentially (from local disk or HTTP/R2) to produce the exact 13-file +//! Compact V2 epoch archive + optional `GETBLOCK-EPOCH-COVERAGE.json`. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::fs::{self, File}; +use std::io::{self, BufReader, BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_archive_v2::{ + ARCHIVE_V2_BLOCK_INDEX_FILE, ARCHIVE_V2_BLOCKHASH_INDEX_V3_FILE, + ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE, ARCHIVE_V2_BLOCKS_FILE, ARCHIVE_V2_META_FILE, + ARCHIVE_V2_POH_FILE, ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_COUNTS_FILE, ARCHIVE_V2_PUBKEY_REGISTRY_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_INDEX_FILE, ARCHIVE_V2_SHREDDING_FILE, ARCHIVE_V2_SIGNATURES_FILE, + ARCHIVE_V2_TX_FLAG_HAS_METADATA, ARCHIVE_V2_VOTE_HASH_REGISTRY_FILE, ArchiveV2BlockAccessBlob, + ArchiveV2BlockhashIndexV3Row, ArchiveV2HotBlockBlob, ArchiveV2HotBlockIndexRow, + ArchiveV2HotMetaRecord, ArchiveV2HotTxRow, ArchiveV2WireReferenceClass, + ArchiveV2WireRewriteLimits, ArchiveV2WireRewriteVisitor, BlockzillaGetBlockBlobEncoding, + BlockzillaGetBlockBundleV1, WINCODE_ARCHIVE_V2_FLAG_LEB128, + WINCODE_ARCHIVE_V2_HOT_BLOCK_VERSION, WincodeArchiveV2Footer, WincodeArchiveV2Header, + WincodeArchiveV2PohRecord, WincodeArchiveV2ShreddingRecord, + rewrite_archive_v2_current_metadata_wire, rewrite_archive_v2_hot_message_wire, + write_archive_v2_blockhash_index_v3, write_archive_v2_hot_block_index, +}; +use blockzilla_compact::OwnedCompactRecentBlockhash; +use blockzilla_primitives::{ + CompactPubkey, WincodeLeb128FramedWriter, wincode_leb128_config, write_u32_varint, +}; +use blockzilla_registry::{KeyIndex, write_registry}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::format::{ + CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, + CHUNK_MANIFEST_FILE, ChunkExtrasReader, ChunkIndexV1, ChunkManifestV1, ChunkSlotKind, + DEGRADED_SOURCE_RPC_ONLY, EPOCH_ARCHIVE_FILES, SLOTS_PER_EPOCH, epoch_slot_range, + merge_pubkey_counts_zstd, +}; +use crate::payload::{MAX_BUNDLE_BYTES, MAX_HOT_BYTES, PubkeyCounts, ordered_registry, remap_pubkey}; + +const INDEX_FLAGS: u32 = 0; +const VOTE_HASH_ROW_LEN: usize = 65; +const RECENT_BLOCKHASH_SLOT_WINDOW: u64 = 150; +const ROLLING_BLOCKHASH_CAPACITY: usize = 300; +pub const LOCAL_COVERAGE_FILE: &str = "GETBLOCK-EPOCH-COVERAGE.json"; +const COVERAGE_KIND: &str = "rooted-ledger-scan-v1"; + +/// Source abstraction supporting both local finalized-chunk directories and +/// streaming HTTPS/R2 downloads with zero raw-ledger disk staging. +pub trait ChunkSource { + fn list_chunks(&self, epoch: u64) -> Result>; + fn load_index(&self, manifest: &ChunkManifestV1) -> Result>; + fn load_counts(&self, manifest: &ChunkManifestV1) -> Result>; + fn open_bundles(&self, manifest: &ChunkManifestV1) -> Result>; + fn open_extras(&self, manifest: &ChunkManifestV1) -> Result>; +} + +/// Local filesystem [`ChunkSource`] rooted at a finalized-ledger directory +/// containing `epoch-N/chunk--/`. +pub struct LocalChunkSource { + root: PathBuf, +} + +impl LocalChunkSource { + pub fn new(root: impl Into) -> Self { + Self { root: root.into() } + } + + fn chunk_dir(&self, manifest: &ChunkManifestV1) -> PathBuf { + self.root + .join(format!("epoch-{}", manifest.epoch)) + .join(crate::format::chunk_dir_name( + manifest.start_slot, + manifest.end_slot, + )) + } +} + +impl ChunkSource for LocalChunkSource { + fn list_chunks(&self, epoch: u64) -> Result> { + let epoch_dir = self.root.join(format!("epoch-{epoch}")); + ensure!( + epoch_dir.is_dir(), + "chunk epoch directory {} does not exist", + epoch_dir.display() + ); + let mut manifests = Vec::new(); + for entry in fs::read_dir(&epoch_dir)? { + let entry = entry?; + let path = entry.path(); + if !path.is_dir() { + continue; + } + let manifest_path = path.join(CHUNK_MANIFEST_FILE); + if !manifest_path.is_file() { + continue; + } + let raw = fs::read(&manifest_path) + .with_context(|| format!("read {}", manifest_path.display()))?; + let manifest: ChunkManifestV1 = serde_json::from_slice(&raw) + .with_context(|| format!("parse {}", manifest_path.display()))?; + manifest.validate()?; + ensure!( + manifest.epoch == epoch, + "chunk manifest in {} belongs to epoch {}, expected {epoch}", + manifest_path.display(), + manifest.epoch + ); + manifests.push(manifest); + } + manifests.sort_by_key(|m| m.start_slot); + Ok(manifests) + } + + fn load_index(&self, manifest: &ChunkManifestV1) -> Result> { + let path = self.chunk_dir(manifest).join(CHUNK_INDEX_FILE); + fs::read(&path).with_context(|| format!("read {}", path.display())) + } + + fn load_counts(&self, manifest: &ChunkManifestV1) -> Result> { + let path = self.chunk_dir(manifest).join(CHUNK_COUNTS_FILE); + fs::read(&path).with_context(|| format!("read {}", path.display())) + } + + fn open_bundles(&self, manifest: &ChunkManifestV1) -> Result> { + let path = self.chunk_dir(manifest).join(CHUNK_BUNDLES_FILE); + let file = File::open(&path).with_context(|| format!("open {}", path.display()))?; + Ok(Box::new(BufReader::new(file))) + } + + fn open_extras(&self, manifest: &ChunkManifestV1) -> Result> { + let path = self.chunk_dir(manifest).join(CHUNK_EXTRAS_FILE); + let file = File::open(&path).with_context(|| format!("open {}", path.display()))?; + Ok(Box::new(BufReader::new(file))) + } +} + +/// First rooted block after the epoch, required when emitting +/// `GETBLOCK-EPOCH-COVERAGE.json` for automatic GetBlock handoff. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EpochHandoffSuccessor { + pub slot: u64, + pub parent_slot: u64, + pub blockhash: String, + pub previous_blockhash: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CompactionReport { + pub epoch: u64, + pub start_slot: u64, + pub end_slot: u64, + pub chunks_processed: usize, + pub blocks: u64, + pub skips: u64, + pub forks: u64, + pub transactions: u64, + pub entries: u64, + pub rewards: u64, + pub nonce_recent_blockhashes: u64, + pub first_block_slot: u64, + pub last_block_slot: u64, + pub boundary_hash: [u8; 32], +} + +/// Compact a full epoch (432,000 slots) from sealed chunks into `output_dir`. +pub fn compact_epoch_from_chunks( + source: &S, + epoch: u64, + output_dir: &Path, + zstd_level: i32, + handoff_successor: Option, +) -> Result { + let (start_slot, end_slot) = epoch_slot_range(epoch)?; + compact_range_from_chunks( + source, + epoch, + start_slot, + end_slot, + output_dir, + zstd_level, + handoff_successor, + ) +} + +/// Compact an inclusive slot range within one epoch from sealed chunks. +pub fn compact_range_from_chunks( + source: &S, + epoch: u64, + start_slot: u64, + end_slot: u64, + output_dir: &Path, + zstd_level: i32, + handoff_successor: Option, +) -> Result { + ensure!( + zstd::compression_level_range().contains(&zstd_level), + "zstd level {zstd_level} out of range" + ); + ensure!(end_slot >= start_slot, "invalid range"); + if handoff_successor.is_some() { + ensure!( + epoch_slot_range(epoch)? == (start_slot, end_slot), + "GetBlock handoff requires a complete epoch" + ); + } + ensure_no_published_archive_file(output_dir)?; + + let all_chunks = source.list_chunks(epoch)?; + let chunks: Vec = all_chunks + .into_iter() + .filter(|m| m.start_slot >= start_slot && m.end_slot <= end_slot) + .collect(); + validate_chunk_coverage(&chunks, start_slot, end_slot)?; + + // Step 1: Download & merge only the small per-chunk pubkey count files. + let mut totals = PubkeyCounts::new(); + for manifest in &chunks { + let counts_bytes = source.load_counts(manifest)?; + verify_bytes( + &counts_bytes, + manifest.objects.counts.length, + &manifest.objects.counts.sha256, + "chunk.counts.zst", + )?; + merge_pubkey_counts_zstd(&counts_bytes, &mut totals)?; + } + + fs::create_dir_all(output_dir) + .with_context(|| format!("create {}", output_dir.display()))?; + let temps = temp_paths(output_dir); + let result = (|| -> Result { + let key_index = prepare_registry(&temps, totals)?; + + // Seed RollingBlockhashes from the first non-empty chunk's previous_tail + // (or synthesize single-parent tail if caller omitted full tail on a non-epoch test range). + let first_block_chunk = chunks + .iter() + .find(|m| m.block_count > 0) + .context("chunk range contains no produced blocks")?; + let boundary_hash = decode_hash( + first_block_chunk + .boundary_previous_blockhash + .as_deref() + .context("first chunk missing boundary_previous_blockhash")?, + )?; + let first_parent_slot = first_block_chunk + .first_parent_slot + .context("first chunk missing first_parent_slot")?; + + let tail = if let Some(tail_items) = &chunks[0].previous_tail { + let mut parsed = Vec::with_capacity(tail_items.len()); + for item in tail_items { + parsed.push(PreviousBlockhash { + slot: item.slot, + hash: decode_hash(&item.blockhash)?, + }); + } + let newest = parsed + .last() + .context("previous_tail is empty")?; + ensure!( + newest.slot == first_parent_slot && newest.hash == boundary_hash, + "previous_tail newest ({}, {}) does not match first block parent ({first_parent_slot})", + newest.slot, + bs58::encode(newest.hash).into_string() + ); + parsed + } else { + vec![PreviousBlockhash { + slot: first_parent_slot, + hash: boundary_hash, + }] + }; + + let mut writer = StreamingArchiveWriter::create(&temps, key_index, tail, zstd_level)?; + let mut block_slots = Vec::new(); + let mut total_skips = 0u64; + let mut total_forks = 0u64; + let mut prev_block: Option<(u64, [u8; 32])> = None; + + // Collect all produced slots first? No — we only need sample slots for + // GetBlock handoff, and we know exact total block_count from manifests! + let total_blocks: u64 = chunks.iter().map(|m| m.block_count).sum(); + let sample_ordinals: [u64; 3] = [0, total_blocks / 2, total_blocks.saturating_sub(1)]; + let mut samples = Vec::new(); + + // Step 2: Single streaming pass over each chunk's bundles + extras. + for manifest in &chunks { + let index_bytes = source.load_index(manifest)?; + verify_bytes( + &index_bytes, + manifest.objects.index.length, + &manifest.objects.index.sha256, + "chunk.index.bin", + )?; + let index = ChunkIndexV1::decode(&index_bytes)?; + ensure!( + index.epoch == manifest.epoch + && index.start_slot == manifest.start_slot + && index.end_slot == manifest.end_slot + && index.bundles_len == manifest.objects.bundles.length + && hex::encode(index.bundles_sha256) == manifest.objects.bundles.sha256, + "chunk index disagrees with manifest for {}..={}", + manifest.start_slot, + manifest.end_slot + ); + + let mut bundles_reader = HashingReader::new(source.open_bundles(manifest)?); + let mut extras_hashing = HashingReader::new(source.open_extras(manifest)?); + let mut extras_zstd = zstd::stream::read::Decoder::new(&mut extras_hashing) + .context("open zstd decoder for chunk.extras.zst")?; + let mut extras_reader = ChunkExtrasReader::new(&mut extras_zstd); + + for (offset_idx, entry) in index.entries.iter().enumerate() { + let slot = index.start_slot + offset_idx as u64; + match entry.kind { + ChunkSlotKind::ProvenSkip => { + total_skips += 1; + } + ChunkSlotKind::AbandonedFork => { + total_forks += 1; + } + ChunkSlotKind::ProducedBlock => { + if let Some((prev_slot, prev_hash)) = prev_block { + ensure!( + entry.parent_slot == prev_slot + && entry.previous_blockhash == prev_hash, + "slot {slot} parent ({}) breaks chain after slot {prev_slot}", + entry.parent_slot + ); + } + let bundle_len = entry.bundle_len as usize; + ensure!( + bundle_len > 0 && bundle_len <= MAX_BUNDLE_BYTES, + "slot {slot} bundle length {bundle_len} out of bounds" + ); + let mut bundle_bytes = vec![0u8; bundle_len]; + bundles_reader + .read_exact(&mut bundle_bytes) + .with_context(|| format!("stream bundle for slot {slot}"))?; + let digest: [u8; 32] = Sha256::digest(&bundle_bytes).into(); + ensure!( + digest == entry.bundle_sha256, + "slot {slot} bundle SHA-256 mismatch" + ); + + let extras = extras_reader + .next_record()? + .with_context(|| format!("missing extras record for slot {slot}"))?; + ensure!( + extras.slot == slot, + "extras stream slot {} does not match bundle slot {slot}", + extras.slot + ); + + let ordinal = block_slots.len() as u64; + if sample_ordinals.contains(&ordinal) + && !samples.iter().any(|s: &EpochHandoffSuccessor| s.slot == slot) + { + samples.push(EpochHandoffSuccessor { + slot, + parent_slot: entry.parent_slot, + blockhash: bs58::encode(entry.blockhash).into_string(), + previous_blockhash: bs58::encode(entry.previous_blockhash) + .into_string(), + }); + } + + writer.write_from_bundle(slot, &bundle_bytes, &extras)?; + block_slots.push(slot); + prev_block = Some((slot, entry.blockhash)); + } + } + } + + ensure!( + extras_reader.next_record()?.is_none(), + "unexpected trailing record in chunk.extras.zst for {}..={}", + manifest.start_slot, + manifest.end_slot + ); + drop(extras_zstd); + drain_to_eof(&mut bundles_reader)?; + drain_to_eof(&mut extras_hashing)?; + let (bundles_read, bundles_sha) = bundles_reader.finish(); + ensure!( + bundles_read == manifest.objects.bundles.length + && hex::encode(bundles_sha) == manifest.objects.bundles.sha256, + "chunk.bundles.bin stream digest mismatch for {}..={}", + manifest.start_slot, + manifest.end_slot + ); + let (extras_read, extras_sha) = extras_hashing.finish(); + ensure!( + extras_read == manifest.objects.extras.length + && hex::encode(extras_sha) == manifest.objects.extras.sha256, + "chunk.extras.zst stream digest mismatch for {}..={}", + manifest.start_slot, + manifest.end_slot + ); + } + + let first_block_slot = *block_slots.first().context("no blocks written")?; + let last_block_slot = *block_slots.last().context("no blocks written")?; + let last_blockhash = prev_block.context("no blocks written")?.1; + + if let Some(successor) = &handoff_successor { + ensure!( + successor.slot > end_slot + && successor.parent_slot == last_block_slot + && decode_hash(&successor.previous_blockhash)? == last_blockhash, + "epoch successor does not chain to last archived block {last_block_slot}" + ); + } + + let stats = writer.finish(output_dir)?; + + if let Some(successor) = handoff_successor { + write_local_coverage( + output_dir, + epoch, + &block_slots, + total_skips, + total_forks, + samples, + successor, + )?; + } + + Ok(CompactionReport { + epoch, + start_slot, + end_slot, + chunks_processed: chunks.len(), + blocks: stats.blocks, + skips: total_skips, + forks: total_forks, + transactions: stats.transactions, + entries: stats.entries, + rewards: stats.rewards, + nonce_recent_blockhashes: stats.nonce_recent_blockhashes, + first_block_slot, + last_block_slot, + boundary_hash, + }) + })(); + + if result.is_err() { + remove_temps(&temps); + } + result +} + +fn validate_chunk_coverage( + chunks: &[ChunkManifestV1], + start_slot: u64, + end_slot: u64, +) -> Result<()> { + ensure!(!chunks.is_empty(), "no chunks found for {start_slot}..={end_slot}"); + let mut expected = start_slot; + for chunk in chunks { + chunk.validate()?; + if chunk.degraded_source.as_deref() == Some(DEGRADED_SOURCE_RPC_ONLY) { + bail!( + "refusing to compact degraded RPC-only chunk {}..={} (source={DEGRADED_SOURCE_RPC_ONLY}): \ + RPC getBlock lacks PoH, shredding, Alpenglow consensus_block_id, and block_markers; \ + replace this range from a canonical CAR or local replay before epoch compaction", + chunk.start_slot, + chunk.end_slot + ); + } + ensure!( + chunk.start_slot == expected, + "chunk coverage gap or overlap: expected start_slot {expected}, found {}", + chunk.start_slot + ); + expected = chunk + .end_slot + .checked_add(1) + .context("chunk end_slot + 1 overflows")?; + } + let want_end = end_slot + .checked_add(1) + .context("range end_slot + 1 overflows")?; + ensure!( + expected == want_end, + "chunk coverage ends at {} instead of {end_slot}", + expected - 1 + ); + Ok(()) +} + +fn ensure_no_published_archive_file(output: &Path) -> Result<()> { + for name in EPOCH_ARCHIVE_FILES { + let path = output.join(name); + if path.exists() { + bail!("archive file {} already exists", path.display()); + } + } + Ok(()) +} + +fn verify_bytes(bytes: &[u8], expected_len: u64, expected_sha: &str, label: &str) -> Result<()> { + ensure!( + bytes.len() as u64 == expected_len, + "{label} length {} does not match manifest {expected_len}", + bytes.len() + ); + let actual_sha = hex::encode(Sha256::digest(bytes)); + ensure!( + actual_sha == expected_sha, + "{label} SHA-256 mismatch: expected {expected_sha}, got {actual_sha}" + ); + Ok(()) +} + +fn drain_to_eof(reader: &mut impl Read) -> Result<()> { + let mut buf = [0u8; 4096]; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + return Ok(()); + } + } +} + +struct HashingReader { + inner: R, + hasher: Sha256, + read: u64, +} + +impl HashingReader { + fn new(inner: R) -> Self { + Self { + inner, + hasher: Sha256::new(), + read: 0, + } + } + + fn finish(self) -> (u64, [u8; 32]) { + (self.read, self.hasher.finalize().into()) + } +} + +impl Read for HashingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let n = self.inner.read(buf)?; + self.hasher.update(&buf[..n]); + self.read += n as u64; + Ok(n) + } +} + +struct ArchivePaths { + blocks: PathBuf, + signatures: PathBuf, + blockhash: PathBuf, + vote: PathBuf, + poh: PathBuf, + shredding: PathBuf, + registry: PathBuf, + registry_counts: PathBuf, + registry_index: PathBuf, + tail: PathBuf, +} + +fn temp_paths(output: &Path) -> ArchivePaths { + ArchivePaths { + blocks: output.join(format!("{ARCHIVE_V2_BLOCKS_FILE}.tmp")), + signatures: output.join(format!("{ARCHIVE_V2_SIGNATURES_FILE}.tmp")), + blockhash: output.join(format!("{ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE}.tmp")), + vote: output.join(format!("{ARCHIVE_V2_VOTE_HASH_REGISTRY_FILE}.tmp")), + poh: output.join(format!("{ARCHIVE_V2_POH_FILE}.tmp")), + shredding: output.join(format!("{ARCHIVE_V2_SHREDDING_FILE}.tmp")), + registry: output.join(format!("{ARCHIVE_V2_PUBKEY_REGISTRY_FILE}.tmp")), + registry_counts: output.join(format!("{ARCHIVE_V2_PUBKEY_REGISTRY_COUNTS_FILE}.tmp")), + registry_index: output.join(format!("{ARCHIVE_V2_PUBKEY_REGISTRY_INDEX_FILE}.tmp")), + tail: output.join(format!("{ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE}.tmp")), + } +} + +fn remove_temps(temps: &ArchivePaths) { + for path in [ + &temps.blocks, + &temps.signatures, + &temps.blockhash, + &temps.vote, + &temps.poh, + &temps.shredding, + &temps.registry, + &temps.registry_counts, + &temps.registry_index, + &temps.tail, + ] { + let _ = fs::remove_file(path); + } +} + +fn prepare_registry(temps: &ArchivePaths, counts: PubkeyCounts) -> Result { + let ordered = ordered_registry(counts); + write_registry(&temps.registry, &ordered.keys) + .with_context(|| format!("write {}", temps.registry.display()))?; + { + let file = File::create(&temps.registry_counts) + .with_context(|| format!("create {}", temps.registry_counts.display()))?; + let mut writer = BufWriter::new(file); + for count in &ordered.counts { + write_u32_varint(&mut writer, *count)?; + } + writer.flush()?; + } + let index = KeyIndex::build_from_slice_low_memory(&ordered.keys); + index + .write(&temps.registry_index) + .with_context(|| format!("write {}", temps.registry_index.display()))?; + Ok(index) +} + +#[derive(Clone, Copy)] +struct PreviousBlockhash { + hash: [u8; 32], + slot: u64, +} + +#[derive(Clone, Copy)] +struct RollingBlockhash { + hash: [u8; 32], + block_id: i32, + slot: u64, +} + +#[derive(Default)] +struct RollingBlockhashes { + map: HashMap<[u8; 32], (i32, u64)>, + order: VecDeque, +} + +impl RollingBlockhashes { + fn seed(&mut self, tail: &[PreviousBlockhash]) -> Result<()> { + for (index, item) in tail.iter().enumerate() { + let distance = + i32::try_from(tail.len() - index).context("previous blockhash tail exceeds i32")?; + self.insert(item.hash, -distance, item.slot)?; + } + Ok(()) + } + + fn insert(&mut self, hash: [u8; 32], block_id: i32, slot: u64) -> Result<()> { + if self.map.contains_key(&hash) { + bail!( + "duplicate blockhash {} at block_id {block_id} slot {slot}", + bs58::encode(hash).into_string() + ); + } + self.map.insert(hash, (block_id, slot)); + self.order.push_back(RollingBlockhash { + hash, + block_id, + slot, + }); + while self.order.len() > ROLLING_BLOCKHASH_CAPACITY { + self.remove_front(); + } + Ok(()) + } + + fn prune_for_slot(&mut self, current_slot: u64) -> Result<()> { + loop { + let Some(entry) = self.order.front().copied() else { + return Ok(()); + }; + if entry.slot > current_slot { + bail!( + "rolling blockhash slot {} is ahead of current slot {current_slot}", + entry.slot + ); + } + if current_slot - entry.slot <= RECENT_BLOCKHASH_SLOT_WINDOW { + return Ok(()); + } + self.remove_front(); + } + } + + fn resolve(&self, hash: &[u8; 32], slot: u64) -> Result { + let Some((block_id, hash_slot)) = self.map.get(hash).copied() else { + return Ok(OwnedCompactRecentBlockhash::Nonce(*hash)); + }; + if hash_slot > slot { + bail!( + "slot {slot} recent_blockhash {} points at future slot {hash_slot}", + bs58::encode(hash).into_string() + ); + } + if slot - hash_slot > RECENT_BLOCKHASH_SLOT_WINDOW { + return Ok(OwnedCompactRecentBlockhash::Nonce(*hash)); + } + Ok(OwnedCompactRecentBlockhash::Id(block_id)) + } + + fn remove_front(&mut self) { + if let Some(old) = self.order.pop_front() + && self.map.get(&old.hash).copied() == Some((old.block_id, old.slot)) + { + self.map.remove(&old.hash); + } + } +} + +struct RekeyVisitor<'a> { + local_to_global: &'a [CompactPubkey], + epoch_key_index: &'a KeyIndex, + rolling: &'a RollingBlockhashes, + slot: u64, + nonce_recent_blockhashes: u64, +} + +impl ArchiveV2WireRewriteVisitor for RekeyVisitor<'_> { + type Checkpoint = u64; + + fn checkpoint(&mut self) -> Self::Checkpoint { + self.nonce_recent_blockhashes + } + + fn rewrite_pubkey( + &mut self, + pubkey: CompactPubkey, + _class: ArchiveV2WireReferenceClass, + ) -> Result { + remap_pubkey(pubkey, self.local_to_global, self.epoch_key_index) + } + + fn rewrite_recent_blockhash_nonce( + &mut self, + nonce: [u8; 32], + ) -> Result { + let resolved = self.rolling.resolve(&nonce, self.slot)?; + if matches!(resolved, OwnedCompactRecentBlockhash::Nonce(_)) { + self.nonce_recent_blockhashes = self + .nonce_recent_blockhashes + .checked_add(1) + .context("nonce_recent_blockhashes overflow")?; + } + Ok(resolved) + } + + fn rollback(&mut self, checkpoint: Self::Checkpoint) { + self.nonce_recent_blockhashes = checkpoint; + } +} + +struct WriterStats { + blocks: u64, + transactions: u64, + entries: u64, + rewards: u64, + nonce_recent_blockhashes: u64, +} + +struct StreamingArchiveWriter { + blocks: BufWriter, + signatures: BufWriter, + poh: WincodeLeb128FramedWriter>, + shredding: WincodeLeb128FramedWriter>, + blockhashes: Vec, + block_times: Vec, + vote_hashes: Vec, + tail: Vec, + rolling: RollingBlockhashes, + zstd_level: i32, + rows: Vec, + compressed_offset: u64, + next_tx_ordinal: u64, + next_signature_ordinal: u64, + entries: u64, + rewards: u64, + nonce_recent_blockhashes: u64, + key_index: KeyIndex, + paths: ArchivePaths, +} + +impl StreamingArchiveWriter { + fn create( + temps: &ArchivePaths, + key_index: KeyIndex, + tail: Vec, + zstd_level: i32, + ) -> Result { + let mut rolling = RollingBlockhashes::default(); + rolling.seed(&tail)?; + Ok(Self { + blocks: BufWriter::new(File::create(&temps.blocks)?), + signatures: BufWriter::new(File::create(&temps.signatures)?), + poh: WincodeLeb128FramedWriter::new(BufWriter::new(File::create(&temps.poh)?)), + shredding: WincodeLeb128FramedWriter::new(BufWriter::new(File::create( + &temps.shredding, + )?)), + blockhashes: Vec::new(), + block_times: Vec::new(), + vote_hashes: Vec::new(), + tail, + rolling, + zstd_level, + rows: Vec::new(), + compressed_offset: 0, + next_tx_ordinal: 0, + next_signature_ordinal: 0, + entries: 0, + rewards: 0, + nonce_recent_blockhashes: 0, + key_index, + paths: ArchivePaths { + blocks: temps.blocks.clone(), + signatures: temps.signatures.clone(), + blockhash: temps.blockhash.clone(), + vote: temps.vote.clone(), + poh: temps.poh.clone(), + shredding: temps.shredding.clone(), + registry: temps.registry.clone(), + registry_counts: temps.registry_counts.clone(), + registry_index: temps.registry_index.clone(), + tail: temps.tail.clone(), + }, + }) + } + + fn write_from_bundle( + &mut self, + expected_slot: u64, + bundle_bytes: &[u8], + extras: &crate::format::ChunkExtrasRecord, + ) -> Result<()> { + let bundle: BlockzillaGetBlockBundleV1 = + wincode::config::deserialize(bundle_bytes, wincode_leb128_config()) + .with_context(|| format!("decode bundle for slot {expected_slot}"))?; + ensure!( + bundle.version == 1 + && bundle.slot == expected_slot + && bundle.hot_block_encoding == BlockzillaGetBlockBlobEncoding::ZstdWincode + && bundle.block_access_encoding == BlockzillaGetBlockBlobEncoding::Wincode, + "invalid bundle envelope for slot {expected_slot}" + ); + let access_bytes = bundle + .block_access + .as_deref() + .with_context(|| format!("missing block_access for slot {expected_slot}"))?; + let access: ArchiveV2BlockAccessBlob = + wincode::config::deserialize(access_bytes, wincode_leb128_config()) + .with_context(|| format!("decode block_access for slot {expected_slot}"))?; + let hot_raw = zstd::bulk::decompress(&bundle.hot_block, MAX_HOT_BYTES) + .with_context(|| format!("decompress hot_block for slot {expected_slot}"))?; + let mut blob: ArchiveV2HotBlockBlob = + wincode::config::deserialize(&hot_raw, wincode_leb128_config()) + .with_context(|| format!("decode hot_block for slot {expected_slot}"))?; + ensure!( + blob.header.slot == expected_slot, + "hot block slot {} disagrees with bundle slot {expected_slot}", + blob.header.slot + ); + + let block_id = u32::try_from(self.rows.len()).context("archive block_id exceeds u32")?; + self.rolling.prune_for_slot(expected_slot)?; + + // Build O(1) block-local pubkey ID -> epoch-global CompactPubkey table. + let mut local_to_global = Vec::with_capacity(access.pubkeys.len()); + for (index, item) in access.pubkeys.iter().enumerate() { + ensure!( + item.id == index as u32 + 1, + "non-sequential local pubkey ID {} at slot {expected_slot}", + item.id + ); + local_to_global.push(self.key_index.compact(&item.pubkey)); + } + + // Rewrite block header. + blob.header.blockhash_id = block_id; + blob.header.previous_blockhash_id = block_id.saturating_sub(1); + if let Some(rewards) = &mut blob.header.rewards { + self.rewards = self + .rewards + .checked_add(rewards.decoded.len() as u64) + .context("reward count overflow")?; + for reward in &mut rewards.decoded { + reward.pubkey = remap_pubkey(reward.pubkey, &local_to_global, &self.key_index)?; + } + } + + // Rewrite messages and metadata directly on the wire using blockzilla-archive-v2's + // bounded streaming wire rewriter (no object-graph allocation, wire-boundary safe). + let mut new_messages = Vec::with_capacity(blob.message_bytes.len()); + let mut new_metadata = Vec::with_capacity(blob.metadata_bytes.len()); + let mut new_rows = Vec::with_capacity(blob.tx_rows.len()); + let limits = ArchiveV2WireRewriteLimits::default(); + let mut visitor = RekeyVisitor { + local_to_global: &local_to_global, + epoch_key_index: &self.key_index, + rolling: &self.rolling, + slot: expected_slot, + nonce_recent_blockhashes: self.nonce_recent_blockhashes, + }; + + for row in &blob.tx_rows { + let msg_start = row.message_offset as usize; + let msg_end = msg_start + .checked_add(row.message_len as usize) + .context("message slice overflow")?; + let msg_slice = blob + .message_bytes + .get(msg_start..msg_end) + .context("message slice out of bounds")?; + let new_msg_offset = + u32::try_from(new_messages.len()).context("rewritten message offset overflow")?; + rewrite_archive_v2_hot_message_wire(msg_slice, &mut new_messages, &mut visitor, limits) + .map_err(|err| { + anyhow::anyhow!( + "rewrite message tx#{} slot {expected_slot}: {err}", + row.tx_index + ) + })?; + let new_msg_len = u32::try_from(new_messages.len() - new_msg_offset as usize) + .context("rewritten message len overflow")?; + + let (new_meta_offset, new_meta_len) = if row.flags & ARCHIVE_V2_TX_FLAG_HAS_METADATA + != 0 + { + let meta_start = row.metadata_offset as usize; + let meta_end = meta_start + .checked_add(row.metadata_len as usize) + .context("metadata slice overflow")?; + let meta_slice = blob + .metadata_bytes + .get(meta_start..meta_end) + .context("metadata slice out of bounds")?; + let offset = u32::try_from(new_metadata.len()) + .context("rewritten metadata offset overflow")?; + rewrite_archive_v2_current_metadata_wire( + meta_slice, + &mut new_metadata, + &mut visitor, + limits, + ) + .map_err(|err| { + anyhow::anyhow!( + "rewrite metadata tx#{} slot {expected_slot}: {err}", + row.tx_index + ) + })?; + let len = u32::try_from(new_metadata.len() - offset as usize) + .context("rewritten metadata len overflow")?; + (offset, len) + } else { + (0, 0) + }; + + new_rows.push(ArchiveV2HotTxRow { + tx_index: row.tx_index, + flags: row.flags, + message_offset: new_msg_offset, + message_len: new_msg_len, + metadata_offset: new_meta_offset, + metadata_len: new_meta_len, + signature_count: row.signature_count, + reserved: row.reserved, + }); + } + + self.nonce_recent_blockhashes = visitor.nonce_recent_blockhashes; + blob.tx_rows = new_rows; + blob.message_bytes = new_messages; + blob.metadata_bytes = new_metadata; + + let reencoded = wincode::config::serialize(&blob, wincode_leb128_config()) + .with_context(|| format!("serialize rekeyed hot block {expected_slot}"))?; + let compressed = zstd::bulk::compress(&reencoded, self.zstd_level) + .with_context(|| format!("compress rekeyed hot block {expected_slot}"))?; + let compressed_len = + u32::try_from(compressed.len()).context("compressed block exceeds u32")?; + let uncompressed_len = + u32::try_from(reencoded.len()).context("uncompressed block exceeds u32")?; + + self.blocks.write_all(&compressed)?; + self.signatures.write_all(&access.signatures)?; + ensure!( + access.signatures.len() % 64 == 0, + "slot {expected_slot} signatures not multiple of 64" + ); + let signature_count = + u32::try_from(access.signatures.len() / 64).context("signature_count exceeds u32")?; + + self.entries = self + .entries + .checked_add(extras.poh.len() as u64) + .context("entries overflow")?; + self.blockhashes.extend_from_slice(&access.blockhash); + self.block_times.push(blob.header.block_time.unwrap_or(0)); + self.rolling.insert( + access.blockhash, + i32::try_from(block_id).context("blockhash id exceeds i32")?, + expected_slot, + )?; + self.vote_hashes.extend_from_slice(&[0u8; VOTE_HASH_ROW_LEN]); + + self.poh.write(&WincodeArchiveV2PohRecord { + block_id, + slot: expected_slot, + entries: extras.poh.clone(), + })?; + self.shredding.write(&WincodeArchiveV2ShreddingRecord { + block_id, + slot: expected_slot, + shredding: extras.shredding.clone(), + })?; + + let tx_count = blob.tx_count; + self.rows.push(ArchiveV2HotBlockIndexRow { + block_id, + slot: expected_slot, + compressed_offset: self.compressed_offset, + compressed_len, + uncompressed_len, + tx_count, + first_tx_ordinal: self.next_tx_ordinal, + first_signature_ordinal: self.next_signature_ordinal, + signature_count, + }); + self.compressed_offset = self + .compressed_offset + .checked_add(u64::from(compressed_len)) + .context("compressed_offset overflow")?; + self.next_tx_ordinal = self + .next_tx_ordinal + .checked_add(u64::from(tx_count)) + .context("tx ordinal overflow")?; + self.next_signature_ordinal = self + .next_signature_ordinal + .checked_add(u64::from(signature_count)) + .context("signature ordinal overflow")?; + Ok(()) + } + + fn finish(mut self, output: &Path) -> Result { + self.blocks.flush()?; + self.signatures.flush()?; + self.poh.flush()?; + self.poh + .into_inner() + .into_inner() + .map_err(|err| anyhow::anyhow!("flush poh: {err}"))?; + self.shredding.flush()?; + self.shredding + .into_inner() + .into_inner() + .map_err(|err| anyhow::anyhow!("flush shredding: {err}"))?; + + fs::write(&self.paths.blockhash, &self.blockhashes)?; + fs::write(&self.paths.vote, &self.vote_hashes)?; + let mut tail_bytes = Vec::with_capacity(self.tail.len() * 40); + for item in &self.tail { + tail_bytes.extend_from_slice(&item.hash); + tail_bytes.extend_from_slice(&item.slot.to_le_bytes()); + } + fs::write(&self.paths.tail, &tail_bytes)?; + + fs::rename(&self.paths.blocks, output.join(ARCHIVE_V2_BLOCKS_FILE))?; + fs::rename( + &self.paths.signatures, + output.join(ARCHIVE_V2_SIGNATURES_FILE), + )?; + fs::rename( + &self.paths.blockhash, + output.join(ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE), + )?; + fs::rename( + &self.paths.tail, + output.join(ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE), + )?; + fs::rename( + &self.paths.vote, + output.join(ARCHIVE_V2_VOTE_HASH_REGISTRY_FILE), + )?; + fs::rename(&self.paths.poh, output.join(ARCHIVE_V2_POH_FILE))?; + fs::rename(&self.paths.shredding, output.join(ARCHIVE_V2_SHREDDING_FILE))?; + fs::rename( + &self.paths.registry, + output.join(ARCHIVE_V2_PUBKEY_REGISTRY_FILE), + )?; + fs::rename( + &self.paths.registry_counts, + output.join(ARCHIVE_V2_PUBKEY_REGISTRY_COUNTS_FILE), + )?; + fs::rename( + &self.paths.registry_index, + output.join(ARCHIVE_V2_PUBKEY_REGISTRY_INDEX_FILE), + )?; + + write_archive_v2_hot_block_index( + &output.join(ARCHIVE_V2_BLOCK_INDEX_FILE), + self.compressed_offset, + self.zstd_level, + INDEX_FLAGS, + &self.rows, + )?; + let bh_rows: Vec = self + .rows + .iter() + .enumerate() + .map(|(index, row)| { + let mut blockhash = [0u8; 32]; + blockhash.copy_from_slice(&self.blockhashes[index * 32..(index + 1) * 32]); + ArchiveV2BlockhashIndexV3Row { + slot: row.slot, + blockhash, + block_time: self.block_times[index], + } + }) + .collect(); + write_archive_v2_blockhash_index_v3( + &output.join(ARCHIVE_V2_BLOCKHASH_INDEX_V3_FILE), + &bh_rows, + )?; + + let blocks = self.rows.len() as u64; + write_metadata_receipt( + output, + blocks, + self.next_tx_ordinal, + self.entries, + self.rewards, + self.nonce_recent_blockhashes, + )?; + Ok(WriterStats { + blocks, + transactions: self.next_tx_ordinal, + entries: self.entries, + rewards: self.rewards, + nonce_recent_blockhashes: self.nonce_recent_blockhashes, + }) + } +} + +fn write_metadata_receipt( + output: &Path, + blocks: u64, + transactions: u64, + entries: u64, + rewards: u64, + nonce_recent_blockhashes: u64, +) -> Result<()> { + let path = output.join(ARCHIVE_V2_META_FILE); + let temporary = output.join(format!("{ARCHIVE_V2_META_FILE}.tmp")); + let result = (|| { + let file = File::create(&temporary)?; + let mut writer = WincodeLeb128FramedWriter::new(BufWriter::new(file)); + writer.write(&ArchiveV2HotMetaRecord::Header(WincodeArchiveV2Header { + version: WINCODE_ARCHIVE_V2_HOT_BLOCK_VERSION, + flags: WINCODE_ARCHIVE_V2_FLAG_LEB128, + }))?; + writer.write(&ArchiveV2HotMetaRecord::Footer(WincodeArchiveV2Footer { + blocks, + transactions, + entries, + rewards, + nonce_recent_blockhashes, + ..WincodeArchiveV2Footer::default() + }))?; + writer.flush()?; + fs::rename(&temporary, &path)?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result +} + +#[derive(Serialize)] +struct LocalCoverage<'a> { + version: u8, + epoch: u64, + coverage: CoverageSummary, + samples: Vec, + successor: EpochHandoffSuccessor, + objects: BTreeMap<&'a str, LocalObjectDigest>, +} + +#[derive(Serialize)] +struct CoverageSummary { + kind: &'static str, + epoch_first_slot: u64, + epoch_last_slot: u64, + block_count: u64, + first_block_slot: u64, + last_block_slot: u64, + slots_sha256: String, + skipped_slot_count: u64, + abandoned_fork_count: u64, +} + +#[derive(Serialize)] +struct LocalObjectDigest { + length: u64, + sha256: String, +} + +fn write_local_coverage( + output: &Path, + epoch: u64, + block_slots: &[u64], + skipped_slot_count: u64, + abandoned_fork_count: u64, + samples: Vec, + successor: EpochHandoffSuccessor, +) -> Result<()> { + let (epoch_first_slot, epoch_last_slot) = epoch_slot_range(epoch)?; + ensure!( + block_slots.len() as u64 + skipped_slot_count + abandoned_fork_count == SLOTS_PER_EPOCH, + "coverage counts do not sum to one epoch" + ); + let mut slot_hasher = Sha256::new(); + for slot in block_slots { + slot_hasher.update(slot.to_le_bytes()); + } + let slots_sha256 = hex::encode(slot_hasher.finalize()); + let mut objects = BTreeMap::new(); + for name in EPOCH_ARCHIVE_FILES { + let path = output.join(name); + let mut file = File::open(&path)?; + let mut hasher = Sha256::new(); + let mut buf = [0u8; 65_536]; + let mut length = 0u64; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + length += n as u64; + } + objects.insert( + name, + LocalObjectDigest { + length, + sha256: hex::encode(hasher.finalize()), + }, + ); + } + let receipt = LocalCoverage { + version: 1, + epoch, + coverage: CoverageSummary { + kind: COVERAGE_KIND, + epoch_first_slot, + epoch_last_slot, + block_count: block_slots.len() as u64, + first_block_slot: *block_slots.first().context("no first block")?, + last_block_slot: *block_slots.last().context("no last block")?, + slots_sha256, + skipped_slot_count, + abandoned_fork_count, + }, + samples, + successor, + objects, + }; + let bytes = serde_json::to_vec_pretty(&receipt)?; + let path = output.join(LOCAL_COVERAGE_FILE); + let tmp = output.join(format!("{LOCAL_COVERAGE_FILE}.tmp")); + fs::write(&tmp, &bytes)?; + fs::rename(&tmp, &path)?; + Ok(()) +} + +fn decode_hash(value: &str) -> Result<[u8; 32]> { + let bytes = bs58::decode(value) + .into_vec() + .with_context(|| format!("decode base58 hash {value}"))?; + bytes + .as_slice() + .try_into() + .with_context(|| format!("hash {value} is not 32 bytes")) +} diff --git a/crates/blockzilla-finalized-chunks/src/format.rs b/crates/blockzilla-finalized-chunks/src/format.rs new file mode 100644 index 00000000..121da883 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/format.rs @@ -0,0 +1,647 @@ +use std::collections::HashMap; +use std::io::{Read, Write}; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_archive_v2::{ + ARCHIVE_V2_BLOCK_INDEX_FILE, ARCHIVE_V2_BLOCKHASH_INDEX_V3_FILE, + ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE, ARCHIVE_V2_BLOCKS_FILE, ARCHIVE_V2_META_FILE, + ARCHIVE_V2_POH_FILE, ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_COUNTS_FILE, ARCHIVE_V2_PUBKEY_REGISTRY_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_INDEX_FILE, ARCHIVE_V2_SHREDDING_FILE, ARCHIVE_V2_SIGNATURES_FILE, + ARCHIVE_V2_VOTE_HASH_REGISTRY_FILE, +}; +use blockzilla_compact::{CompactPohEntry, CompactShredding}; +use blockzilla_primitives::wincode_leb128_config; +use serde::{Deserialize, Serialize}; +use wincode::{SchemaRead, SchemaWrite}; + +pub const SLOTS_PER_EPOCH: u64 = 432_000; +pub const DEFAULT_CHUNK_SLOTS: u64 = 4_096; + +pub const CHUNK_BUNDLES_FILE: &str = "chunk.bundles.bin"; +pub const CHUNK_INDEX_FILE: &str = "chunk.index.bin"; +pub const CHUNK_EXTRAS_FILE: &str = "chunk.extras.zst"; +pub const CHUNK_COUNTS_FILE: &str = "chunk.counts.zst"; +pub const CHUNK_MANIFEST_FILE: &str = "chunk.manifest.json"; + +pub const CHUNK_INDEX_MAGIC: [u8; 8] = *b"BZCHK01!"; +pub const CHUNK_INDEX_VERSION: u16 = 1; +pub const CHUNK_INDEX_HEADER_LEN: usize = 163; +pub const CHUNK_INDEX_ROW_LEN: usize = 151; +pub const MAX_CHUNK_SLOTS: u64 = 65_536; + +pub const CHUNK_EXTRAS_MAGIC: [u8; 8] = *b"BZEXT01!"; +pub const CHUNK_COUNTS_MAGIC: [u8; 8] = *b"BZCNT01!"; +pub const DEGRADED_SOURCE_RPC_ONLY: &str = "rpc_only_no_alpenglow"; +pub const DEGRADED_SOURCE_SHREDS_PLUS_RPC: &str = "shreds_plus_rpc"; +const MAX_EXTRAS_RECORD_BYTES: usize = 32 * 1024 * 1024; +const MAX_PUBKEY_COUNTS: usize = 50_000_000; + +pub const EPOCH_ARCHIVE_FILES: [&str; 13] = [ + ARCHIVE_V2_BLOCKS_FILE, + ARCHIVE_V2_SIGNATURES_FILE, + ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE, + ARCHIVE_V2_VOTE_HASH_REGISTRY_FILE, + ARCHIVE_V2_POH_FILE, + ARCHIVE_V2_SHREDDING_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_COUNTS_FILE, + ARCHIVE_V2_PUBKEY_REGISTRY_INDEX_FILE, + ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE, + ARCHIVE_V2_BLOCK_INDEX_FILE, + ARCHIVE_V2_BLOCKHASH_INDEX_V3_FILE, + ARCHIVE_V2_META_FILE, +]; + +pub fn epoch_for_slot(slot: u64) -> u64 { + slot / SLOTS_PER_EPOCH +} + +pub fn epoch_slot_range(epoch: u64) -> Result<(u64, u64)> { + let start_slot = epoch + .checked_mul(SLOTS_PER_EPOCH) + .context("epoch start overflows")?; + let end_slot = start_slot + .checked_add(SLOTS_PER_EPOCH - 1) + .context("epoch end overflows")?; + Ok((start_slot, end_slot)) +} + +/// Compute the inclusive end slot of a chunk starting at `start_slot`, never +/// crossing the epoch boundary. +pub fn chunk_window_end(start_slot: u64, chunk_slots: u64) -> Result { + ensure!( + (1..=MAX_CHUNK_SLOTS).contains(&chunk_slots), + "chunk_slots {chunk_slots} is outside 1..={MAX_CHUNK_SLOTS}" + ); + let (_, epoch_end) = epoch_slot_range(epoch_for_slot(start_slot))?; + let raw_end = start_slot + .checked_add(chunk_slots - 1) + .context("chunk end overflows")?; + Ok(raw_end.min(epoch_end)) +} + +pub fn chunk_dir_name(start_slot: u64, end_slot: u64) -> String { + format!("chunk-{start_slot:012}-{end_slot:012}") +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum ChunkSlotKind { + ProducedBlock = 1, + ProvenSkip = 2, + AbandonedFork = 3, +} + +impl ChunkSlotKind { + fn from_u8(value: u8) -> Result { + match value { + 1 => Ok(Self::ProducedBlock), + 2 => Ok(Self::ProvenSkip), + 3 => Ok(Self::AbandonedFork), + other => bail!("invalid chunk slot kind {other}"), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChunkSlotEntry { + pub kind: ChunkSlotKind, + pub bundle_offset: u64, + pub bundle_len: u32, + pub bundle_sha256: [u8; 32], + pub parent_slot: u64, + pub blockhash: [u8; 32], + pub previous_blockhash: [u8; 32], + pub compressed_len: u32, + pub uncompressed_len: u32, + pub tx_count: u32, + pub signature_count: u32, + pub block_time: Option, + pub block_height: Option, +} + +impl ChunkSlotEntry { + pub fn skipped(kind: ChunkSlotKind) -> Self { + debug_assert!(matches!( + kind, + ChunkSlotKind::ProvenSkip | ChunkSlotKind::AbandonedFork + )); + Self { + kind, + bundle_offset: 0, + bundle_len: 0, + bundle_sha256: [0; 32], + parent_slot: 0, + blockhash: [0; 32], + previous_blockhash: [0; 32], + compressed_len: 0, + uncompressed_len: 0, + tx_count: 0, + signature_count: 0, + block_time: None, + block_height: None, + } + } + + pub fn encode_into(&self, out: &mut Vec) { + let start = out.len(); + out.push(self.kind as u8); + out.extend_from_slice(&self.bundle_offset.to_le_bytes()); + out.extend_from_slice(&self.bundle_len.to_le_bytes()); + out.extend_from_slice(&self.bundle_sha256); + out.extend_from_slice(&self.parent_slot.to_le_bytes()); + out.extend_from_slice(&self.blockhash); + out.extend_from_slice(&self.previous_blockhash); + out.extend_from_slice(&self.compressed_len.to_le_bytes()); + out.extend_from_slice(&self.uncompressed_len.to_le_bytes()); + out.extend_from_slice(&self.tx_count.to_le_bytes()); + out.extend_from_slice(&self.signature_count.to_le_bytes()); + match self.block_time { + Some(v) => { + out.push(1); + out.extend_from_slice(&v.to_le_bytes()); + } + None => { + out.push(0); + out.extend_from_slice(&0i64.to_le_bytes()); + } + } + match self.block_height { + Some(v) => { + out.push(1); + out.extend_from_slice(&v.to_le_bytes()); + } + None => { + out.push(0); + out.extend_from_slice(&0u64.to_le_bytes()); + } + } + debug_assert_eq!(out.len() - start, CHUNK_INDEX_ROW_LEN); + } + + pub fn decode(row: &[u8]) -> Result { + ensure!(row.len() == CHUNK_INDEX_ROW_LEN, "invalid chunk index row length"); + let kind = ChunkSlotKind::from_u8(row[0])?; + let bundle_offset = u64::from_le_bytes(row[1..9].try_into().unwrap()); + let bundle_len = u32::from_le_bytes(row[9..13].try_into().unwrap()); + let bundle_sha256: [u8; 32] = row[13..45].try_into().unwrap(); + let parent_slot = u64::from_le_bytes(row[45..53].try_into().unwrap()); + let blockhash: [u8; 32] = row[53..85].try_into().unwrap(); + let previous_blockhash: [u8; 32] = row[85..117].try_into().unwrap(); + let compressed_len = u32::from_le_bytes(row[117..121].try_into().unwrap()); + let uncompressed_len = u32::from_le_bytes(row[121..125].try_into().unwrap()); + let tx_count = u32::from_le_bytes(row[125..129].try_into().unwrap()); + let signature_count = u32::from_le_bytes(row[129..133].try_into().unwrap()); + let block_time = match row[133] { + 0 => None, + 1 => Some(i64::from_le_bytes(row[134..142].try_into().unwrap())), + other => bail!("invalid block_time flag {other}"), + }; + let block_height = match row[142] { + 0 => None, + 1 => Some(u64::from_le_bytes(row[143..151].try_into().unwrap())), + other => bail!("invalid block_height flag {other}"), + }; + if kind != ChunkSlotKind::ProducedBlock { + ensure!( + bundle_offset == 0 && bundle_len == 0 && tx_count == 0, + "non-block chunk row has nonzero bundle fields" + ); + } + Ok(Self { + kind, + bundle_offset, + bundle_len, + bundle_sha256, + parent_slot, + blockhash, + previous_blockhash, + compressed_len, + uncompressed_len, + tx_count, + signature_count, + block_time, + block_height, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChunkIndexV1 { + pub epoch: u64, + pub start_slot: u64, + pub end_slot: u64, + pub bundles_len: u64, + pub bundles_sha256: [u8; 32], + pub first_block_slot: Option, + pub last_block_slot: Option, + pub first_parent_slot: Option, + pub boundary_previous_blockhash: Option<[u8; 32]>, + pub last_blockhash: Option<[u8; 32]>, + pub entries: Vec, +} + +impl ChunkIndexV1 { + pub fn validate(&self) -> Result<()> { + ensure!( + self.end_slot >= self.start_slot, + "chunk end slot {} is before start slot {}", + self.end_slot, + self.start_slot + ); + ensure!( + epoch_for_slot(self.start_slot) == self.epoch + && epoch_for_slot(self.end_slot) == self.epoch, + "chunk range {}..={} does not belong to epoch {}", + self.start_slot, + self.end_slot, + self.epoch + ); + let slot_count = self.end_slot - self.start_slot + 1; + ensure!( + slot_count <= MAX_CHUNK_SLOTS && self.entries.len() as u64 == slot_count, + "chunk index slot count mismatch" + ); + let mut cursor = 0u64; + let mut first_slot = None; + let mut last_slot = None; + let mut first_parent = None; + let mut first_prev_hash = None; + let mut last_hash = None; + for (idx, entry) in self.entries.iter().enumerate() { + let slot = self.start_slot + idx as u64; + if entry.kind == ChunkSlotKind::ProducedBlock { + ensure!( + entry.bundle_offset == cursor && entry.bundle_len > 0, + "chunk bundle layout is not contiguous at slot {slot}" + ); + ensure!( + entry.parent_slot < slot, + "chunk slot {slot} parent {} is not earlier", + entry.parent_slot + ); + if let Some(prev) = last_slot { + ensure!( + entry.parent_slot == prev + && Some(entry.previous_blockhash) == last_hash, + "chunk parent chain breaks at slot {slot}" + ); + } else { + first_slot = Some(slot); + first_parent = Some(entry.parent_slot); + first_prev_hash = Some(entry.previous_blockhash); + } + last_slot = Some(slot); + last_hash = Some(entry.blockhash); + cursor = cursor + .checked_add(u64::from(entry.bundle_len)) + .context("chunk bundle length overflows")?; + } + } + ensure!( + cursor == self.bundles_len, + "chunk bundles_len {} does not match sum of frame lengths {cursor}", + self.bundles_len + ); + ensure!( + self.first_block_slot == first_slot + && self.last_block_slot == last_slot + && self.first_parent_slot == first_parent + && self.boundary_previous_blockhash == first_prev_hash + && self.last_blockhash == last_hash, + "chunk index summary fields disagree with slot entries" + ); + Ok(()) + } + + pub fn lookup_slot(&self, slot: u64) -> Option<&ChunkSlotEntry> { + if slot < self.start_slot || slot > self.end_slot { + return None; + } + self.entries.get((slot - self.start_slot) as usize) + } + + pub fn encode(&self) -> Result> { + self.validate()?; + let mut out = + Vec::with_capacity(CHUNK_INDEX_HEADER_LEN + self.entries.len() * CHUNK_INDEX_ROW_LEN); + out.extend_from_slice(&CHUNK_INDEX_MAGIC); + out.extend_from_slice(&CHUNK_INDEX_VERSION.to_le_bytes()); + out.extend_from_slice(&self.epoch.to_le_bytes()); + out.extend_from_slice(&self.start_slot.to_le_bytes()); + out.extend_from_slice(&self.end_slot.to_le_bytes()); + out.extend_from_slice(&self.bundles_len.to_le_bytes()); + out.extend_from_slice(&self.bundles_sha256); + let has_blocks = u8::from(self.first_block_slot.is_some()); + out.push(has_blocks); + out.extend_from_slice(&self.first_block_slot.unwrap_or(0).to_le_bytes()); + out.extend_from_slice(&self.last_block_slot.unwrap_or(0).to_le_bytes()); + out.extend_from_slice(&self.first_parent_slot.unwrap_or(0).to_le_bytes()); + out.extend_from_slice(&self.boundary_previous_blockhash.unwrap_or([0; 32])); + out.extend_from_slice(&self.last_blockhash.unwrap_or([0; 32])); + debug_assert_eq!(out.len(), CHUNK_INDEX_HEADER_LEN); + for entry in &self.entries { + entry.encode_into(&mut out); + } + Ok(out) + } + + pub fn decode(bytes: &[u8]) -> Result { + ensure!( + bytes.len() >= CHUNK_INDEX_HEADER_LEN, + "chunk index shorter than header" + ); + ensure!( + &bytes[0..8] == &CHUNK_INDEX_MAGIC, + "invalid chunk index magic" + ); + let version = u16::from_le_bytes(bytes[8..10].try_into().unwrap()); + ensure!( + version == CHUNK_INDEX_VERSION, + "unsupported chunk index version {version}" + ); + let epoch = u64::from_le_bytes(bytes[10..18].try_into().unwrap()); + let start_slot = u64::from_le_bytes(bytes[18..26].try_into().unwrap()); + let end_slot = u64::from_le_bytes(bytes[26..34].try_into().unwrap()); + let bundles_len = u64::from_le_bytes(bytes[34..42].try_into().unwrap()); + let bundles_sha256: [u8; 32] = bytes[42..74].try_into().unwrap(); + let flags = bytes[74]; + ensure!(flags <= 1, "invalid chunk index flags {flags}"); + let has_blocks = flags == 1; + let first_block_slot = has_blocks.then(|| u64::from_le_bytes(bytes[75..83].try_into().unwrap())); + let last_block_slot = has_blocks.then(|| u64::from_le_bytes(bytes[83..91].try_into().unwrap())); + let first_parent_slot = has_blocks.then(|| u64::from_le_bytes(bytes[91..99].try_into().unwrap())); + let boundary_previous_blockhash = has_blocks.then(|| bytes[99..131].try_into().unwrap()); + let last_blockhash = has_blocks.then(|| bytes[131..163].try_into().unwrap()); + // Check header padding bytes 163..169 are zero? Wait: let's check exact offset! + // 8 + 2 + 8 + 8 + 8 + 8 + 32 + 1 + 8 + 8 + 8 + 32 + 32 = 163! + let count = end_slot + .checked_sub(start_slot) + .and_then(|d| d.checked_add(1)) + .context("chunk slot range overflows")?; + ensure!(count <= MAX_CHUNK_SLOTS, "chunk slot range exceeds limit"); + let expected_len = CHUNK_INDEX_HEADER_LEN + .checked_add((count as usize).checked_mul(CHUNK_INDEX_ROW_LEN).context("index size overflow")?) + .context("index size overflow")?; + ensure!( + bytes.len() == expected_len, + "chunk index byte length {} does not match expected {expected_len}", + bytes.len() + ); + let mut entries = Vec::with_capacity(count as usize); + let mut offset = CHUNK_INDEX_HEADER_LEN; + for _ in 0..count { + entries.push(ChunkSlotEntry::decode( + &bytes[offset..offset + CHUNK_INDEX_ROW_LEN], + )?); + offset += CHUNK_INDEX_ROW_LEN; + } + let index = Self { + epoch, + start_slot, + end_slot, + bundles_len, + bundles_sha256, + first_block_slot, + last_block_slot, + first_parent_slot, + boundary_previous_blockhash, + last_blockhash, + entries, + }; + index.validate()?; + Ok(index) + } + + /// Lookup one slot directly from raw `chunk.index.bin` bytes in O(1) time + /// without decoding every row. + pub fn lookup_in_bytes(bytes: &[u8], slot: u64) -> Result> { + ensure!( + bytes.len() >= CHUNK_INDEX_HEADER_LEN + && &bytes[0..8] == &CHUNK_INDEX_MAGIC + && u16::from_le_bytes(bytes[8..10].try_into().unwrap()) == CHUNK_INDEX_VERSION, + "invalid chunk index header" + ); + let epoch = u64::from_le_bytes(bytes[10..18].try_into().unwrap()); + let start_slot = u64::from_le_bytes(bytes[18..26].try_into().unwrap()); + let end_slot = u64::from_le_bytes(bytes[26..34].try_into().unwrap()); + if slot < start_slot || slot > end_slot { + return Ok(None); + } + let idx = usize::try_from(slot - start_slot).context("slot offset overflows usize")?; + let offset = CHUNK_INDEX_HEADER_LEN + .checked_add(idx.checked_mul(CHUNK_INDEX_ROW_LEN).context("row offset overflow")?) + .context("row offset overflow")?; + let end = offset + .checked_add(CHUNK_INDEX_ROW_LEN) + .context("row end overflow")?; + ensure!(end <= bytes.len(), "chunk index truncated at slot {slot}"); + let entry = ChunkSlotEntry::decode(&bytes[offset..end])?; + Ok(Some((epoch, entry))) + } +} + +/// Per-block PoH and shredding sidecar written to `chunk.extras.zst`. +#[derive(Clone, Debug, SchemaRead, SchemaWrite)] +pub struct ChunkExtrasRecord { + pub slot: u64, + pub poh: Vec, + pub shredding: Vec, +} + +pub fn write_extras_header(writer: &mut impl Write) -> Result<()> { + writer + .write_all(&CHUNK_EXTRAS_MAGIC) + .context("write chunk extras magic") +} + +pub fn write_extras_record(writer: &mut impl Write, record: &ChunkExtrasRecord) -> Result<()> { + let bytes = wincode::config::serialize(record, wincode_leb128_config()) + .context("serialize chunk extras record")?; + ensure!( + bytes.len() <= MAX_EXTRAS_RECORD_BYTES, + "chunk extras record exceeds limit" + ); + let len = u32::try_from(bytes.len()).context("chunk extras length exceeds u32")?; + writer.write_all(&len.to_le_bytes())?; + writer.write_all(&bytes)?; + Ok(()) +} + +pub struct ChunkExtrasReader { + inner: R, + header_checked: bool, +} + +impl ChunkExtrasReader { + pub fn new(inner: R) -> Self { + Self { + inner, + header_checked: false, + } + } + + pub fn next_record(&mut self) -> Result> { + if !self.header_checked { + let mut magic = [0u8; 8]; + self.inner + .read_exact(&mut magic) + .context("read chunk extras magic")?; + ensure!(magic == CHUNK_EXTRAS_MAGIC, "invalid chunk extras magic"); + self.header_checked = true; + } + let mut len_buf = [0u8; 4]; + match self.inner.read_exact(&mut len_buf) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None), + Err(err) => return Err(err).context("read chunk extras record length"), + } + let len = u32::from_le_bytes(len_buf) as usize; + ensure!( + len <= MAX_EXTRAS_RECORD_BYTES, + "chunk extras record length {len} exceeds limit" + ); + let mut buf = vec![0u8; len]; + self.inner + .read_exact(&mut buf) + .context("read chunk extras record body")?; + let record: ChunkExtrasRecord = wincode::config::deserialize(&buf, wincode_leb128_config()) + .context("deserialize chunk extras record")?; + Ok(Some(record)) + } +} + +pub fn write_pubkey_counts_zstd(counts: &HashMap<[u8; 32], u32>, zstd_level: i32) -> Result> { + let mut items: Vec<([u8; 32], u32)> = counts.iter().map(|(k, v)| (*k, *v)).collect(); + items.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + let count = u32::try_from(items.len()).context("pubkey count exceeds u32")?; + let mut raw = Vec::with_capacity(12 + items.len() * 36); + raw.extend_from_slice(&CHUNK_COUNTS_MAGIC); + raw.extend_from_slice(&count.to_le_bytes()); + for (key, freq) in items { + raw.extend_from_slice(&key); + raw.extend_from_slice(&freq.to_le_bytes()); + } + zstd::bulk::compress(&raw, zstd_level).context("compress chunk pubkey counts") +} + +pub fn merge_pubkey_counts_zstd( + compressed: &[u8], + totals: &mut HashMap<[u8; 32], u32>, +) -> Result { + let mut decoder = zstd::stream::read::Decoder::new(compressed) + .context("open zstd decoder for chunk pubkey counts")?; + let mut magic = [0u8; 8]; + decoder + .read_exact(&mut magic) + .context("read chunk counts magic")?; + ensure!(magic == CHUNK_COUNTS_MAGIC, "invalid chunk counts magic"); + let mut count_buf = [0u8; 4]; + decoder + .read_exact(&mut count_buf) + .context("read chunk counts len")?; + let count = u32::from_le_bytes(count_buf) as usize; + ensure!(count <= MAX_PUBKEY_COUNTS, "chunk counts exceeds limit"); + let mut row = [0u8; 36]; + for _ in 0..count { + decoder + .read_exact(&mut row) + .context("read chunk counts entry")?; + let key: [u8; 32] = row[0..32].try_into().unwrap(); + let freq = u32::from_le_bytes(row[32..36].try_into().unwrap()); + let entry = totals.entry(key).or_insert(0); + *entry = entry.saturating_add(freq); + } + let mut trailing = [0u8; 1]; + ensure!( + decoder.read(&mut trailing)? == 0, + "trailing bytes in chunk pubkey counts" + ); + Ok(count) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TailBlockhash { + pub slot: u64, + pub blockhash: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChunkObjectMeta { + pub path: String, + pub length: u64, + pub sha256: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub etag: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChunkObjects { + pub bundles: ChunkObjectMeta, + pub index: ChunkObjectMeta, + pub extras: ChunkObjectMeta, + pub counts: ChunkObjectMeta, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChunkManifestV1 { + pub version: u16, + pub epoch: u64, + pub start_slot: u64, + pub end_slot: u64, + pub block_count: u64, + pub skip_count: u64, + pub fork_count: u64, + pub first_block_slot: Option, + pub last_block_slot: Option, + pub first_parent_slot: Option, + pub boundary_previous_blockhash: Option, + pub last_blockhash: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_tail: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub degraded_source: Option, + pub objects: ChunkObjects, +} + +impl ChunkManifestV1 { + pub fn validate(&self) -> Result<()> { + ensure!(self.version == 1, "unsupported chunk manifest version"); + ensure!(self.end_slot >= self.start_slot, "invalid chunk slot range"); + ensure!( + epoch_for_slot(self.start_slot) == self.epoch + && epoch_for_slot(self.end_slot) == self.epoch, + "chunk manifest crosses epoch boundary" + ); + let expected_slots = self.end_slot - self.start_slot + 1; + ensure!( + self.block_count + self.skip_count + self.fork_count == expected_slots, + "chunk manifest slot counts do not sum to window length" + ); + if self.block_count == 0 { + ensure!( + self.first_block_slot.is_none() + && self.last_block_slot.is_none() + && self.first_parent_slot.is_none() + && self.boundary_previous_blockhash.is_none() + && self.last_blockhash.is_none(), + "empty chunk manifest has block boundary metadata" + ); + } else { + ensure!( + self.first_block_slot.is_some() + && self.last_block_slot.is_some() + && self.first_parent_slot.is_some() + && self.boundary_previous_blockhash.is_some() + && self.last_blockhash.is_some(), + "non-empty chunk manifest is missing boundary metadata" + ); + } + Ok(()) + } +} diff --git a/crates/blockzilla-finalized-chunks/src/lib.rs b/crates/blockzilla-finalized-chunks/src/lib.rs new file mode 100644 index 00000000..92d8b961 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/lib.rs @@ -0,0 +1,34 @@ +//! Immutable finalized ledger chunks for current-epoch `getBlock` and +//! single-pass streaming Compact V2 epoch compaction. + +pub mod builder; +#[cfg(feature = "catalog")] +pub mod catalog; +pub mod check; +pub mod compact; +pub mod format; +pub mod payload; + +#[cfg(test)] +mod tests; + +pub use builder::{ChunkBuilder, SealedChunk}; +#[cfg(feature = "catalog")] +pub use catalog::{ChunkCatalogBinding, ChunkCatalogLookup, ChunkCatalogReader, ChunkCatalogWriter, ChunkStorageMode}; +pub use check::{ + REWARD_SLOT_DISTANCE, RewardNames, classify_abandoned_fork, classify_hole, + hole_uses_parent_chain, reward_names, +}; +pub use compact::{ + ChunkSource, CompactionReport, EpochHandoffSuccessor, LocalChunkSource, + compact_epoch_from_chunks, compact_range_from_chunks, +}; +pub use format::{ + CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, CHUNK_INDEX_MAGIC, + CHUNK_INDEX_VERSION, CHUNK_MANIFEST_FILE, ChunkExtrasRecord, ChunkIndexV1, ChunkManifestV1, + ChunkObjectMeta, ChunkObjects, ChunkSlotEntry, ChunkSlotKind, DEFAULT_CHUNK_SLOTS, + DEGRADED_SOURCE_RPC_ONLY, DEGRADED_SOURCE_SHREDS_PLUS_RPC, EPOCH_ARCHIVE_FILES, + SLOTS_PER_EPOCH, TailBlockhash, chunk_dir_name, chunk_window_end, epoch_for_slot, + epoch_slot_range, +}; +pub use payload::{EncodedChunkBlock, MAX_BUNDLE_BYTES, MAX_HOT_BYTES, MAX_TRANSACTIONS, encode_archive_payload}; diff --git a/crates/blockzilla-finalized-chunks/src/payload.rs b/crates/blockzilla-finalized-chunks/src/payload.rs new file mode 100644 index 00000000..e943d796 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/payload.rs @@ -0,0 +1,597 @@ +//! Convert a native-bridge [`ArchiveBlockPayloadV1`] into a seekable +//! `BlockzillaGetBlockBundleV1`, PoH/shredding sidecar, and registry-eligible +//! pubkey counts matching `hivezilla-ledger-archive` identically. + +use std::collections::HashMap; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_account_bridge_protocol::ArchiveBlockPayloadV1; +use blockzilla_archive_v2::{ + ARCHIVE_V2_TX_FLAG_HAS_ERROR, ARCHIVE_V2_TX_FLAG_HAS_INNER_IX, + ARCHIVE_V2_TX_FLAG_HAS_LOADED_ADDRESSES, ARCHIVE_V2_TX_FLAG_HAS_LOGS, + ARCHIVE_V2_TX_FLAG_HAS_METADATA, ARCHIVE_V2_TX_FLAG_HAS_RETURN_DATA, + ARCHIVE_V2_TX_FLAG_HAS_TOKEN_BALANCES, ARCHIVE_V2_TX_FLAG_MESSAGE_V0, + ArchiveV2BlockAccessBlob, ArchiveV2BlockAccessBlockhash, ArchiveV2BlockAccessPubkey, + ArchiveV2HotBlockBlob, ArchiveV2HotBlockHeader, ArchiveV2HotBlockIndexRow, + ArchiveV2HotInstruction, ArchiveV2HotInstructionData, ArchiveV2HotLegacyMessage, + ArchiveV2HotMessagePayload, ArchiveV2HotRewards, ArchiveV2HotTxRow, ArchiveV2HotV0Message, + ArchiveV2HotV1Message, BlockzillaGetBlockBlobEncoding, BlockzillaGetBlockBundleV1, + WINCODE_ARCHIVE_V2_BLOCK_ACCESS_VERSION, +}; +use blockzilla_compact::{ + CompactMessageHeader, CompactMetaV1, CompactPohEntry, CompactReward, CompactShredding, + CompactTransactionConfig, OwnedCompactAddressTableLookup, OwnedCompactRecentBlockhash, + compact_meta_from_proto, +}; +use blockzilla_primitives::{CompactPubkey, wincode_leb128_config}; +use blockzilla_registry::KeyIndex; +use blockzilla_solana_wire::confirmed_block::{ + Reward as ProtoReward, Rewards as ProtoRewards, TransactionStatusMeta as ProtoStatusMeta, +}; +use blockzilla_solana_wire::versioned_transaction::{ + CompiledInstruction, VersionedMessage, VersionedTransactionReuse, +}; +use prost::Message; +use sha2::{Digest, Sha256}; + +use crate::format::ChunkExtrasRecord; + +pub const DEFAULT_ZSTD_LEVEL: i32 = 1; +pub const MAX_BUNDLE_BYTES: usize = 16 * 1024 * 1024; +pub const MAX_HOT_BYTES: usize = 32 * 1024 * 1024; +pub const MAX_TRANSACTIONS: usize = 65_536; +const MAX_SIGNATURES_BYTES: usize = 8 * 1024 * 1024; +const MAX_LOCAL_REGISTRY_KEYS: usize = 65_536; + +pub type PubkeyCounts = HashMap<[u8; 32], u32>; + +#[derive(Clone, Debug)] +pub struct EncodedChunkBlock { + pub slot: u64, + pub parent_slot: u64, + pub blockhash: [u8; 32], + pub previous_blockhash: [u8; 32], + pub block_time: Option, + pub block_height: Option, + pub hot: ArchiveV2HotBlockIndexRow, + pub bundle_bytes: Vec, + pub bundle_sha256: [u8; 32], + pub extras: ChunkExtrasRecord, + pub pubkey_counts: PubkeyCounts, +} + +pub(crate) fn compute_budget_program_id() -> [u8; 32] { + let bytes = bs58::decode("ComputeBudget111111111111111111111111111111") + .into_vec() + .expect("ComputeBudget program id is valid base58"); + bytes + .as_slice() + .try_into() + .expect("ComputeBudget program id is 32 bytes") +} + +pub(crate) struct OrderedRegistry { + pub keys: Vec<[u8; 32]>, + pub counts: Vec, +} + +/// Deterministic frequency-sorted pubkey ordering matching `hivezilla-ledger-archive`. +pub(crate) fn ordered_registry(counts: PubkeyCounts) -> OrderedRegistry { + let mut items: Vec<([u8; 32], u32)> = counts.into_iter().collect(); + items.sort_unstable_by(|(left_key, left_count), (right_key, right_count)| { + right_count + .cmp(left_count) + .then_with(|| left_key.cmp(right_key)) + }); + let compute_budget = compute_budget_program_id(); + let mut keys = Vec::with_capacity(items.len() + 1); + let mut counts_in_order = Vec::with_capacity(items.len() + 1); + if !items.iter().any(|(key, _)| *key == compute_budget) { + keys.push(compute_budget); + counts_in_order.push(0); + } + for (key, count) in items { + keys.push(key); + counts_in_order.push(count); + } + OrderedRegistry { + keys, + counts: counts_in_order, + } +} + +/// Encode one validated [`ArchiveBlockPayloadV1`] into a `BlockzillaGetBlockBundleV1` +/// (with block-local pubkey IDs and inline recent blockhashes), its PoH + shredding +/// sidecar, and its registry-eligible pubkey counts. +pub fn encode_archive_payload( + payload: &ArchiveBlockPayloadV1, + zstd_level: i32, +) -> Result { + payload.validate().context("validate archive block payload")?; + ensure!( + payload.transactions.len() <= MAX_TRANSACTIONS, + "slot {} has {} transactions, limit is {MAX_TRANSACTIONS}", + payload.slot, + payload.transactions.len() + ); + + let rewards_proto = ProtoRewards::decode(payload.rewards_proto.as_slice()) + .with_context(|| format!("decode block rewards protobuf for slot {}", payload.slot))?; + + let mut tx_reuse = VersionedTransactionReuse::default(); + let mut decoded_statuses = Vec::with_capacity(payload.transactions.len()); + let mut counts = PubkeyCounts::new(); + let mut total_signatures = 0usize; + + for (tx_index, tx) in payload.transactions.iter().enumerate() { + let parsed = tx_reuse + .deserialize_transaction(&tx.wire_bytes) + .map_err(|err| anyhow::anyhow!("decode tx {tx_index} in slot {}: {err}", payload.slot))?; + ensure!( + parsed.signatures.len() <= usize::from(u8::MAX), + "slot {} tx {tx_index} has more than 255 signatures", + payload.slot + ); + total_signatures = total_signatures + .checked_add(parsed.signatures.len()) + .context("signature count overflows")?; + count_message_keys(&parsed.message, &mut counts); + tx_reuse.recycle_transaction(parsed); + + let status = ProtoStatusMeta::decode(tx.status_proto.as_slice()).with_context(|| { + format!( + "decode tx {tx_index} status protobuf in slot {}", + payload.slot + ) + })?; + count_status_keys(&status, &mut counts)?; + decoded_statuses.push(status); + } + + ensure!( + total_signatures <= MAX_SIGNATURES_BYTES / 64, + "slot {} signatures exceed byte limit", + payload.slot + ); + + let ordered = ordered_registry(counts.clone()); + ensure!( + ordered.keys.len() <= MAX_LOCAL_REGISTRY_KEYS, + "slot {} has {} local registry keys, limit is {MAX_LOCAL_REGISTRY_KEYS}", + payload.slot, + ordered.keys.len() + ); + let key_index = KeyIndex::build_from_slice_low_memory(&ordered.keys); + + let mut rows = Vec::with_capacity(payload.transactions.len()); + let mut message_bytes = Vec::new(); + let mut metadata_bytes = Vec::new(); + let mut signatures = Vec::with_capacity(total_signatures * 64); + let mut signature_counts = Vec::with_capacity(payload.transactions.len()); + + for (tx_index, (tx, proto_status)) in payload + .transactions + .iter() + .zip(decoded_statuses.iter()) + .enumerate() + { + let parsed = tx_reuse + .deserialize_transaction(&tx.wire_bytes) + .map_err(|err| anyhow::anyhow!("decode tx {tx_index} in slot {}: {err}", payload.slot))?; + let sig_count = u8::try_from(parsed.signatures.len()) + .context("transaction has more than 255 signatures")?; + signature_counts.push(sig_count); + for sig in &parsed.signatures { + signatures.extend_from_slice(*sig); + } + + let (msg_payload, mut flags) = encode_message(&parsed.message, &key_index); + tx_reuse.recycle_transaction(parsed); + + let compact_meta = compact_meta_from_proto(proto_status, &key_index) + .with_context(|| format!("compact tx {tx_index} status in slot {}", payload.slot))?; + flags |= metadata_flags(&compact_meta); + + let msg_encoded = wincode::config::serialize(&msg_payload, wincode_leb128_config()) + .context("serialize hot message")?; + let meta_encoded = wincode::config::serialize(&compact_meta, wincode_leb128_config()) + .context("serialize hot metadata")?; + + let message_offset = + u32::try_from(message_bytes.len()).context("message region exceeds u32")?; + let message_len = u32::try_from(msg_encoded.len()).context("message exceeds u32")?; + let metadata_offset = + u32::try_from(metadata_bytes.len()).context("metadata region exceeds u32")?; + let metadata_len = u32::try_from(meta_encoded.len()).context("metadata exceeds u32")?; + message_bytes.extend_from_slice(&msg_encoded); + metadata_bytes.extend_from_slice(&meta_encoded); + + rows.push(ArchiveV2HotTxRow { + tx_index: u32::try_from(tx_index).context("tx_index exceeds u32")?, + flags, + message_offset, + message_len, + metadata_offset, + metadata_len, + signature_count: sig_count, + reserved: [0; 3], + }); + } + + ensure!( + signatures.len() <= MAX_SIGNATURES_BYTES, + "slot {} signatures exceed byte limit", + payload.slot + ); + + let num_partitions = rewards_proto.num_partitions.map(|p| p.num_partitions); + let rewards = if rewards_proto.rewards.is_empty() && num_partitions.is_none() { + None + } else { + let decoded = rewards_proto + .rewards + .iter() + .map(|reward| compact_proto_reward(reward, &key_index)) + .collect::>>()?; + Some(ArchiveV2HotRewards { + num_partitions, + decoded, + }) + }; + + let hot_blob = ArchiveV2HotBlockBlob { + header: ArchiveV2HotBlockHeader { + slot: payload.slot, + parent_slot: payload.parent_slot, + blockhash_id: 1, + previous_blockhash_id: 0, + block_time: payload.block_time, + block_height: payload.block_height, + rewards, + }, + tx_count: u32::try_from(payload.transactions.len()).context("tx_count exceeds u32")?, + tx_rows: rows, + message_bytes, + metadata_bytes, + consensus_block_id: Some(payload.consensus_block_id), + block_markers: payload.markers.clone(), + }; + let uncompressed = wincode::config::serialize(&hot_blob, wincode_leb128_config()) + .context("serialize hot block blob")?; + ensure!( + uncompressed.len() <= MAX_HOT_BYTES, + "slot {} hot block exceeds byte limit", + payload.slot + ); + let compressed = zstd::bulk::compress(&uncompressed, zstd_level) + .with_context(|| format!("compress slot {} hot block", payload.slot))?; + let uncompressed_len = u32::try_from(uncompressed.len()).context("hot block exceeds u32")?; + let compressed_len = u32::try_from(compressed.len()).context("compressed block exceeds u32")?; + + let access = ArchiveV2BlockAccessBlob { + version: blockzilla_archive_v2::WINCODE_ARCHIVE_V2_BLOCK_ACCESS_VERSION, + flags: 0, + blockhash: payload.blockhash, + previous_blockhash: payload.previous_blockhash, + signature_counts, + signatures, + pubkeys: ordered + .keys + .into_iter() + .enumerate() + .map(|(index, pubkey)| ArchiveV2BlockAccessPubkey { + id: index as u32 + 1, + pubkey, + }) + .collect(), + blockhashes: vec![ + ArchiveV2BlockAccessBlockhash { + id: 0, + blockhash: payload.previous_blockhash, + }, + ArchiveV2BlockAccessBlockhash { + id: 1, + blockhash: payload.blockhash, + }, + ], + vote_hashes: Vec::new(), + }; + debug_assert_eq!(access.version, WINCODE_ARCHIVE_V2_BLOCK_ACCESS_VERSION); + let access_bytes = wincode::config::serialize(&access, wincode_leb128_config()) + .context("serialize block access")?; + ensure!( + compressed.len().saturating_add(access_bytes.len()) <= MAX_BUNDLE_BYTES, + "slot {} bundle exceeds byte limit", + payload.slot + ); + + let bundle = BlockzillaGetBlockBundleV1 { + version: 1, + slot: payload.slot, + hot_block_encoding: BlockzillaGetBlockBlobEncoding::ZstdWincode, + hot_block: compressed, + block_access_encoding: BlockzillaGetBlockBlobEncoding::Wincode, + block_access: Some(access_bytes), + }; + let bundle_bytes = wincode::config::serialize(&bundle, wincode_leb128_config()) + .context("serialize getBlock bundle")?; + ensure!( + bundle_bytes.len() <= MAX_BUNDLE_BYTES, + "slot {} bundle exceeds byte limit", + payload.slot + ); + let bundle_sha256: [u8; 32] = Sha256::digest(&bundle_bytes).into(); + let signature_count = u32::try_from(total_signatures).context("signature_count exceeds u32")?; + + let hot = ArchiveV2HotBlockIndexRow { + block_id: 1, + slot: payload.slot, + compressed_offset: 0, + compressed_len, + uncompressed_len, + tx_count: u32::try_from(payload.transactions.len()).context("tx_count exceeds u32")?, + first_tx_ordinal: 0, + first_signature_ordinal: 0, + signature_count, + }; + + let extras = ChunkExtrasRecord { + slot: payload.slot, + poh: payload + .entries + .iter() + .map(|entry| CompactPohEntry { + num_hashes: entry.num_hashes, + hash: entry.hash, + tx_count: entry.tx_count, + signature_count: entry.signature_count, + }) + .collect(), + shredding: payload + .shredding + .iter() + .map(|group| CompactShredding { + entry_end_idx: group.entry_end_idx, + shred_end_idx: group.shred_end_idx, + }) + .collect(), + }; + + Ok(EncodedChunkBlock { + slot: payload.slot, + parent_slot: payload.parent_slot, + blockhash: payload.blockhash, + previous_blockhash: payload.previous_blockhash, + block_time: payload.block_time, + block_height: payload.block_height, + hot, + bundle_bytes, + bundle_sha256, + extras, + pubkey_counts: counts, + }) +} + +fn bump_key(counts: &mut PubkeyCounts, key: [u8; 32]) { + let entry = counts.entry(key).or_insert(0); + *entry = entry.saturating_add(1); +} + +fn count_message_keys(message: &VersionedMessage<'_>, counts: &mut PubkeyCounts) { + match message { + VersionedMessage::Legacy(msg) => { + for key in &msg.account_keys { + bump_key(counts, **key); + } + } + VersionedMessage::V0(msg) => { + for key in &msg.account_keys { + bump_key(counts, **key); + } + for lookup in &msg.address_table_lookups { + bump_key(counts, *lookup.account_key); + } + } + VersionedMessage::V1(msg) => { + for key in &msg.account_keys { + bump_key(counts, **key); + } + } + } +} + +fn count_status_keys(meta: &ProtoStatusMeta, counts: &mut PubkeyCounts) -> Result<()> { + for raw in &meta.loaded_writable_addresses { + bump_key(counts, copy32(raw, "loaded writable address")?); + } + for raw in &meta.loaded_readonly_addresses { + bump_key(counts, copy32(raw, "loaded readonly address")?); + } + for tb in meta + .pre_token_balances + .iter() + .chain(meta.post_token_balances.iter()) + { + bump_key(counts, decode_bs58_key(&tb.mint, "token mint")?); + if !tb.owner.is_empty() { + bump_key(counts, decode_bs58_key(&tb.owner, "token owner")?); + } + if !tb.program_id.is_empty() { + bump_key(counts, decode_bs58_key(&tb.program_id, "token program")?); + } + } + for reward in &meta.rewards { + bump_key(counts, decode_bs58_key(&reward.pubkey, "reward pubkey")?); + } + if !meta.return_data_none + && let Some(rd) = &meta.return_data + { + bump_key(counts, copy32(&rd.program_id, "return_data program_id")?); + } + Ok(()) +} + +fn encode_message( + message: &VersionedMessage<'_>, + key_index: &KeyIndex, +) -> (ArchiveV2HotMessagePayload, u32) { + match message { + VersionedMessage::Legacy(msg) => ( + ArchiveV2HotMessagePayload::Legacy(ArchiveV2HotLegacyMessage { + header: CompactMessageHeader { + num_required_signatures: msg.header.num_required_signatures, + num_readonly_signed_accounts: msg.header.num_readonly_signed_accounts, + num_readonly_unsigned_accounts: msg.header.num_readonly_unsigned_accounts, + }, + account_keys: msg + .account_keys + .iter() + .map(|k| key_index.compact(k)) + .collect(), + recent_blockhash: OwnedCompactRecentBlockhash::Nonce(*msg.recent_blockhash), + instructions: map_instructions(&msg.instructions), + }), + 0, + ), + VersionedMessage::V0(msg) => ( + ArchiveV2HotMessagePayload::V0(ArchiveV2HotV0Message { + header: CompactMessageHeader { + num_required_signatures: msg.header.num_required_signatures, + num_readonly_signed_accounts: msg.header.num_readonly_signed_accounts, + num_readonly_unsigned_accounts: msg.header.num_readonly_unsigned_accounts, + }, + account_keys: msg + .account_keys + .iter() + .map(|k| key_index.compact(k)) + .collect(), + recent_blockhash: OwnedCompactRecentBlockhash::Nonce(*msg.recent_blockhash), + instructions: map_instructions(&msg.instructions), + address_table_lookups: msg + .address_table_lookups + .iter() + .map(|lookup| OwnedCompactAddressTableLookup { + account_key: key_index.compact(lookup.account_key), + writable_indexes: lookup.writable_indexes.clone(), + readonly_indexes: lookup.readonly_indexes.clone(), + }) + .collect(), + }), + ARCHIVE_V2_TX_FLAG_MESSAGE_V0, + ), + VersionedMessage::V1(msg) => ( + ArchiveV2HotMessagePayload::V1(ArchiveV2HotV1Message { + header: CompactMessageHeader { + num_required_signatures: msg.header.num_required_signatures, + num_readonly_signed_accounts: msg.header.num_readonly_signed_accounts, + num_readonly_unsigned_accounts: msg.header.num_readonly_unsigned_accounts, + }, + config: CompactTransactionConfig { + priority_fee: msg.config.priority_fee, + compute_unit_limit: msg.config.compute_unit_limit, + loaded_accounts_data_size_limit: msg.config.loaded_accounts_data_size_limit, + heap_size: msg.config.heap_size, + }, + account_keys: msg + .account_keys + .iter() + .map(|k| key_index.compact(k)) + .collect(), + recent_blockhash: OwnedCompactRecentBlockhash::Nonce(*msg.recent_blockhash), + instructions: map_instructions(&msg.instructions), + }), + 0, + ), + } +} + +fn map_instructions(instructions: &[CompiledInstruction]) -> Vec { + instructions + .iter() + .map(|ix| ArchiveV2HotInstruction { + program_id_index: ix.program_id_index, + accounts: ix.accounts.clone(), + data: ArchiveV2HotInstructionData::Raw(ix.data.clone()), + }) + .collect() +} + +fn metadata_flags(meta: &CompactMetaV1) -> u32 { + let mut flags = ARCHIVE_V2_TX_FLAG_HAS_METADATA; + if meta.err.is_some() { + flags |= ARCHIVE_V2_TX_FLAG_HAS_ERROR; + } + if meta.return_data.is_some() { + flags |= ARCHIVE_V2_TX_FLAG_HAS_RETURN_DATA; + } + if meta.logs.is_some() { + flags |= ARCHIVE_V2_TX_FLAG_HAS_LOGS; + } + if meta.inner_instructions.is_some() { + flags |= ARCHIVE_V2_TX_FLAG_HAS_INNER_IX; + } + if !meta.pre_token_balances.is_empty() || !meta.post_token_balances.is_empty() { + flags |= ARCHIVE_V2_TX_FLAG_HAS_TOKEN_BALANCES; + } + if !meta.loaded_writable_addresses.is_empty() || !meta.loaded_readonly_addresses.is_empty() { + flags |= ARCHIVE_V2_TX_FLAG_HAS_LOADED_ADDRESSES; + } + flags +} + +fn compact_proto_reward(reward: &ProtoReward, key_index: &KeyIndex) -> Result { + let pubkey_bytes = decode_bs58_key(&reward.pubkey, "block reward pubkey")?; + let commission = if reward.commission.is_empty() { + None + } else { + Some( + reward + .commission + .parse::() + .with_context(|| format!("invalid reward commission '{}'", reward.commission))?, + ) + }; + Ok(CompactReward { + pubkey: key_index.compact(&pubkey_bytes), + lamports: reward.lamports, + post_balance: reward.post_balance, + reward_type: reward.reward_type, + commission, + }) +} + +fn decode_bs58_key(value: &str, label: &str) -> Result<[u8; 32]> { + let bytes = bs58::decode(value) + .into_vec() + .with_context(|| format!("decode base58 {label}"))?; + copy32(&bytes, label) +} + +fn copy32(bytes: &[u8], label: &str) -> Result<[u8; 32]> { + if bytes.len() != 32 { + bail!("{label} has {} bytes, expected 32", bytes.len()); + } + let mut out = [0u8; 32]; + out.copy_from_slice(bytes); + Ok(out) +} + +/// Helper to remap a [`CompactPubkey`] using a block-local lookup table plus the +/// epoch-wide [`KeyIndex`]. +pub(crate) fn remap_pubkey( + pubkey: CompactPubkey, + local_to_global: &[CompactPubkey], + epoch_key_index: &KeyIndex, +) -> Result { + match pubkey { + CompactPubkey::Id(local_id) => { + let idx = usize::try_from(local_id.checked_sub(1).context("reserved pubkey ID 0")?) + .context("pubkey ID overflows usize")?; + local_to_global + .get(idx) + .copied() + .with_context(|| format!("local pubkey ID {local_id} out of range")) + } + CompactPubkey::Raw(bytes) => Ok(epoch_key_index.compact(&bytes)), + } +} diff --git a/crates/blockzilla-finalized-chunks/src/tests.rs b/crates/blockzilla-finalized-chunks/src/tests.rs new file mode 100644 index 00000000..d9d5b110 --- /dev/null +++ b/crates/blockzilla-finalized-chunks/src/tests.rs @@ -0,0 +1,1267 @@ +use std::fs::{self, File}; +use std::io::{Read, Seek, SeekFrom}; + +use blockzilla_account_bridge_protocol::{ + ArchiveBlockPayloadV1, ArchiveEntry, ArchiveShredGroup, ArchiveTransaction, SlotChainRelation, +}; +use blockzilla_archive_v2::{ + ArchiveV2HotMessagePayload, ArchiveV2HotTxRow, BlockzillaGetBlockBundleV1, + ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE, ARCHIVE_V2_POH_FILE, ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE, + ARCHIVE_V2_SHREDDING_FILE, WincodeArchiveV2PohRecord, WincodeArchiveV2ShreddingRecord, +}; +use blockzilla_compact::OwnedCompactRecentBlockhash; +use blockzilla_compact_v2_reader::{ + ArchiveReader, BlockhashResolver, HashVerification, LocalRangeSource, OpenOptions, + PreviousBlockhashTailSchema, RangeSource, TrustedGenerationIdentity, + parse_previous_blockhash_tail, +}; +use blockzilla_primitives::{CompactPubkey, WincodeLeb128FramedReader, wincode_leb128_config}; +use blockzilla_solana_wire::confirmed_block::{ + InnerInstruction, InnerInstructions, ReturnData, Reward, Rewards, TokenBalance, + TransactionError, TransactionStatusMeta, UiTokenAmount, +}; +use prost::Message as ProstMessage; +use sha2::{Digest, Sha256}; + +use crate::{ + ChunkBuilder, ChunkCatalogBinding, ChunkCatalogLookup, ChunkCatalogReader, ChunkCatalogWriter, + ChunkIndexV1, ChunkSlotEntry, ChunkSlotKind, ChunkStorageMode, EPOCH_ARCHIVE_FILES, + LocalChunkSource, SLOTS_PER_EPOCH, TailBlockhash, check, compact, encode_archive_payload, +}; + +fn encode_short_u16(mut value: usize, out: &mut Vec) { + loop { + let mut elem = (value & 0x7f) as u8; + value >>= 7; + if value == 0 { + out.push(elem); + break; + } + elem |= 0x80; + out.push(elem); + } +} + +fn build_legacy_tx_wire( + sig: [u8; 64], + keys: &[[u8; 32]], + recent_blockhash: [u8; 32], + program_id_index: u8, + accounts: &[u8], + data: &[u8], +) -> Vec { + let mut out = Vec::new(); + encode_short_u16(1, &mut out); + out.extend_from_slice(&sig); + // MessageHeader + out.extend_from_slice(&[1, 0, 1]); + // account_keys + encode_short_u16(keys.len(), &mut out); + for k in keys { + out.extend_from_slice(k); + } + // recent_blockhash + out.extend_from_slice(&recent_blockhash); + // 1 instruction + encode_short_u16(1, &mut out); + out.push(program_id_index); + encode_short_u16(accounts.len(), &mut out); + out.extend_from_slice(accounts); + encode_short_u16(data.len(), &mut out); + out.extend_from_slice(data); + out +} + +fn build_v0_tx_wire( + sig: [u8; 64], + keys: &[[u8; 32]], + recent_blockhash: [u8; 32], + alt_key: [u8; 32], + writable_indexes: &[u8], + readonly_indexes: &[u8], +) -> Vec { + let mut out = Vec::new(); + encode_short_u16(1, &mut out); + out.extend_from_slice(&sig); + // Versioned message prefix: 0x80 | 0 + out.push(0x80); + out.extend_from_slice(&[1, 0, 1]); + encode_short_u16(keys.len(), &mut out); + for k in keys { + out.extend_from_slice(k); + } + out.extend_from_slice(&recent_blockhash); + // 1 instruction + encode_short_u16(1, &mut out); + out.push(1); + encode_short_u16(1, &mut out); + out.push(0); + encode_short_u16(3, &mut out); + out.extend_from_slice(&[7, 8, 9]); + // 1 ALT lookup + encode_short_u16(1, &mut out); + out.extend_from_slice(&alt_key); + encode_short_u16(writable_indexes.len(), &mut out); + out.extend_from_slice(writable_indexes); + encode_short_u16(readonly_indexes.len(), &mut out); + out.extend_from_slice(readonly_indexes); + out +} + +fn build_v1_tx_wire( + sig: [u8; 64], + keys: &[[u8; 32]], + recent_blockhash: [u8; 32], + priority_fee: u64, + compute_unit_limit: u32, +) -> Vec { + let mut out = Vec::new(); + encode_short_u16(1, &mut out); + out.extend_from_slice(&sig); + // Versioned message prefix: 0x80 | 1 + out.push(0x81); + // MessageHeader + out.extend_from_slice(&[1, 0, 1]); + // config_mask: priority_fee (0b11) | compute_unit_limit (0b100) + let config_mask: u32 = 0b11 | 0b100; + out.extend_from_slice(&config_mask.to_le_bytes()); + out.extend_from_slice(&recent_blockhash); + // num_instructions = 1, num_addresses = keys.len() + out.push(1); + out.push(keys.len() as u8); + for k in keys { + out.extend_from_slice(k); + } + out.extend_from_slice(&priority_fee.to_le_bytes()); + out.extend_from_slice(&compute_unit_limit.to_le_bytes()); + // Instruction header: program_id_index=1, num_accounts=1, data_len=4 + out.push(1); + out.push(1); + out.extend_from_slice(&4u16.to_le_bytes()); + // Instruction payload: accounts=[0], data=[0xde, 0xad, 0xbe, 0xef] + out.push(0); + out.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); + out +} + +fn ok_status_proto( + fee: u64, + mint: [u8; 32], + owner: [u8; 32], + program_id: [u8; 32], + loaded_writable: Vec>, + logs: Vec, +) -> Vec { + let meta = TransactionStatusMeta { + err: None, + fee, + pre_balances: vec![10_000, 0], + post_balances: vec![10_000 - fee, 0], + inner_instructions: vec![InnerInstructions { + index: 0, + instructions: vec![InnerInstruction { + program_id_index: 1, + accounts: vec![0], + data: vec![1, 2], + stack_height: Some(2), + }], + }], + inner_instructions_none: false, + log_messages: logs, + log_messages_none: false, + pre_token_balances: vec![TokenBalance { + account_index: 0, + mint: bs58::encode(mint).into_string(), + ui_token_amount: Some(UiTokenAmount { + ui_amount: 1.5, + decimals: 6, + amount: "1500000".into(), + ui_amount_string: "1.5".into(), + }), + owner: bs58::encode(owner).into_string(), + program_id: bs58::encode(program_id).into_string(), + }], + post_token_balances: vec![], + rewards: vec![], + loaded_writable_addresses: loaded_writable, + loaded_readonly_addresses: vec![], + return_data: Some(ReturnData { + program_id: program_id.to_vec(), + data: vec![42, 43], + }), + return_data_none: false, + compute_units_consumed: Some(12_345), + cost_units: Some(20_000), + }; + meta.encode_to_vec() +} + +fn failed_status_proto(fee: u64) -> Vec { + // Bincode-encoded Solana TransactionError::AccountNotFound (discriminant 0u32 LE) + let err_bytes = 0u32.to_le_bytes().to_vec(); + let meta = TransactionStatusMeta { + err: Some(TransactionError { err: err_bytes }), + fee, + pre_balances: vec![5_000, 0], + post_balances: vec![5_000 - fee, 0], + inner_instructions: vec![], + inner_instructions_none: true, + log_messages: vec!["Program failed".into()], + log_messages_none: false, + pre_token_balances: vec![], + post_token_balances: vec![], + rewards: vec![], + loaded_writable_addresses: vec![], + loaded_readonly_addresses: vec![], + return_data: None, + return_data_none: true, + compute_units_consumed: Some(900), + cost_units: None, + }; + meta.encode_to_vec() +} + +fn rewards_proto(pubkey: [u8; 32], lamports: i64) -> Vec { + Rewards { + rewards: vec![Reward { + pubkey: bs58::encode(pubkey).into_string(), + lamports, + post_balance: 500_000, + reward_type: 1, // Fee + commission: String::new(), + }], + num_partitions: None, + } + .encode_to_vec() +} + +#[test] +fn chunk_index_v1_round_trip_and_o1_lookup_and_rejects_corruption() { + let index = ChunkIndexV1 { + epoch: 1, + start_slot: SLOTS_PER_EPOCH, + end_slot: SLOTS_PER_EPOCH + 3, + bundles_len: 300, + bundles_sha256: [0xaa; 32], + first_block_slot: Some(SLOTS_PER_EPOCH), + last_block_slot: Some(SLOTS_PER_EPOCH + 3), + first_parent_slot: Some(SLOTS_PER_EPOCH - 1), + boundary_previous_blockhash: Some([0x10; 32]), + last_blockhash: Some([0x13; 32]), + entries: vec![ + ChunkSlotEntry { + kind: ChunkSlotKind::ProducedBlock, + bundle_offset: 0, + bundle_len: 120, + bundle_sha256: [0x21; 32], + parent_slot: SLOTS_PER_EPOCH - 1, + blockhash: [0x11; 32], + previous_blockhash: [0x10; 32], + compressed_len: 60, + uncompressed_len: 100, + tx_count: 2, + signature_count: 2, + block_time: Some(1_700_000_001), + block_height: Some(100), + }, + ChunkSlotEntry::skipped(ChunkSlotKind::ProvenSkip), + ChunkSlotEntry::skipped(ChunkSlotKind::AbandonedFork), + ChunkSlotEntry { + kind: ChunkSlotKind::ProducedBlock, + bundle_offset: 120, + bundle_len: 180, + bundle_sha256: [0x22; 32], + parent_slot: SLOTS_PER_EPOCH, + blockhash: [0x13; 32], + previous_blockhash: [0x11; 32], + compressed_len: 90, + uncompressed_len: 150, + tx_count: 1, + signature_count: 1, + block_time: None, + block_height: Some(101), + }, + ], + }; + + let bytes = index.encode().expect("encode index"); + let decoded = ChunkIndexV1::decode(&bytes).expect("decode index"); + assert_eq!(decoded, index); + + // O(1) lookup checks + assert_eq!( + ChunkIndexV1::lookup_in_bytes(&bytes, SLOTS_PER_EPOCH - 1).unwrap(), + None + ); + assert_eq!( + ChunkIndexV1::lookup_in_bytes(&bytes, SLOTS_PER_EPOCH + 4).unwrap(), + None + ); + let (epoch0, row0) = ChunkIndexV1::lookup_in_bytes(&bytes, SLOTS_PER_EPOCH) + .unwrap() + .unwrap(); + assert_eq!(epoch0, 1); + assert_eq!(row0, index.entries[0]); + + let (_, row1) = ChunkIndexV1::lookup_in_bytes(&bytes, SLOTS_PER_EPOCH + 1) + .unwrap() + .unwrap(); + assert_eq!(row1.kind, ChunkSlotKind::ProvenSkip); + + let (_, row2) = ChunkIndexV1::lookup_in_bytes(&bytes, SLOTS_PER_EPOCH + 2) + .unwrap() + .unwrap(); + assert_eq!(row2.kind, ChunkSlotKind::AbandonedFork); + + let (_, row3) = ChunkIndexV1::lookup_in_bytes(&bytes, SLOTS_PER_EPOCH + 3) + .unwrap() + .unwrap(); + assert_eq!(row3.bundle_offset, 120); + assert_eq!(row3.block_time, None); + assert_eq!(row3.block_height, Some(101)); + + // Reject bad magic and truncation. + let mut bad_magic = bytes.clone(); + bad_magic[0] ^= 0xff; + assert!(ChunkIndexV1::decode(&bad_magic).is_err()); + assert!(ChunkIndexV1::lookup_in_bytes(&bad_magic, SLOTS_PER_EPOCH).is_err()); + assert!(ChunkIndexV1::decode(&bytes[..bytes.len() - 1]).is_err()); +} + +#[test] +fn encode_archive_payload_handles_legacy_v0_v1_failed_tx_and_metadata() { + let fee_payer = [0x01; 32]; + let prog_a = [0x02; 32]; + let alt_key = [0x03; 32]; + let loaded_w = [0x04; 32]; + let mint = [0x05; 32]; + let owner = [0x06; 32]; + let token_prog = [0x07; 32]; + let reward_key = [0x08; 32]; + + let prev_bh = [0x30; 32]; + let bh = [0x31; 32]; + + let tx0 = build_legacy_tx_wire( + [0xa0; 64], + &[fee_payer, prog_a], + prev_bh, + 1, + &[0], + &[1, 2, 3], + ); + let tx1 = build_v0_tx_wire([0xa1; 64], &[fee_payer, prog_a], prev_bh, alt_key, &[0], &[]); + let tx2 = build_v1_tx_wire([0xa2; 64], &[fee_payer, prog_a], prev_bh, 77_000, 150_000); + + let payload = ArchiveBlockPayloadV1 { + slot: SLOTS_PER_EPOCH, + parent_slot: SLOTS_PER_EPOCH - 1, + blockhash: bh, + previous_blockhash: prev_bh, + block_time: Some(1_700_000_000), + block_height: Some(500), + consensus_block_id: [0x99; 32], + markers: vec![vec![1, 2, 3, 4]], + rewards_proto: rewards_proto(reward_key, 5_000), + entries: vec![ + ArchiveEntry { + num_hashes: 10, + hash: [0x41; 32], + tx_count: 2, + signature_count: 2, + }, + ArchiveEntry { + num_hashes: 12, + hash: bh, + tx_count: 1, + signature_count: 1, + }, + ], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 2, + shred_end_idx: 5, + }], + transactions: vec![ + ArchiveTransaction { + wire_bytes: tx0, + status_proto: ok_status_proto( + 5_000, + mint, + owner, + token_prog, + vec![], + vec![format!("Program {} invoke [1]", bs58::encode(prog_a).into_string())], + ), + }, + ArchiveTransaction { + wire_bytes: tx1, + status_proto: ok_status_proto( + 5_000, + mint, + owner, + token_prog, + vec![loaded_w.to_vec()], + vec!["Program log: ok".into()], + ), + }, + ArchiveTransaction { + wire_bytes: tx2, + status_proto: failed_status_proto(5_000), + }, + ], + }; + + let encoded = encode_archive_payload(&payload, 1).expect("encode archive payload"); + assert_eq!(encoded.slot, SLOTS_PER_EPOCH); + assert_eq!(encoded.hot.tx_count, 3); + assert_eq!(encoded.hot.signature_count, 3); + let actual_sha: [u8; 32] = Sha256::digest(&encoded.bundle_bytes).into(); + assert_eq!(actual_sha, encoded.bundle_sha256); + + // Pubkey frequency counts match message + ALT + loaded + token balances + return_data. + assert_eq!(encoded.pubkey_counts.get(&fee_payer), Some(&3)); + assert_eq!(encoded.pubkey_counts.get(&prog_a), Some(&3)); + assert_eq!(encoded.pubkey_counts.get(&alt_key), Some(&1)); + assert_eq!(encoded.pubkey_counts.get(&loaded_w), Some(&1)); + assert_eq!(encoded.pubkey_counts.get(&mint), Some(&2)); + assert_eq!(encoded.pubkey_counts.get(&owner), Some(&2)); + // token_prog counted twice in pre_token_balances + twice in return_data = 4. + assert_eq!(encoded.pubkey_counts.get(&token_prog), Some(&4)); + // Block-level rewards are NOT counted in registry-eligible counts (matches ledger-archive). + assert_eq!(encoded.pubkey_counts.get(&reward_key), None); + + // Bundle deserializes cleanly as BlockzillaGetBlockBundleV1. + let bundle: BlockzillaGetBlockBundleV1 = + wincode::config::deserialize(&encoded.bundle_bytes, wincode_leb128_config()) + .expect("decode bundle"); + assert_eq!(bundle.version, 1); + assert_eq!(bundle.slot, SLOTS_PER_EPOCH); + assert!(bundle.block_access.is_some()); + assert_eq!(encoded.extras.poh.len(), 2); + assert_eq!(encoded.extras.shredding.len(), 1); +} + +#[test] +fn chunk_catalog_round_trip_r2_and_local_and_security_invariants() { + let dir = tempfile::tempdir().unwrap(); + let chunks_root = dir.path().join("chunks"); + let catalog_path = dir.path().join("catalog.sqlite"); + + let key_a = [0x11; 32]; + let key_b = [0x12; 32]; + let bh_prev = [0x50; 32]; + let bh0 = [0x51; 32]; + let bh2 = [0x52; 32]; + + let b0 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: SLOTS_PER_EPOCH, + parent_slot: SLOTS_PER_EPOCH - 1, + blockhash: bh0, + previous_blockhash: bh_prev, + block_time: Some(1_700_000_010), + block_height: Some(10), + consensus_block_id: [0x61; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 5, + hash: bh0, + tx_count: 1, + signature_count: 1, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![ArchiveTransaction { + wire_bytes: build_legacy_tx_wire([0xb0; 64], &[key_a, key_b], bh_prev, 1, &[0], &[1]), + status_proto: failed_status_proto(5_000), + }], + }, + 1, + ) + .unwrap(); + + let b2 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: SLOTS_PER_EPOCH + 2, + parent_slot: SLOTS_PER_EPOCH, + blockhash: bh2, + previous_blockhash: bh0, + block_time: Some(1_700_000_012), + block_height: Some(11), + consensus_block_id: [0x62; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 5, + hash: bh2, + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }, + 1, + ) + .unwrap(); + + let mut builder = ChunkBuilder::create_default(&chunks_root, SLOTS_PER_EPOCH, SLOTS_PER_EPOCH + 3).unwrap(); + builder.add_block(&b0).unwrap(); + builder.add_skip(SLOTS_PER_EPOCH + 1).unwrap(); + builder.add_block(&b2).unwrap(); + builder.add_abandoned_fork(SLOTS_PER_EPOCH + 3).unwrap(); + let sealed = builder.finish().unwrap(); + + let binding = ChunkCatalogBinding { + version: 1, + generation: "mainnet-gen-1".into(), + prefix: "finalized-chunks/mainnet".into(), + }; + let mut writer = ChunkCatalogWriter::open_or_create(&catalog_path, binding.clone()).unwrap(); + let local_bundles_path = sealed + .dir + .join(crate::CHUNK_BUNDLES_FILE) + .canonicalize() + .unwrap(); + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + ChunkStorageMode::Local, + local_bundles_path.to_str().unwrap(), + None, + ) + .unwrap(); + assert_eq!(writer.highest_sealed_slot().unwrap(), Some(SLOTS_PER_EPOCH + 3)); + + let canonical_catalog = catalog_path.canonicalize().unwrap(); + + // Lookup produced block in Local mode and verify pread range + SHA-256. + let lookup0 = ChunkCatalogReader::lookup( + &canonical_catalog, + &binding.generation, + &binding.prefix, + SLOTS_PER_EPOCH, + ) + .unwrap() + .unwrap(); + match lookup0 { + ChunkCatalogLookup::ProducedBlock { + storage_mode, + bundles_location, + entry, + .. + } => { + assert_eq!(storage_mode, ChunkStorageMode::Local); + let mut file = File::open(&bundles_location).unwrap(); + file.seek(SeekFrom::Start(entry.bundle_offset)).unwrap(); + let mut slice = vec![0u8; entry.bundle_len as usize]; + file.read_exact(&mut slice).unwrap(); + assert_eq!(slice, b0.bundle_bytes); + assert_eq!(<[u8; 32]>::from(Sha256::digest(&slice)), entry.bundle_sha256); + } + other => panic!("expected ProducedBlock, got {other:?}"), + } + + // Lookup ProvenSkip & AbandonedFork. + assert_eq!( + ChunkCatalogReader::lookup( + &canonical_catalog, + &binding.generation, + &binding.prefix, + SLOTS_PER_EPOCH + 1, + ) + .unwrap(), + Some(ChunkCatalogLookup::Skipped { + epoch: 1, + kind: ChunkSlotKind::ProvenSkip, + }) + ); + assert_eq!( + ChunkCatalogReader::lookup( + &canonical_catalog, + &binding.generation, + &binding.prefix, + SLOTS_PER_EPOCH + 3, + ) + .unwrap(), + Some(ChunkCatalogLookup::Skipped { + epoch: 1, + kind: ChunkSlotKind::AbandonedFork, + }) + ); + + // Idempotent promotion to R2 storage mode. + let r2_key = format!( + "{}/epoch-1/{}/{}", + binding.prefix, + crate::chunk_dir_name(SLOTS_PER_EPOCH, SLOTS_PER_EPOCH + 3), + crate::CHUNK_BUNDLES_FILE + ); + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + ChunkStorageMode::R2, + &r2_key, + Some("\"etag-abc123\""), + ) + .unwrap(); + + let lookup2 = ChunkCatalogReader::lookup( + &canonical_catalog, + &binding.generation, + &binding.prefix, + SLOTS_PER_EPOCH + 2, + ) + .unwrap() + .unwrap(); + match lookup2 { + ChunkCatalogLookup::ProducedBlock { + storage_mode, + bundles_location, + bundles_etag, + entry, + .. + } => { + assert_eq!(storage_mode, ChunkStorageMode::R2); + assert_eq!(bundles_location, r2_key); + assert_eq!(bundles_etag.as_deref(), Some("\"etag-abc123\"")); + assert_eq!(entry.bundle_len as usize, b2.bundle_bytes.len()); + } + other => panic!("expected ProducedBlock, got {other:?}"), + } + + // Wrong generation fails closed. + assert!( + ChunkCatalogReader::lookup( + &canonical_catalog, + "wrong-gen", + &binding.prefix, + SLOTS_PER_EPOCH, + ) + .is_err() + ); + + // Overlapping chunk with different bounds is rejected. + let mut overlap_builder = + ChunkBuilder::create_default(&chunks_root, SLOTS_PER_EPOCH + 2, SLOTS_PER_EPOCH + 4) + .unwrap(); + overlap_builder.add_skip(SLOTS_PER_EPOCH + 2).unwrap(); + overlap_builder.add_skip(SLOTS_PER_EPOCH + 3).unwrap(); + overlap_builder.add_skip(SLOTS_PER_EPOCH + 4).unwrap(); + let overlap_sealed = overlap_builder.finish().unwrap(); + assert!( + writer + .register_chunk( + &overlap_sealed.manifest, + &overlap_sealed.index_bytes, + ChunkStorageMode::Local, + overlap_sealed + .dir + .join(crate::CHUNK_BUNDLES_FILE) + .canonicalize() + .unwrap() + .to_str() + .unwrap(), + None, + ) + .is_err() + ); + + // remove_epoch removes all rows for epoch 1. + assert_eq!(writer.remove_epoch(1).unwrap(), 1); + assert_eq!( + ChunkCatalogReader::lookup( + &canonical_catalog, + &binding.generation, + &binding.prefix, + SLOTS_PER_EPOCH, + ) + .unwrap(), + None + ); +} + +#[test] +fn end_to_end_multi_chunk_streaming_compaction_matches_compact_v2_reader() { + let dir = tempfile::tempdir().unwrap(); + let chunks_root = dir.path().join("finalized-chunks"); + let archive_out = dir.path().join("epoch-1-archive"); + + let hot_key = [0x10; 32]; // Appears in every tx across both chunks -> highest frequency! + let cold_key = [0x20; 32]; + let alt_key = [0x30; 32]; + let loaded_w = [0x40; 32]; + let mint = [0x50; 32]; + let owner = [0x51; 32]; + let token_prog = [0x52; 32]; + let reward_key = [0x60; 32]; + + let tail_bh_older = [0x70; 32]; + let tail_bh_parent = [0x71; 32]; + let bh_0 = [0x72; 32]; + let bh_2 = [0x73; 32]; + let bh_4 = [0x74; 32]; + let bh_7 = [0x75; 32]; + let durable_nonce = [0xee; 32]; // Not in rolling window -> stays Nonce + + let s0 = SLOTS_PER_EPOCH; // 432_000 + + // Chunk 1: [s0 ..= s0 + 3] + // s0: Legacy (recent_blockhash = tail_bh_parent -> Id(-1)) + V0 (recent_blockhash = tail_bh_older -> Id(-2)) + let b0 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: s0, + parent_slot: s0 - 1, + blockhash: bh_0, + previous_blockhash: tail_bh_parent, + block_time: Some(1_700_000_100), + block_height: Some(1_000), + consensus_block_id: [0x80; 32], + markers: vec![vec![9, 9, 9]], + rewards_proto: rewards_proto(reward_key, 2_500), + entries: vec![ArchiveEntry { + num_hashes: 3, + hash: bh_0, + tx_count: 2, + signature_count: 2, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 4, + }], + transactions: vec![ + ArchiveTransaction { + wire_bytes: build_legacy_tx_wire( + [0xc0; 64], + &[hot_key, cold_key], + tail_bh_parent, + 1, + &[0], + &[11, 22], + ), + status_proto: ok_status_proto( + 5_000, + mint, + owner, + token_prog, + vec![], + vec!["Program log: hello".into()], + ), + }, + ArchiveTransaction { + wire_bytes: build_v0_tx_wire( + [0xc1; 64], + &[hot_key, cold_key], + tail_bh_older, + alt_key, + &[0], + &[], + ), + status_proto: ok_status_proto( + 5_000, + mint, + owner, + token_prog, + vec![loaded_w.to_vec()], + vec![], + ), + }, + ], + }, + 1, + ) + .unwrap(); + + // s0 + 2: V1 failed tx referencing bh_0 -> Id(0) + let b2 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: s0 + 2, + parent_slot: s0, + blockhash: bh_2, + previous_blockhash: bh_0, + block_time: Some(1_700_000_102), + block_height: Some(1_001), + consensus_block_id: [0x82; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 4, + hash: bh_2, + tx_count: 1, + signature_count: 1, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 2, + }], + transactions: vec![ArchiveTransaction { + wire_bytes: build_v1_tx_wire([0xc2; 64], &[hot_key, cold_key], bh_0, 50_000, 100_000), + status_proto: failed_status_proto(5_000), + }], + }, + 1, + ) + .unwrap(); + + let mut chunk1 = ChunkBuilder::create_default(&chunks_root, s0, s0 + 3).unwrap(); + chunk1.set_previous_tail(vec![ + TailBlockhash { + slot: s0 - 2, + blockhash: bs58::encode(tail_bh_older).into_string(), + }, + TailBlockhash { + slot: s0 - 1, + blockhash: bs58::encode(tail_bh_parent).into_string(), + }, + ]); + chunk1.add_block(&b0).unwrap(); + chunk1.add_skip(s0 + 1).unwrap(); + chunk1.add_block(&b2).unwrap(); + chunk1.add_abandoned_fork(s0 + 3).unwrap(); + chunk1.finish().unwrap(); + + // Chunk 2: [s0 + 4 ..= s0 + 7] + // s0 + 4: Legacy tx using durable_nonce -> stays Nonce! + let b4 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: s0 + 4, + parent_slot: s0 + 2, + blockhash: bh_4, + previous_blockhash: bh_2, + block_time: Some(1_700_000_104), + block_height: Some(1_002), + consensus_block_id: [0x84; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 6, + hash: bh_4, + tx_count: 1, + signature_count: 1, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 3, + }], + transactions: vec![ArchiveTransaction { + wire_bytes: build_legacy_tx_wire( + [0xc4; 64], + &[hot_key, hot_key], + durable_nonce, + 1, + &[0], + &[99], + ), + status_proto: failed_status_proto(5_000), + }], + }, + 1, + ) + .unwrap(); + + // s0 + 7: Legacy tx referencing bh_4 -> Id(2) + let b7 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: s0 + 7, + parent_slot: s0 + 4, + blockhash: bh_7, + previous_blockhash: bh_4, + block_time: Some(1_700_000_107), + block_height: Some(1_003), + consensus_block_id: [0x87; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 7, + hash: bh_7, + tx_count: 1, + signature_count: 1, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 2, + }], + transactions: vec![ArchiveTransaction { + wire_bytes: build_legacy_tx_wire( + [0xc7; 64], + &[hot_key, hot_key], + bh_4, + 1, + &[0], + &[100], + ), + status_proto: failed_status_proto(5_000), + }], + }, + 1, + ) + .unwrap(); + + let mut chunk2 = ChunkBuilder::create_default(&chunks_root, s0 + 4, s0 + 7).unwrap(); + chunk2.add_block(&b4).unwrap(); + chunk2.add_skip(s0 + 5).unwrap(); + chunk2.add_skip(s0 + 6).unwrap(); + chunk2.add_block(&b7).unwrap(); + chunk2.finish().unwrap(); + + // Run single-pass streaming compaction across both chunks! + let source = LocalChunkSource::new(&chunks_root); + let report = compact::compact_range_from_chunks(&source, 1, s0, s0 + 7, &archive_out, 1, None) + .expect("streaming compaction from chunks"); + assert_eq!(report.chunks_processed, 2); + assert_eq!(report.blocks, 4); + assert_eq!(report.skips, 3); + assert_eq!(report.forks, 1); + assert_eq!(report.transactions, 5); + assert_eq!(report.entries, 4); + assert_eq!(report.rewards, 1); + assert_eq!(report.nonce_recent_blockhashes, 1); + assert_eq!(report.first_block_slot, s0); + assert_eq!(report.last_block_slot, s0 + 7); + assert_eq!(report.boundary_hash, tail_bh_parent); + + // Every one of the 13 Compact V2 files must exist. + for file in EPOCH_ARCHIVE_FILES { + assert!( + archive_out.join(file).is_file(), + "missing Compact V2 file {file}" + ); + } + + // Open the output archive with the real production Compact V2 reader! + let reader = ArchiveReader::open_trusted( + LocalRangeSource::new(&archive_out), + TrustedGenerationIdentity { + cluster_id: "mainnet-beta".into(), + epoch: 1, + generation_id: "chunk-compaction-test".into(), + slots_per_epoch: SLOTS_PER_EPOCH, + }, + OpenOptions { + hash_verification: HashVerification::SizesOnly, + ..OpenOptions::default() + }, + ) + .expect("ArchiveReader::open_trusted on compacted chunks"); + + assert_eq!(reader.index().rows.len(), 4); + assert_eq!(reader.metadata_footer().blocks, 4); + assert_eq!(reader.metadata_footer().transactions, 5); + assert_eq!(reader.metadata_footer().entries, 4); + assert_eq!(reader.metadata_footer().rewards, 1); + assert_eq!(reader.metadata_footer().nonce_recent_blockhashes, 1); + + // hot_key was counted 7 times (highest), so it must get ID 2 (ID 1 is ComputeBudget111... when absent). + let hot_id = reader + .compile_pubkey_filter([hot_key]) + .unwrap() + .registry_id_for(&hot_key) + .expect("hot_key in registry"); + let cold_id = reader + .compile_pubkey_filter([cold_key]) + .unwrap() + .registry_id_for(&cold_key) + .expect("cold_key in registry"); + assert!(hot_id < cold_id, "hot_key ({hot_id}) must sort ahead of cold_key ({cold_id})"); + + // Verify BlockhashResolver resolves all 4 epoch blockhashes + both previous-tail blockhashes! + let bh_reg_bytes = reader + .source() + .read_all_bounded(ARCHIVE_V2_BLOCKHASH_REGISTRY_FILE, 1024 * 1024) + .unwrap(); + let tail_reg_bytes = reader + .source() + .read_all_bounded(ARCHIVE_V2_PREV_BLOCKHASH_TAIL_FILE, 1024 * 1024) + .unwrap(); + let parsed_tail = parse_previous_blockhash_tail( + &tail_reg_bytes, + PreviousBlockhashTailSchema::CurrentHashAndSlot, + ) + .unwrap(); + let bh_resolver = BlockhashResolver::from_bytes(&bh_reg_bytes, parsed_tail).unwrap(); + assert_eq!(bh_resolver.resolve(-2).unwrap(), tail_bh_older); + assert_eq!(bh_resolver.resolve(-1).unwrap(), tail_bh_parent); + assert_eq!(bh_resolver.resolve(0).unwrap(), bh_0); + assert_eq!(bh_resolver.resolve(1).unwrap(), bh_2); + assert_eq!(bh_resolver.resolve(2).unwrap(), bh_4); + assert_eq!(bh_resolver.resolve(3).unwrap(), bh_7); + + // Block 0 (slot s0): Legacy (Id(-1)) + V0 (Id(-2)), rewards, markers, signatures. + let dec0 = reader.read_block(0).unwrap(); + assert_eq!(dec0.block.header.slot, s0); + assert_eq!(dec0.block.header.blockhash_id, 0); + assert_eq!(dec0.block.header.previous_blockhash_id, 0); + assert_eq!(dec0.block.consensus_block_id, Some([0x80; 32])); + assert_eq!(dec0.block.block_markers, vec![vec![9, 9, 9]]); + let rewards0 = dec0.block.header.rewards.as_ref().unwrap(); + assert_eq!(rewards0.decoded.len(), 1); + assert_eq!( + reader.resolve_pubkey(&rewards0.decoded[0].pubkey).unwrap(), + reward_key + ); + + let tx0_row: ArchiveV2HotTxRow = dec0.block.tx_rows[0]; + let msg0 = reader + .decode_message( + &dec0.block.message_bytes[tx0_row.message_offset as usize + ..(tx0_row.message_offset + tx0_row.message_len) as usize], + ) + .unwrap(); + match msg0 { + ArchiveV2HotMessagePayload::Legacy(m) => { + assert!(matches!( + m.recent_blockhash, + OwnedCompactRecentBlockhash::Id(-1) + )); + assert_eq!(m.account_keys[0], CompactPubkey::Id(hot_id)); + assert_eq!(reader.resolve_pubkey(&m.account_keys[1]).unwrap(), cold_key); + } + other => panic!("expected Legacy message, got {other:?}"), + } + let meta0 = reader + .decode_metadata( + &dec0.block.metadata_bytes[tx0_row.metadata_offset as usize + ..(tx0_row.metadata_offset + tx0_row.metadata_len) as usize], + ) + .unwrap(); + assert!(meta0.err.is_none()); + assert_eq!(meta0.fee, 5_000); + assert_eq!(meta0.pre_token_balances.len(), 1); + assert_eq!( + reader + .resolve_pubkey(meta0.pre_token_balances[0].mint.as_ref().unwrap()) + .unwrap(), + mint + ); + assert_eq!( + reader + .resolve_pubkey(&meta0.return_data.as_ref().unwrap().program_id) + .unwrap(), + token_prog + ); + assert_eq!(reader.read_signature_ordinal(0).unwrap(), [0xc0; 64]); + assert_eq!(reader.read_signature_ordinal(1).unwrap(), [0xc1; 64]); + + let tx1_row = dec0.block.tx_rows[1]; + let msg1 = reader + .decode_message( + &dec0.block.message_bytes[tx1_row.message_offset as usize + ..(tx1_row.message_offset + tx1_row.message_len) as usize], + ) + .unwrap(); + match msg1 { + ArchiveV2HotMessagePayload::V0(m) => { + assert!(matches!( + m.recent_blockhash, + OwnedCompactRecentBlockhash::Id(-2) + )); + assert_eq!( + reader + .resolve_pubkey(&m.address_table_lookups[0].account_key) + .unwrap(), + alt_key + ); + } + other => panic!("expected V0 message, got {other:?}"), + } + + // Block 1 (slot s0 + 2): V1 failed tx referencing bh_0 -> Id(0)! + let dec1 = reader.read_block(1).unwrap(); + assert_eq!(dec1.block.header.slot, s0 + 2); + assert_eq!(dec1.block.header.blockhash_id, 1); + assert_eq!(dec1.block.header.previous_blockhash_id, 0); + let tx2_row = dec1.block.tx_rows[0]; + let msg2 = reader + .decode_message( + &dec1.block.message_bytes[tx2_row.message_offset as usize + ..(tx2_row.message_offset + tx2_row.message_len) as usize], + ) + .unwrap(); + match msg2 { + ArchiveV2HotMessagePayload::V1(m) => { + assert!(matches!( + m.recent_blockhash, + OwnedCompactRecentBlockhash::Id(0) + )); + assert_eq!(m.config.priority_fee, Some(50_000)); + assert_eq!(m.config.compute_unit_limit, Some(100_000)); + assert_eq!(reader.resolve_pubkey(&m.account_keys[0]).unwrap(), hot_key); + } + other => panic!("expected V1 message, got {other:?}"), + } + let meta2 = reader + .decode_metadata( + &dec1.block.metadata_bytes[tx2_row.metadata_offset as usize + ..(tx2_row.metadata_offset + tx2_row.metadata_len) as usize], + ) + .unwrap(); + assert!(meta2.err.is_some()); + + // Block 2 (slot s0 + 4): durable_nonce stays Nonce! + let dec2 = reader.read_block(2).unwrap(); + let tx3_row = dec2.block.tx_rows[0]; + let msg3 = reader + .decode_message( + &dec2.block.message_bytes[tx3_row.message_offset as usize + ..(tx3_row.message_offset + tx3_row.message_len) as usize], + ) + .unwrap(); + match msg3 { + ArchiveV2HotMessagePayload::Legacy(m) => { + assert!(matches!( + m.recent_blockhash, + OwnedCompactRecentBlockhash::Nonce(h) if h == durable_nonce + )); + } + other => panic!("expected Legacy message, got {other:?}"), + } + + // Block 3 (slot s0 + 7): recent_blockhash bh_4 -> Id(2)! + let dec3 = reader.read_block(3).unwrap(); + let tx4_row = dec3.block.tx_rows[0]; + let msg4 = reader + .decode_message( + &dec3.block.message_bytes[tx4_row.message_offset as usize + ..(tx4_row.message_offset + tx4_row.message_len) as usize], + ) + .unwrap(); + match msg4 { + ArchiveV2HotMessagePayload::Legacy(m) => { + assert!(matches!( + m.recent_blockhash, + OwnedCompactRecentBlockhash::Id(2) + )); + } + other => panic!("expected Legacy message, got {other:?}"), + } + + // Verify PoH and shredding sidecars match all 4 blocks. + let mut poh_reader = + WincodeLeb128FramedReader::new(fs::File::open(archive_out.join(ARCHIVE_V2_POH_FILE)).unwrap()); + let mut poh_slots = Vec::new(); + while let Some((_, rec)) = poh_reader.read::().unwrap() { + poh_slots.push((rec.block_id, rec.slot, rec.entries.len())); + } + assert_eq!( + poh_slots, + vec![(0, s0, 1), (1, s0 + 2, 1), (2, s0 + 4, 1), (3, s0 + 7, 1)] + ); + + let mut shred_reader = WincodeLeb128FramedReader::new( + fs::File::open(archive_out.join(ARCHIVE_V2_SHREDDING_FILE)).unwrap(), + ); + let mut shred_slots = Vec::new(); + while let Some((_, rec)) = shred_reader + .read::() + .unwrap() + { + shred_slots.push((rec.block_id, rec.slot, rec.shredding.len())); + } + assert_eq!( + shred_slots, + vec![(0, s0, 1), (1, s0 + 2, 1), (2, s0 + 4, 1), (3, s0 + 7, 1)] + ); +} + +#[test] +fn alpenglow_check_rules_cover_skips_and_abandoned_forks() { + // No carrier footer -> falls back to parent-chain check. + assert!(check::hole_uses_parent_chain(100, None).unwrap()); + check::classify_hole(100, None, Some(SlotChainRelation::JumpsOver { next_root: 101 })).unwrap(); + assert!( + check::classify_hole( + 100, + None, + Some(SlotChainRelation::DescendsFrom { next_root: 101 }), + ) + .is_err() + ); + assert!( + check::classify_hole( + 100, + None, + Some(SlotChainRelation::NextRootIncomplete { next_root: 101 }), + ) + .is_err() + ); + assert!(check::classify_hole(100, None, None).is_err()); + + // Abandoned fork checks. + check::classify_abandoned_fork( + 100, + SlotChainRelation::JumpsOver { next_root: 101 }, + None, + ) + .unwrap(); + assert!( + check::classify_abandoned_fork( + 100, + SlotChainRelation::DescendsFrom { next_root: 101 }, + None, + ) + .is_err() + ); + assert!( + check::classify_abandoned_fork( + 100, + SlotChainRelation::NextRootIncomplete { next_root: 101 }, + None, + ) + .is_err() + ); +} + +#[test] +fn compaction_refuses_rpc_only_degraded_chunks_until_replaced_by_car() { + let dir = tempfile::tempdir().unwrap(); + let chunks_root = dir.path().join("chunks"); + let archive_out = dir.path().join("archive"); + let s0 = SLOTS_PER_EPOCH; + + let bh_prev = [0x10; 32]; + let bh0 = [0x11; 32]; + let b0 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: s0, + parent_slot: s0 - 1, + blockhash: bh0, + previous_blockhash: bh_prev, + block_time: Some(1_700_000_000), + block_height: Some(1), + consensus_block_id: [0; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![], + shredding: vec![], + transactions: vec![], + }, + 1, + ) + .unwrap(); + + let mut builder = ChunkBuilder::create_default(&chunks_root, s0, s0 + 1).unwrap(); + builder.set_degraded_source(crate::DEGRADED_SOURCE_RPC_ONLY); + builder.add_block(&b0).unwrap(); + builder.add_skip(s0 + 1).unwrap(); + let sealed = builder.finish().unwrap(); + assert_eq!( + sealed.manifest.degraded_source.as_deref(), + Some(crate::DEGRADED_SOURCE_RPC_ONLY) + ); + + let source = LocalChunkSource::new(&chunks_root); + let err = compact::compact_range_from_chunks(&source, 1, s0, s0 + 1, &archive_out, 1, None) + .unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains(crate::DEGRADED_SOURCE_RPC_ONLY) && msg.contains("CAR"), + "unexpected error: {msg}" + ); +} diff --git a/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs b/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs index 93fead72..fe7d0f0b 100644 --- a/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs +++ b/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs @@ -219,6 +219,17 @@ pub trait ArchiveV2WireRewriteVisitor { Ok(()) } + /// Rewrite an inline recent-blockhash nonce (e.g. when promoting a + /// block-local bundle into an epoch archive with a rolling blockhash window). + fn rewrite_recent_blockhash_nonce( + &mut self, + nonce: [u8; 32], + ) -> anyhow::Result { + Ok(blockzilla_compact::OwnedCompactRecentBlockhash::Nonce( + nonce, + )) + } + /// Called for vote-state hashes and TowerSync block-id hashes. Switch-proof hashes are parsed /// and preserved but are intentionally not emitted. fn vote_hash_block_id(&mut self, _block_id: u32) -> anyhow::Result<()> { @@ -1386,8 +1397,9 @@ impl Transformer<'_, V> { debug_assert!(!TRANSCODE_PRE_TO_POST || PRE_UNKNOWN_FALLBACKS); let variant = self.enum_tag("hot message variant")?; match variant { - 0 => self.message_body::(false), - 1 => self.message_body::(true), + 0 => self.message_body::(false, false), + 1 => self.message_body::(true, false), + 2 => self.message_body::(false, true), tag => Err(ArchiveV2WireRewriteError::fallback( ArchiveV2WireFallbackReason::UnsupportedMessageVariant(tag), )), @@ -1397,11 +1409,27 @@ impl Transformer<'_, V> { fn message_body( &mut self, v0: bool, + v1: bool, ) -> ArchiveV2WireRewriteResult<()> { self.scalar::("message required signature count")?; self.scalar::("message readonly signed account count")?; self.scalar::("message readonly unsigned account count")?; + if v1 { + if self.option_tag("v1 message priority_fee tag")? { + self.scalar::("v1 message priority_fee")?; + } + if self.option_tag("v1 message compute_unit_limit tag")? { + self.scalar::("v1 message compute_unit_limit")?; + } + if self.option_tag("v1 message loaded_accounts_data_size_limit tag")? { + self.scalar::("v1 message loaded_accounts_data_size_limit")?; + } + if self.option_tag("v1 message heap_size tag")? { + self.scalar::("v1 message heap_size")?; + } + } + let account_count = self.sequence_len::("message account-key count")?; for _ in 0..account_count { self.pubkey(ArchiveV2WireReferenceClass::Eligible)?; @@ -1429,8 +1457,9 @@ impl Transformer<'_, V> { } fn recent_blockhash(&mut self) -> ArchiveV2WireRewriteResult<()> { - match self.enum_tag("recent blockhash variant")? { + match self.get::("recent blockhash variant")? { 0 => { + self.put_small(&0u32, "recent blockhash id variant")?; let id = self.scalar::("recent blockhash id")?; self.visitor .recent_blockhash_id(id) @@ -1439,8 +1468,26 @@ impl Transformer<'_, V> { Ok(()) } 1 => { - self.scalar::<[u8; 32]>("recent blockhash nonce")?; - Ok(()) + let nonce = self.get::<[u8; 32]>("recent blockhash nonce")?; + let rewritten = self + .visitor + .rewrite_recent_blockhash_nonce(nonce) + .map_err(ArchiveV2WireRewriteError::visitor)?; + match rewritten { + blockzilla_compact::OwnedCompactRecentBlockhash::Id(id) => { + self.put_small(&0u32, "rewritten recent blockhash id variant")?; + self.put_small(&id, "rewritten recent blockhash id")?; + self.visitor + .recent_blockhash_id(id) + .map_err(ArchiveV2WireRewriteError::visitor)?; + self.stats.recent_blockhash_ids += 1; + self.check_output_limit() + } + blockzilla_compact::OwnedCompactRecentBlockhash::Nonce(out_nonce) => { + self.put_small(&1u32, "recent blockhash nonce variant")?; + self.append(&out_nonce, "recent blockhash nonce") + } + } } tag => Err(ArchiveV2WireRewriteError::invalid_value(format_args!( "recent blockhash has invalid variant {tag}" @@ -4603,4 +4650,94 @@ mod tests { .unwrap_err(); assert_eq!(error.kind(), ArchiveV2WireRewriteErrorKind::LimitExceeded); } + + #[test] + fn hot_v1_message_and_nonce_blockhash_promotion_round_trip() { + use blockzilla_compact::{CompactMessageHeader, CompactTransactionConfig, OwnedCompactRecentBlockhash}; + use crate::{ArchiveV2HotInstruction, ArchiveV2HotInstructionData, ArchiveV2HotMessagePayload, ArchiveV2HotV1Message}; + + struct PromoteVisitor { + target_nonce: [u8; 32], + promoted_id: i32, + } + impl ArchiveV2WireRewriteVisitor for PromoteVisitor { + type Checkpoint = (); + fn checkpoint(&mut self) -> Self::Checkpoint {} + fn rewrite_pubkey( + &mut self, + pubkey: CompactPubkey, + _class: ArchiveV2WireReferenceClass, + ) -> anyhow::Result { + match pubkey { + CompactPubkey::Id(id) => Ok(CompactPubkey::Id(id + 100)), + other => Ok(other), + } + } + fn rewrite_recent_blockhash_nonce( + &mut self, + nonce: [u8; 32], + ) -> anyhow::Result { + if nonce == self.target_nonce { + Ok(OwnedCompactRecentBlockhash::Id(self.promoted_id)) + } else { + Ok(OwnedCompactRecentBlockhash::Nonce(nonce)) + } + } + fn rollback(&mut self, _checkpoint: Self::Checkpoint) {} + } + + let target_nonce = [0x44; 32]; + let input_msg = ArchiveV2HotMessagePayload::V1(ArchiveV2HotV1Message { + header: CompactMessageHeader { + num_required_signatures: 1, + num_readonly_signed_accounts: 0, + num_readonly_unsigned_accounts: 1, + }, + config: CompactTransactionConfig { + priority_fee: Some(42_000), + compute_unit_limit: Some(200_000), + loaded_accounts_data_size_limit: None, + heap_size: Some(65_536), + }, + account_keys: vec![CompactPubkey::Id(1), CompactPubkey::Id(2)], + recent_blockhash: OwnedCompactRecentBlockhash::Nonce(target_nonce), + instructions: vec![ArchiveV2HotInstruction { + program_id_index: 1, + accounts: vec![0], + data: ArchiveV2HotInstructionData::Raw(vec![1, 2, 3, 4]), + }], + }); + let encoded = wincode::config::serialize(&input_msg, wincode_leb128_config()).unwrap(); + let mut output = Vec::new(); + let mut visitor = PromoteVisitor { + target_nonce, + promoted_id: -7, + }; + let stats = rewrite_archive_v2_hot_message_wire( + &encoded, + &mut output, + &mut visitor, + ArchiveV2WireRewriteLimits::default(), + ) + .unwrap(); + assert_eq!(stats.eligible_pubkey_references, 2); + + let decoded: ArchiveV2HotMessagePayload = + wincode::config::deserialize(&output, wincode_leb128_config()).unwrap(); + match decoded { + ArchiveV2HotMessagePayload::V1(v1) => { + assert_eq!(v1.account_keys, vec![CompactPubkey::Id(101), CompactPubkey::Id(102)]); + assert!(matches!( + v1.recent_blockhash, + OwnedCompactRecentBlockhash::Id(-7) + )); + assert_eq!(v1.config.priority_fee, Some(42_000)); + assert_eq!(v1.config.compute_unit_limit, Some(200_000)); + assert_eq!(v1.config.loaded_accounts_data_size_limit, None); + assert_eq!(v1.config.heap_size, Some(65_536)); + assert_eq!(v1.instructions.len(), 1); + } + other => panic!("expected V1 message, got {other:?}"), + } + } } From 8cda36e52a800626650e7bc72795d65353265aab Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 19:58:42 +0100 Subject: [PATCH 2/9] feat(finalized-ledger): add sidecar drainer, parallel restart-gap recovery, RPC fallback, and Telegram alerts --- blockzilla/finalized-ledger/Cargo.lock | 2593 +++++++++++++++++ blockzilla/finalized-ledger/Cargo.toml | 39 + blockzilla/finalized-ledger/README.md | 94 + blockzilla/finalized-ledger/src/admin_rpc.rs | 168 ++ blockzilla/finalized-ledger/src/drain.rs | 597 ++++ blockzilla/finalized-ledger/src/lib.rs | 9 + blockzilla/finalized-ledger/src/main.rs | 362 +++ blockzilla/finalized-ledger/src/notify.rs | 110 + blockzilla/finalized-ledger/src/r2.rs | 784 +++++ blockzilla/finalized-ledger/src/recovery.rs | 618 ++++ .../finalized-ledger/src/rpc_fallback.rs | 718 +++++ blockzilla/finalized-ledger/src/tests.rs | 1372 +++++++++ zillastream/agave-compatibility/README.md | 4 +- 13 files changed, 7467 insertions(+), 1 deletion(-) create mode 100644 blockzilla/finalized-ledger/Cargo.lock create mode 100644 blockzilla/finalized-ledger/Cargo.toml create mode 100644 blockzilla/finalized-ledger/README.md create mode 100644 blockzilla/finalized-ledger/src/admin_rpc.rs create mode 100644 blockzilla/finalized-ledger/src/drain.rs create mode 100644 blockzilla/finalized-ledger/src/lib.rs create mode 100644 blockzilla/finalized-ledger/src/main.rs create mode 100644 blockzilla/finalized-ledger/src/notify.rs create mode 100644 blockzilla/finalized-ledger/src/r2.rs create mode 100644 blockzilla/finalized-ledger/src/recovery.rs create mode 100644 blockzilla/finalized-ledger/src/rpc_fallback.rs create mode 100644 blockzilla/finalized-ledger/src/tests.rs diff --git a/blockzilla/finalized-ledger/Cargo.lock b/blockzilla/finalized-ledger/Cargo.lock new file mode 100644 index 00000000..bc365e8a --- /dev/null +++ b/blockzilla/finalized-ledger/Cargo.lock @@ -0,0 +1,2593 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "arrayvec" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "binout" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff5fa7be63dbf62cca511b0e64e4b869ebc68f2b99d65fb1aa127771c5b7cd0d" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitm" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31468ea4a856000d83cb61960dfdc2980ecd96b15b61321c8c76cc96aea6e688" +dependencies = [ + "dyn_size_of", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "blockzilla-account-bridge-protocol" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "bs58", + "serde", + "serde_json", +] + +[[package]] +name = "blockzilla-account-client" +version = "0.1.0" +dependencies = [ + "blockzilla-account-bridge-protocol", + "tokio", +] + +[[package]] +name = "blockzilla-archive-v2" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-compact", + "blockzilla-primitives", + "blockzilla-program-logs", + "blockzilla-solana-wire", + "serde", + "sha2", + "wincode", +] + +[[package]] +name = "blockzilla-compact" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-log-parser", + "blockzilla-primitives", + "blockzilla-program-logs", + "blockzilla-registry", + "blockzilla-solana-wire", + "data-encoding", + "heapless", + "prost", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-compact-v2-reader" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-archive-v2", + "blockzilla-compact", + "blockzilla-model", + "blockzilla-primitives", + "blockzilla-program-logs", + "blockzilla-registry", + "blockzilla-source", + "blockzilla-source-local", + "ed25519-dalek", + "rayon", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "wincode", + "zstd", +] + +[[package]] +name = "blockzilla-finalized-chunks" +version = "0.1.0" +dependencies = [ + "anyhow", + "blockzilla-account-bridge-protocol", + "blockzilla-archive-v2", + "blockzilla-compact", + "blockzilla-primitives", + "blockzilla-registry", + "blockzilla-solana-wire", + "bs58", + "hex", + "prost", + "rusqlite", + "serde", + "serde_json", + "sha2", + "tempfile", + "wincode", + "zstd", +] + +[[package]] +name = "blockzilla-finalized-ledger" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "blockzilla-account-bridge-protocol", + "blockzilla-account-client", + "blockzilla-compact-v2-reader", + "blockzilla-finalized-chunks", + "blockzilla-solana-wire", + "bs58", + "chrono", + "clap", + "hex", + "prost", + "reqwest", + "serde", + "serde_json", + "sha2", + "tempfile", + "tokio", + "url", + "wincode", + "zstd", +] + +[[package]] +name = "blockzilla-log-parser" +version = "0.3.0" + +[[package]] +name = "blockzilla-model" +version = "0.3.0" +dependencies = [ + "serde", + "sha2", + "thiserror", +] + +[[package]] +name = "blockzilla-primitives" +version = "0.3.0" +dependencies = [ + "anyhow", + "five8", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-program-logs" +version = "0.3.0" +dependencies = [ + "blockzilla-primitives", + "data-encoding", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-registry" +version = "0.3.0" +dependencies = [ + "anyhow", + "blockzilla-primitives", + "gxhash", + "memmap2", + "ph", +] + +[[package]] +name = "blockzilla-solana-wire" +version = "0.3.0" +dependencies = [ + "minicbor", + "prost", + "quick-protobuf", + "serde", + "wincode", +] + +[[package]] +name = "blockzilla-source" +version = "0.3.0" +dependencies = [ + "thiserror", +] + +[[package]] +name = "blockzilla-source-local" +version = "0.3.0" +dependencies = [ + "blockzilla-source", + "rustix", + "serde", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "byteorder" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "curve25519-dalek" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn_size_of" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a742b95783b1f45b900129082cbc47717b6a77ee8d17eea70a8ea62462f5de3" + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2", + "subtle", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "five8" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f76610e969fa1784327ded240f1e28a3fd9520c9cec93b636fcf62dd37f772" +dependencies = [ + "five8_core", +] + +[[package]] +name = "five8_core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "059c31d7d36c43fe39d89e55711858b4da8be7eb6dabac23c7289b1a19489406" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "gxhash" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ce1bab7aa741d4e7042b2aae415b78741f267a98a7271ea226cd5ba6c43d7d" +dependencies = [ + "rustversion", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.2", +] + +[[package]] +name = "heapless" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411fdef4df93751117bd9ef8caa0e7f99c65dafec5bd84313eb8e2fdd75e32f2" +dependencies = [ + "hash32", + "serde_core", + "stable_deref_trait", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "minicbor" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7244eafd1e09e7c4e33043881997aa6ab6dffff3ed2cee3395a278980481d6e" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "ph" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a447f203c7254ebb06aa4f111480e821debb361e80fb4d760554a8460f236550" +dependencies = [ + "arrayvec", + "binout", + "bitm", + "dyn_size_of", + "rayon", + "seedable_hash", + "voracious_radix_sort", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quick-protobuf" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d6da84cc204722a989e01ba2f6e1e276e190f22263d0cb6ce8526fcdb0d2e1f" +dependencies = [ + "byteorder", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.40.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "seedable_hash" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba2a159211665e29bbf5a2fbb42da50dd6eadff23eef7a6a7ae4a9b0a7cd0152" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "voracious_radix_sort" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a26840011ddd3172ced523e372fc18d141e68f3b72a17312e51c5fb80b13fe78" +dependencies = [ + "rayon", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "wincode" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfc6339f1ba427bf7ad7c42403b28e524832ba2ddb5eef1bb2cc3b85db6b7b75" +dependencies = [ + "pastey", + "proc-macro2", + "quote", + "smallvec", + "thiserror", + "wincode-derive", +] + +[[package]] +name = "wincode-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d582d9fc9d813264407a9e16bfa16846ccf15ef032f9bbcd700741bdc00255" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/blockzilla/finalized-ledger/Cargo.toml b/blockzilla/finalized-ledger/Cargo.toml new file mode 100644 index 00000000..b26cc93d --- /dev/null +++ b/blockzilla/finalized-ledger/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "blockzilla-finalized-ledger" +version = "0.1.0" +edition = "2024" +rust-version = "1.98" +license = "MIT" +publish = false +description = "Finalized ledger chunk drainer, R2 uploader, safe Blockstore purge driver, and streaming Compact V2 epoch compactor" + +[workspace] + +[[bin]] +name = "blockzilla-finalized-ledger" +path = "src/main.rs" + +[dependencies] +anyhow = "1.0.104" +base64 = "0.22.1" +blockzilla-account-bridge-protocol = { path = "../../crates/blockzilla-account-bridge-protocol" } +blockzilla-account-client = { path = "../../crates/blockzilla-account-client" } +blockzilla-finalized-chunks = { path = "../../crates/blockzilla-finalized-chunks" } +blockzilla-solana-wire = { path = "../../crates/blockzilla-solana-wire", default-features = false, features = ["protobuf"] } +bs58 = "0.5.1" +chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } +clap = { version = "4.6.6", features = ["derive", "env"] } +hex = "0.4.3" +prost = "0.14.4" +reqwest = { version = "0.13.4", default-features = false, features = ["blocking", "rustls"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +sha2 = "0.11.0" +tokio = { version = "1.53.1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] } +url = "2.5.8" +wincode = { version = "=0.6.1", features = ["derive"] } +zstd = "0.14.0" + +[dev-dependencies] +blockzilla-compact-v2-reader = { path = "../../crates/compact-v2/blockzilla-compact-v2-reader" } +tempfile = "3.27.0" diff --git a/blockzilla/finalized-ledger/README.md b/blockzilla/finalized-ledger/README.md new file mode 100644 index 00000000..f83a1d7c --- /dev/null +++ b/blockzilla/finalized-ledger/README.md @@ -0,0 +1,94 @@ +# `blockzilla-finalized-ledger` + +`blockzilla-finalized-ledger` drains finalized blocks from a running Agave +validator into immutable finalized chunks, publishes those chunks for current-epoch +`getBlock`, purges old Blockstore slots safely behind a tail, and compacts complete +epochs into Compact V2 without a full-epoch raw RocksDB ledger on NVMe. + +It has no `solana-ledger` or `rocksdb` dependency. + +## Commands + +### 1. `drain-chunks` + +Polls Agave's live native bridge Unix socket (`GetLedgerStatus`), waits until +`max_root >= chunk_end + 8` (Alpenglow skip/notarization footer distance), seals +each `epoch-N/chunk--/` directory atomically, and optionally: + +1. Uploads all 5 chunk files (`chunk.bundles.bin`, `chunk.index.bin`, + `chunk.extras.zst`, `chunk.counts.zst`, and `chunk.manifest.json` last) to + Cloudflare R2 with size, SHA-256 metadata, and ETag verification. +2. Registers the verified chunk in the shared SQLite catalog (`chunk_catalog.sqlite`) + queried read-only by `get-block/resolver`. +3. Evicts local bulk payloads (`chunk.bundles.bin`, `chunk.extras.zst`, + `chunk.counts.zst`) after R2 upload and catalog commit, keeping `chunk.index.bin` + and `chunk.manifest.json`. +4. Sends `blockstorePurge` over `/admin.rpc` behind `--purge-safety-tail` + (minimum 300 slots, default 512 slots). Pair the validator with + `--rocksdb-periodic-compaction-seconds 1800` so `TransactionStatus` SST files + reclaim space promptly after each purge. + +```sh +blockzilla-finalized-ledger drain-chunks \ + --native-socket /run/agave/native-bridge.sock \ + --source-json /etc/blockzilla/source.json \ + --output-dir /var/lib/blockzilla/finalized-chunks \ + --chunk-slots 4096 \ + --upload-r2 \ + --catalog-db /var/lib/blockzilla/chunk_catalog.sqlite \ + --catalog-generation mainnet-chunks-v1 \ + --evict-local-payloads \ + --purge-ledger /var/lib/agave/ledger \ + --purge-safety-tail 512 \ + --gap-fallback-policy wait-for-car +``` + +### Restart Gap Recovery, Fallbacks, and Telegram Alerts + +When the validator restarts from a newer snapshot (`status.lowest_slot` jumps ahead +of the last sealed slot), `drain-chunks` starts live draining immediately at +`status.lowest_slot` and runs restart-gap recovery in a parallel background task: + +1. Calls Agave's `admin.rpc` `startHistoricalRecovery(gap_start, gap_end)` and + polls `historicalRecoveryStatus` (requires `--historical-recovery-ledger` on + `agave-validator` and `--admin-ledger` or `--purge-ledger` on `drain-chunks`). +2. If Agave recovers the full gap chain and `--replay-command` is set, runs the + replay command with `BLOCKZILLA_GAP_START_SLOT`, `BLOCKZILLA_GAP_END_SLOT`, + `BLOCKZILLA_RECOVERY_LEDGER_DIR`, `BLOCKZILLA_PRESERVED_SNAPSHOT_SLOT`, + `BLOCKZILLA_OUTPUT_DIR`, and `BLOCKZILLA_CHUNK_SLOTS`, then verifies and + publishes the canonical chunks. +3. If local rebuild does not complete for any reason, `drain-chunks` treats the + gap as a failure: + - Logs an `ERROR` line. + - Writes an atomic failure receipt to + `/epoch-/gap--.failed.json`. + - Sends a Telegram alert when `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` are + set (bot token redacted on error logs; Telegram errors never stop draining). + - Runs the configured `--gap-fallback-policy`: + - `wait-for-car` (default): leaves the gap unsealed so `compact-epoch` fails + closed until canonical CAR fills it. + - `rpc-get-block` (with `--fallback-rpc-url `): backfills temporary + `getBlock` chunks from RPC `getBlock` tagged + `degraded_source = "rpc_only_no_alpenglow"`. Because RPC `getBlock` lacks + PoH, shredding, Alpenglow `consensus_block_id`, and `block_markers`, + `compact-epoch` refuses degraded RPC-only chunks until CAR replaces them. + +### 2. `compact-epoch` + +Compacts a complete epoch from local finalized chunks (`--source-dir`) or by +streaming directly over HTTPS from Cloudflare R2 (`--from-r2`, constant memory, +zero raw-ledger disk staging) into the 13 Compact V2 epoch files and optional +`GETBLOCK-EPOCH-COVERAGE.json`. + +```sh +blockzilla-finalized-ledger compact-epoch \ + --epoch 900 \ + --from-r2 \ + --output-dir /var/lib/blockzilla/epochs/epoch-900 \ + --zstd-level 3 \ + --successor-json /var/lib/blockzilla/epoch-900-successor.json +``` + +Environment variables for R2 mode match `hivezilla-ledger-archive`: +`R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT` (or `R2_S3_ENDPOINT`), +`R2_BUCKET`, `R2_PREFIX`, and `R2_REGION` (`auto`). diff --git a/blockzilla/finalized-ledger/src/admin_rpc.rs b/blockzilla/finalized-ledger/src/admin_rpc.rs new file mode 100644 index 00000000..38e8830b --- /dev/null +++ b/blockzilla/finalized-ledger/src/admin_rpc.rs @@ -0,0 +1,168 @@ +//! Minimal JSON-RPC 2.0 client for Agave's local `/admin.rpc` Unix socket. +//! +//! Used for: +//! - `blockstorePurge`: triggered only AFTER finalized chunks are verified in +//! durable storage and registered in the `getBlock` catalog. +//! - `startHistoricalRecovery` / `historicalRecoveryStatus`: drives Agave's +//! isolated background historical shred recovery on node restart gaps. + +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::UnixStream; +use tokio::time::timeout; + +const MAX_RESPONSE_BYTES: usize = 256 * 1024; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HistoricalRecoveryPhase { + #[default] + Idle, + Running, + Completed, + Incomplete, + Failed, +} + +impl HistoricalRecoveryPhase { + pub fn is_terminal(self) -> bool { + matches!(self, Self::Completed | Self::Incomplete | Self::Failed) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoricalRecoveryStatus { + pub phase: HistoricalRecoveryPhase, + pub recovery_ledger_path: String, + pub preserved_snapshot_slot: Option, + pub requested_start_slot: Option, + pub requested_end_slot: Option, + pub chain_reached_start: bool, + pub lowest_recovered_slot: Option, + pub recovered_slots: u64, + pub skipped_slots: u64, + pub unrecoverable_slot_count: u64, + pub unrecoverable_slots: Vec, + pub received_shreds: u64, + pub rejected_shreds: u64, + pub requests_sent: u64, + pub pings_answered: u64, + pub last_error: Option, + pub updated_at_ms: u64, +} + +/// Send `blockstorePurge(maximum_purge_slot)` to `/admin.rpc`. +pub async fn blockstore_purge( + ledger_dir: &Path, + maximum_purge_slot: u64, + rpc_timeout: Duration, +) -> Result<()> { + call_admin_rpc( + ledger_dir, + "blockstorePurge", + json!([maximum_purge_slot]), + rpc_timeout, + ) + .await?; + Ok(()) +} + +/// Send `startHistoricalRecovery(start_slot, end_slot)` to `/admin.rpc`. +pub async fn start_historical_recovery( + ledger_dir: &Path, + start_slot: u64, + end_slot: u64, + rpc_timeout: Duration, +) -> Result<()> { + call_admin_rpc( + ledger_dir, + "startHistoricalRecovery", + json!([start_slot, end_slot]), + rpc_timeout, + ) + .await?; + Ok(()) +} + +/// Query `historicalRecoveryStatus()` from `/admin.rpc`. +pub async fn historical_recovery_status( + ledger_dir: &Path, + rpc_timeout: Duration, +) -> Result { + let result = call_admin_rpc(ledger_dir, "historicalRecoveryStatus", json!([]), rpc_timeout) + .await?; + serde_json::from_value(result).context("parse historicalRecoveryStatus response") +} + +async fn call_admin_rpc( + ledger_dir: &Path, + method: &str, + params: Value, + rpc_timeout: Duration, +) -> Result { + let socket_path = ledger_dir.join("admin.rpc"); + timeout(rpc_timeout, async { + let stream = UnixStream::connect(&socket_path) + .await + .with_context(|| format!("connect to Agave admin RPC {}", socket_path.display()))?; + let (read_half, mut write_half) = stream.into_split(); + let request = json!({ + "jsonrpc": "2.0", + "id": 1, + "method": method, + "params": params, + }); + let mut payload = serde_json::to_vec(&request)?; + payload.push(b'\n'); + write_half + .write_all(&payload) + .await + .with_context(|| format!("write admin.rpc {method} request"))?; + write_half + .flush() + .await + .with_context(|| format!("flush admin.rpc {method} request"))?; + + let mut reader = BufReader::new(read_half); + let mut line = Vec::new(); + let mut total = 0usize; + loop { + let n = reader + .read_until(b'\n', &mut line) + .await + .context("read admin.rpc response")?; + if n == 0 { + break; + } + total += n; + ensure!( + total <= MAX_RESPONSE_BYTES, + "admin.rpc response exceeded {MAX_RESPONSE_BYTES} bytes" + ); + if line.ends_with(b"\n") { + break; + } + } + ensure!(!line.is_empty(), "admin.rpc closed without a response"); + let reply: Value = + serde_json::from_slice(&line).context("parse admin.rpc JSON-RPC response")?; + if let Some(error) = reply.get("error").filter(|v| !v.is_null()) { + bail!("admin.rpc {method} failed: {error}"); + } + ensure!( + reply.get("id") == Some(&json!(1)), + "admin.rpc returned unexpected JSON-RPC id: {reply}" + ); + let Some(result) = reply.get("result") else { + bail!("admin.rpc returned JSON-RPC envelope missing result: {reply}"); + }; + Ok(result.clone()) + }) + .await + .with_context(|| format!("admin.rpc {method} timed out"))? +} diff --git a/blockzilla/finalized-ledger/src/drain.rs b/blockzilla/finalized-ledger/src/drain.rs new file mode 100644 index 00000000..b1fb6133 --- /dev/null +++ b/blockzilla/finalized-ledger/src/drain.rs @@ -0,0 +1,597 @@ +//! Finalized chunk drainer: reads finalized blocks from Agave's live native +//! bridge Unix socket, seals immutable chunks, optionally uploads to R2, +//! registers them in `chunk_catalog.sqlite`, optionally evicts local bulk +//! payloads, and optionally triggers Agave's `admin.rpc` `blockstorePurge` +//! strictly behind a safety tail. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use blockzilla_account_bridge_protocol::{ + ArchiveBlockEnvelope, ArchiveBlockPayloadV1, MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, + MAX_SLOT_STATES_RANGE, SlotStateCode, +}; +use blockzilla_account_client::{AccountClient, ClientOptions, SourceIdentity}; +use blockzilla_finalized_chunks::{ + CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, + CHUNK_MANIFEST_FILE, ChunkBuilder, ChunkCatalogBinding, ChunkCatalogWriter, ChunkManifestV1, + ChunkStorageMode, REWARD_SLOT_DISTANCE, SealedChunk, TailBlockhash, check, chunk_window_end, + encode_archive_payload, epoch_for_slot, epoch_slot_range, +}; +use sha2::{Digest, Sha256}; +use tokio::sync::Mutex; + +use crate::admin_rpc; +use crate::r2::{R2Client, R2Settings}; +use crate::recovery::{GapRecoveryConfig, GapRecoveryOutcome, recover_restart_gap}; + +pub const MIN_PURGE_SAFETY_TAIL: u64 = 300; +pub const DEFAULT_PURGE_SAFETY_TAIL: u64 = 512; + +#[derive(Clone, Debug)] +pub struct CatalogOptions { + pub path: PathBuf, + pub generation: String, + pub prefix: String, +} + +#[derive(Clone, Debug)] +pub struct PurgeOptions { + pub ledger_dir: PathBuf, + pub safety_tail: u64, + pub rpc_timeout: Duration, +} + +#[derive(Clone, Debug)] +pub struct DrainConfig { + pub native_socket: PathBuf, + pub source: SourceIdentity, + pub client_timeout: Duration, + pub output_dir: PathBuf, + pub chunk_slots: u64, + pub zstd_level: i32, + pub start_slot: Option, + pub once: bool, + pub poll_interval: Duration, + pub r2: Option, + pub catalog: Option, + pub evict_local_payloads: bool, + pub purge: Option, + pub gap_recovery: GapRecoveryConfig, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DrainSummary { + pub chunks_sealed: u64, + pub blocks_sealed: u64, + pub skips_sealed: u64, + pub forks_sealed: u64, + pub highest_sealed_slot: Option, + pub highest_purged_slot: Option, + pub gap_recovery_triggered: bool, + pub gap_failure_receipts: Vec, +} + +impl DrainConfig { + pub fn validate(&self) -> Result<()> { + ensure!( + (1..=MAX_SLOT_STATES_RANGE).contains(&self.chunk_slots), + "chunk_slots {} must be in 1..={MAX_SLOT_STATES_RANGE}", + self.chunk_slots + ); + ensure!( + zstd::compression_level_range().contains(&self.zstd_level), + "zstd_level {} out of range", + self.zstd_level + ); + if self.evict_local_payloads { + ensure!( + self.r2.is_some() && self.catalog.is_some(), + "--evict-local-payloads requires both R2 upload and --catalog-db so getBlock can serve from R2" + ); + } + if let Some(purge) = &self.purge { + ensure!( + purge.safety_tail >= MIN_PURGE_SAFETY_TAIL, + "purge safety_tail {} must be >= {MIN_PURGE_SAFETY_TAIL} slots (rolling blockhash tail)", + purge.safety_tail + ); + ensure!( + self.r2.is_some() || !self.evict_local_payloads, + "cannot purge ledger if chunks are neither uploaded to R2 nor retained locally" + ); + } + if let Some(catalog) = &self.catalog { + ChunkCatalogBinding { + version: 1, + generation: catalog.generation.clone(), + prefix: catalog.prefix.clone(), + } + .validate()?; + if let Some(r2) = &self.r2 { + ensure!( + r2.prefix == catalog.prefix, + "R2 prefix '{}' must match catalog prefix '{}'", + r2.prefix, + catalog.prefix + ); + } + } + self.gap_recovery.validate()?; + Ok(()) + } +} + +pub async fn run_drain(config: DrainConfig) -> Result { + config.validate()?; + fs::create_dir_all(&config.output_dir) + .with_context(|| format!("create finalized output dir {}", config.output_dir.display()))?; + + let client = AccountClient::new( + &config.native_socket, + config.source.clone(), + ClientOptions { + timeout: config.client_timeout, + ..ClientOptions::default() + }, + ) + .context("create native bridge client")?; + + let r2_settings = config.r2.clone(); + if let Some(settings) = &r2_settings { + // Validate endpoint/config eagerly before starting the drain loop. + let s = settings.clone(); + tokio::task::spawn_blocking(move || R2Client::new(s).map(|_| ())) + .await + .context("join R2 client validation task")??; + } + + let catalog_writer = config + .catalog + .as_ref() + .map(|cat| { + ChunkCatalogWriter::open_or_create( + &cat.path, + ChunkCatalogBinding { + version: 1, + generation: cat.generation.clone(), + prefix: cat.prefix.clone(), + }, + ) + .map(|writer| Arc::new(Mutex::new(writer))) + }) + .transpose() + .context("open chunk catalog")?; + + let initial_status = client + .get_ledger_status() + .await + .context("query initial Agave ledger status")?; + let expected_slot = + determine_next_slot(&config, catalog_writer.as_ref(), initial_status.lowest_slot).await?; + + let mut summary = DrainSummary::default(); + let (mut next_slot, recovery_task) = if expected_slot < initial_status.lowest_slot { + let gap_start = expected_slot; + let gap_end = initial_status.lowest_slot - 1; + let mut recovery_cfg = config.gap_recovery.clone(); + if recovery_cfg.admin_ledger_dir.is_none() { + recovery_cfg.admin_ledger_dir = config.purge.as_ref().map(|p| p.ledger_dir.clone()); + } + let handle = tokio::spawn(recover_restart_gap( + gap_start, + gap_end, + config.output_dir.clone(), + config.chunk_slots, + config.zstd_level, + r2_settings.clone(), + catalog_writer.clone(), + config.evict_local_payloads, + recovery_cfg, + )); + summary.gap_recovery_triggered = true; + // Start live draining immediately at the fresh snapshot tip! + (initial_status.lowest_slot, Some(handle)) + } else { + (expected_slot, None) + }; + + let mut last_purged: Option = None; + + loop { + let status = client + .get_ledger_status() + .await + .context("query Agave ledger status")?; + let end_slot = chunk_window_end(next_slot, config.chunk_slots)?; + let required_root = end_slot + .checked_add(REWARD_SLOT_DISTANCE) + .context("required root overflows u64")?; + + if status.max_root < required_root { + if config.once { + break; + } + tokio::select! { + _ = tokio::time::sleep(config.poll_interval) => continue, + _ = tokio::signal::ctrl_c() => break, + } + } + + let sealed = seal_chunk_from_bridge( + &client, + &config.output_dir, + next_slot, + end_slot, + config.zstd_level, + ) + .await + .with_context(|| format!("seal finalized chunk {next_slot}..={end_slot}"))?; + + let (storage_mode, bundles_location, bundles_etag) = if let Some(settings) = &r2_settings { + let settings_clone = settings.clone(); + let sealed_dir = sealed.dir.clone(); + let manifest = sealed.manifest.clone(); + let uploaded = tokio::task::spawn_blocking(move || { + let r2 = R2Client::new(settings_clone)?; + upload_sealed_chunk(&r2, &sealed_dir, &manifest) + }) + .await + .context("join R2 chunk upload task")??; + (ChunkStorageMode::R2, uploaded.key, Some(uploaded.etag)) + } else { + let local_bundles = sealed + .dir + .join(CHUNK_BUNDLES_FILE) + .canonicalize() + .context("canonicalize local chunk.bundles.bin")?; + ( + ChunkStorageMode::Local, + local_bundles + .to_str() + .context("local bundles path is not UTF-8")? + .to_owned(), + None, + ) + }; + + // Commit catalog BEFORE any local eviction or validator purge! + if let Some(writer_arc) = &catalog_writer { + let mut writer = writer_arc.lock().await; + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + storage_mode, + &bundles_location, + bundles_etag.as_deref(), + ) + .with_context(|| format!("register chunk {next_slot}..={end_slot} in catalog"))?; + } + + if config.evict_local_payloads { + evict_bulk_payloads(&sealed.dir)?; + } + + if let Some(purge) = &config.purge { + let safe_by_sealed = end_slot.saturating_sub(purge.safety_tail); + let safe_by_root = status.max_root.saturating_sub(purge.safety_tail); + let target = safe_by_sealed.min(safe_by_root); + if target > 0 && last_purged.is_none_or(|prev| target > prev) { + admin_rpc::blockstore_purge(&purge.ledger_dir, target, purge.rpc_timeout) + .await + .with_context(|| format!("trigger Agave blockstorePurge({target})"))?; + last_purged = Some(target); + summary.highest_purged_slot = Some(target); + } + } + + summary.chunks_sealed += 1; + summary.blocks_sealed += sealed.manifest.block_count; + summary.skips_sealed += sealed.manifest.skip_count; + summary.forks_sealed += sealed.manifest.fork_count; + summary.highest_sealed_slot = Some(end_slot); + + eprintln!( + "sealed epoch-{} chunk {}..={} (blocks={}, skips={}, forks={}, mode={:?}, purged={:?})", + sealed.manifest.epoch, + next_slot, + end_slot, + sealed.manifest.block_count, + sealed.manifest.skip_count, + sealed.manifest.fork_count, + storage_mode, + last_purged + ); + + next_slot = end_slot.checked_add(1).context("next_slot overflow")?; + } + + if let Some(handle) = recovery_task { + match handle.await { + Ok(GapRecoveryOutcome::FailedWithFallback { receipt_path, .. }) => { + summary.gap_failure_receipts.push(receipt_path); + } + Ok(GapRecoveryOutcome::LocallyRebuilt { .. }) => {} + Err(join_err) => { + eprintln!("ERROR: parallel gap recovery task panicked: {join_err}"); + } + } + } + + Ok(summary) +} + +async fn determine_next_slot( + config: &DrainConfig, + catalog: Option<&Arc>>, + fallback_lowest_slot: u64, +) -> Result { + let mut highest: Option = None; + if let Some(cat_arc) = catalog { + let cat = cat_arc.lock().await; + if let Some(slot) = cat.highest_sealed_slot()? { + highest = Some(highest.map_or(slot, |h| h.max(slot))); + } + } + if let Some(disk_slot) = highest_local_chunk_end(&config.output_dir)? { + highest = Some(highest.map_or(disk_slot, |h| h.max(disk_slot))); + } + if let Some(h) = highest { + return h.checked_add(1).context("resume slot overflow"); + } + if let Some(explicit) = config.start_slot { + return Ok(explicit); + } + Ok(fallback_lowest_slot) +} + +fn highest_local_chunk_end(root: &Path) -> Result> { + if !root.is_dir() { + return Ok(None); + } + let mut highest: Option = None; + for epoch_entry in fs::read_dir(root)? { + let epoch_path = epoch_entry?.path(); + if !epoch_path.is_dir() { + continue; + } + for chunk_entry in fs::read_dir(&epoch_path)? { + let chunk_path = chunk_entry?.path(); + let manifest_path = chunk_path.join(CHUNK_MANIFEST_FILE); + if !manifest_path.is_file() { + continue; + } + let raw = fs::read(&manifest_path)?; + let manifest: ChunkManifestV1 = serde_json::from_slice(&raw)?; + manifest.validate()?; + highest = Some(highest.map_or(manifest.end_slot, |h| h.max(manifest.end_slot))); + } + } + Ok(highest) +} + +async fn seal_chunk_from_bridge( + client: &AccountClient, + output_dir: &Path, + start_slot: u64, + end_slot: u64, + zstd_level: i32, +) -> Result { + let slot_states = client + .get_slot_states(start_slot, end_slot) + .await + .with_context(|| format!("get_slot_states({start_slot}..={end_slot})"))?; + let expected_len = usize::try_from(end_slot - start_slot + 1)?; + ensure!( + slot_states.states.len() == expected_len, + "bridge returned {} slot states, expected {expected_len}", + slot_states.states.len() + ); + + let mut builder = ChunkBuilder::create(output_dir, start_slot, end_slot, zstd_level)?; + + let epoch = epoch_for_slot(start_slot); + let (epoch_start, _) = epoch_slot_range(epoch)?; + if start_slot == epoch_start && epoch > 0 { + if let Some(first_offset) = slot_states + .states + .iter() + .position(|state| *state == SlotStateCode::RootedFull) + { + let first_rooted = start_slot + first_offset as u64; + let ancestors = client + .get_ancestor_blockhashes(first_rooted, 300) + .await + .with_context(|| format!("get_ancestor_blockhashes({first_rooted})"))?; + let tail = ancestors + .into_iter() + .map(|a| TailBlockhash { + slot: a.slot, + blockhash: a.blockhash, + }) + .collect(); + builder.set_previous_tail(tail); + } + } + + for (offset, state) in slot_states.states.iter().copied().enumerate() { + let slot = start_slot + offset as u64; + match state { + SlotStateCode::RootedFull => { + let envelope = client + .get_archive_block(slot, None) + .await + .with_context(|| format!("get_archive_block({slot})"))?; + let payload = decode_archive_envelope(slot, &envelope)?; + let encoded = encode_archive_payload(&payload, zstd_level)?; + builder.add_block(&encoded)?; + } + SlotStateCode::Absent => { + let carrier = slot + .checked_add(REWARD_SLOT_DISTANCE) + .context("carrier slot overflow")?; + let carrier_info = client + .inspect_slot(carrier, true) + .await + .with_context(|| format!("inspect carrier slot {carrier}"))?; + let carrier_markers = decode_optional_markers(&carrier_info.markers_base64)?; + let chain = if check::hole_uses_parent_chain(slot, carrier_markers.as_deref())? { + client + .inspect_slot(slot, false) + .await + .with_context(|| format!("inspect hole slot {slot}"))? + .chain_relation + } else { + None + }; + check::classify_hole(slot, carrier_markers.as_deref(), chain)?; + builder.add_skip(slot)?; + } + SlotStateCode::NonRoot => { + let slot_info = client + .inspect_slot(slot, false) + .await + .with_context(|| format!("inspect non-root slot {slot}"))?; + let chain = slot_info + .chain_relation + .with_context(|| format!("non-root slot {slot} missing chain_relation"))?; + let carrier = slot + .checked_add(REWARD_SLOT_DISTANCE) + .context("carrier slot overflow")?; + let carrier_info = client + .inspect_slot(carrier, true) + .await + .with_context(|| format!("inspect carrier slot {carrier}"))?; + let carrier_markers = decode_optional_markers(&carrier_info.markers_base64)?; + check::classify_abandoned_fork(slot, chain, carrier_markers.as_deref())?; + builder.add_abandoned_fork(slot)?; + } + SlotStateCode::RootedIncomplete => { + bail!("slot {slot} is rooted but incomplete in validator Blockstore"); + } + SlotStateCode::Pruned => { + bail!("slot {slot} was already pruned from validator Blockstore before sealing"); + } + } + } + + builder.finish() +} + +fn decode_archive_envelope( + expected_slot: u64, + envelope: &ArchiveBlockEnvelope, +) -> Result { + ensure!( + envelope.slot == expected_slot, + "archive envelope slot {} != expected {expected_slot}", + envelope.slot + ); + let uncompressed_len = usize::try_from(envelope.payload_uncompressed_len) + .context("payload_uncompressed_len overflows usize")?; + ensure!( + uncompressed_len <= MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, + "slot {expected_slot} payload uncompressed len {uncompressed_len} exceeds limit" + ); + let zstd_bytes = STANDARD + .decode(&envelope.payload_zstd_base64) + .with_context(|| format!("decode base64 archive payload for slot {expected_slot}"))?; + let uncompressed = zstd::bulk::decompress(&zstd_bytes, uncompressed_len) + .with_context(|| format!("decompress zstd archive payload for slot {expected_slot}"))?; + ensure!( + uncompressed.len() == uncompressed_len, + "slot {expected_slot} uncompressed payload len {} != declared {uncompressed_len}", + uncompressed.len() + ); + let actual_sha = hex::encode(Sha256::digest(&uncompressed)); + ensure!( + actual_sha == envelope.payload_sha256, + "slot {expected_slot} payload SHA-256 mismatch" + ); + let payload = ArchiveBlockPayloadV1::decode(&uncompressed) + .with_context(|| format!("decode ArchiveBlockPayloadV1 for slot {expected_slot}"))?; + ensure!( + payload.slot == expected_slot && payload.parent_slot == envelope.parent_slot, + "decoded payload slot/parent disagrees with envelope for slot {expected_slot}" + ); + Ok(payload) +} + +fn decode_optional_markers(encoded: &Option>) -> Result>>> { + let Some(items) = encoded else { + return Ok(None); + }; + let mut out = Vec::with_capacity(items.len()); + for item in items { + out.push(STANDARD.decode(item).context("decode block marker base64")?); + } + Ok(Some(out)) +} + +pub(crate) fn upload_sealed_chunk( + r2: &R2Client, + chunk_dir: &Path, + manifest: &ChunkManifestV1, +) -> Result { + let settings = r2.settings(); + let bundles_key = settings.chunk_object_key( + manifest.epoch, + manifest.start_slot, + manifest.end_slot, + CHUNK_BUNDLES_FILE, + ); + let bundles = r2.upload_file_verified( + &chunk_dir.join(CHUNK_BUNDLES_FILE), + &bundles_key, + manifest.objects.bundles.length, + &manifest.objects.bundles.sha256, + )?; + + for (file_name, meta) in [ + (CHUNK_INDEX_FILE, &manifest.objects.index), + (CHUNK_EXTRAS_FILE, &manifest.objects.extras), + (CHUNK_COUNTS_FILE, &manifest.objects.counts), + ] { + let key = settings.chunk_object_key( + manifest.epoch, + manifest.start_slot, + manifest.end_slot, + file_name, + ); + r2.upload_file_verified(&chunk_dir.join(file_name), &key, meta.length, &meta.sha256)?; + } + + // Upload chunk.manifest.json LAST so remote listing never observes a half-uploaded chunk. + let manifest_path = chunk_dir.join(CHUNK_MANIFEST_FILE); + let manifest_bytes = fs::read(&manifest_path)?; + let manifest_sha = hex::encode(Sha256::digest(&manifest_bytes)); + let manifest_key = settings.chunk_object_key( + manifest.epoch, + manifest.start_slot, + manifest.end_slot, + CHUNK_MANIFEST_FILE, + ); + r2.upload_file_verified( + &manifest_path, + &manifest_key, + manifest_bytes.len() as u64, + &manifest_sha, + )?; + Ok(bundles) +} + +pub(crate) fn evict_bulk_payloads(chunk_dir: &Path) -> Result<()> { + for file_name in [CHUNK_BUNDLES_FILE, CHUNK_EXTRAS_FILE, CHUNK_COUNTS_FILE] { + let path = chunk_dir.join(file_name); + if path.exists() { + fs::remove_file(&path) + .with_context(|| format!("evict local chunk payload {}", path.display()))?; + } + } + Ok(()) +} diff --git a/blockzilla/finalized-ledger/src/lib.rs b/blockzilla/finalized-ledger/src/lib.rs new file mode 100644 index 00000000..092ad8e4 --- /dev/null +++ b/blockzilla/finalized-ledger/src/lib.rs @@ -0,0 +1,9 @@ +pub mod admin_rpc; +pub mod drain; +pub mod notify; +pub mod r2; +pub mod recovery; +pub mod rpc_fallback; + +#[cfg(test)] +mod tests; diff --git a/blockzilla/finalized-ledger/src/main.rs b/blockzilla/finalized-ledger/src/main.rs new file mode 100644 index 00000000..8b00d169 --- /dev/null +++ b/blockzilla/finalized-ledger/src/main.rs @@ -0,0 +1,362 @@ +//! CLI & sidecar daemon for Blockzilla's finalized-ledger chunk architecture. +//! +//! Subcommands: +//! - `drain-chunks`: polls Agave's live native bridge Unix socket, seals +//! immutable finalized chunks, optionally uploads to R2, updates the shared +//! `getBlock` SQLite chunk catalog, optionally evicts local bulk payloads, +//! and optionally triggers Agave's `admin.rpc` `blockstorePurge`. +//! - `compact-epoch`: compacts an epoch (or slot range) from local finalized +//! chunks or streaming directly over HTTPS from R2 into the 13 Compact V2 +//! epoch files (+ optional `GETBLOCK-EPOCH-COVERAGE.json`). + +use std::fs; +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_account_client::SourceIdentity; +use blockzilla_finalized_chunks::{ + DEFAULT_CHUNK_SLOTS, EpochHandoffSuccessor, LocalChunkSource, compact, + compact_epoch_from_chunks, +}; +use blockzilla_finalized_ledger::drain::{ + CatalogOptions, DEFAULT_PURGE_SAFETY_TAIL, DrainConfig, PurgeOptions, run_drain, +}; +use blockzilla_finalized_ledger::notify::TelegramConfig; +use blockzilla_finalized_ledger::r2::{R2ChunkSource, R2Client, R2Settings}; +use blockzilla_finalized_ledger::recovery::{ + DEFAULT_FALLBACK_RPC_TIMEOUT, DEFAULT_GAP_RECOVERY_POLL_INTERVAL, DEFAULT_GAP_RECOVERY_TIMEOUT, + GapFallbackPolicy, GapRecoveryConfig, +}; +use clap::{Parser, Subcommand, ValueEnum}; + +#[derive(Clone, Copy, Debug, ValueEnum)] +enum CliGapFallbackPolicy { + WaitForCar, + RpcGetBlock, +} + +impl From for GapFallbackPolicy { + fn from(value: CliGapFallbackPolicy) -> Self { + match value { + CliGapFallbackPolicy::WaitForCar => Self::WaitForCar, + CliGapFallbackPolicy::RpcGetBlock => Self::RpcGetBlock, + } + } +} + +#[derive(Parser)] +#[command( + name = "blockzilla-finalized-ledger", + about = "Seal finalized ledger chunks from Agave and compact Compact V2 epochs without raw-ledger spikes" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Drain finalized blocks from Agave's live native bridge into immutable chunks. + DrainChunks { + /// Path to Agave's private native-account-bridge Unix socket. + #[arg(long)] + native_socket: PathBuf, + /// Path to JSON file containing pinned SourceIdentity (`genesis_hash`, `node_identity`, `instance_id`, `agave_revision`). + #[arg(long)] + source_json: PathBuf, + /// Local directory where `epoch-N/chunk--/` folders are written. + #[arg(long)] + output_dir: PathBuf, + /// Number of slots per sealed chunk (default 4096, never crosses epoch boundary). + #[arg(long, default_value_t = DEFAULT_CHUNK_SLOTS)] + chunk_slots: u64, + /// Zstd compression level for chunk bundles, extras, and pubkey counts. + #[arg(long, default_value_t = 1)] + zstd_level: i32, + /// Optional starting slot when initializing a fresh finalized-ledger directory. + #[arg(long)] + start_slot: Option, + /// Seal all currently finalized chunks and exit instead of polling continuously. + #[arg(long)] + once: bool, + /// Poll interval in milliseconds while waiting for new rooted chunks. + #[arg(long, default_value_t = 2_000)] + poll_ms: u64, + /// Native bridge RPC timeout in milliseconds. + #[arg(long, default_value_t = 30_000)] + bridge_timeout_ms: u64, + /// Upload each verified chunk to Cloudflare R2 (reads R2_* env vars). + #[arg(long)] + upload_r2: bool, + /// Optional override for `R2_PREFIX` when uploading chunks. + #[arg(long)] + r2_prefix: Option, + /// Path to shared SQLite chunk catalog queried by `get-block/resolver`. + #[arg(long)] + catalog_db: Option, + /// Generation identifier bound into the chunk catalog. + #[arg(long)] + catalog_generation: Option, + /// Storage prefix bound into the chunk catalog (defaults to R2 prefix). + #[arg(long)] + catalog_prefix: Option, + /// After R2 upload + catalog commit, delete local bulk payloads (`bundles.bin`, `extras.zst`, `counts.zst`), keeping `index.bin` and `manifest.json`. + #[arg(long)] + evict_local_payloads: bool, + /// Validator ledger directory containing `admin.rpc` to trigger `blockstorePurge` after sealing & publishing. + #[arg(long)] + purge_ledger: Option, + /// Minimum safety tail of slots retained in Agave Blockstore behind the highest sealed chunk (minimum 300). + #[arg(long, default_value_t = DEFAULT_PURGE_SAFETY_TAIL)] + purge_safety_tail: u64, + /// Validator ledger directory containing `admin.rpc` for background historical recovery (defaults to `--purge-ledger`). + #[arg(long)] + admin_ledger: Option, + /// Fallback policy when local gap rebuild fails (always logged as an error, written to `gap-*.failed.json`, and alerted to Telegram). + #[arg(long, value_enum, default_value_t = CliGapFallbackPolicy::WaitForCar)] + gap_fallback_policy: CliGapFallbackPolicy, + /// Solana JSON-RPC endpoint used when `--gap-fallback-policy=rpc-get-block`. + #[arg(long)] + fallback_rpc_url: Option, + /// Per-request timeout in milliseconds for fallback RPC `getBlock` calls. + #[arg(long, default_value_t = DEFAULT_FALLBACK_RPC_TIMEOUT.as_millis() as u64)] + fallback_rpc_timeout_ms: u64, + /// Maximum seconds to wait for Agave background historical shred recovery before declaring failure and falling back. + #[arg(long, default_value_t = DEFAULT_GAP_RECOVERY_TIMEOUT.as_secs())] + gap_recovery_timeout_secs: u64, + /// Optional shell command invoked after Agave recovers gap shreds to replay from preserved snapshots and seal canonical chunks. + #[arg(long)] + replay_command: Option, + }, + /// Compact an epoch (or slot range) into the 13 Compact V2 archive files from sealed chunks. + CompactEpoch { + /// Epoch number to compact. + #[arg(long)] + epoch: u64, + /// Output directory for the 13 Compact V2 archive files. + #[arg(long)] + output_dir: PathBuf, + /// Read chunks from a local finalized-ledger directory (mutually exclusive with --from-r2). + #[arg(long, conflicts_with = "from_r2")] + source_dir: Option, + /// Stream chunks directly over HTTPS from Cloudflare R2 (reads R2_* env vars; zero raw-ledger disk staging). + #[arg(long, conflicts_with = "source_dir")] + from_r2: bool, + /// Optional override for `R2_PREFIX` when streaming from R2. + #[arg(long)] + r2_prefix: Option, + /// Zstd compression level for `blocks.bin`. + #[arg(long, default_value_t = 3)] + zstd_level: i32, + /// Optional start slot for compacting a sub-epoch range (testing). + #[arg(long)] + start_slot: Option, + /// Optional inclusive end slot for compacting a sub-epoch range (testing). + #[arg(long)] + end_slot: Option, + /// Optional JSON file describing the first rooted successor block in `epoch + 1` (emits `GETBLOCK-EPOCH-COVERAGE.json`). + #[arg(long)] + successor_json: Option, + }, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + match cli.command { + Command::DrainChunks { + native_socket, + source_json, + output_dir, + chunk_slots, + zstd_level, + start_slot, + once, + poll_ms, + bridge_timeout_ms, + upload_r2, + r2_prefix, + catalog_db, + catalog_generation, + catalog_prefix, + evict_local_payloads, + purge_ledger, + purge_safety_tail, + admin_ledger, + gap_fallback_policy, + fallback_rpc_url, + fallback_rpc_timeout_ms, + gap_recovery_timeout_secs, + replay_command, + } => { + let source_raw = fs::read(&source_json) + .with_context(|| format!("read source identity {}", source_json.display()))?; + let source: SourceIdentity = serde_json::from_slice(&source_raw) + .with_context(|| format!("parse source identity {}", source_json.display()))?; + + let r2 = if upload_r2 { + Some(R2Settings::from_env(r2_prefix)?) + } else { + None + }; + + let catalog = match catalog_db { + Some(path) => { + let generation = catalog_generation + .context("--catalog-generation is required with --catalog-db")?; + let prefix = catalog_prefix + .or_else(|| r2.as_ref().map(|r| r.prefix.clone())) + .context("--catalog-prefix (or --upload-r2 with R2_PREFIX) is required with --catalog-db")?; + Some(CatalogOptions { + path, + generation, + prefix, + }) + } + None => None, + }; + + let purge = purge_ledger.clone().map(|ledger_dir| PurgeOptions { + ledger_dir, + safety_tail: purge_safety_tail, + rpc_timeout: Duration::from_secs(30), + }); + + let gap_recovery = GapRecoveryConfig { + admin_ledger_dir: admin_ledger.or(purge_ledger), + admin_rpc_timeout: Duration::from_secs(30), + poll_interval: DEFAULT_GAP_RECOVERY_POLL_INTERVAL, + recovery_timeout: Duration::from_secs(gap_recovery_timeout_secs.max(1)), + replay_command, + fallback_policy: gap_fallback_policy.into(), + fallback_rpc_url, + fallback_rpc_timeout: Duration::from_millis(fallback_rpc_timeout_ms.max(100)), + telegram: TelegramConfig::from_env(), + }; + + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .context("build tokio runtime")?; + let summary = runtime.block_on(run_drain(DrainConfig { + native_socket, + source, + client_timeout: Duration::from_millis(bridge_timeout_ms), + output_dir, + chunk_slots, + zstd_level, + start_slot, + once, + poll_interval: Duration::from_millis(poll_ms), + r2, + catalog, + evict_local_payloads, + purge, + gap_recovery, + }))?; + + eprintln!( + "drain complete: chunks={}, blocks={}, skips={}, forks={}, highest_sealed={:?}, highest_purged={:?}, gap_recovery_triggered={}, gap_failure_receipts={}", + summary.chunks_sealed, + summary.blocks_sealed, + summary.skips_sealed, + summary.forks_sealed, + summary.highest_sealed_slot, + summary.highest_purged_slot, + summary.gap_recovery_triggered, + summary.gap_failure_receipts.len(), + ); + Ok(()) + } + Command::CompactEpoch { + epoch, + output_dir, + source_dir, + from_r2, + r2_prefix, + zstd_level, + start_slot, + end_slot, + successor_json, + } => { + ensure!( + source_dir.is_some() || from_r2, + "specify either --source-dir or --from-r2" + ); + let successor = match successor_json { + Some(path) => { + let raw = fs::read(&path) + .with_context(|| format!("read successor {}", path.display()))?; + Some( + serde_json::from_slice::(&raw) + .with_context(|| format!("parse successor {}", path.display()))?, + ) + } + None => None, + }; + let range = match (start_slot, end_slot) { + (None, None) => None, + (Some(s), Some(e)) => Some((s, e)), + _ => bail!("--start-slot and --end-slot must be provided together"), + }; + + let report = if let Some(dir) = source_dir { + let source = LocalChunkSource::new(dir); + match range { + Some((s, e)) => compact::compact_range_from_chunks( + &source, + epoch, + s, + e, + &output_dir, + zstd_level, + successor, + )?, + None => compact_epoch_from_chunks( + &source, + epoch, + &output_dir, + zstd_level, + successor, + )?, + } + } else { + let settings = R2Settings::from_env(r2_prefix)?; + let client = R2Client::new(settings)?; + let source = R2ChunkSource::new(client); + match range { + Some((s, e)) => compact::compact_range_from_chunks( + &source, + epoch, + s, + e, + &output_dir, + zstd_level, + successor, + )?, + None => compact_epoch_from_chunks( + &source, + epoch, + &output_dir, + zstd_level, + successor, + )?, + } + }; + + eprintln!( + "compacted epoch {}: chunks={}, blocks={}, skips={}, forks={}, txs={}, entries={}, rewards={}, nonces={}", + report.epoch, + report.chunks_processed, + report.blocks, + report.skips, + report.forks, + report.transactions, + report.entries, + report.rewards, + report.nonce_recent_blockhashes + ); + Ok(()) + } + } +} diff --git a/blockzilla/finalized-ledger/src/notify.rs b/blockzilla/finalized-ledger/src/notify.rs new file mode 100644 index 00000000..8ee3dbf2 --- /dev/null +++ b/blockzilla/finalized-ledger/src/notify.rs @@ -0,0 +1,110 @@ +//! Pure-Rust Telegram alert notifications for gap recovery failures and fallbacks. +//! +//! Follows Blockzilla's `TELEGRAM_BOT_TOKEN` / `TELEGRAM_CHAT_ID` convention: +//! - Empty credentials skip cleanly. +//! - Network or Telegram API errors are logged with the bot token redacted and +//! never fail or abort the main drainer loop. + +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use reqwest::blocking::Client; + +pub const TELEGRAM_BOT_TOKEN_ENV: &str = "TELEGRAM_BOT_TOKEN"; +pub const TELEGRAM_CHAT_ID_ENV: &str = "TELEGRAM_CHAT_ID"; +pub const TELEGRAM_API_BASE_URL_ENV: &str = "TELEGRAM_API_BASE_URL"; +const DEFAULT_TELEGRAM_API_BASE_URL: &str = "https://api.telegram.org"; +const TELEGRAM_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +const TELEGRAM_REQUEST_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TelegramConfig { + pub bot_token: String, + pub chat_id: String, + pub api_base_url: String, +} + +impl TelegramConfig { + pub fn from_env() -> Self { + let bot_token = std::env::var(TELEGRAM_BOT_TOKEN_ENV).unwrap_or_default(); + let chat_id = std::env::var(TELEGRAM_CHAT_ID_ENV).unwrap_or_default(); + let api_base_url = std::env::var(TELEGRAM_API_BASE_URL_ENV) + .ok() + .filter(|v| !v.trim().is_empty()) + .unwrap_or_else(|| DEFAULT_TELEGRAM_API_BASE_URL.to_owned()); + Self { + bot_token, + chat_id, + api_base_url, + } + } + + pub fn is_ready(&self) -> bool { + !self.bot_token.trim().is_empty() && !self.chat_id.trim().is_empty() + } +} + +/// Redact the Telegram bot token from any diagnostic string before printing. +pub fn redact_token(text: &str, token: &str) -> String { + let token = token.trim(); + if token.is_empty() { + text.to_owned() + } else { + text.replace(token, "[token]") + } +} + +/// Send a Telegram alert message asynchronously (using `spawn_blocking` so we +/// never block Tokio or drop a blocking client on an async worker thread). +/// +/// Returns `true` if Telegram accepted the message, `false` if skipped or failed. +pub async fn send_alert(config: &TelegramConfig, text: String) -> bool { + if !config.is_ready() { + eprintln!("telegram: skipped, TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is empty"); + return false; + } + let cfg = config.clone(); + match tokio::task::spawn_blocking(move || send_alert_blocking(&cfg, &text)).await { + Ok(Ok(())) => true, + Ok(Err(err)) => { + eprintln!( + "telegram: {}", + redact_token(&format!("{err:#}"), &config.bot_token) + ); + false + } + Err(join_err) => { + eprintln!("telegram: task join failed: {join_err}"); + false + } + } +} + +fn send_alert_blocking(config: &TelegramConfig, text: &str) -> Result<()> { + let token = config.bot_token.trim(); + let chat_id = config.chat_id.trim(); + let base = config.api_base_url.trim_end_matches('/'); + let url = format!("{base}/bot{token}/sendMessage"); + let client = Client::builder() + .no_proxy() + .connect_timeout(TELEGRAM_CONNECT_TIMEOUT) + .timeout(TELEGRAM_REQUEST_TIMEOUT) + .build() + .context("build Telegram HTTP client")?; + let body = serde_json::json!({ + "chat_id": chat_id, + "text": text, + }); + let response = client + .post(&url) + .header("content-type", "application/json") + .body(serde_json::to_vec(&body).context("serialize Telegram payload")?) + .send() + .context("send Telegram HTTP POST")?; + let status = response.status(); + if !status.is_success() { + let resp_body = response.text().unwrap_or_default(); + bail!("Telegram sendMessage returned HTTP {status}: {resp_body}"); + } + Ok(()) +} diff --git a/blockzilla/finalized-ledger/src/r2.rs b/blockzilla/finalized-ledger/src/r2.rs new file mode 100644 index 00000000..c79640a8 --- /dev/null +++ b/blockzilla/finalized-ledger/src/r2.rs @@ -0,0 +1,784 @@ +//! Cloudflare R2 / S3 SigV4 uploader and streaming [`ChunkSource`]. +//! +//! Uses the same environment conventions as `hivezilla-ledger-archive`: +//! `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT` (or `R2_S3_ENDPOINT`), +//! `R2_BUCKET`, `R2_PREFIX`, and `R2_REGION` (`auto`). + +use std::collections::BTreeMap; +use std::fs::File; +use std::io::Read; +use std::os::unix::fs::FileExt; +use std::path::Path; +use std::thread; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_finalized_chunks::{ + CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, + CHUNK_MANIFEST_FILE, ChunkManifestV1, ChunkSource, chunk_dir_name, +}; +use chrono::Utc; +use reqwest::Method; +use reqwest::blocking::{Body, Client, Response}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; +use sha2::{Digest, Sha256}; + +pub const R2_ACCESS_KEY_ID_ENV: &str = "R2_ACCESS_KEY_ID"; +pub const R2_SECRET_ACCESS_KEY_ENV: &str = "R2_SECRET_ACCESS_KEY"; +pub const R2_ENDPOINT_ENV: &str = "R2_ENDPOINT"; +pub const R2_S3_ENDPOINT_ENV: &str = "R2_S3_ENDPOINT"; +pub const R2_BUCKET_ENV: &str = "R2_BUCKET"; +pub const R2_PREFIX_ENV: &str = "R2_PREFIX"; +pub const R2_REGION_ENV: &str = "R2_REGION"; + +const DEFAULT_REGION: &str = "auto"; +const PART_SIZE: u64 = 128 * 1024 * 1024; +const UNSIGNED_PAYLOAD: &str = "UNSIGNED-PAYLOAD"; +const PAYLOAD_SHA256: &str = "x-amz-content-sha256"; +const OBJECT_SHA256: &str = "x-amz-meta-blockzilla-sha256"; +const MAX_SMALL_RESPONSE_BYTES: usize = 32 * 1024 * 1024; +const ATTEMPTS: u32 = 4; + +#[derive(Clone, Debug)] +pub struct R2Settings { + pub endpoint: String, + pub bucket: String, + pub prefix: String, + pub region: String, + pub access_key: String, + pub secret_key: String, + pub allow_http_loopback: bool, +} + +impl R2Settings { + pub fn from_env(prefix_override: Option) -> Result { + Self::resolve_with(&|name| std::env::var(name).ok(), prefix_override, false) + } + + pub fn resolve_with( + lookup: &dyn Fn(&str) -> Option, + prefix_override: Option, + allow_http_loopback: bool, + ) -> Result { + let endpoint = first_present(lookup, &[R2_ENDPOINT_ENV, R2_S3_ENDPOINT_ENV]); + ensure!(!endpoint.is_empty(), "{R2_ENDPOINT_ENV} is empty"); + validate_endpoint(&endpoint, allow_http_loopback)?; + let bucket = required(lookup, R2_BUCKET_ENV)?; + let raw_prefix = match prefix_override { + Some(p) if !p.trim().is_empty() => p, + _ => required(lookup, R2_PREFIX_ENV)?, + }; + let region = present_or(lookup, R2_REGION_ENV, DEFAULT_REGION); + ensure!( + !bucket.is_empty() && !bucket.contains('/') && !bucket.chars().any(|c| c < '!'), + "R2 bucket name is invalid" + ); + Ok(Self { + endpoint: endpoint.trim_end_matches('/').to_owned(), + bucket, + prefix: normalize_prefix(&raw_prefix)?, + region, + access_key: required(lookup, R2_ACCESS_KEY_ID_ENV)?, + secret_key: required(lookup, R2_SECRET_ACCESS_KEY_ENV)?, + allow_http_loopback, + }) + } + + pub fn chunk_object_key( + &self, + epoch: u64, + start_slot: u64, + end_slot: u64, + file_name: &str, + ) -> String { + format!( + "{}/epoch-{}/{}/{file_name}", + self.prefix, + epoch, + chunk_dir_name(start_slot, end_slot) + ) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UploadedObject { + pub key: String, + pub etag: String, + pub length: u64, +} + +#[derive(Clone)] +pub struct R2Client { + settings: R2Settings, + host: String, + client: Client, +} + +impl R2Client { + pub fn new(settings: R2Settings) -> Result { + validate_endpoint(&settings.endpoint, settings.allow_http_loopback)?; + let parsed = url::Url::parse(&settings.endpoint)?; + let host = match parsed.port() { + Some(port) => format!("{}:{port}", parsed.host_str().context("missing host")?), + None => parsed.host_str().context("missing host")?.to_owned(), + }; + let mut builder = Client::builder() + .connect_timeout(Duration::from_secs(30)) + .timeout(Duration::from_secs(600)); + if settings.allow_http_loopback { + builder = builder.no_proxy(); + } + let client = builder.build().context("build reqwest blocking client")?; + Ok(Self { + settings, + host, + client, + }) + } + + pub fn settings(&self) -> &R2Settings { + &self.settings + } + + /// Upload one verified local file idempotently, confirming size, SHA-256 + /// metadata, and strong quoted ETag via HEAD after upload. + pub fn upload_file_verified( + &self, + path: &Path, + key: &str, + expected_len: u64, + expected_sha256: &str, + ) -> Result { + let meta = std::fs::metadata(path) + .with_context(|| format!("stat local file {}", path.display()))?; + ensure!( + meta.len() == expected_len, + "local file {} length {} differs from manifest {expected_len}", + path.display(), + meta.len() + ); + + if let Some((remote_len, remote_etag, remote_sha)) = self.head_object(key)? { + ensure!( + remote_len == expected_len, + "remote object {key} has length {remote_len}, expected {expected_len}" + ); + if let Some(sha) = remote_sha { + ensure!( + sha == expected_sha256, + "remote object {key} SHA-256 metadata {sha} differs from {expected_sha256}" + ); + } + return Ok(UploadedObject { + key: key.to_owned(), + etag: remote_etag, + length: remote_len, + }); + } + + if expected_len <= PART_SIZE { + let bytes = std::fs::read(path) + .with_context(|| format!("read local file {}", path.display()))?; + let actual_sha = hex::encode(Sha256::digest(&bytes)); + ensure!( + actual_sha == expected_sha256, + "local file {} SHA-256 changed before upload", + path.display() + ); + let headers = BTreeMap::from([ + ( + "content-type".to_owned(), + "application/octet-stream".to_owned(), + ), + (PAYLOAD_SHA256.to_owned(), actual_sha), + (OBJECT_SHA256.to_owned(), expected_sha256.to_owned()), + ]); + let resp = self.request_buffered( + Method::PUT, + key, + &BTreeMap::new(), + &headers, + &bytes, + 1024 * 1024, + )?; + ensure!( + resp.status == 200, + "PUT {key} returned HTTP {}", + resp.status + ); + } else { + self.upload_multipart(path, key, expected_len, expected_sha256)?; + } + + let (remote_len, remote_etag, remote_sha) = self + .head_object(key)? + .with_context(|| format!("uploaded object {key} missing on HEAD"))?; + ensure!( + remote_len == expected_len, + "uploaded object {key} HEAD length {remote_len} != {expected_len}" + ); + if let Some(sha) = remote_sha { + ensure!( + sha == expected_sha256, + "uploaded object {key} HEAD SHA-256 {sha} != {expected_sha256}" + ); + } + Ok(UploadedObject { + key: key.to_owned(), + etag: remote_etag, + length: remote_len, + }) + } + + fn upload_multipart( + &self, + path: &Path, + key: &str, + total_len: u64, + expected_sha256: &str, + ) -> Result<()> { + let init_params = BTreeMap::from([("uploads".to_owned(), String::new())]); + let init_headers = BTreeMap::from([ + ("content-type".to_owned(), "application/xml".to_owned()), + (OBJECT_SHA256.to_owned(), expected_sha256.to_owned()), + ]); + let init_resp = self.request_buffered( + Method::POST, + key, + &init_params, + &init_headers, + &[], + 1024 * 1024, + )?; + ensure!( + init_resp.status == 200, + "create multipart {key} returned HTTP {}", + init_resp.status + ); + let init_xml = String::from_utf8(init_resp.body).context("multipart XML not UTF-8")?; + let upload_id = xml_elements(&init_xml, "UploadId") + .into_iter() + .next() + .filter(|v| !v.is_empty()) + .context("multipart response missing UploadId")? + .to_owned(); + + let file = File::open(path)?; + let mut parts: Vec<(u32, String)> = Vec::new(); + let mut offset = 0u64; + let mut part_number = 1u32; + while offset < total_len { + let size = PART_SIZE.min(total_len - offset) as usize; + let mut buf = vec![0u8; size]; + file.read_exact_at(&mut buf, offset)?; + let params = BTreeMap::from([ + ("partNumber".to_owned(), part_number.to_string()), + ("uploadId".to_owned(), upload_id.clone()), + ]); + let headers = BTreeMap::from([ + ( + "content-type".to_owned(), + "application/octet-stream".to_owned(), + ), + (PAYLOAD_SHA256.to_owned(), hex::encode(Sha256::digest(&buf))), + ]); + let resp = self.request_buffered( + Method::PUT, + key, + ¶ms, + &headers, + &buf, + 1024 * 1024, + )?; + ensure!( + resp.status == 200, + "upload part {part_number} of {key} returned HTTP {}", + resp.status + ); + let etag = quote_etag(header_value(&resp.headers, "etag", "upload part")?); + parts.push((part_number, etag)); + offset += size as u64; + part_number += 1; + } + + let mut xml = String::from(""); + for (number, etag) in &parts { + xml.push_str(&format!( + "{number}{etag}" + )); + } + xml.push_str(""); + let complete_params = BTreeMap::from([("uploadId".to_owned(), upload_id)]); + let complete_headers = BTreeMap::from([ + ("content-type".to_owned(), "application/xml".to_owned()), + ( + PAYLOAD_SHA256.to_owned(), + hex::encode(Sha256::digest(xml.as_bytes())), + ), + ]); + let resp = self.request_buffered( + Method::POST, + key, + &complete_params, + &complete_headers, + xml.as_bytes(), + 1024 * 1024, + )?; + ensure!( + resp.status == 200, + "complete multipart {key} returned HTTP {}", + resp.status + ); + Ok(()) + } + + pub fn head_object(&self, key: &str) -> Result)>> { + let resp = self.request_buffered( + Method::HEAD, + key, + &BTreeMap::new(), + &BTreeMap::new(), + &[], + 64 * 1024, + )?; + if resp.status == 404 { + return Ok(None); + } + ensure!(resp.status == 200, "HEAD {key} returned HTTP {}", resp.status); + let len: u64 = header_value(&resp.headers, "content-length", "HEAD")? + .parse() + .context("invalid HEAD content-length")?; + let etag = quote_etag(header_value(&resp.headers, "etag", "HEAD")?); + let sha = resp + .headers + .get(OBJECT_SHA256) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + Ok(Some((len, etag, sha))) + } + + /// List all object keys under `key_prefix` via S3 ListObjectsV2. + pub fn list_keys(&self, key_prefix: &str) -> Result> { + let mut keys = Vec::new(); + let mut continuation: Option = None; + loop { + let mut params = BTreeMap::from([ + ("list-type".to_owned(), "2".to_owned()), + ("prefix".to_owned(), key_prefix.to_owned()), + ]); + if let Some(token) = &continuation { + params.insert("continuation-token".to_owned(), token.clone()); + } + let resp = self.request_buffered( + Method::GET, + "", + ¶ms, + &BTreeMap::new(), + &[], + MAX_SMALL_RESPONSE_BYTES, + )?; + ensure!( + resp.status == 200, + "ListObjectsV2({key_prefix}) returned HTTP {}", + resp.status + ); + let xml = String::from_utf8(resp.body).context("ListObjectsV2 XML not UTF-8")?; + for k in xml_elements(&xml, "Key") { + keys.push(unescape_xml(k)); + } + let truncated = xml_elements(&xml, "IsTruncated") + .into_iter() + .next() + .is_some_and(|v| v == "true"); + if !truncated { + break; + } + continuation = Some( + xml_elements(&xml, "NextContinuationToken") + .into_iter() + .next() + .map(unescape_xml) + .context("truncated ListObjectsV2 missing NextContinuationToken")?, + ); + } + Ok(keys) + } + + pub fn get_bytes(&self, key: &str, max_bytes: usize) -> Result> { + let resp = self.request_buffered( + Method::GET, + key, + &BTreeMap::new(), + &BTreeMap::new(), + &[], + max_bytes, + )?; + ensure!( + resp.status == 200, + "GET {key} returned HTTP {}", + resp.status + ); + Ok(resp.body) + } + + pub fn open_stream(&self, key: &str) -> Result> { + let resp = self.send_with_retry(Method::GET, key, &BTreeMap::new(), &BTreeMap::new(), &[])?; + let status = resp.status().as_u16(); + ensure!(status == 200, "GET stream {key} returned HTTP {status}"); + Ok(Box::new(resp)) + } + + fn request_buffered( + &self, + method: Method, + key: &str, + params: &BTreeMap, + headers: &BTreeMap, + body: &[u8], + max_response_bytes: usize, + ) -> Result { + let resp = self.send_with_retry(method.clone(), key, params, headers, body)?; + let status = resp.status().as_u16(); + let resp_headers = resp.headers().clone(); + let mut bytes = Vec::new(); + resp.take(max_response_bytes as u64 + 1) + .read_to_end(&mut bytes) + .with_context(|| format!("read {method} {key} response"))?; + ensure!( + bytes.len() <= max_response_bytes, + "{method} {key} response exceeds {max_response_bytes} bytes" + ); + Ok(HttpResult { + status, + headers: resp_headers, + body: bytes, + }) + } + + fn send_with_retry( + &self, + method: Method, + key: &str, + params: &BTreeMap, + headers: &BTreeMap, + body: &[u8], + ) -> Result { + let mut last_err = None; + for attempt in 1..=ATTEMPTS { + match self.send_once(method.clone(), key, params, headers, body) { + Ok(resp) => return Ok(resp), + Err(err) => { + last_err = Some(err); + if attempt < ATTEMPTS { + thread::sleep(Duration::from_millis(200 * u64::from(attempt))); + } + } + } + } + Err(last_err.unwrap()) + } + + fn send_once( + &self, + method: Method, + key: &str, + params: &BTreeMap, + headers: &BTreeMap, + body: &[u8], + ) -> Result { + let now = Utc::now(); + let date = now.format("%Y%m%d").to_string(); + let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string(); + let trimmed = key.trim_start_matches('/'); + let canonical_uri = if trimmed.is_empty() { + format!("/{}", uri_encode(&self.settings.bucket, false)) + } else { + format!( + "/{}/{}", + uri_encode(&self.settings.bucket, false), + uri_encode(trimmed, true) + ) + }; + let canonical_query = params + .iter() + .map(|(k, v)| format!("{}={}", uri_encode(k, false), uri_encode(v, false))) + .collect::>() + .join("&"); + let mut signed = BTreeMap::from([ + ("host".to_owned(), self.host.clone()), + (PAYLOAD_SHA256.to_owned(), UNSIGNED_PAYLOAD.to_owned()), + ("x-amz-date".to_owned(), amz_date.clone()), + ]); + for (name, value) in headers { + signed.insert(name.to_ascii_lowercase(), value.trim().to_owned()); + } + let canonical_headers = signed + .iter() + .map(|(k, v)| format!("{k}:{v}\n")) + .collect::(); + let signed_names = signed.keys().cloned().collect::>().join(";"); + let payload_hash = &signed[PAYLOAD_SHA256]; + let canonical_request = format!( + "{}\n{canonical_uri}\n{canonical_query}\n{canonical_headers}\n{signed_names}\n{payload_hash}", + method.as_str() + ); + let scope = format!("{date}/{}/s3/aws4_request", self.settings.region); + let string_to_sign = format!( + "AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}", + hex::encode(Sha256::digest(canonical_request.as_bytes())) + ); + let signature = hex::encode(hmac_sha256( + &signing_key(&self.settings.secret_key, &date, &self.settings.region), + string_to_sign.as_bytes(), + )); + let authorization = format!( + "AWS4-HMAC-SHA256 Credential={}/{scope},SignedHeaders={signed_names},Signature={signature}", + self.settings.access_key + ); + let mut url = format!("{}{}", self.settings.endpoint, canonical_uri); + if !canonical_query.is_empty() { + url.push('?'); + url.push_str(&canonical_query); + } + let mut req = self.client.request(method.clone(), &url); + if !body.is_empty() { + req = req.body(Body::from(body.to_vec())); + } + for (name, value) in &signed { + req = req.header( + HeaderName::from_bytes(name.as_bytes()).context("invalid R2 header name")?, + HeaderValue::from_str(value).context("invalid R2 header value")?, + ); + } + req = req.header("authorization", authorization); + let resp = req.send().with_context(|| format!("{method} {key}"))?; + let status = resp.status().as_u16(); + if status >= 500 || status == 429 { + bail!("{method} {key} returned HTTP {status}"); + } + Ok(resp) + } +} + +/// Streaming HTTPS/R2 [`ChunkSource`] for single-pass epoch compaction with +/// zero raw-ledger disk staging. +pub struct R2ChunkSource { + client: R2Client, +} + +impl R2ChunkSource { + pub fn new(client: R2Client) -> Self { + Self { client } + } + + fn key(&self, manifest: &ChunkManifestV1, file_name: &str) -> String { + self.client.settings().chunk_object_key( + manifest.epoch, + manifest.start_slot, + manifest.end_slot, + file_name, + ) + } +} + +impl ChunkSource for R2ChunkSource { + fn list_chunks(&self, epoch: u64) -> Result> { + let prefix = format!("{}/epoch-{epoch}/", self.client.settings().prefix); + let keys = self.client.list_keys(&prefix)?; + let suffix = format!("/{CHUNK_MANIFEST_FILE}"); + let mut manifests = Vec::new(); + for key in keys { + if !key.ends_with(&suffix) { + continue; + } + let raw = self.client.get_bytes(&key, 4 * 1024 * 1024)?; + let manifest: ChunkManifestV1 = serde_json::from_slice(&raw) + .with_context(|| format!("parse remote chunk manifest {key}"))?; + manifest.validate()?; + ensure!( + manifest.epoch == epoch, + "remote chunk manifest {key} has epoch {}, expected {epoch}", + manifest.epoch + ); + manifests.push(manifest); + } + manifests.sort_by_key(|m| m.start_slot); + Ok(manifests) + } + + fn load_index(&self, manifest: &ChunkManifestV1) -> Result> { + let key = self.key(manifest, CHUNK_INDEX_FILE); + self.client.get_bytes(&key, MAX_SMALL_RESPONSE_BYTES) + } + + fn load_counts(&self, manifest: &ChunkManifestV1) -> Result> { + let key = self.key(manifest, CHUNK_COUNTS_FILE); + self.client.get_bytes(&key, MAX_SMALL_RESPONSE_BYTES) + } + + fn open_bundles(&self, manifest: &ChunkManifestV1) -> Result> { + let key = self.key(manifest, CHUNK_BUNDLES_FILE); + self.client.open_stream(&key) + } + + fn open_extras(&self, manifest: &ChunkManifestV1) -> Result> { + let key = self.key(manifest, CHUNK_EXTRAS_FILE); + self.client.open_stream(&key) + } +} + +struct HttpResult { + status: u16, + headers: HeaderMap, + body: Vec, +} + +fn validate_endpoint(endpoint: &str, allow_http_loopback: bool) -> Result<()> { + let parsed = url::Url::parse(endpoint).context("R2 endpoint is not a URL")?; + let host = parsed.host_str().context("R2 endpoint has no host")?; + let scheme_ok = parsed.scheme() == "https" + || (allow_http_loopback + && parsed.scheme() == "http" + && matches!(host, "127.0.0.1" | "localhost" | "[::1]")); + ensure!(scheme_ok, "R2 endpoint must be an absolute HTTPS URL"); + ensure!( + parsed.username().is_empty() && parsed.password().is_none(), + "R2 endpoint must not contain user info" + ); + ensure!( + matches!(parsed.path(), "" | "/") && parsed.query().is_none() && parsed.fragment().is_none(), + "R2 endpoint must not contain a path, query, or fragment" + ); + Ok(()) +} + +fn normalize_prefix(raw: &str) -> Result { + let trimmed = raw.trim().trim_matches('/'); + ensure!( + !trimmed.is_empty() + && trimmed.len() <= 512 + && !trimmed + .split('/') + .any(|part| part.is_empty() || part == "." || part == ".."), + "invalid R2 prefix '{raw}'" + ); + Ok(trimmed.to_owned()) +} + +fn first_present(lookup: &dyn Fn(&str) -> Option, keys: &[&str]) -> String { + for key in keys { + if let Some(value) = lookup(key).map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()) { + return value; + } + } + String::new() +} + +fn present_or(lookup: &dyn Fn(&str) -> Option, key: &str, fallback: &str) -> String { + let v = first_present(lookup, &[key]); + if v.is_empty() { fallback.to_owned() } else { v } +} + +fn required(lookup: &dyn Fn(&str) -> Option, key: &str) -> Result { + let v = first_present(lookup, &[key]); + ensure!(!v.is_empty(), "{key} is empty"); + Ok(v) +} + +fn header_value<'a>(headers: &'a HeaderMap, name: &str, op: &str) -> Result<&'a str> { + headers + .get(name) + .with_context(|| format!("{op} response missing {name}"))? + .to_str() + .with_context(|| format!("{op} response has non-ASCII {name}")) +} + +fn quote_etag(raw: &str) -> String { + let trimmed = raw.trim(); + if trimmed.starts_with('"') && trimmed.ends_with('"') && trimmed.len() >= 2 { + trimmed.to_owned() + } else { + format!("\"{trimmed}\"") + } +} + +pub(crate) fn xml_elements<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> { + let open = format!("<{tag}"); + let close = format!(""); + let mut out = Vec::new(); + let mut rest = xml; + while let Some(start) = rest.find(&open) { + let after_open = &rest[start + open.len()..]; + let Some(gt) = after_open.find('>') else { + break; + }; + // Ensure exact tag name match (followed by '>' or whitespace). + let next_ch = after_open.as_bytes().first().copied(); + if !matches!(next_ch, Some(b'>' | b' ' | b'\t' | b'\n')) { + rest = &after_open[gt + 1..]; + continue; + } + let content_start = &after_open[gt + 1..]; + let Some(end) = content_start.find(&close) else { + break; + }; + out.push(content_start[..end].trim()); + rest = &content_start[end + close.len()..]; + } + out +} + +fn unescape_xml(value: &str) -> String { + value + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") +} + +fn uri_encode(input: &str, keep_slash: bool) -> String { + let mut out = String::with_capacity(input.len()); + for byte in input.bytes() { + let unreserved = byte.is_ascii_alphanumeric() + || matches!(byte, b'-' | b'_' | b'.' | b'~') + || (keep_slash && byte == b'/'); + if unreserved { + out.push(byte as char); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +fn signing_key(secret: &str, date: &str, region: &str) -> [u8; 32] { + let k_date = hmac_sha256(format!("AWS4{secret}").as_bytes(), date.as_bytes()); + let k_region = hmac_sha256(&k_date, region.as_bytes()); + let k_service = hmac_sha256(&k_region, b"s3"); + hmac_sha256(&k_service, b"aws4_request") +} + +fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] { + let mut padded = [0u8; 64]; + if key.len() > 64 { + let digest: [u8; 32] = Sha256::digest(key).into(); + padded[..32].copy_from_slice(&digest); + } else { + padded[..key.len()].copy_from_slice(key); + } + let mut ipad = [0x36u8; 64]; + let mut opad = [0x5cu8; 64]; + for i in 0..64 { + ipad[i] ^= padded[i]; + opad[i] ^= padded[i]; + } + let mut inner = Sha256::new(); + inner.update(ipad); + inner.update(data); + let inner_hash: [u8; 32] = inner.finalize().into(); + let mut outer = Sha256::new(); + outer.update(opad); + outer.update(inner_hash); + outer.finalize().into() +} diff --git a/blockzilla/finalized-ledger/src/recovery.rs b/blockzilla/finalized-ledger/src/recovery.rs new file mode 100644 index 00000000..f3833b06 --- /dev/null +++ b/blockzilla/finalized-ledger/src/recovery.rs @@ -0,0 +1,618 @@ +//! Parallel restart-gap recovery, fallback handling, durable failure receipts, +//! and Telegram failure alerting. +//! +//! Policy: +//! - Live draining starts immediately at Agave's post-restart `lowest_slot`. +//! - Simultaneously, any skipped gap `[gap_start..=gap_end]` is attempted via +//! Agave's isolated `HistoricalRecoveryService` + optional local replay. +//! - Any inability to locally rebuild canonical chunks is treated as a FAILURE: +//! logged as an error, recorded durably in `gap--.failed.json`, +//! and reported to Telegram. +//! - Fallback is either `wait_for_car` (default) or `rpc_get_block` (degraded +//! RPC backfill tagged `rpc_only_no_alpenglow`, which serves temporary +//! `getBlock` while epoch compaction still refuses it until CAR arrives). + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_finalized_chunks::{ + CHUNK_BUNDLES_FILE, CHUNK_INDEX_FILE, CHUNK_MANIFEST_FILE, ChunkCatalogWriter, ChunkManifestV1, + ChunkStorageMode, DEGRADED_SOURCE_RPC_ONLY, SealedChunk, chunk_dir_name, epoch_for_slot, +}; +use chrono::Utc; +use serde::{Deserialize, Serialize}; +use tokio::process::Command; +use tokio::sync::Mutex; + +use crate::admin_rpc::{self, HistoricalRecoveryPhase, HistoricalRecoveryStatus}; +use crate::drain::{evict_bulk_payloads, upload_sealed_chunk}; +use crate::notify::{self, TelegramConfig}; +use crate::r2::{R2Client, R2Settings}; +use crate::rpc_fallback; + +pub const DEFAULT_GAP_RECOVERY_POLL_INTERVAL: Duration = Duration::from_secs(2); +pub const DEFAULT_GAP_RECOVERY_TIMEOUT: Duration = Duration::from_secs(30 * 60); +pub const DEFAULT_FALLBACK_RPC_TIMEOUT: Duration = Duration::from_secs(30); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GapFallbackPolicy { + #[default] + WaitForCar, + RpcGetBlock, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GapFallbackStatus { + WaitingForCar, + RpcBackfilledDegradedWaitingForCar, + RpcFallbackFailed, +} + +#[derive(Clone, Debug)] +pub struct GapRecoveryConfig { + pub admin_ledger_dir: Option, + pub admin_rpc_timeout: Duration, + pub poll_interval: Duration, + pub recovery_timeout: Duration, + pub replay_command: Option, + pub fallback_policy: GapFallbackPolicy, + pub fallback_rpc_url: Option, + pub fallback_rpc_timeout: Duration, + pub telegram: TelegramConfig, +} + +impl Default for GapRecoveryConfig { + fn default() -> Self { + Self { + admin_ledger_dir: None, + admin_rpc_timeout: Duration::from_secs(30), + poll_interval: DEFAULT_GAP_RECOVERY_POLL_INTERVAL, + recovery_timeout: DEFAULT_GAP_RECOVERY_TIMEOUT, + replay_command: None, + fallback_policy: GapFallbackPolicy::WaitForCar, + fallback_rpc_url: None, + fallback_rpc_timeout: DEFAULT_FALLBACK_RPC_TIMEOUT, + telegram: TelegramConfig::from_env(), + } + } +} + +impl GapRecoveryConfig { + pub fn validate(&self) -> Result<()> { + if self.fallback_policy == GapFallbackPolicy::RpcGetBlock { + ensure!( + self.fallback_rpc_url + .as_deref() + .is_some_and(|u| !u.trim().is_empty()), + "--fallback-rpc-url is required when --gap-fallback-policy=rpc-get-block" + ); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GapFailureReceipt { + pub version: u16, + pub epoch: u64, + pub gap_start_slot: u64, + pub gap_end_slot: u64, + pub gap_slots: u64, + pub reason: String, + pub historical_recovery_status: Option, + pub fallback_policy: GapFallbackPolicy, + pub fallback_status: GapFallbackStatus, + pub rpc_chunks_sealed: Vec, + pub telegram_notified: bool, + pub detected_at_utc: String, + pub updated_at_utc: String, +} + +#[derive(Clone, Debug)] +pub enum GapRecoveryOutcome { + LocallyRebuilt { + chunks_published: usize, + recovery_status: HistoricalRecoveryStatus, + }, + FailedWithFallback { + receipt_path: PathBuf, + receipt: GapFailureReceipt, + }, +} + +pub fn gap_receipt_path(output_dir: &Path, gap_start: u64, gap_end: u64) -> PathBuf { + let epoch = epoch_for_slot(gap_start); + output_dir + .join(format!("epoch-{epoch}")) + .join(format!("gap-{gap_start:012}-{gap_end:012}.failed.json")) +} + +pub fn write_receipt_atomic(path: &Path, receipt: &GapFailureReceipt) -> Result<()> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("create receipt dir {}", parent.display()))?; + } + let tmp = path.with_extension("json.tmp"); + let bytes = serde_json::to_vec_pretty(receipt).context("serialize gap failure receipt")?; + fs::write(&tmp, bytes).with_context(|| format!("write {}", tmp.display()))?; + fs::rename(&tmp, path).with_context(|| format!("install receipt {}", path.display()))?; + Ok(()) +} + +/// Run parallel restart-gap recovery for `[gap_start..=gap_end]` without +/// blocking live snapshot catchup or live chunk draining. +#[allow(clippy::too_many_arguments)] +pub async fn recover_restart_gap( + gap_start: u64, + gap_end: u64, + output_dir: PathBuf, + chunk_slots: u64, + zstd_level: i32, + r2_settings: Option, + catalog_writer: Option>>, + evict_local_payloads: bool, + config: GapRecoveryConfig, +) -> GapRecoveryOutcome { + let epoch = epoch_for_slot(gap_start); + let gap_slots = gap_end.saturating_sub(gap_start).saturating_add(1); + let detected_at_utc = Utc::now().to_rfc3339(); + + eprintln!( + "gap-recovery: detected restart gap epoch-{epoch} slots {gap_start}..={gap_end} ({gap_slots} slots); live draining continues immediately while parallel recovery runs" + ); + + // Step 1: Attempt local historical shred recovery via Agave admin.rpc + optional replay command. + let (failure_reason, last_status) = match try_local_recovery( + gap_start, + gap_end, + &output_dir, + chunk_slots, + &r2_settings, + &catalog_writer, + evict_local_payloads, + &config, + ) + .await + { + Ok((chunks_published, recovery_status)) => { + eprintln!( + "gap-recovery: SUCCEEDED locally for epoch-{epoch} slots {gap_start}..={gap_end} (published {chunks_published} canonical chunks)" + ); + let _ = notify::send_alert( + &config.telegram, + format!( + "✅ Blockzilla gap recovery succeeded locally: epoch {epoch} slots {gap_start}..={gap_end} ({chunks_published} canonical chunks)" + ), + ) + .await; + return GapRecoveryOutcome::LocallyRebuilt { + chunks_published, + recovery_status, + }; + } + Err((reason, status)) => (reason, status), + }; + + // Step 2: FAILURE PATH — log error, write durable receipt, and notify Telegram! + eprintln!( + "ERROR: gap-recovery FAILED for epoch-{epoch} slots {gap_start}..={gap_end} ({gap_slots} slots): {failure_reason}; fallback={:?}", + config.fallback_policy + ); + + let receipt_path = gap_receipt_path(&output_dir, gap_start, gap_end); + let mut receipt = GapFailureReceipt { + version: 1, + epoch, + gap_start_slot: gap_start, + gap_end_slot: gap_end, + gap_slots, + reason: failure_reason.clone(), + historical_recovery_status: last_status, + fallback_policy: config.fallback_policy, + fallback_status: GapFallbackStatus::WaitingForCar, + rpc_chunks_sealed: Vec::new(), + telegram_notified: false, + detected_at_utc: detected_at_utc.clone(), + updated_at_utc: detected_at_utc, + }; + + if let Err(err) = write_receipt_atomic(&receipt_path, &receipt) { + eprintln!( + "ERROR: failed to write gap failure receipt {}: {err:#}", + receipt_path.display() + ); + } + + let fallback_label = match config.fallback_policy { + GapFallbackPolicy::WaitForCar => "wait_for_car (CAR required before epoch compaction)", + GapFallbackPolicy::RpcGetBlock => { + "rpc_get_block (attempting degraded RPC backfill; CAR still required before epoch compaction)" + } + }; + let alert_text = format!( + "🚨 Blockzilla gap recovery FAILED: epoch {epoch} slots {gap_start}..={gap_end} ({gap_slots} slots) — {failure_reason} | fallback: {fallback_label}" + ); + receipt.telegram_notified = notify::send_alert(&config.telegram, alert_text).await; + receipt.updated_at_utc = Utc::now().to_rfc3339(); + let _ = write_receipt_atomic(&receipt_path, &receipt); + + // Step 3: Execute configured fallback policy. + if config.fallback_policy == GapFallbackPolicy::RpcGetBlock { + let rpc_url = config + .fallback_rpc_url + .clone() + .unwrap_or_default(); + let out_clone = output_dir.clone(); + let rpc_timeout = config.fallback_rpc_timeout; + let backfill_res = tokio::task::spawn_blocking(move || { + rpc_fallback::seal_rpc_fallback_gap( + &rpc_url, + rpc_timeout, + &out_clone, + gap_start, + gap_end, + chunk_slots, + zstd_level, + ) + }) + .await + .map_err(|err| anyhow::anyhow!("join RPC backfill task: {err}")) + .and_then(|inner| inner); + + match backfill_res { + Ok(sealed_chunks) => { + let mut publish_err = None; + let mut sealed_names = Vec::with_capacity(sealed_chunks.len()); + for sealed in &sealed_chunks { + sealed_names.push(chunk_dir_name( + sealed.manifest.start_slot, + sealed.manifest.end_slot, + )); + if let Err(err) = publish_chunk( + sealed, + r2_settings.as_ref(), + catalog_writer.as_ref(), + evict_local_payloads, + ) + .await + { + publish_err = Some(err); + break; + } + } + if let Some(err) = publish_err { + receipt.fallback_status = GapFallbackStatus::RpcFallbackFailed; + receipt.reason = format!( + "{}; RPC fallback publish failed: {err:#}", + receipt.reason + ); + eprintln!( + "ERROR: gap-recovery RPC fallback publish failed for {gap_start}..={gap_end}: {err:#}" + ); + let _ = notify::send_alert( + &config.telegram, + format!( + "🚨 Blockzilla RPC fallback FAILED for epoch {epoch} slots {gap_start}..={gap_end}: {err:#} — waiting for CAR" + ), + ) + .await; + } else { + receipt.fallback_status = + GapFallbackStatus::RpcBackfilledDegradedWaitingForCar; + receipt.rpc_chunks_sealed = sealed_names; + eprintln!( + "WARN: gap-recovery sealed {} degraded RPC chunks ({DEGRADED_SOURCE_RPC_ONLY}) for {gap_start}..={gap_end}; getBlock can serve them temporarily, but epoch compaction will refuse until CAR replaces them", + receipt.rpc_chunks_sealed.len() + ); + let _ = notify::send_alert( + &config.telegram, + format!( + "⚠️ Blockzilla RPC degraded backfill complete for epoch {epoch} slots {gap_start}..={gap_end} ({} chunks, source={DEGRADED_SOURCE_RPC_ONLY}); CAR still required before epoch compaction", + receipt.rpc_chunks_sealed.len() + ), + ) + .await; + } + } + Err(err) => { + receipt.fallback_status = GapFallbackStatus::RpcFallbackFailed; + receipt.reason = format!("{}; RPC fallback failed: {err:#}", receipt.reason); + eprintln!( + "ERROR: gap-recovery RPC fallback failed for {gap_start}..={gap_end}: {err:#}" + ); + let _ = notify::send_alert( + &config.telegram, + format!( + "🚨 Blockzilla RPC fallback FAILED for epoch {epoch} slots {gap_start}..={gap_end}: {err:#} — waiting for CAR" + ), + ) + .await; + } + } + receipt.updated_at_utc = Utc::now().to_rfc3339(); + let _ = write_receipt_atomic(&receipt_path, &receipt); + } + + GapRecoveryOutcome::FailedWithFallback { + receipt_path, + receipt, + } +} + +#[allow(clippy::too_many_arguments)] +async fn try_local_recovery( + gap_start: u64, + gap_end: u64, + output_dir: &Path, + chunk_slots: u64, + r2_settings: &Option, + catalog_writer: &Option>>, + evict_local_payloads: bool, + config: &GapRecoveryConfig, +) -> std::result::Result<(usize, HistoricalRecoveryStatus), (String, Option)> +{ + let Some(admin_ledger) = config.admin_ledger_dir.as_deref() else { + return Err(( + "no --admin-ledger / --purge-ledger configured to invoke Agave historical shred recovery" + .to_owned(), + None, + )); + }; + + if let Err(err) = + admin_rpc::start_historical_recovery(admin_ledger, gap_start, gap_end, config.admin_rpc_timeout) + .await + { + let msg = format!("{err:#}"); + if !msg.contains("already running") { + return Err((format!("startHistoricalRecovery RPC failed: {msg}"), None)); + } + } + + let deadline = Instant::now() + config.recovery_timeout; + let final_status = loop { + let status = match admin_rpc::historical_recovery_status( + admin_ledger, + config.admin_rpc_timeout, + ) + .await + { + Ok(s) => s, + Err(err) => { + return Err((format!("historicalRecoveryStatus RPC failed: {err:#}"), None)); + } + }; + + if status.phase.is_terminal() { + break status; + } + if Instant::now() >= deadline { + return Err(( + format!( + "Agave historical shred recovery timed out after {:?} (recovered_slots={}, skipped_slots={})", + config.recovery_timeout, status.recovered_slots, status.skipped_slots + ), + Some(status), + )); + } + tokio::time::sleep(config.poll_interval).await; + }; + + if final_status.phase != HistoricalRecoveryPhase::Completed { + return Err(( + format!( + "Agave historical shred recovery ended in phase {:?} (recovered_slots={}, skipped_slots={}, unrecoverable_slot_count={}, chain_reached_start={}, last_error={:?})", + final_status.phase, + final_status.recovered_slots, + final_status.skipped_slots, + final_status.unrecoverable_slot_count, + final_status.chain_reached_start, + final_status.last_error + ), + Some(final_status), + )); + } + + let Some(replay_cmd) = config + .replay_command + .as_deref() + .filter(|cmd| !cmd.trim().is_empty()) + else { + return Err(( + format!( + "Agave recovered all shreds into {} (preserved_snapshot_slot={:?}), but no --replay-command is configured to rebuild canonical chunks", + final_status.recovery_ledger_path, final_status.preserved_snapshot_slot + ), + Some(final_status), + )); + }; + + let mut command = Command::new("/bin/sh"); + command + .arg("-c") + .arg(replay_cmd) + .env("BLOCKZILLA_GAP_START_SLOT", gap_start.to_string()) + .env("BLOCKZILLA_GAP_END_SLOT", gap_end.to_string()) + .env( + "BLOCKZILLA_RECOVERY_LEDGER_DIR", + &final_status.recovery_ledger_path, + ) + .env( + "BLOCKZILLA_PRESERVED_SNAPSHOT_SLOT", + final_status + .preserved_snapshot_slot + .map(|s| s.to_string()) + .unwrap_or_default(), + ) + .env("BLOCKZILLA_OUTPUT_DIR", output_dir) + .env("BLOCKZILLA_CHUNK_SLOTS", chunk_slots.to_string()); + + let output = match command.output().await { + Ok(out) => out, + Err(err) => { + return Err(( + format!("failed to execute --replay-command: {err}"), + Some(final_status), + )); + } + }; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(( + format!( + "--replay-command exited with {}: {}", + output.status, + stderr.trim() + ), + Some(final_status), + )); + } + + // Verify canonical (non-degraded) chunks cover [gap_start..=gap_end] and publish them. + let canonical_chunks = match load_canonical_gap_chunks(output_dir, gap_start, gap_end) { + Ok(chunks) => chunks, + Err(err) => { + return Err(( + format!("--replay-command did not produce verified canonical chunks for {gap_start}..={gap_end}: {err:#}"), + Some(final_status), + )); + } + }; + + for sealed in &canonical_chunks { + if let Err(err) = publish_chunk( + sealed, + r2_settings.as_ref(), + catalog_writer.as_ref(), + evict_local_payloads, + ) + .await + { + return Err(( + format!( + "failed to publish locally rebuilt chunk {}..={}: {err:#}", + sealed.manifest.start_slot, sealed.manifest.end_slot + ), + Some(final_status), + )); + } + } + + Ok((canonical_chunks.len(), final_status)) +} + +fn load_canonical_gap_chunks( + output_dir: &Path, + gap_start: u64, + gap_end: u64, +) -> Result> { + let mut found = Vec::new(); + let first_epoch = epoch_for_slot(gap_start); + let last_epoch = epoch_for_slot(gap_end); + for epoch in first_epoch..=last_epoch { + let epoch_dir = output_dir.join(format!("epoch-{epoch}")); + if !epoch_dir.is_dir() { + continue; + } + for entry in fs::read_dir(&epoch_dir)? { + let dir = entry?.path(); + let manifest_path = dir.join(CHUNK_MANIFEST_FILE); + if !manifest_path.is_file() { + continue; + } + let manifest: ChunkManifestV1 = serde_json::from_slice(&fs::read(&manifest_path)?)?; + manifest.validate()?; + if manifest.start_slot >= gap_start && manifest.end_slot <= gap_end { + ensure!( + manifest.degraded_source.is_none(), + "chunk {}..={} is marked degraded ({:?}), not canonical", + manifest.start_slot, + manifest.end_slot, + manifest.degraded_source + ); + let index_bytes = fs::read(dir.join(CHUNK_INDEX_FILE))?; + found.push(SealedChunk { + dir, + manifest, + index_bytes, + }); + } + } + } + found.sort_by_key(|c| c.manifest.start_slot); + let mut expected = gap_start; + for chunk in &found { + ensure!( + chunk.manifest.start_slot == expected, + "rebuilt chunk gap or overlap: expected {expected}, found {}", + chunk.manifest.start_slot + ); + expected = chunk + .manifest + .end_slot + .checked_add(1) + .context("chunk end overflow")?; + } + if expected != gap_end.saturating_add(1) { + bail!( + "rebuilt canonical chunks cover only up to {} instead of {gap_end}", + expected.saturating_sub(1) + ); + } + Ok(found) +} + +async fn publish_chunk( + sealed: &SealedChunk, + r2_settings: Option<&R2Settings>, + catalog_writer: Option<&Arc>>, + evict_local: bool, +) -> Result<()> { + let (storage_mode, bundles_location, bundles_etag) = if let Some(settings) = r2_settings { + let settings_clone = settings.clone(); + let sealed_dir = sealed.dir.clone(); + let manifest = sealed.manifest.clone(); + let uploaded = tokio::task::spawn_blocking(move || { + let r2 = R2Client::new(settings_clone)?; + upload_sealed_chunk(&r2, &sealed_dir, &manifest) + }) + .await + .context("join R2 chunk upload task")??; + (ChunkStorageMode::R2, uploaded.key, Some(uploaded.etag)) + } else { + let local_bundles = sealed + .dir + .join(CHUNK_BUNDLES_FILE) + .canonicalize() + .context("canonicalize local chunk.bundles.bin")?; + ( + ChunkStorageMode::Local, + local_bundles + .to_str() + .context("local bundles path is not UTF-8")? + .to_owned(), + None, + ) + }; + + if let Some(writer_arc) = catalog_writer { + let mut writer = writer_arc.lock().await; + writer.register_chunk( + &sealed.manifest, + &sealed.index_bytes, + storage_mode, + &bundles_location, + bundles_etag.as_deref(), + )?; + } + + if evict_local { + evict_bulk_payloads(&sealed.dir)?; + } + Ok(()) +} diff --git a/blockzilla/finalized-ledger/src/rpc_fallback.rs b/blockzilla/finalized-ledger/src/rpc_fallback.rs new file mode 100644 index 00000000..fd2253f4 --- /dev/null +++ b/blockzilla/finalized-ledger/src/rpc_fallback.rs @@ -0,0 +1,718 @@ +//! Degraded RPC `getBlock` fallback for temporary `getBlock` availability. +//! +//! IMPORTANT: Standard Solana JSON-RPC `getBlock` does NOT return PoH entries, +//! shredding boundaries, Alpenglow `consensus_block_id`, or `block_markers`. +//! Every chunk sealed from this module MUST be tagged with +//! [`blockzilla_finalized_chunks::DEGRADED_SOURCE_RPC_ONLY`] so epoch +//! compaction refuses it until canonical CAR or local replay replaces it. + +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result, anyhow, bail, ensure}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use blockzilla_account_bridge_protocol::{ArchiveBlockPayloadV1, ArchiveEntry, ArchiveTransaction}; +use blockzilla_finalized_chunks::{ + ChunkBuilder, DEGRADED_SOURCE_RPC_ONLY, SealedChunk, chunk_window_end, encode_archive_payload, +}; +use blockzilla_solana_wire::confirmed_block::{ + InnerInstruction, InnerInstructions, NumPartitions, ReturnData, Reward, RewardType, Rewards, + TokenBalance, TransactionError, TransactionStatusMeta, UiTokenAmount, +}; +use blockzilla_solana_wire::stored_transaction::{InstructionError, StoredTransactionError}; +use prost::Message as ProstMessage; +use reqwest::blocking::Client; +use serde::Deserialize; +use serde_json::{Value, json}; + +const RPC_ERROR_SLOT_SKIPPED: i64 = -32007; +const RPC_ERROR_SLOT_MISSING_LONG_TERM: i64 = -32009; + +#[derive(Debug)] +pub enum RpcBlockResult { + Block(ArchiveBlockPayloadV1), + Skipped, +} + +pub struct RpcFallbackClient { + rpc_url: String, + http: Client, +} + +impl RpcFallbackClient { + pub fn new(rpc_url: String, timeout: Duration) -> Result { + let http = Client::builder() + .no_proxy() + .connect_timeout(Duration::from_secs(10)) + .timeout(timeout) + .build() + .context("build RPC fallback HTTP client")?; + Ok(Self { rpc_url, http }) + } + + pub fn fetch_block(&self, slot: u64) -> Result { + let request = json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "getBlock", + "params": [ + slot, + { + "encoding": "base64", + "transactionDetails": "full", + "rewards": true, + "maxSupportedTransactionVersion": 1, + "commitment": "finalized" + } + ] + }); + + let response = self + .http + .post(&self.rpc_url) + .header("content-type", "application/json") + .body(serde_json::to_vec(&request).context("serialize getBlock RPC request")?) + .send() + .with_context(|| format!("POST getBlock({slot}) to {}", self.rpc_url))?; + let status = response.status(); + let body = response + .bytes() + .with_context(|| format!("read getBlock({slot}) response body"))?; + if !status.is_success() { + bail!( + "RPC getBlock({slot}) returned HTTP {status}: {}", + String::from_utf8_lossy(&body) + ); + } + + let envelope: JsonRpcResponse = + serde_json::from_slice(&body).with_context(|| format!("parse getBlock({slot}) JSON"))?; + if let Some(err) = envelope.error { + if err.code == RPC_ERROR_SLOT_SKIPPED || err.code == RPC_ERROR_SLOT_MISSING_LONG_TERM { + return Ok(RpcBlockResult::Skipped); + } + bail!( + "RPC getBlock({slot}) failed (code {}): {}", + err.code, + err.message + ); + } + + let Some(result) = envelope.result else { + return Ok(RpcBlockResult::Skipped); + }; + if result.is_null() { + return Ok(RpcBlockResult::Skipped); + } + + let block: RpcConfirmedBlock = serde_json::from_value(result) + .with_context(|| format!("decode UiConfirmedBlock JSON for slot {slot}"))?; + let payload = convert_rpc_block(slot, block)?; + Ok(RpcBlockResult::Block(payload)) + } +} + +/// Backfill `[gap_start..=gap_end]` into degraded RPC-only finalized chunks +/// aligned to `chunk_slots` (never crossing epoch boundaries). +pub fn seal_rpc_fallback_gap( + rpc_url: &str, + timeout: Duration, + output_dir: &Path, + gap_start: u64, + gap_end: u64, + chunk_slots: u64, + zstd_level: i32, +) -> Result> { + ensure!(gap_start <= gap_end, "invalid RPC backfill gap range"); + let client = RpcFallbackClient::new(rpc_url.to_owned(), timeout)?; + let mut sealed_chunks = Vec::new(); + let mut cursor = gap_start; + + while cursor <= gap_end { + let window_end = chunk_window_end(cursor, chunk_slots)?.min(gap_end); + let mut builder = ChunkBuilder::create(output_dir, cursor, window_end, zstd_level)?; + builder.set_degraded_source(DEGRADED_SOURCE_RPC_ONLY); + + for slot in cursor..=window_end { + match client.fetch_block(slot)? { + RpcBlockResult::Block(payload) => { + let encoded = encode_archive_payload(&payload, zstd_level)?; + builder.add_block(&encoded)?; + } + RpcBlockResult::Skipped => { + builder.add_skip(slot)?; + } + } + } + + let sealed = builder.finish()?; + sealed_chunks.push(sealed); + cursor = window_end + .checked_add(1) + .context("RPC backfill cursor overflow")?; + } + + Ok(sealed_chunks) +} + +#[derive(Deserialize)] +struct JsonRpcResponse { + result: Option, + error: Option, +} + +#[derive(Deserialize)] +struct JsonRpcError { + code: i64, + message: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcConfirmedBlock { + previous_blockhash: String, + blockhash: String, + parent_slot: u64, + #[serde(default)] + transactions: Vec, + #[serde(default)] + rewards: Vec, + #[serde(default)] + num_reward_partitions: Option, + #[serde(default)] + block_time: Option, + #[serde(default)] + block_height: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcEncodedTransactionWithMeta { + transaction: Value, + meta: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcTransactionStatusMeta { + #[serde(default)] + err: Option, + fee: u64, + #[serde(default)] + pre_balances: Vec, + #[serde(default)] + post_balances: Vec, + #[serde(default)] + inner_instructions: Option>, + #[serde(default)] + log_messages: Option>, + #[serde(default)] + pre_token_balances: Option>, + #[serde(default)] + post_token_balances: Option>, + #[serde(default)] + rewards: Option>, + #[serde(default)] + loaded_addresses: Option, + #[serde(default)] + return_data: Option, + #[serde(default)] + compute_units_consumed: Option, + #[serde(default)] + cost_units: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcInnerInstructions { + index: u32, + instructions: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcCompiledInstruction { + program_id_index: u32, + accounts: Vec, + data: String, + #[serde(default)] + stack_height: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcTokenBalance { + account_index: u32, + mint: String, + ui_token_amount: RpcUiTokenAmount, + #[serde(default)] + owner: Option, + #[serde(default)] + program_id: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcUiTokenAmount { + #[serde(default)] + ui_amount: Option, + decimals: u32, + amount: String, + #[serde(default)] + ui_amount_string: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcLoadedAddresses { + #[serde(default)] + writable: Vec, + #[serde(default)] + readonly: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcReturnData { + program_id: String, + data: (String, String), +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RpcReward { + pubkey: String, + lamports: i64, + post_balance: u64, + #[serde(default)] + reward_type: Option, + #[serde(default)] + commission: Option, +} + +fn convert_rpc_block(slot: u64, block: RpcConfirmedBlock) -> Result { + let blockhash = decode_hash32(&block.blockhash, "blockhash")?; + let previous_blockhash = decode_hash32(&block.previous_blockhash, "previousBlockhash")?; + + let rewards_proto = Rewards { + rewards: block.rewards.into_iter().map(convert_reward).collect(), + num_partitions: block + .num_reward_partitions + .map(|num_partitions| NumPartitions { num_partitions }), + } + .encode_to_vec(); + + let mut transactions = Vec::with_capacity(block.transactions.len()); + for (tx_idx, item) in block.transactions.into_iter().enumerate() { + let wire_bytes = decode_base64_tx(&item.transaction) + .with_context(|| format!("decode base64 tx {tx_idx} in slot {slot}"))?; + let meta = item + .meta + .with_context(|| format!("RPC getBlock({slot}) tx {tx_idx} is missing meta"))?; + let status_proto = convert_meta(meta) + .with_context(|| format!("encode status meta for tx {tx_idx} in slot {slot}"))? + .encode_to_vec(); + transactions.push(ArchiveTransaction { + wire_bytes, + status_proto, + }); + } + + // RPC getBlock does NOT expose PoH entries, shredding boundaries, Alpenglow + // consensus_block_id, or block_markers. Provide one placeholder entry matching + // transactions.len() so ArchiveBlockPayloadV1 encodes the getBlock bundle; + // the chunk manifest is ALWAYS tagged DEGRADED_SOURCE_RPC_ONLY so compaction + // refuses it until canonical CAR or local replay replaces this range. + let entries = if transactions.is_empty() { + vec![] + } else { + let tx_count = + u32::try_from(transactions.len()).context("RPC block transaction count overflows u32")?; + vec![ArchiveEntry { + num_hashes: 0, + hash: blockhash, + tx_count, + signature_count: 0, + }] + }; + + Ok(ArchiveBlockPayloadV1 { + slot, + parent_slot: block.parent_slot, + blockhash, + previous_blockhash, + block_time: block.block_time, + block_height: block.block_height, + consensus_block_id: [0; 32], + markers: vec![], + rewards_proto, + entries, + shredding: vec![], + transactions, + }) +} + +fn decode_hash32(s: &str, label: &str) -> Result<[u8; 32]> { + let bytes = bs58::decode(s) + .into_vec() + .with_context(|| format!("decode base58 {label} '{s}'"))?; + bytes + .try_into() + .map_err(|_| anyhow!("base58 {label} '{s}' is not 32 bytes")) +} + +fn decode_base64_tx(value: &Value) -> Result> { + let arr = value + .as_array() + .context("expected [base64, \"base64\"] array for RPC transaction")?; + ensure!( + arr.len() >= 2 && arr[1].as_str() == Some("base64"), + "expected base64 encoding for RPC transaction" + ); + let encoded = arr[0] + .as_str() + .context("expected base64 string in transaction[0]")?; + STANDARD + .decode(encoded) + .context("decode transaction base64 bytes") +} + +fn convert_reward(r: RpcReward) -> Reward { + let reward_type = match r.reward_type.as_deref().map(str::to_ascii_lowercase).as_deref() { + Some("fee") => RewardType::Fee as i32, + Some("rent") => RewardType::Rent as i32, + Some("staking") => RewardType::Staking as i32, + Some("voting") => RewardType::Voting as i32, + _ => RewardType::Unspecified as i32, + }; + Reward { + pubkey: r.pubkey, + lamports: r.lamports, + post_balance: r.post_balance, + reward_type, + commission: r.commission.map(|c| c.to_string()).unwrap_or_default(), + } +} + +fn convert_token_balance(tb: RpcTokenBalance) -> TokenBalance { + let ui_amount = tb.ui_token_amount.ui_amount.unwrap_or(0.0); + let ui_amount_string = tb + .ui_token_amount + .ui_amount_string + .unwrap_or_else(|| ui_amount.to_string()); + TokenBalance { + account_index: tb.account_index, + mint: tb.mint, + ui_token_amount: Some(UiTokenAmount { + ui_amount, + decimals: tb.ui_token_amount.decimals, + amount: tb.ui_token_amount.amount, + ui_amount_string, + }), + owner: tb.owner.unwrap_or_default(), + program_id: tb.program_id.unwrap_or_default(), + } +} + +fn convert_meta(meta: RpcTransactionStatusMeta) -> Result { + let err = match meta.err { + None | Some(Value::Null) => None, + Some(err_val) => { + let stored = parse_rpc_transaction_error(&err_val)?; + let bytes = wincode::serialize(&stored).context("serialize StoredTransactionError")?; + Some(TransactionError { err: bytes }) + } + }; + + let (inner_instructions, inner_instructions_none) = match meta.inner_instructions { + None => (Vec::new(), true), + Some(list) => { + let mut converted = Vec::with_capacity(list.len()); + for group in list { + let mut ixs = Vec::with_capacity(group.instructions.len()); + for ix in group.instructions { + let data = bs58::decode(&ix.data) + .into_vec() + .with_context(|| format!("decode inner ix base58 data '{}'", ix.data))?; + ixs.push(InnerInstruction { + program_id_index: ix.program_id_index, + accounts: ix.accounts, + data, + stack_height: ix.stack_height, + }); + } + converted.push(InnerInstructions { + index: group.index, + instructions: ixs, + }); + } + (converted, false) + } + }; + + let (log_messages, log_messages_none) = match meta.log_messages { + None => (Vec::new(), true), + Some(logs) => (logs, false), + }; + + let pre_token_balances = meta + .pre_token_balances + .unwrap_or_default() + .into_iter() + .map(convert_token_balance) + .collect(); + let post_token_balances = meta + .post_token_balances + .unwrap_or_default() + .into_iter() + .map(convert_token_balance) + .collect(); + let rewards = meta + .rewards + .unwrap_or_default() + .into_iter() + .map(convert_reward) + .collect(); + + let (loaded_writable_addresses, loaded_readonly_addresses) = match meta.loaded_addresses { + None => (Vec::new(), Vec::new()), + Some(loaded) => { + let mut writable = Vec::with_capacity(loaded.writable.len()); + for key in loaded.writable { + writable.push(decode_hash32(&key, "loadedAddresses.writable")?.to_vec()); + } + let mut readonly = Vec::with_capacity(loaded.readonly.len()); + for key in loaded.readonly { + readonly.push(decode_hash32(&key, "loadedAddresses.readonly")?.to_vec()); + } + (writable, readonly) + } + }; + + let (return_data, return_data_none) = match meta.return_data { + None => (None, true), + Some(rd) => { + ensure!( + rd.data.1 == "base64", + "unsupported returnData encoding '{}'", + rd.data.1 + ); + let program_id = decode_hash32(&rd.program_id, "returnData.programId")?.to_vec(); + let data = STANDARD + .decode(&rd.data.0) + .context("decode returnData base64")?; + (Some(ReturnData { program_id, data }), false) + } + }; + + Ok(TransactionStatusMeta { + err, + fee: meta.fee, + pre_balances: meta.pre_balances, + post_balances: meta.post_balances, + inner_instructions, + inner_instructions_none, + log_messages, + log_messages_none, + pre_token_balances, + post_token_balances, + rewards, + loaded_writable_addresses, + loaded_readonly_addresses, + return_data, + return_data_none, + compute_units_consumed: meta.compute_units_consumed, + cost_units: meta.cost_units, + }) +} + +fn parse_rpc_transaction_error(value: &Value) -> Result { + if let Some(name) = value.as_str() { + return match name { + "AccountInUse" => Ok(StoredTransactionError::AccountInUse), + "AccountLoadedTwice" => Ok(StoredTransactionError::AccountLoadedTwice), + "AccountNotFound" => Ok(StoredTransactionError::AccountNotFound), + "ProgramAccountNotFound" => Ok(StoredTransactionError::ProgramAccountNotFound), + "InsufficientFundsForFee" => Ok(StoredTransactionError::InsufficientFundsForFee), + "InvalidAccountForFee" => Ok(StoredTransactionError::InvalidAccountForFee), + "AlreadyProcessed" => Ok(StoredTransactionError::AlreadyProcessed), + "BlockhashNotFound" => Ok(StoredTransactionError::BlockhashNotFound), + "CallChainTooDeep" => Ok(StoredTransactionError::CallChainTooDeep), + "MissingSignatureForFee" => Ok(StoredTransactionError::MissingSignatureForFee), + "InvalidAccountIndex" => Ok(StoredTransactionError::InvalidAccountIndex), + "SignatureFailure" => Ok(StoredTransactionError::SignatureFailure), + "InvalidProgramForExecution" => Ok(StoredTransactionError::InvalidProgramForExecution), + "SanitizeFailure" => Ok(StoredTransactionError::SanitizeFailure), + "ClusterMaintenance" => Ok(StoredTransactionError::ClusterMaintenance), + "AccountBorrowOutstanding" => Ok(StoredTransactionError::AccountBorrowOutstanding), + "WouldExceedMaxBlockCostLimit" => { + Ok(StoredTransactionError::WouldExceedMaxBlockCostLimit) + } + "UnsupportedVersion" => Ok(StoredTransactionError::UnsupportedVersion), + "InvalidWritableAccount" => Ok(StoredTransactionError::InvalidWritableAccount), + "WouldExceedMaxAccountCostLimit" => { + Ok(StoredTransactionError::WouldExceedMaxAccountCostLimit) + } + "WouldExceedAccountDataBlockLimit" => { + Ok(StoredTransactionError::WouldExceedAccountDataBlockLimit) + } + "TooManyAccountLocks" => Ok(StoredTransactionError::TooManyAccountLocks), + "AddressLookupTableNotFound" => Ok(StoredTransactionError::AddressLookupTableNotFound), + "InvalidAddressLookupTableOwner" => { + Ok(StoredTransactionError::InvalidAddressLookupTableOwner) + } + "InvalidAddressLookupTableData" => { + Ok(StoredTransactionError::InvalidAddressLookupTableData) + } + "InvalidAddressLookupTableIndex" => { + Ok(StoredTransactionError::InvalidAddressLookupTableIndex) + } + "InvalidRentPayingAccount" => Ok(StoredTransactionError::InvalidRentPayingAccount), + "WouldExceedMaxVoteCostLimit" => { + Ok(StoredTransactionError::WouldExceedMaxVoteCostLimit) + } + "WouldExceedAccountDataTotalLimit" => { + Ok(StoredTransactionError::WouldExceedAccountDataTotalLimit) + } + "MaxLoadedAccountsDataSizeExceeded" => { + Ok(StoredTransactionError::MaxLoadedAccountsDataSizeExceeded) + } + "InvalidLoadedAccountsDataSizeLimit" => { + Ok(StoredTransactionError::InvalidLoadedAccountsDataSizeLimit) + } + "ResanitizationNeeded" => Ok(StoredTransactionError::ResanitizationNeeded), + "UnbalancedTransaction" => Ok(StoredTransactionError::UnbalancedTransaction), + "ProgramCacheHitMaxLimit" => Ok(StoredTransactionError::ProgramCacheHitMaxLimit), + "CommitCancelled" => Ok(StoredTransactionError::CommitCancelled), + other => bail!("unsupported RPC TransactionError variant '{other}'"), + }; + } + + let obj = value + .as_object() + .with_context(|| format!("unexpected RPC TransactionError JSON: {value}"))?; + if let Some(arr) = obj.get("InstructionError").and_then(Value::as_array) { + ensure!( + arr.len() == 2, + "InstructionError JSON must be a 2-element array: {value}" + ); + let idx = u8::try_from( + arr[0] + .as_u64() + .context("InstructionError index must be integer")?, + ) + .context("InstructionError index overflows u8")?; + let ix_err = parse_rpc_instruction_error(&arr[1])?; + return Ok(StoredTransactionError::InstructionError(idx, ix_err)); + } + if let Some(idx) = obj.get("DuplicateInstruction").and_then(Value::as_u64) { + return Ok(StoredTransactionError::DuplicateInstruction( + u8::try_from(idx).context("DuplicateInstruction overflows u8")?, + )); + } + if let Some(inner) = obj.get("InsufficientFundsForRent").and_then(Value::as_object) { + let idx = inner + .get("account_index") + .and_then(Value::as_u64) + .context("InsufficientFundsForRent missing account_index")?; + return Ok(StoredTransactionError::InsufficientFundsForRent { + account_index: u8::try_from(idx).context("account_index overflows u8")?, + }); + } + if let Some(inner) = obj + .get("ProgramExecutionTemporarilyRestricted") + .and_then(Value::as_object) + { + let idx = inner + .get("account_index") + .and_then(Value::as_u64) + .context("ProgramExecutionTemporarilyRestricted missing account_index")?; + return Ok(StoredTransactionError::ProgramExecutionTemporarilyRestricted { + account_index: u8::try_from(idx).context("account_index overflows u8")?, + }); + } + bail!("unsupported RPC TransactionError object: {value}") +} + +fn parse_rpc_instruction_error(value: &Value) -> Result { + if let Some(name) = value.as_str() { + return match name { + "GenericError" => Ok(InstructionError::GenericError), + "InvalidArgument" => Ok(InstructionError::InvalidArgument), + "InvalidInstructionData" => Ok(InstructionError::InvalidInstructionData), + "InvalidAccountData" => Ok(InstructionError::InvalidAccountData), + "AccountDataTooSmall" => Ok(InstructionError::AccountDataTooSmall), + "InsufficientFunds" => Ok(InstructionError::InsufficientFunds), + "IncorrectProgramId" => Ok(InstructionError::IncorrectProgramId), + "MissingRequiredSignature" => Ok(InstructionError::MissingRequiredSignature), + "AccountAlreadyInitialized" => Ok(InstructionError::AccountAlreadyInitialized), + "UninitializedAccount" => Ok(InstructionError::UninitializedAccount), + "UnbalancedInstruction" => Ok(InstructionError::UnbalancedInstruction), + "ModifiedProgramId" => Ok(InstructionError::ModifiedProgramId), + "ExternalAccountLamportSpend" => Ok(InstructionError::ExternalAccountLamportSpend), + "ExternalAccountDataModified" => Ok(InstructionError::ExternalAccountDataModified), + "ReadonlyLamportChange" => Ok(InstructionError::ReadonlyLamportChange), + "ReadonlyDataModified" => Ok(InstructionError::ReadonlyDataModified), + "DuplicateAccountIndex" => Ok(InstructionError::DuplicateAccountIndex), + "ExecutableModified" => Ok(InstructionError::ExecutableModified), + "RentEpochModified" => Ok(InstructionError::RentEpochModified), + "NotEnoughAccountKeys" => Ok(InstructionError::NotEnoughAccountKeys), + "AccountDataSizeChanged" => Ok(InstructionError::AccountDataSizeChanged), + "AccountNotExecutable" => Ok(InstructionError::AccountNotExecutable), + "AccountBorrowFailed" => Ok(InstructionError::AccountBorrowFailed), + "AccountBorrowOutstanding" => Ok(InstructionError::AccountBorrowOutstanding), + "DuplicateAccountOutOfSync" => Ok(InstructionError::DuplicateAccountOutOfSync), + "InvalidError" => Ok(InstructionError::InvalidError), + "ExecutableDataModified" => Ok(InstructionError::ExecutableDataModified), + "ExecutableLamportChange" => Ok(InstructionError::ExecutableLamportChange), + "ExecutableAccountNotRentExempt" => { + Ok(InstructionError::ExecutableAccountNotRentExempt) + } + "UnsupportedProgramId" => Ok(InstructionError::UnsupportedProgramId), + "CallDepth" => Ok(InstructionError::CallDepth), + "MissingAccount" => Ok(InstructionError::MissingAccount), + "ReentrancyNotAllowed" => Ok(InstructionError::ReentrancyNotAllowed), + "MaxSeedLengthExceeded" => Ok(InstructionError::MaxSeedLengthExceeded), + "InvalidSeeds" => Ok(InstructionError::InvalidSeeds), + "InvalidRealloc" => Ok(InstructionError::InvalidRealloc), + "ComputationalBudgetExceeded" => Ok(InstructionError::ComputationalBudgetExceeded), + "PrivilegeEscalation" => Ok(InstructionError::PrivilegeEscalation), + "ProgramEnvironmentSetupFailure" => { + Ok(InstructionError::ProgramEnvironmentSetupFailure) + } + "ProgramFailedToComplete" => Ok(InstructionError::ProgramFailedToComplete), + "ProgramFailedToCompile" => Ok(InstructionError::ProgramFailedToCompile), + "Immutable" => Ok(InstructionError::Immutable), + "IncorrectAuthority" => Ok(InstructionError::IncorrectAuthority), + "AccountNotRentExempt" => Ok(InstructionError::AccountNotRentExempt), + "InvalidAccountOwner" => Ok(InstructionError::InvalidAccountOwner), + "ArithmeticOverflow" => Ok(InstructionError::ArithmeticOverflow), + "UnsupportedSysvar" => Ok(InstructionError::UnsupportedSysvar), + "IllegalOwner" => Ok(InstructionError::IllegalOwner), + "MaxAccountsDataAllocationsExceeded" => { + Ok(InstructionError::MaxAccountsDataAllocationsExceeded) + } + "MaxAccountsExceeded" => Ok(InstructionError::MaxAccountsExceeded), + "MaxInstructionTraceLengthExceeded" => { + Ok(InstructionError::MaxInstructionTraceLengthExceeded) + } + "BuiltinProgramsMustConsumeComputeUnits" => { + Ok(InstructionError::BuiltinProgramsMustConsumeComputeUnits) + } + other => bail!("unsupported RPC InstructionError variant '{other}'"), + }; + } + + let obj = value + .as_object() + .with_context(|| format!("unexpected RPC InstructionError JSON: {value}"))?; + if let Some(code) = obj.get("Custom").and_then(Value::as_u64) { + return Ok(InstructionError::Custom( + u32::try_from(code).context("Custom InstructionError overflows u32")?, + )); + } + if let Some(msg) = obj.get("BorshIoError").and_then(Value::as_str) { + return Ok(InstructionError::BorshIoError(msg.to_owned())); + } + bail!("unsupported RPC InstructionError object: {value}") +} diff --git a/blockzilla/finalized-ledger/src/tests.rs b/blockzilla/finalized-ledger/src/tests.rs new file mode 100644 index 00000000..8b9a0bb7 --- /dev/null +++ b/blockzilla/finalized-ledger/src/tests.rs @@ -0,0 +1,1372 @@ +use std::collections::HashMap; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::os::unix::net::UnixListener; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use base64::{Engine, engine::general_purpose::STANDARD}; +use blockzilla_account_bridge_protocol::{ + ArchiveBlockEnvelope, ArchiveBlockPayloadV1, ArchiveEntry, ArchiveShredGroup, + ArchiveTransaction, LedgerStatus, Operation, Response, ResponseData, SlotBlockhash, + SlotChainRelation, SlotInspection, SlotStateCode, SlotStates, SourceIdentity, read_request, + write_response, +}; +use blockzilla_compact_v2_reader::{ + ArchiveReader, HashVerification, LocalRangeSource, OpenOptions, TrustedGenerationIdentity, +}; +use blockzilla_finalized_chunks::{ + CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, + CHUNK_MANIFEST_FILE, ChunkCatalogLookup, ChunkCatalogReader, ChunkManifestV1, ChunkSlotKind, + ChunkStorageMode, DEGRADED_SOURCE_RPC_ONLY, EPOCH_ARCHIVE_FILES, LocalChunkSource, + SLOTS_PER_EPOCH, chunk_dir_name, compact, +}; +use sha2::{Digest, Sha256}; + +use crate::admin_rpc::{self, HistoricalRecoveryPhase, HistoricalRecoveryStatus}; +use crate::drain::{CatalogOptions, DrainConfig, PurgeOptions, run_drain}; +use crate::notify::{TelegramConfig, redact_token}; +use crate::r2::{R2ChunkSource, R2Client, R2Settings}; +use crate::recovery::{GapFailureReceipt, GapFallbackPolicy, GapFallbackStatus, GapRecoveryConfig}; + +fn source_identity() -> SourceIdentity { + SourceIdentity { + genesis_hash: hash_b58(1), + node_identity: hash_b58(2), + instance_id: "validator-instance-01".into(), + agave_revision: "v4.4.2-blockzilla".into(), + } +} + +fn hash_b58(byte: u8) -> String { + // Simple canonical 32-byte base58 via standard alphabet using fixed 32-byte arrays. + let mut digits = [0u8; 45]; + // Use known valid base58 encoding by encoding with manual base58 helper. + let raw = [byte; 32]; + encode_base58(&raw, &mut digits) +} + +fn encode_base58(input: &[u8], _scratch: &mut [u8]) -> String { + const ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + let mut zeros = 0; + while zeros < input.len() && input[zeros] == 0 { + zeros += 1; + } + let mut b58 = vec![0u8; (input.len() - zeros) * 138 / 100 + 1]; + let mut length = 0; + for &byte in &input[zeros..] { + let mut carry = byte as u32; + let mut i = 0; + for elem in b58.iter_mut().rev() { + if carry == 0 && i >= length { + break; + } + carry += 256 * (*elem as u32); + *elem = (carry % 58) as u8; + carry /= 58; + i += 1; + } + length = i; + } + let start = b58.iter().position(|&v| v != 0).unwrap_or(b58.len()); + let mut out = String::with_capacity(zeros + b58.len() - start); + for _ in 0..zeros { + out.push('1'); + } + for &digit in &b58[start..] { + out.push(ALPHABET[digit as usize] as char); + } + out +} + +fn build_legacy_tx(sig: [u8; 64], keys: &[[u8; 32]], recent_blockhash: [u8; 32]) -> Vec { + let mut out = Vec::new(); + out.push(1); // 1 signature + out.extend_from_slice(&sig); + out.extend_from_slice(&[1, 0, 1]); // header + out.push(keys.len() as u8); + for k in keys { + out.extend_from_slice(k); + } + out.extend_from_slice(&recent_blockhash); + out.push(1); // 1 ix + out.push(1); // program_id_index + out.push(1); // accounts len + out.push(0); // account[0] + out.push(2); // data len + out.extend_from_slice(&[0xaa, 0xbb]); + out +} + +fn make_envelope( + slot: u64, + parent_slot: u64, + blockhash: [u8; 32], + previous_blockhash: [u8; 32], + tx_sig: [u8; 64], + recent_bh: [u8; 32], +) -> ArchiveBlockEnvelope { + let payload = ArchiveBlockPayloadV1 { + slot, + parent_slot, + blockhash, + previous_blockhash, + block_time: Some(1_700_000_000 + slot as i64), + block_height: Some(slot - SLOTS_PER_EPOCH + 100), + consensus_block_id: [0x99; 32], + markers: vec![], + rewards_proto: vec![], + entries: vec![ArchiveEntry { + num_hashes: 5, + hash: blockhash, + tx_count: 1, + signature_count: 1, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 2, + }], + transactions: vec![ArchiveTransaction { + wire_bytes: build_legacy_tx(tx_sig, &[[0x11; 32], [0x22; 32]], recent_bh), + // Empty proto decodes as default TransactionStatusMeta (err=None, fee=0). + status_proto: vec![], + }], + }; + let raw = payload.encode().unwrap(); + let sha = hex::encode(Sha256::digest(&raw)); + let compressed = zstd::bulk::compress(&raw, 1).unwrap(); + ArchiveBlockEnvelope { + slot, + parent_slot, + blockhash: encode_base58(&blockhash, &mut []), + previous_blockhash: encode_base58(&previous_blockhash, &mut []), + consensus_block_id: encode_base58(&[0x99; 32], &mut []), + payload_uncompressed_len: raw.len() as u32, + payload_sha256: sha, + payload_zstd_base64: STANDARD.encode(compressed), + } +} + +#[derive(Clone)] +struct StoredObject { + body: Vec, + etag: String, + sha256_meta: Option, +} + +/// Minimal in-process loopback S3/R2 HTTP server supporting PUT, HEAD, GET, +/// and ListObjectsV2 (`list-type=2&prefix=...`). +struct MockR2Server { + endpoint: String, + bucket: String, + objects: Arc>>, + stop: Arc, + handle: Option>, +} + +impl MockR2Server { + fn start(bucket: &str) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let addr = listener.local_addr().unwrap(); + let objects: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + let stop = Arc::new(AtomicBool::new(false)); + let objs_clone = objects.clone(); + let stop_clone = stop.clone(); + let bucket_owned = bucket.to_owned(); + + let handle = thread::spawn(move || { + while !stop_clone.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let _ = handle_http_conn(&mut stream, &bucket_owned, &objs_clone); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + Self { + endpoint: format!("http://{addr}"), + bucket: bucket.to_owned(), + objects, + stop, + handle: Some(handle), + } + } + + fn settings(&self, prefix: &str) -> R2Settings { + R2Settings { + endpoint: self.endpoint.clone(), + bucket: self.bucket.clone(), + prefix: prefix.to_owned(), + region: "auto".into(), + access_key: "test-ak".into(), + secret_key: "test-sk".into(), + allow_http_loopback: true, + } + } +} + +impl Drop for MockR2Server { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + } +} + +fn handle_http_conn( + stream: &mut std::net::TcpStream, + bucket: &str, + objects: &Arc>>, +) -> std::io::Result<()> { + let mut reader = BufReader::new(stream.try_clone()?); + let mut req_line = String::new(); + if reader.read_line(&mut req_line)? == 0 { + return Ok(()); + } + let parts: Vec<&str> = req_line.split_whitespace().collect(); + if parts.len() < 2 { + return Ok(()); + } + let method = parts[0]; + let target = parts[1]; + + let mut headers = HashMap::new(); + loop { + let mut line = String::new(); + reader.read_line(&mut line)?; + let trimmed = line.trim_end_matches(['\r', '\n']); + if trimmed.is_empty() { + break; + } + if let Some((k, v)) = trimmed.split_once(':') { + headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned()); + } + } + + let content_len: usize = headers + .get("content-length") + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + let mut body = vec![0u8; content_len]; + if content_len > 0 { + reader.read_exact(&mut body)?; + } + + let (path, query) = target.split_once('?').unwrap_or((target, "")); + let bucket_prefix = format!("/{bucket}"); + let key = path + .strip_prefix(&bucket_prefix) + .unwrap_or("") + .trim_start_matches('/') + .to_owned(); + + match method { + "PUT" => { + let etag = format!("\"{}\"", hex::encode(&Sha256::digest(&body)[..16])); + let sha_meta = headers.get("x-amz-meta-blockzilla-sha256").cloned(); + objects.lock().unwrap().insert( + key, + StoredObject { + body, + etag: etag.clone(), + sha256_meta: sha_meta, + }, + ); + write!( + stream, + "HTTP/1.1 200 OK\r\nETag: {etag}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + )?; + } + "HEAD" => { + let guard = objects.lock().unwrap(); + if let Some(obj) = guard.get(&key) { + let mut resp = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nETag: {}\r\n", + obj.body.len(), + obj.etag + ); + if let Some(sha) = &obj.sha256_meta { + resp.push_str(&format!("x-amz-meta-blockzilla-sha256: {sha}\r\n")); + } + resp.push_str("Connection: close\r\n\r\n"); + stream.write_all(resp.as_bytes())?; + } else { + stream.write_all( + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + )?; + } + } + "GET" if key.is_empty() && query.contains("list-type=2") => { + let prefix_param = query + .split('&') + .find_map(|pair| pair.strip_prefix("prefix=")) + .map(percent_decode) + .unwrap_or_default(); + let guard = objects.lock().unwrap(); + let mut matched: Vec<&String> = guard + .keys() + .filter(|k| k.starts_with(&prefix_param)) + .collect(); + matched.sort(); + let mut xml = String::from("false"); + for k in matched { + xml.push_str(&format!("{k}")); + } + xml.push_str(""); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + xml.len(), + xml + )?; + } + "GET" => { + let guard = objects.lock().unwrap(); + if let Some(obj) = guard.get(&key) { + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nETag: {}\r\nConnection: close\r\n\r\n", + obj.body.len(), + obj.etag + )?; + stream.write_all(&obj.body)?; + } else { + stream.write_all( + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + )?; + } + } + _ => { + stream.write_all( + b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + )?; + } + } + stream.flush() +} + +fn percent_decode(input: &str) -> String { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && i + 2 < bytes.len() + && let Ok(hex_str) = std::str::from_utf8(&bytes[i + 1..i + 3]) + && let Ok(val) = u8::from_str_radix(hex_str, 16) + { + out.push(val); + i += 3; + continue; + } + out.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +#[tokio::test] +async fn end_to_end_drain_r2_catalog_evict_purge_and_streaming_compact() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let ledger_dir = root.path().join("ledger"); + std::fs::create_dir(&ledger_dir).unwrap(); + let admin_sock = ledger_dir.join("admin.rpc"); + let output_dir = root.path().join("finalized-chunks"); + let catalog_path = root.path().join("chunk_catalog.sqlite"); + let archive_out = root.path().join("epoch-1-archive"); + + let s0 = SLOTS_PER_EPOCH; // 432_000 + let parent_bh = [0x40; 32]; + let bh0 = [0x41; 32]; + let bh2 = [0x42; 32]; + let bh4 = [0x44; 32]; + let bh7 = [0x47; 32]; + + let envelopes = HashMap::from([ + (s0, make_envelope(s0, s0 - 1, bh0, parent_bh, [0xd0; 64], parent_bh)), + (s0 + 2, make_envelope(s0 + 2, s0, bh2, bh0, [0xd2; 64], bh0)), + (s0 + 4, make_envelope(s0 + 4, s0 + 2, bh4, bh2, [0xd4; 64], bh2)), + (s0 + 7, make_envelope(s0 + 7, s0 + 4, bh7, bh4, [0xd7; 64], bh4)), + ]); + + // 1. Start mock Agave native-account-bridge Unix server. + let bridge_stop = Arc::new(AtomicBool::new(false)); + let bridge_stop_clone = bridge_stop.clone(); + let bridge_listener = UnixListener::bind(&bridge_sock).unwrap(); + bridge_listener.set_nonblocking(true).unwrap(); + let bridge_handle = thread::spawn(move || { + while !bridge_stop_clone.load(Ordering::Relaxed) { + match bridge_listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let req = read_request(&mut stream).unwrap(); + let data = match &req.operation { + Operation::GetLedgerStatus => ResponseData::GetLedgerStatus { + status: LedgerStatus { + lowest_slot: s0, + lowest_cleanup_slot: s0 - 10, + // Rooted past s0 + 7 + 8 = s0 + 15 so 2 chunks of 4 slots seal! + max_root: s0 + 15, + highest_slot: Some(s0 + 20), + }, + }, + Operation::GetSlotStates { + start_slot, + end_slot, + } => { + let mut states = Vec::new(); + for slot in *start_slot..=*end_slot { + let code = if envelopes.contains_key(&slot) { + SlotStateCode::RootedFull + } else if slot == s0 + 3 { + SlotStateCode::NonRoot + } else { + SlotStateCode::Absent + }; + states.push(code); + } + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: *start_slot, + end_slot: *end_slot, + states, + }, + } + } + Operation::GetAncestorBlockhashes { before_slot, .. } => { + assert_eq!(*before_slot, s0); + ResponseData::GetAncestorBlockhashes { + ancestors: vec![SlotBlockhash { + slot: s0 - 1, + blockhash: encode_base58(&parent_bh, &mut []), + }], + } + } + Operation::InspectSlot { + slot, + include_markers, + } => { + if *include_markers { + // Carrier slot without footer markers -> triggers parent-chain fallback. + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: SlotStateCode::RootedFull, + parent_slot: Some(*slot - 1), + blockhash: Some(hash_b58(0x55)), + chain_relation: None, + markers_base64: None, + }, + } + } else { + let next_root = if *slot < s0 + 2 { + s0 + 2 + } else if *slot < s0 + 4 { + s0 + 4 + } else { + s0 + 7 + }; + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: if *slot == s0 + 3 { + SlotStateCode::NonRoot + } else { + SlotStateCode::Absent + }, + parent_slot: None, + blockhash: None, + chain_relation: Some(SlotChainRelation::JumpsOver { + next_root, + }), + markers_base64: None, + }, + } + } + } + Operation::GetArchiveBlock { slot, .. } => ResponseData::GetArchiveBlock { + block: envelopes.get(slot).cloned().expect("block envelope"), + }, + other => panic!("unexpected bridge op {other:?}"), + }; + let resp = Response::ok(&req, source_identity(), data); + write_response(&mut stream, &resp).unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + // 2. Start mock Agave admin.rpc Unix server recording blockstorePurge slots. + let purged_slots = Arc::new(Mutex::new(Vec::::new())); + let purged_clone = purged_slots.clone(); + let admin_stop = Arc::new(AtomicBool::new(false)); + let admin_stop_clone = admin_stop.clone(); + let admin_listener = UnixListener::bind(&admin_sock).unwrap(); + admin_listener.set_nonblocking(true).unwrap(); + let admin_handle = thread::spawn(move || { + while !admin_stop_clone.load(Ordering::Relaxed) { + match admin_listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let mut line = String::new(); + BufReader::new(stream.try_clone().unwrap()) + .read_line(&mut line) + .unwrap(); + let req: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(req["method"], "blockstorePurge"); + let slot = req["params"][0].as_u64().unwrap(); + purged_clone.lock().unwrap().push(slot); + stream + .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":null}\n") + .unwrap(); + stream.flush().unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + // 3. Start mock S3/R2 HTTP server. + let r2_server = MockR2Server::start("blockzilla-test"); + let r2_settings = r2_server.settings("finalized-chunks/mainnet"); + + // 4. Run drain-chunks in `--once` mode: seals 2 chunks (4 slots each), uploads + // to R2, commits catalog, evicts local bulk payloads, and triggers admin.rpc purge! + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: true, + poll_interval: Duration::from_millis(50), + r2: Some(r2_settings.clone()), + catalog: Some(CatalogOptions { + path: catalog_path.clone(), + generation: "gen-e2e-1".into(), + prefix: "finalized-chunks/mainnet".into(), + }), + evict_local_payloads: true, + purge: Some(PurgeOptions { + ledger_dir: ledger_dir.clone(), + safety_tail: 300, + rpc_timeout: Duration::from_secs(5), + }), + gap_recovery: GapRecoveryConfig::default(), + }) + .await + .expect("run_drain end-to-end"); + + assert_eq!(summary.chunks_sealed, 2); + assert_eq!(summary.blocks_sealed, 4); + assert_eq!(summary.skips_sealed, 3); + assert_eq!(summary.forks_sealed, 1); + assert_eq!(summary.highest_sealed_slot, Some(s0 + 7)); + assert_eq!(summary.highest_purged_slot, Some(s0 + 7 - 300)); + assert_eq!(r2_server.objects.lock().unwrap().len(), 10); + + // Verify admin.rpc received both monotonic blockstorePurge calls behind safety_tail=300! + assert_eq!( + *purged_slots.lock().unwrap(), + vec![s0 + 3 - 300, s0 + 7 - 300] + ); + + // Verify local bulk payloads were evicted while index + manifest remain on disk! + let c1_dir = output_dir + .join("epoch-1") + .join(chunk_dir_name(s0, s0 + 3)); + assert!(!c1_dir.join(CHUNK_BUNDLES_FILE).exists()); + assert!(!c1_dir.join(CHUNK_EXTRAS_FILE).exists()); + assert!(!c1_dir.join(CHUNK_COUNTS_FILE).exists()); + assert!(c1_dir.join(CHUNK_INDEX_FILE).is_file()); + assert!(c1_dir.join(CHUNK_MANIFEST_FILE).is_file()); + + // Verify SQLite catalog resolves R2 range locators and ProvenSkip / AbandonedFork! + let canonical_catalog = catalog_path.canonicalize().unwrap(); + match ChunkCatalogReader::lookup( + &canonical_catalog, + "gen-e2e-1", + "finalized-chunks/mainnet", + s0 + 2, + ) + .unwrap() + .unwrap() + { + ChunkCatalogLookup::ProducedBlock { + storage_mode, + bundles_etag, + .. + } => { + assert_eq!(storage_mode, ChunkStorageMode::R2); + assert!(bundles_etag.is_some()); + } + other => panic!("expected R2 ProducedBlock, got {other:?}"), + } + assert_eq!( + ChunkCatalogReader::lookup( + &canonical_catalog, + "gen-e2e-1", + "finalized-chunks/mainnet", + s0 + 3, + ) + .unwrap(), + Some(ChunkCatalogLookup::Skipped { + epoch: 1, + kind: ChunkSlotKind::AbandonedFork, + }) + ); + + // 5. Compact epoch 1 range streaming DIRECTLY over HTTP from mock R2 (zero local bulk files!). + let archive_out_clone = archive_out.clone(); + let report = tokio::task::spawn_blocking(move || { + let r2_client = R2Client::new(r2_settings).unwrap(); + let r2_source = R2ChunkSource::new(r2_client); + compact::compact_range_from_chunks(&r2_source, 1, s0, s0 + 7, &archive_out_clone, 1, None) + }) + .await + .unwrap() + .expect("streaming compaction from R2"); + assert_eq!(report.chunks_processed, 2); + assert_eq!(report.blocks, 4); + assert_eq!(report.skips, 3); + assert_eq!(report.forks, 1); + assert_eq!(report.transactions, 4); + + for file in EPOCH_ARCHIVE_FILES { + assert!(archive_out.join(file).is_file(), "missing {file}"); + } + + // Open compacted output with real Compact V2 reader! + let reader = ArchiveReader::open_trusted( + LocalRangeSource::new(&archive_out), + TrustedGenerationIdentity { + cluster_id: "mainnet-beta".into(), + epoch: 1, + generation_id: "r2-stream-test".into(), + slots_per_epoch: SLOTS_PER_EPOCH, + }, + OpenOptions { + hash_verification: HashVerification::SizesOnly, + ..OpenOptions::default() + }, + ) + .expect("ArchiveReader::open_trusted on R2-streamed compaction"); + assert_eq!(reader.index().rows.len(), 4); + assert_eq!(reader.read_signature_ordinal(0).unwrap(), [0xd0; 64]); + assert_eq!(reader.read_signature_ordinal(3).unwrap(), [0xd7; 64]); + + bridge_stop.store(true, Ordering::Relaxed); + admin_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); + admin_handle.join().unwrap(); +} + +#[tokio::test] +async fn admin_rpc_blockstore_purge_surfaces_jsonrpc_errors() { + let dir = tempfile::tempdir().unwrap(); + let sock = dir.path().join("admin.rpc"); + let listener = UnixListener::bind(&sock).unwrap(); + let server = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut line = String::new(); + BufReader::new(stream.try_clone().unwrap()) + .read_line(&mut line) + .unwrap(); + stream + .write_all( + b"{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32600,\"message\":\"slot ahead of max root\"}}\n", + ) + .unwrap(); + stream.flush().unwrap(); + }); + let err = admin_rpc::blockstore_purge(dir.path(), 999_999, Duration::from_secs(5)) + .await + .unwrap_err(); + assert!(err.to_string().contains("slot ahead of max root")); + server.join().unwrap(); +} + +struct MockHttpJsonServer { + url: String, + requests: Arc>>, + stop: Arc, + handle: Option>, +} + +impl MockHttpJsonServer { + fn start(handler: F) -> Self + where + F: Fn(&str, &str) -> (u16, String) + Send + Sync + 'static, + { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let addr = listener.local_addr().unwrap(); + let requests = Arc::new(Mutex::new(Vec::new())); + let reqs_clone = requests.clone(); + let stop = Arc::new(AtomicBool::new(false)); + let stop_clone = stop.clone(); + let handler = Arc::new(handler); + + let handle = thread::spawn(move || { + while !stop_clone.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut req_line = String::new(); + if reader.read_line(&mut req_line).unwrap_or(0) == 0 { + continue; + } + let path = req_line + .split_whitespace() + .nth(1) + .unwrap_or("/") + .to_owned(); + let mut content_len = 0usize; + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let trimmed = line.trim_end_matches(['\r', '\n']); + if trimmed.is_empty() { + break; + } + if let Some((k, v)) = trimmed.split_once(':') + && k.trim().eq_ignore_ascii_case("content-length") + { + content_len = v.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; content_len]; + if content_len > 0 { + reader.read_exact(&mut body).unwrap(); + } + let body_str = String::from_utf8_lossy(&body).into_owned(); + reqs_clone.lock().unwrap().push((path.clone(), body_str.clone())); + let (status, resp_body) = handler(&path, &body_str); + let reason = if status == 200 { "OK" } else { "Error" }; + let _ = write!( + stream, + "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{resp_body}", + resp_body.len() + ); + let _ = stream.flush(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + Self { + url: format!("http://{addr}"), + requests, + stop, + handle: Some(handle), + } + } +} + +impl Drop for MockHttpJsonServer { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + } +} + +fn spawn_mock_live_bridge_at_tip( + bridge_sock: &std::path::Path, + lowest_slot: u64, + envelopes: HashMap, + max_root: u64, +) -> (Arc, thread::JoinHandle<()>) { + let stop = Arc::new(AtomicBool::new(false)); + let stop_clone = stop.clone(); + let listener = UnixListener::bind(bridge_sock).unwrap(); + listener.set_nonblocking(true).unwrap(); + let handle = thread::spawn(move || { + while !stop_clone.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let req = read_request(&mut stream).unwrap(); + let data = match &req.operation { + Operation::GetLedgerStatus => ResponseData::GetLedgerStatus { + status: LedgerStatus { + lowest_slot, + lowest_cleanup_slot: lowest_slot, + max_root, + highest_slot: Some(max_root + 4), + }, + }, + Operation::GetSlotStates { + start_slot, + end_slot, + } => { + let states = (*start_slot..=*end_slot) + .map(|slot| { + if envelopes.contains_key(&slot) { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + } + }) + .collect(); + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: *start_slot, + end_slot: *end_slot, + states, + }, + } + } + Operation::InspectSlot { + slot, + include_markers, + } => { + if *include_markers { + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: SlotStateCode::RootedFull, + parent_slot: Some(*slot - 1), + blockhash: Some(hash_b58(0x55)), + chain_relation: None, + markers_base64: None, + }, + } + } else { + let next_root = envelopes + .keys() + .copied() + .filter(|k| *k > *slot) + .min() + .unwrap_or(max_root); + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: SlotStateCode::Absent, + parent_slot: None, + blockhash: None, + chain_relation: Some(SlotChainRelation::JumpsOver { + next_root, + }), + markers_base64: None, + }, + } + } + } + Operation::GetArchiveBlock { slot, .. } => ResponseData::GetArchiveBlock { + block: envelopes.get(slot).cloned().expect("live envelope"), + }, + other => panic!("unexpected live bridge op {other:?}"), + }; + let resp = Response::ok(&req, source_identity(), data); + write_response(&mut stream, &resp).unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + (stop, handle) +} + +#[tokio::test] +async fn restart_gap_drains_live_immediately_and_wait_for_car_writes_receipt_and_alerts_telegram() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let ledger_dir = root.path().join("ledger"); + std::fs::create_dir(&ledger_dir).unwrap(); + let admin_sock = ledger_dir.join("admin.rpc"); + let output_dir = root.path().join("finalized-chunks"); + + let s0 = SLOTS_PER_EPOCH; // 432_000 + // Gap is [s0 ..= s0 + 3]; validator restarted from fresh snapshot at s0 + 4! + let live_start = s0 + 4; + let bh2 = [0x42; 32]; + let bh4 = [0x44; 32]; + let bh7 = [0x47; 32]; + let live_envelopes = HashMap::from([ + ( + live_start, + make_envelope(live_start, s0 + 2, bh4, bh2, [0xe4; 64], bh2), + ), + ( + live_start + 3, + make_envelope(live_start + 3, live_start, bh7, bh4, [0xe7; 64], bh4), + ), + ]); + let (bridge_stop, bridge_handle) = + spawn_mock_live_bridge_at_tip(&bridge_sock, live_start, live_envelopes, live_start + 12); + + // Mock admin.rpc: records startHistoricalRecovery(s0, s0 + 3), returns Running once then Incomplete. + let admin_stop = Arc::new(AtomicBool::new(false)); + let admin_stop_clone = admin_stop.clone(); + let start_calls = Arc::new(Mutex::new(Vec::<(u64, u64)>::new())); + let start_calls_clone = start_calls.clone(); + let admin_listener = UnixListener::bind(&admin_sock).unwrap(); + admin_listener.set_nonblocking(true).unwrap(); + let admin_handle = thread::spawn(move || { + let mut status_polls = 0u32; + while !admin_stop_clone.load(Ordering::Relaxed) { + match admin_listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let mut line = String::new(); + BufReader::new(stream.try_clone().unwrap()) + .read_line(&mut line) + .unwrap(); + let req: serde_json::Value = serde_json::from_str(&line).unwrap(); + let reply = match req["method"].as_str().unwrap() { + "startHistoricalRecovery" => { + let start = req["params"][0].as_u64().unwrap(); + let end = req["params"][1].as_u64().unwrap(); + start_calls_clone.lock().unwrap().push((start, end)); + serde_json::json!({"jsonrpc":"2.0","id":1,"result":null}) + } + "historicalRecoveryStatus" => { + status_polls += 1; + let status = if status_polls == 1 { + HistoricalRecoveryStatus { + phase: HistoricalRecoveryPhase::Running, + recovery_ledger_path: "/tmp/recovery-ledger".into(), + requested_start_slot: Some(s0), + requested_end_slot: Some(s0 + 3), + ..HistoricalRecoveryStatus::default() + } + } else { + HistoricalRecoveryStatus { + phase: HistoricalRecoveryPhase::Incomplete, + recovery_ledger_path: "/tmp/recovery-ledger".into(), + preserved_snapshot_slot: Some(s0 - 1), + requested_start_slot: Some(s0), + requested_end_slot: Some(s0 + 3), + chain_reached_start: false, + lowest_recovered_slot: Some(s0 + 2), + recovered_slots: 1, + skipped_slots: 1, + unrecoverable_slot_count: 1, + unrecoverable_slots: vec![s0], + ..HistoricalRecoveryStatus::default() + } + }; + serde_json::json!({"jsonrpc":"2.0","id":1,"result":status}) + } + other => panic!("unexpected admin.rpc method {other}"), + }; + let mut bytes = serde_json::to_vec(&reply).unwrap(); + bytes.push(b'\n'); + stream.write_all(&bytes).unwrap(); + stream.flush().unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + // Mock Telegram server capturing alert POSTs. + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + let secret_token = "999111:SECRET_BOT_TOKEN"; + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: true, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: None, + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig { + admin_ledger_dir: Some(ledger_dir.clone()), + admin_rpc_timeout: Duration::from_secs(5), + poll_interval: Duration::from_millis(20), + recovery_timeout: Duration::from_secs(5), + replay_command: None, + fallback_policy: GapFallbackPolicy::WaitForCar, + fallback_rpc_url: None, + fallback_rpc_timeout: Duration::from_secs(5), + telegram: TelegramConfig { + bot_token: secret_token.into(), + chat_id: "-100999".into(), + api_base_url: tg_server.url.clone(), + }, + }, + }) + .await + .expect("run_drain with restart gap"); + + // Live chunk [s0 + 4 ..= s0 + 7] sealed immediately! + assert_eq!(summary.chunks_sealed, 1); + assert_eq!(summary.blocks_sealed, 2); + assert_eq!(summary.highest_sealed_slot, Some(s0 + 7)); + assert!(summary.gap_recovery_triggered); + assert_eq!(summary.gap_failure_receipts.len(), 1); + assert_eq!(*start_calls.lock().unwrap(), vec![(s0, s0 + 3)]); + + // Durable failure receipt verified on disk. + let receipt_path = &summary.gap_failure_receipts[0]; + let receipt: GapFailureReceipt = + serde_json::from_slice(&std::fs::read(receipt_path).unwrap()).unwrap(); + assert_eq!(receipt.epoch, 1); + assert_eq!(receipt.gap_start_slot, s0); + assert_eq!(receipt.gap_end_slot, s0 + 3); + assert_eq!(receipt.fallback_policy, GapFallbackPolicy::WaitForCar); + assert_eq!(receipt.fallback_status, GapFallbackStatus::WaitingForCar); + assert!(receipt.telegram_notified); + assert_eq!( + receipt.historical_recovery_status.unwrap().unrecoverable_slots, + vec![s0] + ); + + // Telegram received the failure alert on the exact bot endpoint. + let tg_reqs = tg_server.requests.lock().unwrap(); + assert_eq!(tg_reqs.len(), 1); + assert_eq!(tg_reqs[0].0, format!("/bot{secret_token}/sendMessage")); + let tg_body: serde_json::Value = serde_json::from_str(&tg_reqs[0].1).unwrap(); + assert_eq!(tg_body["chat_id"], "-100999"); + let alert_text = tg_body["text"].as_str().unwrap(); + assert!(alert_text.contains("FAILED"), "alert text: {alert_text}"); + assert!(alert_text.contains("wait_for_car"), "alert text: {alert_text}"); + assert_eq!( + redact_token(&format!("url=/bot{secret_token}/sendMessage"), secret_token), + "url=/bot[token]/sendMessage" + ); + + bridge_stop.store(true, Ordering::Relaxed); + admin_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); + admin_handle.join().unwrap(); +} + +#[tokio::test] +async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_alerts_telegram() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let output_dir = root.path().join("finalized-chunks"); + let catalog_path = root.path().join("chunk_catalog.sqlite"); + let archive_out = root.path().join("epoch-1-archive"); + + let s0 = SLOTS_PER_EPOCH; // 432_000 + let live_start = s0 + 4; + let bh_parent = [0x40; 32]; + let bh0 = [0x41; 32]; + let bh2 = [0x42; 32]; + let bh4 = [0x44; 32]; + let bh7 = [0x47; 32]; + + let live_envelopes = HashMap::from([ + ( + live_start, + make_envelope(live_start, s0 + 2, bh4, bh2, [0xf4; 64], bh2), + ), + ( + live_start + 3, + make_envelope(live_start + 3, live_start, bh7, bh4, [0xf7; 64], bh4), + ), + ]); + let (bridge_stop, bridge_handle) = + spawn_mock_live_bridge_at_tip(&bridge_sock, live_start, live_envelopes, live_start + 12); + + // Mock Solana JSON-RPC server serving gap [s0 ..= s0 + 3]: + // s0: block with tx + InstructionError(0, Custom(42)) + full meta + reward + // s0 + 1: -32007 skipped slot + // s0 + 2: block chaining to s0 + // s0 + 3: -32009 skipped slot + let tx0_wire = build_legacy_tx([0xa0; 64], &[[0x11; 32], [0x22; 32]], bh_parent); + let tx0_b64 = STANDARD.encode(&tx0_wire); + let tx2_wire = build_legacy_tx([0xa2; 64], &[[0x11; 32], [0x22; 32]], bh0); + let tx2_b64 = STANDARD.encode(&tx2_wire); + let bh_parent_b58 = encode_base58(&bh_parent, &mut []); + let bh0_b58 = encode_base58(&bh0, &mut []); + let bh2_b58 = encode_base58(&bh2, &mut []); + let reward_key_b58 = encode_base58(&[0x33; 32], &mut []); + let mint_b58 = encode_base58(&[0x44; 32], &mut []); + let loaded_w_b58 = encode_base58(&[0x55; 32], &mut []); + let return_prog_b58 = encode_base58(&[0x66; 32], &mut []); + + let rpc_server = MockHttpJsonServer::start(move |_path, body| { + let req: serde_json::Value = serde_json::from_str(body).unwrap(); + assert_eq!(req["method"], "getBlock"); + let slot = req["params"][0].as_u64().unwrap(); + let resp = if slot == s0 { + serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "result": { + "previousBlockhash": bh_parent_b58, + "blockhash": bh0_b58, + "parentSlot": s0 - 1, + "blockTime": 1_700_000_000i64, + "blockHeight": 100u64, + "rewards": [{ + "pubkey": reward_key_b58, + "lamports": 5000, + "postBalance": 100000, + "rewardType": "Fee", + "commission": null + }], + "transactions": [{ + "transaction": [tx0_b64, "base64"], + "meta": { + "err": {"InstructionError": [0, {"Custom": 42}]}, + "fee": 5000, + "preBalances": [10000, 0], + "postBalances": [5000, 0], + "innerInstructions": [{ + "index": 0, + "instructions": [{ + "programIdIndex": 1, + "accounts": [0], + "data": "2CC", + "stackHeight": 2 + }] + }], + "logMessages": ["Program failed: custom 42"], + "preTokenBalances": [{ + "accountIndex": 0, + "mint": mint_b58, + "uiTokenAmount": { + "uiAmount": 1.0, + "decimals": 6, + "amount": "1000000", + "uiAmountString": "1" + }, + "owner": reward_key_b58, + "programId": return_prog_b58 + }], + "postTokenBalances": [], + "rewards": [], + "loadedAddresses": { + "writable": [loaded_w_b58], + "readonly": [] + }, + "returnData": { + "programId": return_prog_b58, + "data": ["AQID", "base64"] + }, + "computeUnitsConsumed": 1234, + "costUnits": 2345 + } + }] + } + }) + } else if slot == s0 + 1 { + serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32007, "message": "Slot was skipped"} + }) + } else if slot == s0 + 2 { + serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "result": { + "previousBlockhash": bh0_b58, + "blockhash": bh2_b58, + "parentSlot": s0, + "blockTime": 1_700_000_002i64, + "blockHeight": 101u64, + "rewards": [], + "transactions": [{ + "transaction": [tx2_b64, "base64"], + "meta": { + "err": null, + "fee": 5000, + "preBalances": [10000, 0], + "postBalances": [5000, 0], + "innerInstructions": [], + "logMessages": [], + "preTokenBalances": [], + "postTokenBalances": [], + "rewards": [], + "loadedAddresses": {"writable": [], "readonly": []}, + "computeUnitsConsumed": 500 + } + }] + } + }) + } else if slot == s0 + 3 { + serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32009, "message": "Slot was skipped or missing in long-term storage"} + }) + } else { + panic!("unexpected RPC getBlock({slot})"); + }; + (200, resp.to_string()) + }); + + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: true, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: Some(CatalogOptions { + path: catalog_path.clone(), + generation: "gen-rpc-fallback".into(), + prefix: "finalized-chunks/mainnet".into(), + }), + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig { + // No admin_ledger_dir -> local recovery fails -> logs + Telegram + RPC fallback! + admin_ledger_dir: None, + admin_rpc_timeout: Duration::from_secs(5), + poll_interval: Duration::from_millis(20), + recovery_timeout: Duration::from_secs(5), + replay_command: None, + fallback_policy: GapFallbackPolicy::RpcGetBlock, + fallback_rpc_url: Some(rpc_server.url.clone()), + fallback_rpc_timeout: Duration::from_secs(5), + telegram: TelegramConfig { + bot_token: "123:TESTTOKEN".into(), + chat_id: "-100123".into(), + api_base_url: tg_server.url.clone(), + }, + }, + }) + .await + .expect("run_drain with RPC fallback"); + + assert_eq!(summary.chunks_sealed, 1); + assert!(summary.gap_recovery_triggered); + assert_eq!(summary.gap_failure_receipts.len(), 1); + + // Failure receipt confirms degraded RPC backfill + Telegram notification. + let receipt: GapFailureReceipt = + serde_json::from_slice(&std::fs::read(&summary.gap_failure_receipts[0]).unwrap()).unwrap(); + assert_eq!(receipt.fallback_policy, GapFallbackPolicy::RpcGetBlock); + assert_eq!( + receipt.fallback_status, + GapFallbackStatus::RpcBackfilledDegradedWaitingForCar + ); + assert_eq!( + receipt.rpc_chunks_sealed, + vec![chunk_dir_name(s0, s0 + 3)] + ); + assert!(receipt.telegram_notified); + + // Degraded RPC chunk manifest carries degraded_source = rpc_only_no_alpenglow. + let degraded_manifest: ChunkManifestV1 = serde_json::from_slice( + &std::fs::read( + output_dir + .join("epoch-1") + .join(chunk_dir_name(s0, s0 + 3)) + .join(CHUNK_MANIFEST_FILE), + ) + .unwrap(), + ) + .unwrap(); + assert_eq!( + degraded_manifest.degraded_source.as_deref(), + Some(DEGRADED_SOURCE_RPC_ONLY) + ); + assert_eq!(degraded_manifest.block_count, 2); + assert_eq!(degraded_manifest.skip_count, 2); + + // SQLite catalog serves both the degraded RPC gap slots AND the live drained slots! + let canonical_catalog = catalog_path.canonicalize().unwrap(); + assert!(matches!( + ChunkCatalogReader::lookup( + &canonical_catalog, + "gen-rpc-fallback", + "finalized-chunks/mainnet", + s0, + ) + .unwrap(), + Some(ChunkCatalogLookup::ProducedBlock { .. }) + )); + assert_eq!( + ChunkCatalogReader::lookup( + &canonical_catalog, + "gen-rpc-fallback", + "finalized-chunks/mainnet", + s0 + 1, + ) + .unwrap(), + Some(ChunkCatalogLookup::Skipped { + epoch: 1, + kind: ChunkSlotKind::ProvenSkip, + }) + ); + assert!(matches!( + ChunkCatalogReader::lookup( + &canonical_catalog, + "gen-rpc-fallback", + "finalized-chunks/mainnet", + s0 + 4, + ) + .unwrap(), + Some(ChunkCatalogLookup::ProducedBlock { .. }) + )); + + // Epoch compaction MUST refuse to compact the degraded RPC chunk until CAR replaces it! + let source = LocalChunkSource::new(&output_dir); + let compact_err = + compact::compact_range_from_chunks(&source, 1, s0, s0 + 7, &archive_out, 1, None) + .unwrap_err(); + assert!( + compact_err.to_string().contains(DEGRADED_SOURCE_RPC_ONLY), + "expected compaction refusal for degraded RPC chunk, got: {compact_err:#}" + ); + + // Telegram received both the failure alert AND the degraded backfill alert! + let tg_reqs = tg_server.requests.lock().unwrap(); + assert_eq!(tg_reqs.len(), 2); + assert!(tg_reqs[0].1.contains("FAILED")); + assert!(tg_reqs[1].1.contains(DEGRADED_SOURCE_RPC_ONLY)); + + bridge_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); +} diff --git a/zillastream/agave-compatibility/README.md b/zillastream/agave-compatibility/README.md index 05f5930f..f3debf3a 100644 --- a/zillastream/agave-compatibility/README.md +++ b/zillastream/agave-compatibility/README.md @@ -24,7 +24,9 @@ compatible plugin binary. | `native-bank-state` | Supplies exact Bank/parent identity, native blockhash expiry, and actual confirmation. A processed or frozen Bank alone does not prove confirmation. | The selected upstream release supplies the same native values and passes the tuple, delayed-confirmation, and host-load checks. | | `bank-dead-id` | Identifies which Bank failed when multiple Banks use one slot. Slot-only failure can invalidate the wrong branch. | The selected release includes the fix and passes same-slot Bank and descendant-invalidation checks. | | `rpc-independent-observer` | Keeps native observations and execution-history storage available when RPC listeners are disabled. | Stock initialization supplies the same ordered events and metadata without RPC or a mandatory plugin. | -| `native-read-completeness` | Provides exact-Bank account reads and complete finalized ledger reads through Agave-owned handles. Completion records and cleanup guards reject partial or changed data. | An equivalent read path passes the account, ledger, cleanup, and restart checks, or all callers migrate away from this API. | +| `native-read-completeness` | Provides exact-Bank account reads and complete finalized ledger reads through Agave-owned handles, including live archive-grade finalized block extraction (`GetLedgerStatus`, `GetSlotStates`, `InspectSlot`, `GetAncestorBlockhashes`, `GetArchiveBlock`). Completion records and cleanup guards reject partial or changed data. | An equivalent read path passes the account, ledger, archive-extraction, cleanup, and restart checks, or all callers migrate away from this API. | +| `rocksdb-periodic-compaction-override` | Exposes optional `--rocksdb-periodic-compaction-seconds` (default unchanged at 86400s) so `TransactionStatus` SST files reclaim space promptly after manual `admin.rpc` `blockstorePurge`. | Upstream Agave exposes an equivalent option and passes default, override, and zero-rejection checks. | +| `historical-shred-recovery` | Adds opt-in background historical shred recovery (`--historical-recovery-ledger`, `startHistoricalRecovery`, `historicalRecoveryStatus`) and pre-download local snapshot preservation so fast snapshot catchup and gap shred recovery run concurrently without touching live replay. | Upstream Agave exposes equivalent isolated historical repair and snapshot preservation and passes the loopback UDP, forged-shred, timeout, and CLI checks. | | `read-only-ledger-file-cap` | Bounds the optional read-only RocksDB file cache without changing primary or default behavior. | The selected API provides an equivalent limit and passes default, limit and overflow checks. | `native-read-completeness` includes the transaction-count snapshot before From 69634ee661b1971b210e1dcf5a51d239b8974f5d Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 20:08:16 +0100 Subject: [PATCH 3/9] feat(finalized-ledger): add catchup stall watchdog, mid-run restart reload, and fatal Telegram alerts --- blockzilla/finalized-ledger/README.md | 19 + blockzilla/finalized-ledger/src/drain.rs | 428 ++++++++++++++++---- blockzilla/finalized-ledger/src/main.rs | 43 +- blockzilla/finalized-ledger/src/notify.rs | 20 + blockzilla/finalized-ledger/src/tests.rs | 453 ++++++++++++++++++++++ 5 files changed, 883 insertions(+), 80 deletions(-) diff --git a/blockzilla/finalized-ledger/README.md b/blockzilla/finalized-ledger/README.md index f83a1d7c..12151bd8 100644 --- a/blockzilla/finalized-ledger/README.md +++ b/blockzilla/finalized-ledger/README.md @@ -73,6 +73,25 @@ of the last sealed slot), `drain-chunks` starts live draining immediately at PoH, shredding, Alpenglow `consensus_block_id`, and `block_markers`, `compact-epoch` refuses degraded RPC-only chunks until CAR replaces them. +### Catchup Stall Watchdog, Mid-Run Restarts, and Fatal Alerts + +In continuous mode (`drain-chunks` without `--once`): + +- **Mid-run validator restarts**: if `agave-validator` restarts while + `drain-chunks` is running, `drain-chunks` reloads `--source-json` when the + `instance_id` changes (strictly requiring identical `genesis_hash` and + `node_identity`), detects `next_slot < status.lowest_slot` in-loop, immediately + resumes live sealing at `status.lowest_slot`, and launches parallel gap + recovery + failure receipts + Telegram alerts for the skipped range. +- **Catchup / drain stall watchdog**: if `--native-socket` stays unreachable or + `max_root` stops advancing for `--stall-alert-secs` (default `600` seconds; + `0` disables), `drain-chunks` sends a `🚨 Blockzilla catchup/drain STALLED` + Telegram alert (repeating every `--stall-repeat-secs`, default `1800`s) and + sends `✅ Blockzilla catchup/drain RECOVERED` once progress resumes. +- **Fatal error alerts**: fatal `drain-chunks` errors (such as R2 upload or + `blockstorePurge` failures) and `compact-epoch` failures send a `🚨` Telegram + alert before exiting non-zero. + ### 2. `compact-epoch` Compacts a complete epoch from local finalized chunks (`--source-dir`) or by diff --git a/blockzilla/finalized-ledger/src/drain.rs b/blockzilla/finalized-ledger/src/drain.rs index b1fb6133..867532dd 100644 --- a/blockzilla/finalized-ledger/src/drain.rs +++ b/blockzilla/finalized-ledger/src/drain.rs @@ -7,7 +7,8 @@ use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::time::Duration; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail, ensure}; use base64::{Engine, engine::general_purpose::STANDARD}; @@ -24,13 +25,17 @@ use blockzilla_finalized_chunks::{ }; use sha2::{Digest, Sha256}; use tokio::sync::Mutex; +use tokio::task::JoinHandle; use crate::admin_rpc; +use crate::notify::{self, TelegramConfig}; use crate::r2::{R2Client, R2Settings}; use crate::recovery::{GapRecoveryConfig, GapRecoveryOutcome, recover_restart_gap}; pub const MIN_PURGE_SAFETY_TAIL: u64 = 300; pub const DEFAULT_PURGE_SAFETY_TAIL: u64 = 512; +pub const DEFAULT_STALL_ALERT_SECS: u64 = 600; +pub const DEFAULT_STALL_REPEAT_SECS: u64 = 1_800; #[derive(Clone, Debug)] pub struct CatalogOptions { @@ -50,6 +55,10 @@ pub struct PurgeOptions { pub struct DrainConfig { pub native_socket: PathBuf, pub source: SourceIdentity, + /// Optional path to Agave's `.source.json` so continuous mode can reload a + /// refreshed `instance_id` after an in-place validator restart (while + /// strictly enforcing matching `genesis_hash` and `node_identity`). + pub source_json_path: Option, pub client_timeout: Duration, pub output_dir: PathBuf, pub chunk_slots: u64, @@ -62,6 +71,12 @@ pub struct DrainConfig { pub evict_local_payloads: bool, pub purge: Option, pub gap_recovery: GapRecoveryConfig, + /// Alert Telegram if catchup / draining makes no progress for this long. + pub stall_alert_after: Option, + /// Repeat interval for ongoing stall alerts. + pub stall_repeat_interval: Duration, + /// Optional cooperative shutdown flag (in addition to Ctrl-C). + pub shutdown: Option>, } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -74,6 +89,8 @@ pub struct DrainSummary { pub highest_purged_slot: Option, pub gap_recovery_triggered: bool, pub gap_failure_receipts: Vec, + pub stall_alerts_sent: u64, + pub stall_recoveries_sent: u64, } impl DrainConfig { @@ -126,20 +143,114 @@ impl DrainConfig { } } +struct StallTracker { + alert_after: Option, + repeat_interval: Duration, + last_progress_at: Instant, + last_seen_max_root: Option, + stalled_since: Option, + last_alert_at: Option, + stall_alerts_sent: u64, + stall_recoveries_sent: u64, +} + +impl StallTracker { + fn new(alert_after: Option, repeat_interval: Duration) -> Self { + Self { + alert_after: alert_after.filter(|d| !d.is_zero()), + repeat_interval: repeat_interval.max(Duration::from_secs(1)), + last_progress_at: Instant::now(), + last_seen_max_root: None, + stalled_since: None, + last_alert_at: None, + stall_alerts_sent: 0, + stall_recoveries_sent: 0, + } + } + + async fn record_progress(&mut self, max_root: u64, next_slot: Option, tg: &TelegramConfig) { + self.last_seen_max_root = Some(self.last_seen_max_root.map_or(max_root, |p| p.max(max_root))); + self.last_progress_at = Instant::now(); + if let Some(since) = self.stalled_since.take() { + self.last_alert_at = None; + let downtime_secs = since.elapsed().as_secs(); + eprintln!( + "catchup/drain RECOVERED after {downtime_secs}s (max_root={max_root}, next_slot={next_slot:?})" + ); + if notify::send_alert( + tg, + format!( + "✅ Blockzilla catchup/drain RECOVERED after {downtime_secs}s (max_root={max_root}, next_slot={next_slot:?})" + ), + ) + .await + { + self.stall_recoveries_sent += 1; + } + } + } + + async fn check_stall(&mut self, reason: &str, next_slot: Option, tg: &TelegramConfig) { + let Some(threshold) = self.alert_after else { + return; + }; + let elapsed = self.last_progress_at.elapsed(); + if elapsed < threshold { + return; + } + let should_send = self + .last_alert_at + .is_none_or(|prev| prev.elapsed() >= self.repeat_interval); + if !should_send { + return; + } + let now = Instant::now(); + self.stalled_since.get_or_insert(now); + self.last_alert_at = Some(now); + let secs = elapsed.as_secs(); + eprintln!( + "ERROR: catchup/drain STALLED for {secs}s: {reason} (next_slot={next_slot:?}, last_max_root={:?})", + self.last_seen_max_root + ); + if notify::send_alert( + tg, + format!( + "🚨 Blockzilla catchup/drain STALLED for {secs}s: {reason} (next_slot={next_slot:?}, last_max_root={:?})", + self.last_seen_max_root + ), + ) + .await + { + self.stall_alerts_sent += 1; + } + } +} + pub async fn run_drain(config: DrainConfig) -> Result { + let telegram = config.gap_recovery.telegram.clone(); + match run_drain_inner(config).await { + Ok(summary) => Ok(summary), + Err(err) => { + eprintln!("ERROR: blockzilla-finalized-ledger drain-chunks FATAL error: {err:#}"); + let _ = notify::send_alert( + &telegram, + format!("🚨 Blockzilla drain-chunks FATAL error: {err:#}"), + ) + .await; + Err(err) + } + } +} + +async fn run_drain_inner(config: DrainConfig) -> Result { config.validate()?; fs::create_dir_all(&config.output_dir) .with_context(|| format!("create finalized output dir {}", config.output_dir.display()))?; - let client = AccountClient::new( - &config.native_socket, - config.source.clone(), - ClientOptions { - timeout: config.client_timeout, - ..ClientOptions::default() - }, - ) - .context("create native bridge client")?; + let pinned_genesis_hash = config.source.genesis_hash.clone(); + let pinned_node_identity = config.source.node_identity.clone(); + let mut current_source = config.source.clone(); + let mut client = build_account_client(&config, ¤t_source)?; let r2_settings = config.r2.clone(); if let Some(settings) = &r2_settings { @@ -167,47 +278,95 @@ pub async fn run_drain(config: DrainConfig) -> Result { .transpose() .context("open chunk catalog")?; - let initial_status = client - .get_ledger_status() + let mut next_slot = determine_saved_next_slot(&config, catalog_writer.as_ref()).await?; + let mut summary = DrainSummary::default(); + let mut recovery_tasks: Vec> = Vec::new(); + let mut stall_tracker = + StallTracker::new(config.stall_alert_after, config.stall_repeat_interval); + let mut last_purged: Option = None; + + loop { + reap_finished_recovery_tasks(&mut recovery_tasks, &mut summary).await; + if shutdown_requested(&config) { + break; + } + + let status = match query_status_with_reload( + &config, + &pinned_genesis_hash, + &pinned_node_identity, + &mut current_source, + &mut client, + ) .await - .context("query initial Agave ledger status")?; - let expected_slot = - determine_next_slot(&config, catalog_writer.as_ref(), initial_status.lowest_slot).await?; + { + Ok(status) => status, + Err(err) => { + if config.once { + return Err(err).context("query Agave ledger status"); + } + let reason = format!("validator native bridge error: {err:#}"); + stall_tracker + .check_stall(&reason, next_slot, &config.gap_recovery.telegram) + .await; + if wait_poll_or_shutdown(&config).await { + break; + } + continue; + } + }; - let mut summary = DrainSummary::default(); - let (mut next_slot, recovery_task) = if expected_slot < initial_status.lowest_slot { - let gap_start = expected_slot; - let gap_end = initial_status.lowest_slot - 1; - let mut recovery_cfg = config.gap_recovery.clone(); - if recovery_cfg.admin_ledger_dir.is_none() { - recovery_cfg.admin_ledger_dir = config.purge.as_ref().map(|p| p.ledger_dir.clone()); + let slot_cursor = match next_slot { + Some(slot) => slot, + None => { + next_slot = Some(status.lowest_slot); + status.lowest_slot + } + }; + + if stall_tracker + .last_seen_max_root + .is_none_or(|prev| status.max_root > prev) + { + stall_tracker + .record_progress( + status.max_root, + Some(slot_cursor), + &config.gap_recovery.telegram, + ) + .await; } - let handle = tokio::spawn(recover_restart_gap( - gap_start, - gap_end, - config.output_dir.clone(), - config.chunk_slots, - config.zstd_level, - r2_settings.clone(), - catalog_writer.clone(), - config.evict_local_payloads, - recovery_cfg, - )); - summary.gap_recovery_triggered = true; - // Start live draining immediately at the fresh snapshot tip! - (initial_status.lowest_slot, Some(handle)) - } else { - (expected_slot, None) - }; - let mut last_purged: Option = None; + // Detect restart/prune gaps BOTH on startup AND mid-run if Agave restarts + // from a newer snapshot while `drain-chunks` is already running! + let current_slot = if slot_cursor < status.lowest_slot { + let gap_start = slot_cursor; + let gap_end = status.lowest_slot - 1; + let mut recovery_cfg = config.gap_recovery.clone(); + if recovery_cfg.admin_ledger_dir.is_none() { + recovery_cfg.admin_ledger_dir = + config.purge.as_ref().map(|p| p.ledger_dir.clone()); + } + let handle = tokio::spawn(recover_restart_gap( + gap_start, + gap_end, + config.output_dir.clone(), + config.chunk_slots, + config.zstd_level, + r2_settings.clone(), + catalog_writer.clone(), + config.evict_local_payloads, + recovery_cfg, + )); + recovery_tasks.push(handle); + summary.gap_recovery_triggered = true; + next_slot = Some(status.lowest_slot); + status.lowest_slot + } else { + slot_cursor + }; - loop { - let status = client - .get_ledger_status() - .await - .context("query Agave ledger status")?; - let end_slot = chunk_window_end(next_slot, config.chunk_slots)?; + let end_slot = chunk_window_end(current_slot, config.chunk_slots)?; let required_root = end_slot .checked_add(REWARD_SLOT_DISTANCE) .context("required root overflows u64")?; @@ -216,21 +375,53 @@ pub async fn run_drain(config: DrainConfig) -> Result { if config.once { break; } - tokio::select! { - _ = tokio::time::sleep(config.poll_interval) => continue, - _ = tokio::signal::ctrl_c() => break, + let reason = format!( + "max_root ({}) has not advanced past required_root ({required_root})", + status.max_root + ); + stall_tracker + .check_stall(&reason, Some(current_slot), &config.gap_recovery.telegram) + .await; + if wait_poll_or_shutdown(&config).await { + break; } + continue; } - let sealed = seal_chunk_from_bridge( + let sealed = match seal_chunk_from_bridge( &client, &config.output_dir, - next_slot, + current_slot, end_slot, config.zstd_level, ) .await - .with_context(|| format!("seal finalized chunk {next_slot}..={end_slot}"))?; + { + Ok(sealed) => sealed, + Err(err) => { + // In continuous mode, check whether Agave restarted mid-chunk (new + // instance_id or jumped lowest_slot) before treating the error as fatal. + if !config.once + && let Ok(rechecked) = query_status_with_reload( + &config, + &pinned_genesis_hash, + &pinned_node_identity, + &mut current_source, + &mut client, + ) + .await + && rechecked.lowest_slot > current_slot + { + eprintln!( + "WARN: validator jumped to lowest_slot={} mid-chunk ({current_slot}..={end_slot}): {err:#}; handing off to parallel gap recovery", + rechecked.lowest_slot + ); + continue; + } + return Err(err) + .with_context(|| format!("seal finalized chunk {current_slot}..={end_slot}")); + } + }; let (storage_mode, bundles_location, bundles_etag) = if let Some(settings) = &r2_settings { let settings_clone = settings.clone(); @@ -270,7 +461,7 @@ pub async fn run_drain(config: DrainConfig) -> Result { &bundles_location, bundles_etag.as_deref(), ) - .with_context(|| format!("register chunk {next_slot}..={end_slot} in catalog"))?; + .with_context(|| format!("register chunk {current_slot}..={end_slot} in catalog"))?; } if config.evict_local_payloads { @@ -299,7 +490,7 @@ pub async fn run_drain(config: DrainConfig) -> Result { eprintln!( "sealed epoch-{} chunk {}..={} (blocks={}, skips={}, forks={}, mode={:?}, purged={:?})", sealed.manifest.epoch, - next_slot, + current_slot, end_slot, sealed.manifest.block_count, sealed.manifest.skip_count, @@ -308,29 +499,125 @@ pub async fn run_drain(config: DrainConfig) -> Result { last_purged ); - next_slot = end_slot.checked_add(1).context("next_slot overflow")?; + let advanced_slot = end_slot.checked_add(1).context("next_slot overflow")?; + next_slot = Some(advanced_slot); + stall_tracker + .record_progress( + status.max_root, + next_slot, + &config.gap_recovery.telegram, + ) + .await; } - if let Some(handle) = recovery_task { - match handle.await { - Ok(GapRecoveryOutcome::FailedWithFallback { receipt_path, .. }) => { - summary.gap_failure_receipts.push(receipt_path); - } - Ok(GapRecoveryOutcome::LocallyRebuilt { .. }) => {} - Err(join_err) => { - eprintln!("ERROR: parallel gap recovery task panicked: {join_err}"); + for handle in recovery_tasks { + record_recovery_outcome(handle.await, &mut summary); + } + summary.stall_alerts_sent = stall_tracker.stall_alerts_sent; + summary.stall_recoveries_sent = stall_tracker.stall_recoveries_sent; + + Ok(summary) +} + +fn build_account_client(config: &DrainConfig, source: &SourceIdentity) -> Result { + AccountClient::new( + &config.native_socket, + source.clone(), + ClientOptions { + timeout: config.client_timeout, + ..ClientOptions::default() + }, + ) + .context("create native bridge client") +} + +async fn query_status_with_reload( + config: &DrainConfig, + pinned_genesis_hash: &str, + pinned_node_identity: &str, + current_source: &mut SourceIdentity, + client: &mut AccountClient, +) -> Result { + match client.get_ledger_status().await { + Ok(status) => Ok(status), + Err(first_err) => { + if let Some(source_path) = &config.source_json_path + && let Ok(raw) = fs::read(source_path) + && let Ok(reloaded) = serde_json::from_slice::(&raw) + && reloaded != *current_source + { + ensure!( + reloaded.genesis_hash == pinned_genesis_hash + && reloaded.node_identity == pinned_node_identity, + "refusing to follow source.json identity change (genesis/node_identity mismatch)" + ); + eprintln!( + "bridge source reloaded after validator restart: instance_id {} -> {}", + current_source.instance_id, reloaded.instance_id + ); + *client = build_account_client(config, &reloaded)?; + *current_source = reloaded; + return client + .get_ledger_status() + .await + .map_err(|err| anyhow::anyhow!("{err}")); } + Err(anyhow::anyhow!("{first_err}")) } } +} - Ok(summary) +fn shutdown_requested(config: &DrainConfig) -> bool { + config + .shutdown + .as_ref() + .is_some_and(|flag| flag.load(Ordering::Relaxed)) +} + +async fn wait_poll_or_shutdown(config: &DrainConfig) -> bool { + if shutdown_requested(config) { + return true; + } + tokio::select! { + _ = tokio::time::sleep(config.poll_interval) => shutdown_requested(config), + _ = tokio::signal::ctrl_c() => true, + } +} + +async fn reap_finished_recovery_tasks( + tasks: &mut Vec>, + summary: &mut DrainSummary, +) { + let mut i = 0; + while i < tasks.len() { + if tasks[i].is_finished() { + let handle = tasks.swap_remove(i); + record_recovery_outcome(handle.await, summary); + } else { + i += 1; + } + } } -async fn determine_next_slot( +fn record_recovery_outcome( + result: std::result::Result, + summary: &mut DrainSummary, +) { + match result { + Ok(GapRecoveryOutcome::FailedWithFallback { receipt_path, .. }) => { + summary.gap_failure_receipts.push(receipt_path); + } + Ok(GapRecoveryOutcome::LocallyRebuilt { .. }) => {} + Err(join_err) => { + eprintln!("ERROR: parallel gap recovery task panicked: {join_err}"); + } + } +} + +async fn determine_saved_next_slot( config: &DrainConfig, catalog: Option<&Arc>>, - fallback_lowest_slot: u64, -) -> Result { +) -> Result> { let mut highest: Option = None; if let Some(cat_arc) = catalog { let cat = cat_arc.lock().await; @@ -342,12 +629,9 @@ async fn determine_next_slot( highest = Some(highest.map_or(disk_slot, |h| h.max(disk_slot))); } if let Some(h) = highest { - return h.checked_add(1).context("resume slot overflow"); - } - if let Some(explicit) = config.start_slot { - return Ok(explicit); + return Ok(Some(h.checked_add(1).context("resume slot overflow")?)); } - Ok(fallback_lowest_slot) + Ok(config.start_slot) } fn highest_local_chunk_end(root: &Path) -> Result> { diff --git a/blockzilla/finalized-ledger/src/main.rs b/blockzilla/finalized-ledger/src/main.rs index 8b00d169..d0f73761 100644 --- a/blockzilla/finalized-ledger/src/main.rs +++ b/blockzilla/finalized-ledger/src/main.rs @@ -20,9 +20,10 @@ use blockzilla_finalized_chunks::{ compact_epoch_from_chunks, }; use blockzilla_finalized_ledger::drain::{ - CatalogOptions, DEFAULT_PURGE_SAFETY_TAIL, DrainConfig, PurgeOptions, run_drain, + CatalogOptions, DEFAULT_PURGE_SAFETY_TAIL, DEFAULT_STALL_ALERT_SECS, DEFAULT_STALL_REPEAT_SECS, + DrainConfig, PurgeOptions, run_drain, }; -use blockzilla_finalized_ledger::notify::TelegramConfig; +use blockzilla_finalized_ledger::notify::{self, TelegramConfig}; use blockzilla_finalized_ledger::r2::{R2ChunkSource, R2Client, R2Settings}; use blockzilla_finalized_ledger::recovery::{ DEFAULT_FALLBACK_RPC_TIMEOUT, DEFAULT_GAP_RECOVERY_POLL_INTERVAL, DEFAULT_GAP_RECOVERY_TIMEOUT, @@ -128,6 +129,12 @@ enum Command { /// Optional shell command invoked after Agave recovers gap shreds to replay from preserved snapshots and seal canonical chunks. #[arg(long)] replay_command: Option, + /// Send a Telegram catchup/drain STALLED alert if no progress occurs for this many seconds (`0` disables). + #[arg(long, default_value_t = DEFAULT_STALL_ALERT_SECS)] + stall_alert_secs: u64, + /// Repeat interval in seconds for persistent stall alerts. + #[arg(long, default_value_t = DEFAULT_STALL_REPEAT_SECS)] + stall_repeat_secs: u64, }, /// Compact an epoch (or slot range) into the 13 Compact V2 archive files from sealed chunks. CompactEpoch { @@ -188,6 +195,8 @@ fn main() -> Result<()> { fallback_rpc_timeout_ms, gap_recovery_timeout_secs, replay_command, + stall_alert_secs, + stall_repeat_secs, } => { let source_raw = fs::read(&source_json) .with_context(|| format!("read source identity {}", source_json.display()))?; @@ -241,6 +250,7 @@ fn main() -> Result<()> { let summary = runtime.block_on(run_drain(DrainConfig { native_socket, source, + source_json_path: Some(source_json), client_timeout: Duration::from_millis(bridge_timeout_ms), output_dir, chunk_slots, @@ -253,10 +263,14 @@ fn main() -> Result<()> { evict_local_payloads, purge, gap_recovery, + stall_alert_after: (stall_alert_secs > 0) + .then(|| Duration::from_secs(stall_alert_secs)), + stall_repeat_interval: Duration::from_secs(stall_repeat_secs.max(1)), + shutdown: None, }))?; eprintln!( - "drain complete: chunks={}, blocks={}, skips={}, forks={}, highest_sealed={:?}, highest_purged={:?}, gap_recovery_triggered={}, gap_failure_receipts={}", + "drain complete: chunks={}, blocks={}, skips={}, forks={}, highest_sealed={:?}, highest_purged={:?}, gap_recovery_triggered={}, gap_failure_receipts={}, stall_alerts={}, stall_recoveries={}", summary.chunks_sealed, summary.blocks_sealed, summary.skips_sealed, @@ -265,6 +279,8 @@ fn main() -> Result<()> { summary.highest_purged_slot, summary.gap_recovery_triggered, summary.gap_failure_receipts.len(), + summary.stall_alerts_sent, + summary.stall_recoveries_sent, ); Ok(()) } @@ -300,7 +316,7 @@ fn main() -> Result<()> { _ => bail!("--start-slot and --end-slot must be provided together"), }; - let report = if let Some(dir) = source_dir { + let compact_result = if let Some(dir) = source_dir { let source = LocalChunkSource::new(dir); match range { Some((s, e)) => compact::compact_range_from_chunks( @@ -311,14 +327,14 @@ fn main() -> Result<()> { &output_dir, zstd_level, successor, - )?, + ), None => compact_epoch_from_chunks( &source, epoch, &output_dir, zstd_level, successor, - )?, + ), } } else { let settings = R2Settings::from_env(r2_prefix)?; @@ -333,14 +349,25 @@ fn main() -> Result<()> { &output_dir, zstd_level, successor, - )?, + ), None => compact_epoch_from_chunks( &source, epoch, &output_dir, zstd_level, successor, - )?, + ), + } + }; + let report = match compact_result { + Ok(report) => report, + Err(err) => { + let tg = TelegramConfig::from_env(); + let _ = notify::send_alert_sync( + &tg, + &format!("🚨 Blockzilla compact-epoch {epoch} FAILED: {err:#}"), + ); + return Err(err); } }; diff --git a/blockzilla/finalized-ledger/src/notify.rs b/blockzilla/finalized-ledger/src/notify.rs index 8ee3dbf2..38dbbdad 100644 --- a/blockzilla/finalized-ledger/src/notify.rs +++ b/blockzilla/finalized-ledger/src/notify.rs @@ -80,6 +80,26 @@ pub async fn send_alert(config: &TelegramConfig, text: String) -> bool { } } +/// Send a Telegram alert synchronously (for non-async CLI paths like `compact-epoch`). +/// +/// Returns `true` if Telegram accepted the message, `false` if skipped or failed. +pub fn send_alert_sync(config: &TelegramConfig, text: &str) -> bool { + if !config.is_ready() { + eprintln!("telegram: skipped, TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is empty"); + return false; + } + match send_alert_blocking(config, text) { + Ok(()) => true, + Err(err) => { + eprintln!( + "telegram: {}", + redact_token(&format!("{err:#}"), &config.bot_token) + ); + false + } + } +} + fn send_alert_blocking(config: &TelegramConfig, text: &str) -> Result<()> { let token = config.bot_token.trim(); let chat_id = config.chat_id.trim(); diff --git a/blockzilla/finalized-ledger/src/tests.rs b/blockzilla/finalized-ledger/src/tests.rs index 8b9a0bb7..d00619d0 100644 --- a/blockzilla/finalized-ledger/src/tests.rs +++ b/blockzilla/finalized-ledger/src/tests.rs @@ -556,6 +556,7 @@ async fn end_to_end_drain_r2_catalog_evict_purge_and_streaming_compact() { let summary = run_drain(DrainConfig { native_socket: bridge_sock.clone(), source: source_identity(), + source_json_path: None, client_timeout: Duration::from_secs(5), output_dir: output_dir.clone(), chunk_slots: 4, @@ -576,6 +577,9 @@ async fn end_to_end_drain_r2_catalog_evict_purge_and_streaming_compact() { rpc_timeout: Duration::from_secs(5), }), gap_recovery: GapRecoveryConfig::default(), + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + shutdown: None, }) .await .expect("run_drain end-to-end"); @@ -1005,6 +1009,7 @@ async fn restart_gap_drains_live_immediately_and_wait_for_car_writes_receipt_and let summary = run_drain(DrainConfig { native_socket: bridge_sock.clone(), source: source_identity(), + source_json_path: None, client_timeout: Duration::from_secs(5), output_dir: output_dir.clone(), chunk_slots: 4, @@ -1031,6 +1036,9 @@ async fn restart_gap_drains_live_immediately_and_wait_for_car_writes_receipt_and api_base_url: tg_server.url.clone(), }, }, + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + shutdown: None, }) .await .expect("run_drain with restart gap"); @@ -1244,6 +1252,7 @@ async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_ale let summary = run_drain(DrainConfig { native_socket: bridge_sock.clone(), source: source_identity(), + source_json_path: None, client_timeout: Duration::from_secs(5), output_dir: output_dir.clone(), chunk_slots: 4, @@ -1275,6 +1284,9 @@ async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_ale api_base_url: tg_server.url.clone(), }, }, + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + shutdown: None, }) .await .expect("run_drain with RPC fallback"); @@ -1370,3 +1382,444 @@ async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_ale bridge_stop.store(true, Ordering::Relaxed); bridge_handle.join().unwrap(); } + +#[tokio::test] +async fn catchup_stall_alerts_telegram_and_sends_recovery_when_max_root_advances() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let output_dir = root.path().join("finalized-chunks"); + + let s0 = SLOTS_PER_EPOCH; + let bh_parent = [0x40; 32]; + let bh0 = [0x41; 32]; + let bh3 = [0x43; 32]; + let envelopes = HashMap::from([ + (s0, make_envelope(s0, s0 - 1, bh0, bh_parent, [0x10; 64], bh_parent)), + (s0 + 3, make_envelope(s0 + 3, s0, bh3, bh0, [0x13; 64], bh0)), + ]); + + let shared_max_root = Arc::new(std::sync::atomic::AtomicU64::new(s0 + 2)); // below required_root (s0 + 11) + let max_root_server = shared_max_root.clone(); + let bridge_stop = Arc::new(AtomicBool::new(false)); + let bridge_stop_clone = bridge_stop.clone(); + let listener = UnixListener::bind(&bridge_sock).unwrap(); + listener.set_nonblocking(true).unwrap(); + let bridge_handle = thread::spawn(move || { + while !bridge_stop_clone.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let req = read_request(&mut stream).unwrap(); + let cur_max_root = max_root_server.load(Ordering::Relaxed); + let data = match &req.operation { + Operation::GetLedgerStatus => ResponseData::GetLedgerStatus { + status: LedgerStatus { + lowest_slot: s0, + lowest_cleanup_slot: s0, + max_root: cur_max_root, + highest_slot: Some(cur_max_root + 2), + }, + }, + Operation::GetSlotStates { start_slot, end_slot } => { + let states = (*start_slot..=*end_slot) + .map(|slot| { + if envelopes.contains_key(&slot) { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + } + }) + .collect(); + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: *start_slot, + end_slot: *end_slot, + states, + }, + } + } + Operation::GetAncestorBlockhashes { .. } => { + ResponseData::GetAncestorBlockhashes { + ancestors: vec![SlotBlockhash { + slot: s0 - 1, + blockhash: encode_base58(&bh_parent, &mut []), + }], + } + } + Operation::InspectSlot { + slot, + include_markers, + } => ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: if *include_markers { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + }, + parent_slot: (*include_markers).then(|| *slot - 1), + blockhash: (*include_markers).then(|| hash_b58(0x55)), + chain_relation: (!*include_markers).then_some( + SlotChainRelation::JumpsOver { next_root: s0 + 3 }, + ), + markers_base64: None, + }, + }, + Operation::GetArchiveBlock { slot, .. } => ResponseData::GetArchiveBlock { + block: envelopes.get(slot).cloned().expect("envelope"), + }, + other => panic!("unexpected op {other:?}"), + }; + let resp = Response::ok(&req, source_identity(), data); + write_response(&mut stream, &resp).unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + let shutdown = Arc::new(AtomicBool::new(false)); + let shutdown_ctrl = shutdown.clone(); + let tg_reqs_watch = tg_server.requests.clone(); + let max_root_ctrl = shared_max_root.clone(); + + // Watch Telegram alerts: once STALLED fires, advance max_root so drainer seals and sends RECOVERED! + let controller = tokio::spawn(async move { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while std::time::Instant::now() < deadline { + let count = tg_reqs_watch.lock().unwrap().len(); + if count == 1 { + max_root_ctrl.store(s0 + 12, Ordering::Relaxed); + } else if count >= 2 { + // Wait briefly for chunk seal to finish, then stop cleanly. + tokio::time::sleep(Duration::from_millis(80)).await; + shutdown_ctrl.store(true, Ordering::Relaxed); + return; + } + tokio::time::sleep(Duration::from_millis(15)).await; + } + shutdown_ctrl.store(true, Ordering::Relaxed); + }); + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: false, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: None, + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig { + telegram: TelegramConfig { + bot_token: "123:STALL".into(), + chat_id: "-1001".into(), + api_base_url: tg_server.url.clone(), + }, + ..GapRecoveryConfig::default() + }, + stall_alert_after: Some(Duration::from_millis(80)), + stall_repeat_interval: Duration::from_secs(30), + shutdown: Some(shutdown.clone()), + }) + .await + .expect("run_drain stall recovery"); + controller.await.unwrap(); + + assert_eq!(summary.chunks_sealed, 1); + assert_eq!(summary.stall_alerts_sent, 1); + assert_eq!(summary.stall_recoveries_sent, 1); + + let tg_reqs = tg_server.requests.lock().unwrap(); + assert!(tg_reqs.len() >= 2); + assert!(tg_reqs[0].1.contains("STALLED"), "req0: {}", tg_reqs[0].1); + assert!(tg_reqs[1].1.contains("RECOVERED"), "req1: {}", tg_reqs[1].1); + + bridge_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); +} + +#[tokio::test] +async fn mid_run_validator_restart_reloads_source_and_triggers_parallel_gap_recovery() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let source_json_path = root.path().join("accounts.source.json"); + let output_dir = root.path().join("finalized-chunks"); + + let s0 = SLOTS_PER_EPOCH; + let bh_parent = [0x40; 32]; + let bh0 = [0x41; 32]; + let bh3 = [0x43; 32]; + let bh7 = [0x47; 32]; + let bh8 = [0x48; 32]; + let bh11 = [0x4b; 32]; + + let initial_source = source_identity(); + std::fs::write( + &source_json_path, + serde_json::to_vec(&initial_source).unwrap(), + ) + .unwrap(); + + let restarted_source = SourceIdentity { + instance_id: "validator-instance-02-after-restart".into(), + ..initial_source.clone() + }; + + let envelopes = HashMap::from([ + (s0, make_envelope(s0, s0 - 1, bh0, bh_parent, [0x20; 64], bh_parent)), + (s0 + 3, make_envelope(s0 + 3, s0, bh3, bh0, [0x23; 64], bh0)), + (s0 + 8, make_envelope(s0 + 8, s0 + 7, bh8, bh7, [0x28; 64], bh7)), + (s0 + 11, make_envelope(s0 + 11, s0 + 8, bh11, bh8, [0x2b; 64], bh8)), + ]); + + // Shared validator state: switches to restarted instance + lowest_slot = s0 + 8 mid-run! + let restarted_flag = Arc::new(AtomicBool::new(false)); + let restarted_srv = restarted_flag.clone(); + let initial_src_srv = initial_source.clone(); + let restarted_src_srv = restarted_source.clone(); + let bridge_stop = Arc::new(AtomicBool::new(false)); + let bridge_stop_clone = bridge_stop.clone(); + let listener = UnixListener::bind(&bridge_sock).unwrap(); + listener.set_nonblocking(true).unwrap(); + + let bridge_handle = thread::spawn(move || { + while !bridge_stop_clone.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let req = read_request(&mut stream).unwrap(); + let is_restarted = restarted_srv.load(Ordering::Relaxed); + let active_source = if is_restarted { + restarted_src_srv.clone() + } else { + initial_src_srv.clone() + }; + let data = match &req.operation { + Operation::GetLedgerStatus => ResponseData::GetLedgerStatus { + status: if is_restarted { + LedgerStatus { + lowest_slot: s0 + 8, // jumped over [s0 + 4 ..= s0 + 7]! + lowest_cleanup_slot: s0 + 8, + max_root: s0 + 20, + highest_slot: Some(s0 + 22), + } + } else { + LedgerStatus { + lowest_slot: s0, + lowest_cleanup_slot: s0, + max_root: s0 + 11, // allows sealing chunk [s0 ..= s0 + 3] only + highest_slot: Some(s0 + 12), + } + }, + }, + Operation::GetSlotStates { start_slot, end_slot } => { + let states = (*start_slot..=*end_slot) + .map(|slot| { + if envelopes.contains_key(&slot) { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + } + }) + .collect(); + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: *start_slot, + end_slot: *end_slot, + states, + }, + } + } + Operation::GetAncestorBlockhashes { .. } => { + ResponseData::GetAncestorBlockhashes { + ancestors: vec![SlotBlockhash { + slot: s0 - 1, + blockhash: encode_base58(&bh_parent, &mut []), + }], + } + } + Operation::InspectSlot { + slot, + include_markers, + } => { + let next_root = if *slot < s0 + 3 { s0 + 3 } else { s0 + 11 }; + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: if *include_markers { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + }, + parent_slot: (*include_markers).then(|| *slot - 1), + blockhash: (*include_markers).then(|| hash_b58(0x55)), + chain_relation: (!*include_markers) + .then_some(SlotChainRelation::JumpsOver { next_root }), + markers_base64: None, + }, + } + } + Operation::GetArchiveBlock { slot, .. } => ResponseData::GetArchiveBlock { + block: envelopes.get(slot).cloned().expect("envelope"), + }, + other => panic!("unexpected op {other:?}"), + }; + let resp = Response::ok(&req, active_source, data); + write_response(&mut stream, &resp).unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + let shutdown = Arc::new(AtomicBool::new(false)); + let shutdown_ctrl = shutdown.clone(); + let restarted_ctrl = restarted_flag.clone(); + let out_watch = output_dir.clone(); + let src_path_ctrl = source_json_path.clone(); + let restarted_src_ctrl = restarted_source.clone(); + + let controller = tokio::spawn(async move { + let c1 = out_watch + .join("epoch-1") + .join(chunk_dir_name(s0, s0 + 3)) + .join(CHUNK_MANIFEST_FILE); + let c3 = out_watch + .join("epoch-1") + .join(chunk_dir_name(s0 + 8, s0 + 11)) + .join(CHUNK_MANIFEST_FILE); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let mut flipped = false; + while std::time::Instant::now() < deadline { + if !flipped && c1.is_file() { + // Simulate live validator restart: update accounts.source.json + flip server! + std::fs::write( + &src_path_ctrl, + serde_json::to_vec(&restarted_src_ctrl).unwrap(), + ) + .unwrap(); + restarted_ctrl.store(true, Ordering::Relaxed); + flipped = true; + } + if flipped && c3.is_file() { + tokio::time::sleep(Duration::from_millis(80)).await; + shutdown_ctrl.store(true, Ordering::Relaxed); + return; + } + tokio::time::sleep(Duration::from_millis(15)).await; + } + shutdown_ctrl.store(true, Ordering::Relaxed); + }); + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: initial_source, + source_json_path: Some(source_json_path), + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: false, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: None, + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig { + admin_ledger_dir: None, + fallback_policy: GapFallbackPolicy::WaitForCar, + telegram: TelegramConfig { + bot_token: "123:RESTART".into(), + chat_id: "-1002".into(), + api_base_url: tg_server.url.clone(), + }, + ..GapRecoveryConfig::default() + }, + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + shutdown: Some(shutdown.clone()), + }) + .await + .expect("run_drain survived mid-run restart"); + controller.await.unwrap(); + + // Sealed BOTH pre-restart [s0..=s0+3] AND post-restart [s0+8..=s0+11], and logged gap [s0+4..=s0+7]! + assert_eq!(summary.chunks_sealed, 2); + assert_eq!(summary.highest_sealed_slot, Some(s0 + 11)); + assert!(summary.gap_recovery_triggered); + assert_eq!(summary.gap_failure_receipts.len(), 1); + let receipt: GapFailureReceipt = + serde_json::from_slice(&std::fs::read(&summary.gap_failure_receipts[0]).unwrap()).unwrap(); + assert_eq!(receipt.gap_start_slot, s0 + 4); + assert_eq!(receipt.gap_end_slot, s0 + 7); + assert!(receipt.telegram_notified); + + let tg_reqs = tg_server.requests.lock().unwrap(); + assert_eq!(tg_reqs.len(), 1); + assert!(tg_reqs[0].1.contains("FAILED")); + assert!(tg_reqs[0].1.contains(&format!("{}..={}", s0 + 4, s0 + 7))); + + bridge_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); +} + +#[tokio::test] +async fn fatal_drain_error_sends_telegram_alert_before_exiting() { + let root = tempfile::tempdir().unwrap(); + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + + let err = run_drain(DrainConfig { + native_socket: root.path().join("does-not-exist.sock"), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(2), + output_dir: root.path().join("out"), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(SLOTS_PER_EPOCH), + once: true, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: None, + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig { + telegram: TelegramConfig { + bot_token: "123:FATAL".into(), + chat_id: "-1003".into(), + api_base_url: tg_server.url.clone(), + }, + ..GapRecoveryConfig::default() + }, + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + shutdown: None, + }) + .await + .unwrap_err(); + assert!(err.to_string().contains("query Agave ledger status")); + + let tg_reqs = tg_server.requests.lock().unwrap(); + assert_eq!(tg_reqs.len(), 1); + assert!(tg_reqs[0].1.contains("FATAL"), "req: {}", tg_reqs[0].1); +} From 0726ad3f28a90d04137986f4e9b67defec742dd2 Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 20:40:27 +0100 Subject: [PATCH 4/9] feat(get-block,finalized-chunks): support .bin ChunkBundle streaming, persistent WAL, and canonical chunk grid --- blockzilla/get-block/src/worker.rs | 165 +++++++++++++++- .../src/catalog.rs | 82 +++++++- .../src/compact.rs | 178 +++++++++++++++--- .../blockzilla-finalized-chunks/src/format.rs | 23 ++- crates/blockzilla-finalized-chunks/src/lib.rs | 10 +- .../blockzilla-finalized-chunks/src/tests.rs | 171 +++++++++++++++++ 6 files changed, 590 insertions(+), 39 deletions(-) diff --git a/blockzilla/get-block/src/worker.rs b/blockzilla/get-block/src/worker.rs index cee028f6..4ce0dac8 100644 --- a/blockzilla/get-block/src/worker.rs +++ b/blockzilla/get-block/src/worker.rs @@ -1360,18 +1360,31 @@ async fn handle_authenticated_direct_block( "RECENT_ONLY" }; // Older slots use the archive even when the recent feed is unavailable. + let finalized_binary_eligible = request.format == BlockResponseFormat::Wincode + && mode == RouteBlockMode::Full + && !client_binary + && access_mode == BlockBinAccessMode::Include; if config.should_lookup_finalized(request.slot) - && request.format == BlockResponseFormat::Json + && (request.format == BlockResponseFormat::Json || finalized_binary_eligible) && client_locator.is_none() { match config.lookup_finalized(&source, request.slot).await { Ok(result @ foundation_first::Outcome::Native { .. }) => { - foundation_status = "NATIVE_RECENT"; - source.foundation_prepared.borrow_mut().replace(result); + if request.format == BlockResponseFormat::Json { + foundation_status = "NATIVE_RECENT"; + source.foundation_prepared.borrow_mut().replace(result); + } else { + drop(result); + foundation_status = "NATIVE_JSON_ONLY"; + } } Ok(result @ foundation_first::Outcome::NativeArchive { .. }) => { - foundation_status = "NATIVE_ARCHIVE"; - source.foundation_prepared.borrow_mut().replace(result); + if request.format == BlockResponseFormat::Json { + foundation_status = "NATIVE_ARCHIVE"; + source.foundation_prepared.borrow_mut().replace(result); + } else { + foundation_status = "NATIVE_JSON_ONLY"; + } } Ok(result @ foundation_first::Outcome::ChunkBundle { .. }) => { foundation_status = "CHUNK_BUNDLE"; @@ -1443,7 +1456,28 @@ async fn handle_authenticated_direct_block( foundation_first::Unavailable::SourceChanged => (409, "source_changed"), foundation_first::Unavailable::HashMismatch => (409, "hash_mismatch"), }; - let mut response = json_error_profiled(status, code, code, profile.as_ref())?; + let mut response = if reason == foundation_first::Unavailable::Unavailable + && request.format == BlockResponseFormat::Json + { + json_rpc_response_profiled( + error_response( + Value::from(1), + -32004, + format!("Block not available for slot {}", request.slot), + ), + profile.as_ref(), + )? + .with_status(404) + } else if reason == foundation_first::Unavailable::Unavailable { + json_error_profiled( + 404, + "block_unavailable", + "Block is not available for the requested slot", + profile.as_ref(), + )? + } else { + json_error_profiled(status, code, code, profile.as_ref())? + }; response .headers_mut() .set("X-Blockzilla-Foundation-Result", code)?; @@ -1576,7 +1610,28 @@ async fn handle_authenticated_direct_block( foundation_first::Unavailable::SourceChanged => (409, "source_changed"), foundation_first::Unavailable::HashMismatch => (409, "hash_mismatch"), }; - let mut response = json_error_profiled(status, code, code, profile.as_ref())?; + let mut response = if reason == foundation_first::Unavailable::Unavailable + && request.format == BlockResponseFormat::Json + { + json_rpc_response_profiled( + error_response( + Value::from(1), + -32004, + format!("Block not available for slot {}", request.slot), + ), + profile.as_ref(), + )? + .with_status(404) + } else if reason == foundation_first::Unavailable::Unavailable { + json_error_profiled( + 404, + "block_unavailable", + "Block is not available for the requested slot", + profile.as_ref(), + )? + } else { + json_error_profiled(status, code, code, profile.as_ref())? + }; response .headers_mut() .set("X-Blockzilla-Foundation-Result", code)?; @@ -3582,11 +3637,107 @@ async fn foundation_binary_response( foundation_first::Outcome::Resolution { checked, .. } => { resolution::binary_response_checked(source, slot, checked, ctx, metrics, key).await } + foundation_first::Outcome::ChunkBundle { locator } => { + let length = usize::try_from(locator.object.length) + .map_err(|_| "chunk bundle exceeds runtime bounds")?; + let expected_digest = foundation_first::decode_digest(&locator.metadata.sha256)?; + let identity = crate::slot_resolution::SourceObjectIdentity { + etag: locator.object.etag.clone(), + length: locator.object.object_length, + }; + let origin = resolution::pinned_origin_response( + source, + &locator.object.key, + locator.object.offset, + length, + &identity, + ) + .await?; + let (_, body) = origin.into_parts(); + let parts = stream_parts::response_and_completion_from_parts( + Vec::new(), + body, + length as u64, + Vec::new(), + worker::ResponseBody::Empty, + 0, + Vec::new(), + ) + .map_err(|e| e.to_string())?; + let mut response = parts.response; + response + .headers_mut() + .set("Content-Type", foundation_first::BUNDLE_TYPE) + .map_err(|e| e.to_string())?; + response + .headers_mut() + .set("Cache-Control", BLOCK_CACHE_CONTROL) + .map_err(|e| e.to_string())?; + response + .headers_mut() + .set("ETag", &format!("\"{}\"", hex_lower(&expected_digest))) + .map_err(|e| e.to_string())?; + response + .headers_mut() + .set("X-Blockzilla-Body", "native-stream") + .map_err(|e| e.to_string())?; + response + .headers_mut() + .set("X-Blockzilla-Storage-Bytes-Mode", "streamed-completion") + .map_err(|e| e.to_string())?; + response + .headers_mut() + .set("X-Blockzilla-Origin-Expected-Bytes", &length.to_string()) + .map_err(|e| e.to_string())?; + response + .headers_mut() + .set("X-Blockzilla-Foundation-Expected-Bytes", "0") + .map_err(|e| e.to_string())?; + add_profile_headers(response.headers(), source.profile.as_ref()) + .map_err(|e| e.to_string())?; + let dataset = metrics.clone(); + let key_id = key.key_id.clone(); + let customer_id = key.customer_id.clone(); + ctx.wait_until(async move { + let Ok(value) = wasm_bindgen_futures::JsFuture::from(parts.completion).await else { + console_error!("Chunk bundle stream failed or was cancelled"); + return; + }; + let Some(dataset) = dataset else { + return; + }; + let bytes = js_sys::Reflect::get(&value, &JsValue::from_str("hotBytes")) + .ok() + .and_then(|v| v.as_f64()) + .unwrap_or(0.0); + let mut doubles = [0.0; 20]; + doubles[7] = bytes; + doubles[13] = 1.0; + let _ = AnalyticsEngineDataPointBuilder::new() + .indexes([key_id.as_str()]) + .blobs([ + customer_id.as_str(), + "getBlock", + "source_range_complete", + "continuation", + "http_binary", + ]) + .doubles(doubles) + .write_to(&dataset); + }); + Ok(response) + } foundation_first::Outcome::Complete { response, length, digest, .. + } + | foundation_first::Outcome::LedgerCompact { + response, + length, + digest, + .. } => { let (_, body) = response.into_parts(); let parts = stream_parts::response_and_completion_from_parts( diff --git a/crates/blockzilla-finalized-chunks/src/catalog.rs b/crates/blockzilla-finalized-chunks/src/catalog.rs index b1b1672a..2281891e 100644 --- a/crates/blockzilla-finalized-chunks/src/catalog.rs +++ b/crates/blockzilla-finalized-chunks/src/catalog.rs @@ -89,6 +89,18 @@ pub enum ChunkCatalogLookup { }, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CatalogChunkRecord { + pub epoch: u64, + pub start_slot: u64, + pub end_slot: u64, + pub storage_mode: ChunkStorageMode, + pub bundles_location: String, + pub bundles_etag: Option, + pub bundles_length: u64, + pub bundles_sha256: String, +} + pub struct ChunkCatalogWriter { db: Connection, binding: ChunkCatalogBinding, @@ -106,6 +118,8 @@ impl ChunkCatalogWriter { db.execute_batch( "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; + PRAGMA busy_timeout=5000; + PRAGMA wal_autocheckpoint=1000; PRAGMA trusted_schema=OFF; CREATE TABLE IF NOT EXISTS meta ( id INTEGER PRIMARY KEY CHECK (id = 1), @@ -125,6 +139,10 @@ impl ChunkCatalogWriter { CREATE INDEX IF NOT EXISTS idx_chunks_epoch ON chunks(epoch, start_slot); CREATE INDEX IF NOT EXISTS idx_chunks_end_slot ON chunks(end_slot);", )?; + // Persist `-wal` and `-shm` across clean writer closes so read-only + // resolvers (e.g. under `ProtectSystem=strict`) never hit + // SQLITE_CANTOPEN when the writer restarts. + enable_persist_wal(&db)?; let existing: Option = { let mut stmt = db.prepare("SELECT record FROM meta WHERE id = 1")?; @@ -241,12 +259,69 @@ impl ChunkCatalogWriter { Ok(rows.next()?.and_then(|row| row.get::<_, Option>(0).ok()).flatten()) } + pub fn contains_chunk(&self, start_slot: u64, end_slot: u64) -> Result { + let mut stmt = self.db.prepare( + "SELECT 1 FROM chunks WHERE start_slot = ?1 AND end_slot = ?2 LIMIT 1", + )?; + let mut rows = stmt.query(params![start_slot, end_slot])?; + Ok(rows.next()?.is_some()) + } + + pub fn epoch_chunks(&self, epoch: u64) -> Result> { + let mut stmt = self.db.prepare( + "SELECT epoch, start_slot, end_slot, storage_mode, bundles_location, + bundles_etag, bundles_length, bundles_sha256 + FROM chunks + WHERE epoch = ?1 + ORDER BY start_slot ASC", + )?; + let mut rows = stmt.query([epoch])?; + let mut out = Vec::new(); + while let Some(row) = rows.next()? { + out.push(CatalogChunkRecord { + epoch: row.get(0)?, + start_slot: row.get(1)?, + end_slot: row.get(2)?, + storage_mode: ChunkStorageMode::parse(&row.get::<_, String>(3)?)?, + bundles_location: row.get(4)?, + bundles_etag: row.get(5)?, + bundles_length: row.get(6)?, + bundles_sha256: row.get(7)?, + }); + } + Ok(out) + } + pub fn remove_epoch(&mut self, epoch: u64) -> Result { let deleted = self .db .execute("DELETE FROM chunks WHERE epoch = ?1", [epoch])?; Ok(deleted) } + + /// Truncate WAL file contents without unlinking `-wal`/`-shm` (safe with + /// `SQLITE_FCNTL_PERSIST_WAL`). + pub fn checkpoint_truncate(&self) -> Result<()> { + let _ = self.db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);"); + Ok(()) + } +} + +fn enable_persist_wal(db: &Connection) -> Result<()> { + let mut persist: std::ffi::c_int = 1; + let rc = unsafe { + rusqlite::ffi::sqlite3_file_control( + db.handle(), + c"main".as_ptr(), + rusqlite::ffi::SQLITE_FCNTL_PERSIST_WAL, + (&mut persist as *mut std::ffi::c_int).cast(), + ) + }; + ensure!( + rc == rusqlite::ffi::SQLITE_OK, + "failed to set SQLITE_FCNTL_PERSIST_WAL (sqlite rc={rc})" + ); + Ok(()) } pub struct ChunkCatalogReader; @@ -270,7 +345,12 @@ impl ChunkCatalogReader { path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, )?; - db.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN;")?; + db.execute_batch( + "PRAGMA query_only=ON; + PRAGMA busy_timeout=2000; + PRAGMA trusted_schema=OFF; + BEGIN;", + )?; let binding_raw: String = { let mut stmt = db.prepare("SELECT length(CAST(record AS BLOB)), record FROM meta WHERE id = 1")?; let mut rows = stmt.query([])?; diff --git a/crates/blockzilla-finalized-chunks/src/compact.rs b/crates/blockzilla-finalized-chunks/src/compact.rs index 4f4912d1..0359adda 100644 --- a/crates/blockzilla-finalized-chunks/src/compact.rs +++ b/crates/blockzilla-finalized-chunks/src/compact.rs @@ -48,6 +48,7 @@ const VOTE_HASH_ROW_LEN: usize = 65; const RECENT_BLOCKHASH_SLOT_WINDOW: u64 = 150; const ROLLING_BLOCKHASH_CAPACITY: usize = 300; pub const LOCAL_COVERAGE_FILE: &str = "GETBLOCK-EPOCH-COVERAGE.json"; +pub const READY_FILE: &str = "GETBLOCK-EPOCH-READY.json"; const COVERAGE_KIND: &str = "rooted-ledger-scan-v1"; /// Source abstraction supporting both local finalized-chunk directories and @@ -1182,33 +1183,166 @@ fn write_metadata_receipt( result } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LocalCoverage { + pub version: u8, + pub epoch: u64, + pub coverage: CoverageSummary, + pub samples: Vec, + pub successor: EpochHandoffSuccessor, + pub objects: BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CoverageSummary { + pub kind: String, + pub epoch_first_slot: u64, + pub epoch_last_slot: u64, + pub block_count: u64, + pub first_block_slot: u64, + pub last_block_slot: u64, + pub slots_sha256: String, + pub skipped_slot_count: u64, + pub abandoned_fork_count: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LocalObjectDigest { + pub length: u64, + pub sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RemoteObjectDigest { + pub length: u64, + pub etag: String, + pub sha256: String, +} + #[derive(Serialize)] -struct LocalCoverage<'a> { +struct EpochReadyReceipt<'a> { version: u8, epoch: u64, - coverage: CoverageSummary, - samples: Vec, - successor: EpochHandoffSuccessor, - objects: BTreeMap<&'a str, LocalObjectDigest>, + bucket: &'a str, + source_prefix: &'a str, + coverage: &'a CoverageSummary, + samples: &'a [EpochHandoffSuccessor], + successor: &'a EpochHandoffSuccessor, + message_schema: u8, + metadata_schema: u8, + tail_schema: &'static str, + objects: &'a BTreeMap, } -#[derive(Serialize)] -struct CoverageSummary { - kind: &'static str, - epoch_first_slot: u64, - epoch_last_slot: u64, - block_count: u64, - first_block_slot: u64, - last_block_slot: u64, - slots_sha256: String, - skipped_slot_count: u64, - abandoned_fork_count: u64, +impl LocalCoverage { + pub fn read(directory: &Path, expected_epoch: u64) -> Result { + let path = directory.join(LOCAL_COVERAGE_FILE); + let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?; + let parsed: Self = serde_json::from_slice(&bytes) + .with_context(|| format!("parse {}", path.display()))?; + ensure!( + parsed.version == 1 + && parsed.epoch == expected_epoch + && parsed.coverage.kind == COVERAGE_KIND + && parsed.objects.len() == EPOCH_ARCHIVE_FILES.len() + && EPOCH_ARCHIVE_FILES + .iter() + .all(|name| parsed.objects.contains_key(*name)), + "invalid GETBLOCK-EPOCH-COVERAGE.json for epoch {expected_epoch}" + ); + Ok(parsed) + } + + /// Build the exact `GETBLOCK-EPOCH-READY.json` payload matching + /// `blockzilla/ledger-archive/src/publication.rs` for `archive_index_handoff`. + pub fn ready_bytes( + &self, + bucket: &str, + source_prefix: &str, + remote_objects: &BTreeMap, + ) -> Result> { + ensure!( + remote_objects.len() == self.objects.len() + && self.objects.iter().all(|(name, local)| { + remote_objects.get(name).is_some_and(|remote| { + remote.length == local.length + && remote.sha256 == local.sha256 + && valid_quoted_etag(&remote.etag) + }) + }), + "remote Compact V2 objects differ from checked local coverage" + ); + let ready = EpochReadyReceipt { + version: self.version, + epoch: self.epoch, + bucket, + source_prefix, + coverage: &self.coverage, + samples: &self.samples, + successor: &self.successor, + message_schema: 0, + metadata_schema: 0, + tail_schema: "hash_and_slot40", + objects: remote_objects, + }; + let mut bytes = serde_json::to_vec(&ready)?; + bytes.push(b'\n'); + Ok(bytes) + } } -#[derive(Serialize)] -struct LocalObjectDigest { - length: u64, - sha256: String, +/// Extract the first produced block in `epoch + 1` directly from a sealed +/// chunk index (`ChunkIndexV1`) to serve as `GETBLOCK-EPOCH-COVERAGE.json`'s +/// successor anchor for `epoch`. +pub fn extract_epoch_successor( + source: &S, + epoch: u64, +) -> Result { + let next_epoch = epoch.checked_add(1).context("next epoch overflow")?; + let (_, epoch_end) = epoch_slot_range(epoch)?; + let next_chunks = source.list_chunks(next_epoch)?; + let first_non_empty = next_chunks + .iter() + .find(|m| m.block_count > 0) + .with_context(|| format!("epoch {next_epoch} has no sealed chunk with a produced block"))?; + let index_bytes = source.load_index(first_non_empty)?; + verify_bytes( + &index_bytes, + first_non_empty.objects.index.length, + &first_non_empty.objects.index.sha256, + CHUNK_INDEX_FILE, + )?; + let index = ChunkIndexV1::decode(&index_bytes)?; + for (offset, row) in index.entries.iter().enumerate() { + if row.kind == ChunkSlotKind::ProducedBlock { + let slot = index.start_slot + offset as u64; + ensure!( + slot > epoch_end && row.parent_slot <= epoch_end, + "first produced block {slot} in epoch {next_epoch} has parent_slot {} outside epoch {epoch}", + row.parent_slot + ); + return Ok(EpochHandoffSuccessor { + slot, + parent_slot: row.parent_slot, + blockhash: bs58::encode(row.blockhash).into_string(), + previous_blockhash: bs58::encode(row.previous_blockhash).into_string(), + }); + } + } + bail!("chunk {}..={} reported blocks but index had no ProducedBlock", first_non_empty.start_slot, first_non_empty.end_slot) +} + +fn valid_quoted_etag(etag: &str) -> bool { + let Some(opaque) = etag.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else { + return false; + }; + !opaque.is_empty() + && opaque.len() <= 128 + && opaque.bytes().all(|b| b.is_ascii_graphic() && b != b'"') } fn write_local_coverage( @@ -1246,7 +1380,7 @@ fn write_local_coverage( length += n as u64; } objects.insert( - name, + name.to_owned(), LocalObjectDigest { length, sha256: hex::encode(hasher.finalize()), @@ -1257,7 +1391,7 @@ fn write_local_coverage( version: 1, epoch, coverage: CoverageSummary { - kind: COVERAGE_KIND, + kind: COVERAGE_KIND.to_owned(), epoch_first_slot, epoch_last_slot, block_count: block_slots.len() as u64, diff --git a/crates/blockzilla-finalized-chunks/src/format.rs b/crates/blockzilla-finalized-chunks/src/format.rs index 121da883..626a12e2 100644 --- a/crates/blockzilla-finalized-chunks/src/format.rs +++ b/crates/blockzilla-finalized-chunks/src/format.rs @@ -67,18 +67,29 @@ pub fn epoch_slot_range(epoch: u64) -> Result<(u64, u64)> { Ok((start_slot, end_slot)) } -/// Compute the inclusive end slot of a chunk starting at `start_slot`, never -/// crossing the epoch boundary. +/// Compute the inclusive end slot of the canonical epoch-relative chunk window +/// containing `start_slot`, never crossing the epoch boundary. +/// +/// Starts aligned to `epoch_start + k * chunk_slots` produce full `chunk_slots` +/// windows. If a node restarts mid-chunk (e.g. `epoch_start + 500`), only the +/// partial remainder `[500..=chunk_slots-1]` is shorter, and every subsequent +/// chunk snaps back onto the exact deterministic epoch grid across all nodes +/// and CAR backfill shards. pub fn chunk_window_end(start_slot: u64, chunk_slots: u64) -> Result { ensure!( (1..=MAX_CHUNK_SLOTS).contains(&chunk_slots), "chunk_slots {chunk_slots} is outside 1..={MAX_CHUNK_SLOTS}" ); - let (_, epoch_end) = epoch_slot_range(epoch_for_slot(start_slot))?; - let raw_end = start_slot - .checked_add(chunk_slots - 1) + let (epoch_start, epoch_end) = epoch_slot_range(epoch_for_slot(start_slot))?; + let offset = start_slot - epoch_start; + let next_grid_idx = (offset / chunk_slots) + .checked_add(1) + .context("chunk grid index overflows")?; + let next_grid_start = next_grid_idx + .checked_mul(chunk_slots) + .and_then(|span| epoch_start.checked_add(span)) .context("chunk end overflows")?; - Ok(raw_end.min(epoch_end)) + Ok(next_grid_start.saturating_sub(1).min(epoch_end)) } pub fn chunk_dir_name(start_slot: u64, end_slot: u64) -> String { diff --git a/crates/blockzilla-finalized-chunks/src/lib.rs b/crates/blockzilla-finalized-chunks/src/lib.rs index 92d8b961..3fc971ff 100644 --- a/crates/blockzilla-finalized-chunks/src/lib.rs +++ b/crates/blockzilla-finalized-chunks/src/lib.rs @@ -14,14 +14,18 @@ mod tests; pub use builder::{ChunkBuilder, SealedChunk}; #[cfg(feature = "catalog")] -pub use catalog::{ChunkCatalogBinding, ChunkCatalogLookup, ChunkCatalogReader, ChunkCatalogWriter, ChunkStorageMode}; +pub use catalog::{ + CatalogChunkRecord, ChunkCatalogBinding, ChunkCatalogLookup, ChunkCatalogReader, + ChunkCatalogWriter, ChunkStorageMode, +}; pub use check::{ REWARD_SLOT_DISTANCE, RewardNames, classify_abandoned_fork, classify_hole, hole_uses_parent_chain, reward_names, }; pub use compact::{ - ChunkSource, CompactionReport, EpochHandoffSuccessor, LocalChunkSource, - compact_epoch_from_chunks, compact_range_from_chunks, + ChunkSource, CompactionReport, CoverageSummary, EpochHandoffSuccessor, LOCAL_COVERAGE_FILE, + LocalChunkSource, LocalCoverage, LocalObjectDigest, READY_FILE, RemoteObjectDigest, + compact_epoch_from_chunks, compact_range_from_chunks, extract_epoch_successor, }; pub use format::{ CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, CHUNK_INDEX_MAGIC, diff --git a/crates/blockzilla-finalized-chunks/src/tests.rs b/crates/blockzilla-finalized-chunks/src/tests.rs index d9d5b110..f91fb6a7 100644 --- a/crates/blockzilla-finalized-chunks/src/tests.rs +++ b/crates/blockzilla-finalized-chunks/src/tests.rs @@ -1265,3 +1265,174 @@ fn compaction_refuses_rpc_only_degraded_chunks_until_replaced_by_car() { "unexpected error: {msg}" ); } + +#[test] +fn chunk_window_end_snaps_mid_epoch_restarts_back_to_canonical_grid() { + let epoch_start = SLOTS_PER_EPOCH * 10; + let epoch_end = epoch_start + SLOTS_PER_EPOCH - 1; + let chunk_slots = 4_096; + + // Aligned start stays on the exact canonical grid. + assert_eq!( + crate::chunk_window_end(epoch_start, chunk_slots).unwrap(), + epoch_start + 4_095 + ); + assert_eq!( + crate::chunk_window_end(epoch_start + 4_096, chunk_slots).unwrap(), + epoch_start + 8_191 + ); + + // Mid-chunk restart at offset 500 produces one partial window ending at 4095, + // and the very next chunk snaps cleanly onto the exact canonical grid [4096..=8191]. + let partial_end = crate::chunk_window_end(epoch_start + 500, chunk_slots).unwrap(); + assert_eq!(partial_end, epoch_start + 4_095); + assert_eq!( + crate::chunk_window_end(partial_end + 1, chunk_slots).unwrap(), + epoch_start + 8_191 + ); + + // Final window of epoch clamps cleanly to epoch_end. + assert_eq!( + crate::chunk_window_end(epoch_end - 10, chunk_slots).unwrap(), + epoch_end + ); + assert_eq!( + crate::chunk_window_end(epoch_end, chunk_slots).unwrap(), + epoch_end + ); +} + +#[test] +fn catalog_persists_wal_after_clean_writer_close_for_readonly_readers() { + let dir = tempfile::tempdir().unwrap(); + let chunks_root = dir.path().join("chunks"); + let catalog_path = dir.path().join("chunk_catalog.sqlite"); + let s0 = SLOTS_PER_EPOCH; + + let b0 = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: s0, + parent_slot: s0 - 1, + blockhash: [0x21; 32], + previous_blockhash: [0x20; 32], + block_time: Some(1_700_000_000), + block_height: Some(1), + consensus_block_id: [0x22; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 1, + hash: [0x21; 32], + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }, + 1, + ) + .unwrap(); + + let mut builder = ChunkBuilder::create_default(&chunks_root, s0, s0 + 1).unwrap(); + builder.add_block(&b0).unwrap(); + builder.add_skip(s0 + 1).unwrap(); + let sealed = builder.finish().unwrap(); + + let binding = ChunkCatalogBinding { + version: 1, + generation: "persist-wal-gen".into(), + prefix: "finalized-chunks/test".into(), + }; + { + let mut writer = ChunkCatalogWriter::open_or_create(&catalog_path, binding.clone()).unwrap(); + let r2_key = format!( + "{}/epoch-1/{}/{}", + binding.prefix, + crate::chunk_dir_name(s0, s0 + 1), + crate::CHUNK_BUNDLES_FILE + ); + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + ChunkStorageMode::R2, + &r2_key, + Some("\"etag-wal-1\""), + ) + .unwrap(); + assert!(writer.contains_chunk(s0, s0 + 1).unwrap()); + assert_eq!(writer.epoch_chunks(1).unwrap().len(), 1); + writer.checkpoint_truncate().unwrap(); + // Drop writer cleanly! + } + + // With SQLITE_FCNTL_PERSIST_WAL enabled, `-wal` and `-shm` stay on disk after clean close. + let wal_path = dir.path().join("chunk_catalog.sqlite-wal"); + let shm_path = dir.path().join("chunk_catalog.sqlite-shm"); + assert!(wal_path.exists(), "-wal must persist across clean writer close"); + assert!(shm_path.exists(), "-shm must persist across clean writer close"); + + let canonical = catalog_path.canonicalize().unwrap(); + let lookup = ChunkCatalogReader::lookup(&canonical, &binding.generation, &binding.prefix, s0) + .unwrap() + .unwrap(); + assert!(matches!(lookup, ChunkCatalogLookup::ProducedBlock { .. })); +} + +#[test] +fn extract_epoch_successor_reads_first_produced_block_of_next_epoch() { + let dir = tempfile::tempdir().unwrap(); + let chunks_root = dir.path().join("chunks"); + let epoch = 1u64; + let next_start = SLOTS_PER_EPOCH * 2; + let last_in_prev = next_start - 3; + + let bh_prev = [0x44; 32]; + let bh_next = [0x55; 32]; + let succ_block = encode_archive_payload( + &ArchiveBlockPayloadV1 { + slot: next_start + 1, + parent_slot: last_in_prev, + blockhash: bh_next, + previous_blockhash: bh_prev, + block_time: Some(1_700_000_100), + block_height: Some(500), + consensus_block_id: [0x66; 32], + markers: vec![], + rewards_proto: Rewards::default().encode_to_vec(), + entries: vec![ArchiveEntry { + num_hashes: 1, + hash: bh_next, + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }, + 1, + ) + .unwrap(); + + // First slot of epoch 2 is skipped; second slot is the first produced block. + let mut builder = ChunkBuilder::create_default(&chunks_root, next_start, next_start + 2).unwrap(); + builder.add_skip(next_start).unwrap(); + builder.add_block(&succ_block).unwrap(); + builder.add_skip(next_start + 2).unwrap(); + builder.finish().unwrap(); + + let source = LocalChunkSource::new(&chunks_root); + let successor = crate::extract_epoch_successor(&source, epoch).unwrap(); + assert_eq!(successor.slot, next_start + 1); + assert_eq!(successor.parent_slot, last_in_prev); + assert_eq!(successor.blockhash, bs58::encode(bh_next).into_string()); + assert_eq!( + successor.previous_blockhash, + bs58::encode(bh_prev).into_string() + ); +} From 8a1e1bd97c337ce1c063a8fa28a660686a2d1844 Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 20:40:27 +0100 Subject: [PATCH 5/9] feat(finalized-ledger): add disk-space guard, crash repair, multi-epoch recovery caps, and epoch graduation --- blockzilla/finalized-ledger/Cargo.lock | 2 + blockzilla/finalized-ledger/Cargo.toml | 2 + blockzilla/finalized-ledger/README.md | 63 +++- blockzilla/finalized-ledger/src/disk.rs | 125 ++++++ blockzilla/finalized-ledger/src/drain.rs | 399 +++++++++++++++++++- blockzilla/finalized-ledger/src/graduate.rs | 342 +++++++++++++++++ blockzilla/finalized-ledger/src/lib.rs | 2 + blockzilla/finalized-ledger/src/main.rs | 247 +++++++++++- blockzilla/finalized-ledger/src/r2.rs | 261 +++++++++---- blockzilla/finalized-ledger/src/recovery.rs | 295 ++++++++++----- blockzilla/finalized-ledger/src/tests.rs | 317 ++++++++++++++++ 11 files changed, 1869 insertions(+), 186 deletions(-) create mode 100644 blockzilla/finalized-ledger/src/disk.rs create mode 100644 blockzilla/finalized-ledger/src/graduate.rs diff --git a/blockzilla/finalized-ledger/Cargo.lock b/blockzilla/finalized-ledger/Cargo.lock index bc365e8a..28985e58 100644 --- a/blockzilla/finalized-ledger/Cargo.lock +++ b/blockzilla/finalized-ledger/Cargo.lock @@ -258,9 +258,11 @@ dependencies = [ "blockzilla-finalized-chunks", "blockzilla-solana-wire", "bs58", + "bytes", "chrono", "clap", "hex", + "libc", "prost", "reqwest", "serde", diff --git a/blockzilla/finalized-ledger/Cargo.toml b/blockzilla/finalized-ledger/Cargo.toml index b26cc93d..2a51e682 100644 --- a/blockzilla/finalized-ledger/Cargo.toml +++ b/blockzilla/finalized-ledger/Cargo.toml @@ -21,9 +21,11 @@ blockzilla-account-client = { path = "../../crates/blockzilla-account-client" } blockzilla-finalized-chunks = { path = "../../crates/blockzilla-finalized-chunks" } blockzilla-solana-wire = { path = "../../crates/blockzilla-solana-wire", default-features = false, features = ["protobuf"] } bs58 = "0.5.1" +bytes = "1.12.2" chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } clap = { version = "4.6.6", features = ["derive", "env"] } hex = "0.4.3" +libc = "0.2.191" prost = "0.14.4" reqwest = { version = "0.13.4", default-features = false, features = ["blocking", "rustls"] } serde = { version = "1.0.229", features = ["derive"] } diff --git a/blockzilla/finalized-ledger/README.md b/blockzilla/finalized-ledger/README.md index 12151bd8..6048b3d9 100644 --- a/blockzilla/finalized-ledger/README.md +++ b/blockzilla/finalized-ledger/README.md @@ -73,6 +73,39 @@ of the last sealed slot), `drain-chunks` starts live draining immediately at PoH, shredding, Alpenglow `consensus_block_id`, and `block_markers`, `compact-epoch` refuses degraded RPC-only chunks until CAR replaces them. +### Disk-Space, Performance, Crash-Consistency, and Outage Hardening + +- **Deterministic epoch chunk grid**: chunk windows snap to canonical epoch-relative + boundaries (`epoch_start + k * chunk_slots`). After a mid-chunk restart, only + the first partial chunk is shorter, and every subsequent chunk aligns across + all producers and CAR backfill shards. +- **Low-disk-space guard (`--min-free-disk-gib`, default `100`, `0` disables)**: + uses POSIX `statvfs` before sealing each chunk and before `compact-epoch` / + `publish-epoch`. In continuous `drain-chunks`, falling below the floor pauses + sealing, sends a rate-limited `🚨 Blockzilla LOW DISK SPACE` Telegram alert, + and resumes with `✅` when space recovers — preventing `ENOSPC` crashes on + hosts shared with `agave-validator`. +- **Startup crash recovery**: sweeps leftover `.chunk-tmp-*` and + `.graduate-epoch-*` temp directories from SIGKILL/OOM crashes, and finishes + publishing (idempotent R2 upload + SQLite catalog commit + optional payload + eviction) any locally sealed chunk not yet registered in `chunk_catalog.sqlite` + before advancing `next_slot`. +- **Bounded R2 memory & multipart hygiene**: uploads use 32 MiB zero-copy `Bytes` + parts and issue best-effort `AbortMultipartUpload` on failure. In continuous + mode, transient R2 upload failures retry with exponential backoff up to 30s + while the stall watchdog alerts Telegram if the outage persists. +- **SQLite persistent WAL**: `chunk_catalog.sqlite` sets `PRAGMA journal_mode=WAL`, + `PRAGMA busy_timeout=5000`, `PRAGMA wal_autocheckpoint=1000`, and + `SQLITE_FCNTL_PERSIST_WAL` so `-wal` and `-shm` stay on disk across clean + writer restarts for read-only resolvers. +- **Co-located I/O pacing**: optional `--slot-pace-ms ` adds a per-block + delay during bridge reads to keep NVMe/CPU gentle during backlog catchup. +- **Multi-day / multi-week outage bounds**: `--max-local-recovery-slots` + (default `432000`, 1 epoch) and `--max-rpc-fallback-slots` (default `16384`) + fast-fail huge outages directly to `wait_for_car`, writing one durable + `gap--.failed.json` receipt into every missed `epoch-N/` + directory while sending one concise Telegram summary alert. + ### Catchup Stall Watchdog, Mid-Run Restarts, and Fatal Alerts In continuous mode (`drain-chunks` without `--once`): @@ -83,14 +116,14 @@ In continuous mode (`drain-chunks` without `--once`): `node_identity`), detects `next_slot < status.lowest_slot` in-loop, immediately resumes live sealing at `status.lowest_slot`, and launches parallel gap recovery + failure receipts + Telegram alerts for the skipped range. -- **Catchup / drain stall watchdog**: if `--native-socket` stays unreachable or - `max_root` stops advancing for `--stall-alert-secs` (default `600` seconds; - `0` disables), `drain-chunks` sends a `🚨 Blockzilla catchup/drain STALLED` - Telegram alert (repeating every `--stall-repeat-secs`, default `1800`s) and - sends `✅ Blockzilla catchup/drain RECOVERED` once progress resumes. -- **Fatal error alerts**: fatal `drain-chunks` errors (such as R2 upload or - `blockstorePurge` failures) and `compact-epoch` failures send a `🚨` Telegram - alert before exiting non-zero. +- **Catchup / drain stall watchdog**: if `--native-socket` stays unreachable, + R2 uploads stay failing, or `max_root` stops advancing for `--stall-alert-secs` + (default `600` seconds; `0` disables), `drain-chunks` sends a + `🚨 Blockzilla catchup/drain STALLED` Telegram alert (repeating every + `--stall-repeat-secs`, default `1800`s) and sends + `✅ Blockzilla catchup/drain RECOVERED` once progress resumes. +- **Fatal error alerts**: fatal `drain-chunks`, `compact-epoch`, and + `publish-epoch` errors send a `🚨` Telegram alert before exiting non-zero. ### 2. `compact-epoch` @@ -108,6 +141,20 @@ blockzilla-finalized-ledger compact-epoch \ --successor-json /var/lib/blockzilla/epoch-900-successor.json ``` +### 3. `publish-epoch` (and opt-in `--auto-graduate-epochs`) + +End-to-end epoch graduation pipeline: +1. Checks `--min-free-disk-gib` on `--staging-dir`. +2. Extracts the successor anchor automatically from chunk 0 of `epoch + 1` (or reads `--successor-json`). +3. Compacts the epoch into a temporary `.graduate-epoch-N-*` staging directory (auto-removed on both success and failure). +4. Uploads all 13 Compact V2 files + `GETBLOCK-EPOCH-READY.json` to `--publish-r2-prefix` with HEAD length, SHA-256, and ETag verification, then immediately frees the staging directory. +5. Runs optional `--handoff-command` and verifies optional `--verify-catalog-json` contains `epoch`. +6. Only after upload + handoff + admission verification succeed: removes `epoch` from `--catalog-db` (with WAL truncate), deletes R2 chunk objects under `/epoch-N/` if `--cleanup-r2-chunks` is set, and removes local `epoch-N/` if `--cleanup-local-chunks-dir` is set. + +Passing `--auto-graduate-epochs --graduate-r2-prefix ` to `drain-chunks` +triggers this pipeline automatically in the background whenever the first +produced block of `epoch + 1` seals (disabled by default). + Environment variables for R2 mode match `hivezilla-ledger-archive`: `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT` (or `R2_S3_ENDPOINT`), `R2_BUCKET`, `R2_PREFIX`, and `R2_REGION` (`auto`). diff --git a/blockzilla/finalized-ledger/src/disk.rs b/blockzilla/finalized-ledger/src/disk.rs new file mode 100644 index 00000000..c7e0c2bf --- /dev/null +++ b/blockzilla/finalized-ledger/src/disk.rs @@ -0,0 +1,125 @@ +//! Pure-Rust POSIX disk-space guard (`statvfs`) and stale temp-directory cleanup. +//! +//! Prevents `drain-chunks` and `compact-epoch` / `publish-epoch` from ever +//! writing into `ENOSPC` on hosts co-located with `agave-validator` and +//! FireWatch. + +use std::ffi::CString; +use std::fs; +use std::os::unix::ffi::OsStrExt; +use std::path::Path; + +use anyhow::{Context, Result, ensure}; + +pub const DEFAULT_MIN_FREE_DISK_GIB: u64 = 100; +const GIB: u64 = 1024 * 1024 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DiskSpaceStatus { + pub available_bytes: u64, + pub required_bytes: u64, +} + +impl DiskSpaceStatus { + pub fn is_sufficient(self) -> bool { + self.available_bytes >= self.required_bytes + } + + pub fn available_gib(self) -> f64 { + self.available_bytes as f64 / GIB as f64 + } + + pub fn required_gib(self) -> f64 { + self.required_bytes as f64 / GIB as f64 + } +} + +/// Return available unprivileged bytes (`f_bavail * f_frsize`) on the +/// filesystem containing `path` (or its nearest existing ancestor). +pub fn available_bytes(path: &Path) -> Result { + let mut probe = path; + while !probe.exists() { + let Some(parent) = probe.parent() else { + break; + }; + if parent.as_os_str().is_empty() { + probe = Path::new("."); + break; + } + probe = parent; + } + let c_path = CString::new(probe.as_os_str().as_bytes()) + .with_context(|| format!("path contains interior NUL: {}", probe.display()))?; + let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; + let rc = unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) }; + if rc != 0 { + return Err(std::io::Error::last_os_error()) + .with_context(|| format!("statvfs({})", probe.display())); + } + let bavail = u64::from(stat.f_bavail); + let frsize = stat.f_frsize as u64; + Ok(bavail.saturating_mul(frsize)) +} + +/// Check free space on `path` against `min_free_gib` (`0` disables the floor). +pub fn check_free_space(path: &Path, min_free_gib: u64) -> Result { + let available = available_bytes(path)?; + let required = min_free_gib.saturating_mul(GIB); + Ok(DiskSpaceStatus { + available_bytes: available, + required_bytes: required, + }) +} + +/// Fail closed if free disk space on `path` is below `min_free_gib`. +pub fn ensure_free_space(path: &Path, min_free_gib: u64) -> Result { + let status = check_free_space(path, min_free_gib)?; + ensure!( + status.is_sufficient(), + "insufficient free disk space on {}: {:.1} GiB available < {:.1} GiB required", + path.display(), + status.available_gib(), + status.required_gib() + ); + Ok(status) +} + +/// Remove any leftover `.chunk-tmp-*` directories under `output_dir/epoch-*` +/// (and any stale `.graduate-epoch-*` directories directly under `output_dir`) +/// left behind by a previous SIGKILL or OOM crash. +pub fn sweep_stale_chunk_temps(output_dir: &Path) -> Result { + if !output_dir.is_dir() { + return Ok(0); + } + let mut removed = 0usize; + for entry in fs::read_dir(output_dir)? { + let entry = entry?; + let path = entry.path(); + if !path.is_dir() { + continue; + } + let name = entry.file_name(); + let name_str = name.to_string_lossy(); + if name_str.starts_with(".graduate-epoch-") || name_str.starts_with(".chunk-tmp-") { + if fs::remove_dir_all(&path).is_ok() { + removed += 1; + } + continue; + } + if !name_str.starts_with("epoch-") { + continue; + } + for child in fs::read_dir(&path)? { + let child = child?; + let child_path = child.path(); + if child_path.is_dir() + && child.file_name().to_string_lossy().starts_with(".chunk-tmp-") + { + if fs::remove_dir_all(&child_path).is_ok() { + removed += 1; + } + } + } + } + Ok(removed) +} diff --git a/blockzilla/finalized-ledger/src/drain.rs b/blockzilla/finalized-ledger/src/drain.rs index 867532dd..8ed72912 100644 --- a/blockzilla/finalized-ledger/src/drain.rs +++ b/blockzilla/finalized-ledger/src/drain.rs @@ -4,6 +4,7 @@ //! payloads, and optionally triggers Agave's `admin.rpc` `blockstorePurge` //! strictly behind a safety tail. +use std::collections::BTreeSet; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -19,15 +20,18 @@ use blockzilla_account_bridge_protocol::{ use blockzilla_account_client::{AccountClient, ClientOptions, SourceIdentity}; use blockzilla_finalized_chunks::{ CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, - CHUNK_MANIFEST_FILE, ChunkBuilder, ChunkCatalogBinding, ChunkCatalogWriter, ChunkManifestV1, - ChunkStorageMode, REWARD_SLOT_DISTANCE, SealedChunk, TailBlockhash, check, chunk_window_end, - encode_archive_payload, epoch_for_slot, epoch_slot_range, + CHUNK_MANIFEST_FILE, ChunkBuilder, ChunkCatalogBinding, ChunkCatalogWriter, ChunkIndexV1, + ChunkManifestV1, ChunkSlotKind, ChunkStorageMode, EpochHandoffSuccessor, REWARD_SLOT_DISTANCE, + SealedChunk, TailBlockhash, check, chunk_window_end, encode_archive_payload, epoch_for_slot, + epoch_slot_range, }; use sha2::{Digest, Sha256}; use tokio::sync::Mutex; use tokio::task::JoinHandle; use crate::admin_rpc; +use crate::disk; +use crate::graduate::{self, GraduateEpochConfig, GraduationReport}; use crate::notify::{self, TelegramConfig}; use crate::r2::{R2Client, R2Settings}; use crate::recovery::{GapRecoveryConfig, GapRecoveryOutcome, recover_restart_gap}; @@ -51,6 +55,17 @@ pub struct PurgeOptions { pub rpc_timeout: Duration, } +#[derive(Clone, Debug)] +pub struct AutoGraduateOptions { + pub publish_r2: R2Settings, + pub staging_dir: PathBuf, + pub zstd_level: i32, + pub handoff_command: Option, + pub verify_catalog_json: Option, + pub cleanup_r2_chunks: bool, + pub cleanup_local_chunks: bool, +} + #[derive(Clone, Debug)] pub struct DrainConfig { pub native_socket: PathBuf, @@ -75,6 +90,16 @@ pub struct DrainConfig { pub stall_alert_after: Option, /// Repeat interval for ongoing stall alerts. pub stall_repeat_interval: Duration, + /// Minimum free disk space (GiB) required on `output_dir` before sealing + /// each chunk (`0` disables the check). + pub min_free_disk_gib: u64, + /// Optional per-block pacing delay during bridge reads to limit NVMe/CPU + /// contention with co-located services during backlog catchup. + pub slot_pace: Duration, + /// Optional opt-in automatic epoch graduation triggered when chunk 0 of + /// `epoch + 1` seals a produced block. Disabled by default so canary nodes + /// never publish to production Compact V2 prefixes unless explicitly armed. + pub auto_graduate: Option, /// Optional cooperative shutdown flag (in addition to Ctrl-C). pub shutdown: Option>, } @@ -91,6 +116,10 @@ pub struct DrainSummary { pub gap_failure_receipts: Vec, pub stall_alerts_sent: u64, pub stall_recoveries_sent: u64, + pub stale_temps_swept: usize, + pub unpublished_chunks_repaired: u64, + pub low_disk_alerts_sent: u64, + pub epochs_graduated: Vec, } impl DrainConfig { @@ -247,6 +276,16 @@ async fn run_drain_inner(config: DrainConfig) -> Result { fs::create_dir_all(&config.output_dir) .with_context(|| format!("create finalized output dir {}", config.output_dir.display()))?; + let mut summary = DrainSummary::default(); + summary.stale_temps_swept = disk::sweep_stale_chunk_temps(&config.output_dir)?; + if summary.stale_temps_swept > 0 { + eprintln!( + "startup cleanup: removed {} stale temp directories under {}", + summary.stale_temps_swept, + config.output_dir.display() + ); + } + let pinned_genesis_hash = config.source.genesis_hash.clone(); let pinned_node_identity = config.source.node_identity.clone(); let mut current_source = config.source.clone(); @@ -278,15 +317,30 @@ async fn run_drain_inner(config: DrainConfig) -> Result { .transpose() .context("open chunk catalog")?; + // Crash-consistency repair: finish publishing (R2 upload + catalog register + // + optional eviction) any locally sealed chunk written before a crash that + // had not yet committed to `chunk_catalog.sqlite`, BEFORE advancing next_slot! + summary.unpublished_chunks_repaired = repair_unpublished_local_chunks( + &config.output_dir, + r2_settings.as_ref(), + catalog_writer.as_ref(), + config.evict_local_payloads, + ) + .await?; + let mut next_slot = determine_saved_next_slot(&config, catalog_writer.as_ref()).await?; - let mut summary = DrainSummary::default(); let mut recovery_tasks: Vec> = Vec::new(); + let mut graduate_tasks: Vec>> = Vec::new(); + let mut triggered_graduations: BTreeSet = BTreeSet::new(); let mut stall_tracker = StallTracker::new(config.stall_alert_after, config.stall_repeat_interval); + let mut low_disk_active = false; + let mut last_low_disk_alert_at: Option = None; let mut last_purged: Option = None; loop { reap_finished_recovery_tasks(&mut recovery_tasks, &mut summary).await; + reap_finished_graduate_tasks(&mut graduate_tasks, &mut summary).await; if shutdown_requested(&config) { break; } @@ -388,12 +442,55 @@ async fn run_drain_inner(config: DrainConfig) -> Result { continue; } + // Disk-space guard BEFORE writing any chunk so we never trigger ENOSPC + // on hosts shared with agave-validator and FireWatch. + if config.min_free_disk_gib > 0 { + let space = disk::check_free_space(&config.output_dir, config.min_free_disk_gib)?; + if !space.is_sufficient() { + let msg = format!( + "🚨 Blockzilla LOW DISK SPACE on {}: {:.1} GiB free < {:.1} GiB floor — pausing chunk sealing (next_slot={current_slot})", + config.output_dir.display(), + space.available_gib(), + space.required_gib(), + ); + if config.once { + bail!("{msg}"); + } + let should_alert = last_low_disk_alert_at + .is_none_or(|prev| prev.elapsed() >= config.stall_repeat_interval); + if should_alert { + eprintln!("ERROR: {msg}"); + if notify::send_alert(&config.gap_recovery.telegram, msg).await { + summary.low_disk_alerts_sent += 1; + } + last_low_disk_alert_at = Some(Instant::now()); + } + low_disk_active = true; + if wait_poll_or_shutdown(&config).await { + break; + } + continue; + } else if low_disk_active { + low_disk_active = false; + last_low_disk_alert_at = None; + let msg = format!( + "✅ Blockzilla disk space RECOVERED on {}: {:.1} GiB free >= {:.1} GiB floor — resuming chunk sealing", + config.output_dir.display(), + space.available_gib(), + space.required_gib(), + ); + eprintln!("{msg}"); + let _ = notify::send_alert(&config.gap_recovery.telegram, msg).await; + } + } + let sealed = match seal_chunk_from_bridge( &client, &config.output_dir, current_slot, end_slot, config.zstd_level, + config.slot_pace, ) .await { @@ -424,15 +521,41 @@ async fn run_drain_inner(config: DrainConfig) -> Result { }; let (storage_mode, bundles_location, bundles_etag) = if let Some(settings) = &r2_settings { - let settings_clone = settings.clone(); - let sealed_dir = sealed.dir.clone(); - let manifest = sealed.manifest.clone(); - let uploaded = tokio::task::spawn_blocking(move || { - let r2 = R2Client::new(settings_clone)?; - upload_sealed_chunk(&r2, &sealed_dir, &manifest) - }) - .await - .context("join R2 chunk upload task")??; + let mut backoff = config.poll_interval.max(Duration::from_millis(250)); + let uploaded = loop { + let settings_clone = settings.clone(); + let sealed_dir = sealed.dir.clone(); + let manifest = sealed.manifest.clone(); + let upload_res = tokio::task::spawn_blocking(move || { + let r2 = R2Client::new(settings_clone)?; + upload_sealed_chunk(&r2, &sealed_dir, &manifest) + }) + .await + .context("join R2 chunk upload task")?; + match upload_res { + Ok(obj) => break obj, + Err(err) => { + if config.once { + return Err(err).with_context(|| { + format!("upload sealed chunk {current_slot}..={end_slot} to R2") + }); + } + let reason = format!( + "transient R2 upload error for {current_slot}..={end_slot}: {err:#}" + ); + eprintln!("WARN: {reason}; retrying in {:?}", backoff); + stall_tracker + .check_stall(&reason, Some(current_slot), &config.gap_recovery.telegram) + .await; + if sleep_or_shutdown(&config, backoff).await { + return Err(err).with_context(|| { + format!("interrupted while retrying R2 upload for {current_slot}..={end_slot}") + }); + } + backoff = (backoff.saturating_mul(2)).min(Duration::from_secs(30)); + } + } + }; (ChunkStorageMode::R2, uploaded.key, Some(uploaded.etag)) } else { let local_bundles = sealed @@ -501,6 +624,68 @@ async fn run_drain_inner(config: DrainConfig) -> Result { let advanced_slot = end_slot.checked_add(1).context("next_slot overflow")?; next_slot = Some(advanced_slot); + + // When the first produced block of a new epoch seals, persist + // `epoch-/successor.json` automatically and—if explicitly armed + // via `--auto-graduate-epochs`—spawn background Compact V2 graduation + // for `prev_epoch` without stalling live chunk draining. + if sealed.manifest.epoch > 0 && sealed.manifest.block_count > 0 { + let prev_epoch = sealed.manifest.epoch - 1; + let successor_path = config + .output_dir + .join(format!("epoch-{prev_epoch}")) + .join("successor.json"); + if !successor_path.exists() + && let Ok(Some(successor)) = + extract_first_produced_successor(&sealed.index_bytes, prev_epoch) + { + if let Err(err) = write_successor_atomic(&successor_path, &successor) { + eprintln!( + "WARN: failed to persist {}: {err:#}", + successor_path.display() + ); + } else { + eprintln!( + "saved epoch-{prev_epoch} successor anchor (slot={}) -> {}", + successor.slot, + successor_path.display() + ); + } + if let Some(grad_opts) = &config.auto_graduate + && triggered_graduations.insert(prev_epoch) + { + let grad_cfg = GraduateEpochConfig { + epoch: prev_epoch, + source_dir: if r2_settings.is_some() { + None + } else { + Some(config.output_dir.clone()) + }, + chunk_r2: r2_settings.clone(), + publish_r2: grad_opts.publish_r2.clone(), + staging_dir: grad_opts.staging_dir.clone(), + zstd_level: grad_opts.zstd_level, + successor: Some(successor), + handoff_command: grad_opts.handoff_command.clone(), + verify_catalog_json: grad_opts.verify_catalog_json.clone(), + catalog: config.catalog.clone(), + cleanup_r2_chunks: grad_opts.cleanup_r2_chunks, + cleanup_local_chunks_dir: grad_opts + .cleanup_local_chunks + .then(|| config.output_dir.clone()), + min_free_disk_gib: config.min_free_disk_gib, + telegram: config.gap_recovery.telegram.clone(), + }; + eprintln!( + "auto-graduate: spawning background Compact V2 graduation for epoch {prev_epoch}" + ); + graduate_tasks.push(tokio::task::spawn_blocking(move || { + graduate::graduate_epoch(&grad_cfg) + })); + } + } + } + stall_tracker .record_progress( status.max_root, @@ -513,6 +698,9 @@ async fn run_drain_inner(config: DrainConfig) -> Result { for handle in recovery_tasks { record_recovery_outcome(handle.await, &mut summary); } + for handle in graduate_tasks { + record_graduate_outcome(handle.await, &mut summary); + } summary.stall_alerts_sent = stall_tracker.stall_alerts_sent; summary.stall_recoveries_sent = stall_tracker.stall_recoveries_sent; @@ -575,15 +763,49 @@ fn shutdown_requested(config: &DrainConfig) -> bool { } async fn wait_poll_or_shutdown(config: &DrainConfig) -> bool { + sleep_or_shutdown(config, config.poll_interval).await +} + +async fn sleep_or_shutdown(config: &DrainConfig, duration: Duration) -> bool { if shutdown_requested(config) { return true; } tokio::select! { - _ = tokio::time::sleep(config.poll_interval) => shutdown_requested(config), + _ = tokio::time::sleep(duration) => shutdown_requested(config), _ = tokio::signal::ctrl_c() => true, } } +async fn reap_finished_graduate_tasks( + tasks: &mut Vec>>, + summary: &mut DrainSummary, +) { + let mut i = 0; + while i < tasks.len() { + if tasks[i].is_finished() { + let handle = tasks.swap_remove(i); + record_graduate_outcome(handle.await, summary); + } else { + i += 1; + } + } +} + +fn record_graduate_outcome( + result: std::result::Result, tokio::task::JoinError>, + summary: &mut DrainSummary, +) { + match result { + Ok(Ok(report)) => summary.epochs_graduated.push(report.epoch), + Ok(Err(err)) => { + eprintln!("ERROR: background auto-graduation failed: {err:#}"); + } + Err(join_err) => { + eprintln!("ERROR: background auto-graduation task panicked: {join_err}"); + } + } +} + async fn reap_finished_recovery_tasks( tasks: &mut Vec>, summary: &mut DrainSummary, @@ -604,8 +826,8 @@ fn record_recovery_outcome( summary: &mut DrainSummary, ) { match result { - Ok(GapRecoveryOutcome::FailedWithFallback { receipt_path, .. }) => { - summary.gap_failure_receipts.push(receipt_path); + Ok(GapRecoveryOutcome::FailedWithFallback { receipt_paths, .. }) => { + summary.gap_failure_receipts.extend(receipt_paths); } Ok(GapRecoveryOutcome::LocallyRebuilt { .. }) => {} Err(join_err) => { @@ -614,6 +836,147 @@ fn record_recovery_outcome( } } +/// Finish publishing (R2 upload + catalog commit + optional local payload +/// eviction) any locally sealed chunk that is not yet registered in +/// `chunk_catalog.sqlite` (for example after a crash mid-upload). +async fn repair_unpublished_local_chunks( + output_dir: &Path, + r2_settings: Option<&R2Settings>, + catalog_writer: Option<&Arc>>, + evict_local_payloads: bool, +) -> Result { + let Some(writer_arc) = catalog_writer else { + return Ok(0); + }; + if !output_dir.is_dir() { + return Ok(0); + } + + let mut local_chunks: Vec<(ChunkManifestV1, PathBuf)> = Vec::new(); + for epoch_entry in fs::read_dir(output_dir)? { + let epoch_path = epoch_entry?.path(); + if !epoch_path.is_dir() { + continue; + } + for chunk_entry in fs::read_dir(&epoch_path)? { + let chunk_path = chunk_entry?.path(); + if !chunk_path.is_dir() { + continue; + } + let manifest_path = chunk_path.join(CHUNK_MANIFEST_FILE); + if !manifest_path.is_file() { + continue; + } + let raw = fs::read(&manifest_path) + .with_context(|| format!("read {}", manifest_path.display()))?; + let manifest: ChunkManifestV1 = serde_json::from_slice(&raw) + .with_context(|| format!("parse {}", manifest_path.display()))?; + manifest.validate()?; + local_chunks.push((manifest, chunk_path)); + } + } + local_chunks.sort_by_key(|(m, _)| m.start_slot); + + let mut repaired = 0u64; + for (manifest, chunk_dir) in local_chunks { + let already_in_catalog = { + let writer = writer_arc.lock().await; + writer.contains_chunk(manifest.start_slot, manifest.end_slot)? + }; + if already_in_catalog { + continue; + } + let index_path = chunk_dir.join(CHUNK_INDEX_FILE); + let bundles_path = chunk_dir.join(CHUNK_BUNDLES_FILE); + if !index_path.is_file() || !bundles_path.is_file() { + bail!( + "unpublished local chunk {}..={} in {} is missing {} or {}; manual inspection required", + manifest.start_slot, + manifest.end_slot, + chunk_dir.display(), + CHUNK_INDEX_FILE, + CHUNK_BUNDLES_FILE + ); + } + eprintln!( + "crash-recovery: finishing publish for locally sealed chunk {}..={}", + manifest.start_slot, manifest.end_slot + ); + let index_bytes = fs::read(&index_path)?; + let (storage_mode, bundles_location, bundles_etag) = if let Some(settings) = r2_settings { + let settings_clone = settings.clone(); + let dir_clone = chunk_dir.clone(); + let manifest_clone = manifest.clone(); + let uploaded = tokio::task::spawn_blocking(move || { + let r2 = R2Client::new(settings_clone)?; + upload_sealed_chunk(&r2, &dir_clone, &manifest_clone) + }) + .await + .context("join startup R2 repair upload task")??; + (ChunkStorageMode::R2, uploaded.key, Some(uploaded.etag)) + } else { + let canonical = bundles_path.canonicalize()?; + ( + ChunkStorageMode::Local, + canonical + .to_str() + .context("local bundles path not UTF-8")? + .to_owned(), + None, + ) + }; + { + let mut writer = writer_arc.lock().await; + writer.register_chunk( + &manifest, + &index_bytes, + storage_mode, + &bundles_location, + bundles_etag.as_deref(), + )?; + } + if evict_local_payloads { + evict_bulk_payloads(&chunk_dir)?; + } + repaired += 1; + } + Ok(repaired) +} + +fn extract_first_produced_successor( + index_bytes: &[u8], + prev_epoch: u64, +) -> Result> { + let (_, prev_epoch_end) = epoch_slot_range(prev_epoch)?; + let index = ChunkIndexV1::decode(index_bytes)?; + for (offset, row) in index.entries.iter().enumerate() { + if row.kind == ChunkSlotKind::ProducedBlock { + let slot = index.start_slot + offset as u64; + if slot > prev_epoch_end && row.parent_slot <= prev_epoch_end { + return Ok(Some(EpochHandoffSuccessor { + slot, + parent_slot: row.parent_slot, + blockhash: bs58::encode(row.blockhash).into_string(), + previous_blockhash: bs58::encode(row.previous_blockhash).into_string(), + })); + } + return Ok(None); + } + } + Ok(None) +} + +fn write_successor_atomic(path: &Path, successor: &EpochHandoffSuccessor) -> Result<()> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let tmp = path.with_extension("json.tmp"); + let bytes = serde_json::to_vec_pretty(successor)?; + fs::write(&tmp, bytes)?; + fs::rename(&tmp, path)?; + Ok(()) +} + async fn determine_saved_next_slot( config: &DrainConfig, catalog: Option<&Arc>>, @@ -665,6 +1028,7 @@ async fn seal_chunk_from_bridge( start_slot: u64, end_slot: u64, zstd_level: i32, + slot_pace: Duration, ) -> Result { let slot_states = client .get_slot_states(start_slot, end_slot) @@ -707,6 +1071,9 @@ async fn seal_chunk_from_bridge( let slot = start_slot + offset as u64; match state { SlotStateCode::RootedFull => { + if !slot_pace.is_zero() { + tokio::time::sleep(slot_pace).await; + } let envelope = client .get_archive_block(slot, None) .await diff --git a/blockzilla/finalized-ledger/src/graduate.rs b/blockzilla/finalized-ledger/src/graduate.rs new file mode 100644 index 00000000..1118bed9 --- /dev/null +++ b/blockzilla/finalized-ledger/src/graduate.rs @@ -0,0 +1,342 @@ +//! End-to-end automated epoch graduation: +//! 1. Disk-space preflight (`statvfs` floor). +//! 2. Resolve successor anchor from `epoch + 1`'s first produced block (or explicit JSON). +//! 3. Compact epoch into a RAII-guarded staging directory (auto-cleaned on success OR error). +//! 4. Upload all 13 Compact V2 files to R2 (`publish_r2`) with HEAD SHA-256 + ETag verification. +//! 5. Upload `GETBLOCK-EPOCH-READY.json` (exact `ledger-archive/src/publication.rs` schema). +//! 6. Free local staging directory immediately. +//! 7. Invoke optional `--handoff-command` and verify optional `--verify-catalog-json` admission. +//! 8. ONLY after admission succeeds: prune `epoch` from `chunk_catalog.sqlite`, delete R2 +//! chunk objects for `epoch-N/`, and remove local chunk metadata for `epoch-N/`. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{Context, Result, bail, ensure}; +use blockzilla_finalized_chunks::{ + ChunkCatalogBinding, ChunkCatalogWriter, ChunkSource, CompactionReport, EPOCH_ARCHIVE_FILES, + EpochHandoffSuccessor, LocalChunkSource, LocalCoverage, READY_FILE, RemoteObjectDigest, + compact_epoch_from_chunks, extract_epoch_successor, +}; +use bytes::Bytes; +use serde::Deserialize; + +use crate::disk; +use crate::drain::CatalogOptions; +use crate::notify::{self, TelegramConfig}; +use crate::r2::{R2ChunkSource, R2Client, R2Settings}; + +#[derive(Clone, Debug)] +pub struct GraduateEpochConfig { + pub epoch: u64, + /// Local finalized-chunk root (`epoch-N/chunk-.../`) if reading locally. + pub source_dir: Option, + /// R2 settings for source finalized chunks (used when `source_dir` is `None`, + /// and for R2 chunk cleanup after admission if `cleanup_r2_chunks` is true). + pub chunk_r2: Option, + /// Destination R2 settings for Compact V2 publication (`compact-v2//epoch-N/...`). + pub publish_r2: R2Settings, + /// Directory where temporary `.graduate-epoch-N-/` staging files are written + /// during compaction, then immediately deleted after R2 upload. + pub staging_dir: PathBuf, + pub zstd_level: i32, + /// Optional explicit successor anchor; if `None`, automatically extracted from + /// chunk 0 of `epoch + 1`. + pub successor: Option, + /// Optional shell command run after `GETBLOCK-EPOCH-READY.json` is uploaded + /// (e.g. triggering `blockzilla-archive-index-handoff.service`). + pub handoff_command: Option, + /// Optional path to resolver `catalog.json`; when set, verifies `epoch` is + /// present in `catalog.json` BEFORE removing any chunks from SQLite/R2. + pub verify_catalog_json: Option, + /// Optional shared SQLite chunk catalog from which `epoch` is pruned ONLY + /// after publication + handoff + admission verification succeed. + pub catalog: Option, + /// Delete `/epoch-N/` objects from R2 ONLY after admission succeeds. + pub cleanup_r2_chunks: bool, + /// Delete `/epoch-N/` locally ONLY after admission succeeds. + pub cleanup_local_chunks_dir: Option, + /// Minimum free disk space (GiB) required on `staging_dir` before compacting (`0` disables). + pub min_free_disk_gib: u64, + pub telegram: TelegramConfig, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GraduationReport { + pub epoch: u64, + pub compaction: CompactionReport, + pub ready_key: String, + pub uploaded_files: usize, + pub handoff_invoked: bool, + pub catalog_verified: bool, + pub catalog_rows_removed: usize, + pub r2_chunk_objects_deleted: usize, + pub local_epoch_dir_removed: bool, +} + +struct StagingDirGuard { + path: PathBuf, +} + +impl StagingDirGuard { + fn create(parent: &Path, epoch: u64) -> Result { + fs::create_dir_all(parent) + .with_context(|| format!("create staging parent {}", parent.display()))?; + let pid = std::process::id(); + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let path = parent.join(format!(".graduate-epoch-{epoch}-{pid}-{nonce}")); + fs::create_dir_all(&path) + .with_context(|| format!("create staging dir {}", path.display()))?; + Ok(Self { path }) + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for StagingDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +#[derive(Deserialize)] +struct ResolverCatalogSnapshot { + epochs: Vec, +} + +#[derive(Deserialize)] +struct ResolverCatalogEpoch { + epoch: u64, +} + +pub fn verify_epoch_in_catalog_json(path: &Path, epoch: u64) -> Result<()> { + let raw = fs::read(path) + .with_context(|| format!("read archive catalog {}", path.display()))?; + let parsed: ResolverCatalogSnapshot = serde_json::from_slice(&raw) + .with_context(|| format!("parse archive catalog {}", path.display()))?; + ensure!( + parsed.epochs.iter().any(|entry| entry.epoch == epoch), + "epoch {epoch} is not yet admitted in archive catalog {}", + path.display() + ); + Ok(()) +} + +/// Run full end-to-end epoch graduation, sending Telegram notifications on both +/// failure and success. +pub fn graduate_epoch(config: &GraduateEpochConfig) -> Result { + match graduate_epoch_inner(config) { + Ok(report) => { + let msg = format!( + "✅ Blockzilla epoch {} graduated to Compact V2 ({} blocks, ready={}, catalog_pruned={}, r2_chunks_deleted={})", + report.epoch, + report.compaction.blocks, + report.ready_key, + report.catalog_rows_removed, + report.r2_chunk_objects_deleted, + ); + eprintln!("{msg}"); + let _ = notify::send_alert_sync(&config.telegram, &msg); + Ok(report) + } + Err(err) => { + let msg = format!( + "🚨 Blockzilla epoch {} graduation FAILED (chunks retained safely): {err:#}", + config.epoch + ); + eprintln!("ERROR: {msg}"); + let _ = notify::send_alert_sync(&config.telegram, &msg); + Err(err) + } + } +} + +fn graduate_epoch_inner(config: &GraduateEpochConfig) -> Result { + ensure!( + config.source_dir.is_some() || config.chunk_r2.is_some(), + "graduate_epoch requires either local source_dir or chunk_r2 settings" + ); + if config.cleanup_r2_chunks { + ensure!( + config.chunk_r2.is_some(), + "--cleanup-r2-chunks requires chunk R2 settings" + ); + } + + // 1. Refuse to start compaction if NVMe free space is below the configured safety floor. + disk::ensure_free_space(&config.staging_dir, config.min_free_disk_gib)?; + + let publish_client = R2Client::new(config.publish_r2.clone()) + .context("create publish R2 client")?; + + // 2 & 3. Resolve successor and compact epoch into a RAII-guarded staging dir. + let (compaction, ready_key, uploaded_files) = { + let stage = StagingDirGuard::create(&config.staging_dir, config.epoch)?; + let compaction = if let Some(dir) = &config.source_dir { + let source = LocalChunkSource::new(dir); + compact_with_resolved_successor(&source, config, stage.path())? + } else { + let chunk_settings = config + .chunk_r2 + .clone() + .context("missing chunk R2 settings")?; + let chunk_client = R2Client::new(chunk_settings).context("create chunk R2 client")?; + let source = R2ChunkSource::new(chunk_client); + compact_with_resolved_successor(&source, config, stage.path())? + }; + + let coverage = LocalCoverage::read(stage.path(), config.epoch)?; + let epoch_prefix = format!("{}/epoch-{}", config.publish_r2.prefix, config.epoch); + + // 4. Upload all 13 Compact V2 files with HEAD length + SHA-256 + ETag verification. + let mut remote_objects: BTreeMap = BTreeMap::new(); + for file_name in EPOCH_ARCHIVE_FILES { + let local = coverage + .objects + .get(file_name) + .with_context(|| format!("coverage missing {file_name}"))?; + let key = format!("{epoch_prefix}/{file_name}"); + let uploaded = publish_client + .upload_file_verified( + &stage.path().join(file_name), + &key, + local.length, + &local.sha256, + ) + .with_context(|| format!("upload {key}"))?; + remote_objects.insert( + file_name.to_owned(), + RemoteObjectDigest { + length: uploaded.length, + etag: uploaded.etag, + sha256: local.sha256.clone(), + }, + ); + } + + // 5. Upload GETBLOCK-EPOCH-READY.json ONLY after all 13 objects verified on HEAD. + let ready_bytes = coverage.ready_bytes( + &config.publish_r2.bucket, + &config.publish_r2.prefix, + &remote_objects, + )?; + let ready_key = format!("{epoch_prefix}/{READY_FILE}"); + publish_client + .put_bytes_verified(&ready_key, Bytes::from(ready_bytes), "application/json") + .with_context(|| format!("upload {ready_key}"))?; + + // 6. StagingDirGuard drops right here, freeing 100% of local Compact V2 staging space! + (compaction, ready_key, remote_objects.len() + 1) + }; + + // 7. Trigger optional archive index handoff command (fail closed before any cleanup!). + let mut handoff_invoked = false; + if let Some(cmd) = config + .handoff_command + .as_deref() + .filter(|s| !s.trim().is_empty()) + { + handoff_invoked = true; + let output = Command::new("/bin/sh") + .arg("-c") + .arg(cmd) + .env("BLOCKZILLA_GRADUATED_EPOCH", config.epoch.to_string()) + .env("BLOCKZILLA_PUBLISH_BUCKET", &config.publish_r2.bucket) + .env("BLOCKZILLA_PUBLISH_PREFIX", &config.publish_r2.prefix) + .env("BLOCKZILLA_READY_KEY", &ready_key) + .output() + .with_context(|| format!("spawn handoff command '{cmd}'"))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + bail!( + "handoff command exited with {:?}: {}", + output.status.code(), + stderr.trim() + ); + } + } + + // 8. Verify ARCHIVE admission in resolver `catalog.json` before any destructive cleanup. + let mut catalog_verified = false; + if let Some(catalog_json) = &config.verify_catalog_json { + verify_epoch_in_catalog_json(catalog_json, config.epoch)?; + catalog_verified = true; + } + + // 9. Safe post-admission cleanup (only reached after upload + handoff + admission check!). + let mut catalog_rows_removed = 0usize; + if let Some(cat) = &config.catalog { + let mut writer = ChunkCatalogWriter::open_or_create( + &cat.path, + ChunkCatalogBinding { + version: 1, + generation: cat.generation.clone(), + prefix: cat.prefix.clone(), + }, + )?; + catalog_rows_removed = writer.remove_epoch(config.epoch)?; + writer.checkpoint_truncate()?; + } + + let mut r2_chunk_objects_deleted = 0usize; + if config.cleanup_r2_chunks { + let chunk_settings = config + .chunk_r2 + .clone() + .context("missing chunk R2 settings for cleanup")?; + let chunk_client = R2Client::new(chunk_settings.clone())?; + let chunk_epoch_prefix = format!("{}/epoch-{}/", chunk_settings.prefix, config.epoch); + r2_chunk_objects_deleted = chunk_client + .delete_prefix(&chunk_epoch_prefix) + .with_context(|| format!("delete R2 chunks under {chunk_epoch_prefix}"))?; + } + + let mut local_epoch_dir_removed = false; + if let Some(local_root) = &config.cleanup_local_chunks_dir { + let local_epoch_dir = local_root.join(format!("epoch-{}", config.epoch)); + if local_epoch_dir.is_dir() { + fs::remove_dir_all(&local_epoch_dir).with_context(|| { + format!("remove local graduated epoch dir {}", local_epoch_dir.display()) + })?; + local_epoch_dir_removed = true; + } + } + + Ok(GraduationReport { + epoch: config.epoch, + compaction, + ready_key, + uploaded_files, + handoff_invoked, + catalog_verified, + catalog_rows_removed, + r2_chunk_objects_deleted, + local_epoch_dir_removed, + }) +} + +fn compact_with_resolved_successor( + source: &S, + config: &GraduateEpochConfig, + stage_dir: &Path, +) -> Result { + let successor = match &config.successor { + Some(s) => s.clone(), + None => extract_epoch_successor(source, config.epoch) + .with_context(|| format!("extract successor anchor for epoch {}", config.epoch))?, + }; + compact_epoch_from_chunks( + source, + config.epoch, + stage_dir, + config.zstd_level, + Some(successor), + ) +} diff --git a/blockzilla/finalized-ledger/src/lib.rs b/blockzilla/finalized-ledger/src/lib.rs index 092ad8e4..0b0ec634 100644 --- a/blockzilla/finalized-ledger/src/lib.rs +++ b/blockzilla/finalized-ledger/src/lib.rs @@ -1,5 +1,7 @@ pub mod admin_rpc; +pub mod disk; pub mod drain; +pub mod graduate; pub mod notify; pub mod r2; pub mod recovery; diff --git a/blockzilla/finalized-ledger/src/main.rs b/blockzilla/finalized-ledger/src/main.rs index d0f73761..aef7b331 100644 --- a/blockzilla/finalized-ledger/src/main.rs +++ b/blockzilla/finalized-ledger/src/main.rs @@ -4,10 +4,15 @@ //! - `drain-chunks`: polls Agave's live native bridge Unix socket, seals //! immutable finalized chunks, optionally uploads to R2, updates the shared //! `getBlock` SQLite chunk catalog, optionally evicts local bulk payloads, -//! and optionally triggers Agave's `admin.rpc` `blockstorePurge`. +//! optionally triggers Agave's `admin.rpc` `blockstorePurge`, and optionally +//! auto-graduates closed epochs to Compact V2. //! - `compact-epoch`: compacts an epoch (or slot range) from local finalized //! chunks or streaming directly over HTTPS from R2 into the 13 Compact V2 //! epoch files (+ optional `GETBLOCK-EPOCH-COVERAGE.json`). +//! - `publish-epoch`: end-to-end epoch graduation (disk preflight -> compact +//! from local chunks or R2 -> upload 13 Compact V2 files + +//! `GETBLOCK-EPOCH-READY.json` -> handoff -> catalog admission verification -> +//! safe post-admission chunk cleanup). use std::fs; use std::path::PathBuf; @@ -19,15 +24,18 @@ use blockzilla_finalized_chunks::{ DEFAULT_CHUNK_SLOTS, EpochHandoffSuccessor, LocalChunkSource, compact, compact_epoch_from_chunks, }; +use blockzilla_finalized_ledger::disk::{self, DEFAULT_MIN_FREE_DISK_GIB}; use blockzilla_finalized_ledger::drain::{ - CatalogOptions, DEFAULT_PURGE_SAFETY_TAIL, DEFAULT_STALL_ALERT_SECS, DEFAULT_STALL_REPEAT_SECS, - DrainConfig, PurgeOptions, run_drain, + AutoGraduateOptions, CatalogOptions, DEFAULT_PURGE_SAFETY_TAIL, DEFAULT_STALL_ALERT_SECS, + DEFAULT_STALL_REPEAT_SECS, DrainConfig, PurgeOptions, run_drain, }; +use blockzilla_finalized_ledger::graduate::{GraduateEpochConfig, graduate_epoch}; use blockzilla_finalized_ledger::notify::{self, TelegramConfig}; use blockzilla_finalized_ledger::r2::{R2ChunkSource, R2Client, R2Settings}; use blockzilla_finalized_ledger::recovery::{ DEFAULT_FALLBACK_RPC_TIMEOUT, DEFAULT_GAP_RECOVERY_POLL_INTERVAL, DEFAULT_GAP_RECOVERY_TIMEOUT, - GapFallbackPolicy, GapRecoveryConfig, + DEFAULT_MAX_LOCAL_RECOVERY_SLOTS, DEFAULT_MAX_RPC_FALLBACK_SLOTS, GapFallbackPolicy, + GapRecoveryConfig, }; use clap::{Parser, Subcommand, ValueEnum}; @@ -49,7 +57,7 @@ impl From for GapFallbackPolicy { #[derive(Parser)] #[command( name = "blockzilla-finalized-ledger", - about = "Seal finalized ledger chunks from Agave and compact Compact V2 epochs without raw-ledger spikes" + about = "Seal finalized ledger chunks from Agave, compact Compact V2 epochs, and graduate closed epochs without raw-ledger spikes" )] struct Cli { #[command(subcommand)] @@ -69,7 +77,7 @@ enum Command { /// Local directory where `epoch-N/chunk--/` folders are written. #[arg(long)] output_dir: PathBuf, - /// Number of slots per sealed chunk (default 4096, never crosses epoch boundary). + /// Number of slots per sealed chunk (default 4096, snaps to canonical epoch grid). #[arg(long, default_value_t = DEFAULT_CHUNK_SLOTS)] chunk_slots: u64, /// Zstd compression level for chunk bundles, extras, and pubkey counts. @@ -126,15 +134,51 @@ enum Command { /// Maximum seconds to wait for Agave background historical shred recovery before declaring failure and falling back. #[arg(long, default_value_t = DEFAULT_GAP_RECOVERY_TIMEOUT.as_secs())] gap_recovery_timeout_secs: u64, + /// Maximum gap span in slots attempted via Agave shred recovery (`0` disables cap). + #[arg(long, default_value_t = DEFAULT_MAX_LOCAL_RECOVERY_SLOTS)] + max_local_recovery_slots: u64, + /// Maximum gap span in slots attempted via degraded RPC `getBlock` fallback (`0` disables cap). + #[arg(long, default_value_t = DEFAULT_MAX_RPC_FALLBACK_SLOTS)] + max_rpc_fallback_slots: u64, /// Optional shell command invoked after Agave recovers gap shreds to replay from preserved snapshots and seal canonical chunks. #[arg(long)] replay_command: Option, /// Send a Telegram catchup/drain STALLED alert if no progress occurs for this many seconds (`0` disables). #[arg(long, default_value_t = DEFAULT_STALL_ALERT_SECS)] stall_alert_secs: u64, - /// Repeat interval in seconds for persistent stall alerts. + /// Repeat interval in seconds for persistent stall alerts and low-disk alerts. #[arg(long, default_value_t = DEFAULT_STALL_REPEAT_SECS)] stall_repeat_secs: u64, + /// Minimum free disk space in GiB required on `--output-dir` before sealing each chunk (`0` disables). + #[arg(long, default_value_t = DEFAULT_MIN_FREE_DISK_GIB)] + min_free_disk_gib: u64, + /// Optional delay in milliseconds between bridge block reads to reduce NVMe/CPU contention during catchup. + #[arg(long, default_value_t = 0)] + slot_pace_ms: u64, + /// Opt-in: automatically graduate epoch `N - 1` to Compact V2 when chunk 0 of epoch `N` seals. + #[arg(long)] + auto_graduate_epochs: bool, + /// Destination R2 prefix for Compact V2 publication when `--auto-graduate-epochs` is enabled. + #[arg(long)] + graduate_r2_prefix: Option, + /// Optional staging directory for temporary Compact V2 files during auto-graduation (defaults to `--output-dir`). + #[arg(long)] + graduate_staging_dir: Option, + /// Zstd compression level for Compact V2 `blocks.bin` during auto-graduation. + #[arg(long, default_value_t = 3)] + graduate_zstd_level: i32, + /// Optional shell command invoked after `GETBLOCK-EPOCH-READY.json` upload (e.g. `sudo systemctl start blockzilla-archive-index-handoff.service`). + #[arg(long)] + graduate_handoff_command: Option, + /// Optional resolver `catalog.json` path verified to contain the graduated epoch BEFORE pruning chunks. + #[arg(long)] + graduate_verify_catalog_json: Option, + /// Delete R2 chunk objects for the graduated epoch ONLY after publication + handoff + admission verification succeed. + #[arg(long)] + graduate_cleanup_r2_chunks: bool, + /// Delete local `epoch-N/` chunk metadata directory ONLY after admission succeeds. + #[arg(long)] + graduate_cleanup_local_chunks: bool, }, /// Compact an epoch (or slot range) into the 13 Compact V2 archive files from sealed chunks. CompactEpoch { @@ -165,6 +209,60 @@ enum Command { /// Optional JSON file describing the first rooted successor block in `epoch + 1` (emits `GETBLOCK-EPOCH-COVERAGE.json`). #[arg(long)] successor_json: Option, + /// Minimum free disk space in GiB required on `--output-dir` before compacting (`0` disables). + #[arg(long, default_value_t = DEFAULT_MIN_FREE_DISK_GIB)] + min_free_disk_gib: u64, + }, + /// End-to-end epoch graduation: compact -> upload 13 files + GETBLOCK-EPOCH-READY.json -> handoff -> verify -> clean up chunks. + PublishEpoch { + /// Epoch number to graduate. + #[arg(long)] + epoch: u64, + /// Read chunks from a local finalized-ledger directory (mutually exclusive with --from-r2). + #[arg(long, conflicts_with = "from_r2")] + source_dir: Option, + /// Stream chunks directly over HTTPS from Cloudflare R2 (reads R2_* env vars). + #[arg(long, conflicts_with = "source_dir")] + from_r2: bool, + /// Optional override for source chunk `R2_PREFIX`. + #[arg(long)] + chunk_r2_prefix: Option, + /// Destination Compact V2 R2 prefix (e.g. `compact-v2/blockzilla-20261004` or a canary prefix). + #[arg(long)] + publish_r2_prefix: String, + /// Directory for temporary staging during compaction (auto-deleted after R2 upload). + #[arg(long)] + staging_dir: PathBuf, + /// Zstd compression level for `blocks.bin`. + #[arg(long, default_value_t = 3)] + zstd_level: i32, + /// Optional explicit successor JSON; if omitted, auto-extracted from chunk 0 of `epoch + 1`. + #[arg(long)] + successor_json: Option, + /// Optional handoff shell command invoked after `GETBLOCK-EPOCH-READY.json` is uploaded. + #[arg(long)] + handoff_command: Option, + /// Optional resolver `catalog.json` path verified to contain `epoch` BEFORE any chunk cleanup. + #[arg(long)] + verify_catalog_json: Option, + /// Optional shared SQLite chunk catalog from which `epoch` is removed ONLY after admission succeeds. + #[arg(long)] + catalog_db: Option, + /// Generation identifier bound into `--catalog-db`. + #[arg(long)] + catalog_generation: Option, + /// Storage prefix bound into `--catalog-db`. + #[arg(long)] + catalog_prefix: Option, + /// Delete R2 chunk objects for `epoch` ONLY after publication + handoff + verification succeed. + #[arg(long)] + cleanup_r2_chunks: bool, + /// Optional local chunk root whose `epoch-N/` subdirectory is removed ONLY after admission succeeds. + #[arg(long)] + cleanup_local_chunks_dir: Option, + /// Minimum free disk space in GiB required on `--staging-dir` before compacting (`0` disables). + #[arg(long, default_value_t = DEFAULT_MIN_FREE_DISK_GIB)] + min_free_disk_gib: u64, }, } @@ -194,9 +292,21 @@ fn main() -> Result<()> { fallback_rpc_url, fallback_rpc_timeout_ms, gap_recovery_timeout_secs, + max_local_recovery_slots, + max_rpc_fallback_slots, replay_command, stall_alert_secs, stall_repeat_secs, + min_free_disk_gib, + slot_pace_ms, + auto_graduate_epochs, + graduate_r2_prefix, + graduate_staging_dir, + graduate_zstd_level, + graduate_handoff_command, + graduate_verify_catalog_json, + graduate_cleanup_r2_chunks, + graduate_cleanup_local_chunks, } => { let source_raw = fs::read(&source_json) .with_context(|| format!("read source identity {}", source_json.display()))?; @@ -225,6 +335,23 @@ fn main() -> Result<()> { None => None, }; + let auto_graduate = if auto_graduate_epochs { + let publish_prefix = graduate_r2_prefix + .context("--graduate-r2-prefix is required with --auto-graduate-epochs")?; + let publish_r2 = R2Settings::from_env(Some(publish_prefix))?; + Some(AutoGraduateOptions { + publish_r2, + staging_dir: graduate_staging_dir.unwrap_or_else(|| output_dir.clone()), + zstd_level: graduate_zstd_level, + handoff_command: graduate_handoff_command, + verify_catalog_json: graduate_verify_catalog_json, + cleanup_r2_chunks: graduate_cleanup_r2_chunks, + cleanup_local_chunks: graduate_cleanup_local_chunks, + }) + } else { + None + }; + let purge = purge_ledger.clone().map(|ledger_dir| PurgeOptions { ledger_dir, safety_tail: purge_safety_tail, @@ -240,6 +367,8 @@ fn main() -> Result<()> { fallback_policy: gap_fallback_policy.into(), fallback_rpc_url, fallback_rpc_timeout: Duration::from_millis(fallback_rpc_timeout_ms.max(100)), + max_local_recovery_slots, + max_rpc_fallback_slots, telegram: TelegramConfig::from_env(), }; @@ -266,21 +395,28 @@ fn main() -> Result<()> { stall_alert_after: (stall_alert_secs > 0) .then(|| Duration::from_secs(stall_alert_secs)), stall_repeat_interval: Duration::from_secs(stall_repeat_secs.max(1)), + min_free_disk_gib, + slot_pace: Duration::from_millis(slot_pace_ms), + auto_graduate, shutdown: None, }))?; eprintln!( - "drain complete: chunks={}, blocks={}, skips={}, forks={}, highest_sealed={:?}, highest_purged={:?}, gap_recovery_triggered={}, gap_failure_receipts={}, stall_alerts={}, stall_recoveries={}", + "drain complete: chunks={}, blocks={}, skips={}, forks={}, highest_sealed={:?}, highest_purged={:?}, repaired={}, temps_swept={}, gap_recovery_triggered={}, gap_failure_receipts={}, low_disk_alerts={}, stall_alerts={}, stall_recoveries={}, epochs_graduated={:?}", summary.chunks_sealed, summary.blocks_sealed, summary.skips_sealed, summary.forks_sealed, summary.highest_sealed_slot, summary.highest_purged_slot, + summary.unpublished_chunks_repaired, + summary.stale_temps_swept, summary.gap_recovery_triggered, summary.gap_failure_receipts.len(), + summary.low_disk_alerts_sent, summary.stall_alerts_sent, summary.stall_recoveries_sent, + summary.epochs_graduated, ); Ok(()) } @@ -294,11 +430,20 @@ fn main() -> Result<()> { start_slot, end_slot, successor_json, + min_free_disk_gib, } => { ensure!( source_dir.is_some() || from_r2, "specify either --source-dir or --from-r2" ); + if let Err(err) = disk::ensure_free_space(&output_dir, min_free_disk_gib) { + let tg = TelegramConfig::from_env(); + let _ = notify::send_alert_sync( + &tg, + &format!("🚨 Blockzilla compact-epoch {epoch} REFUSED (low disk): {err:#}"), + ); + return Err(err); + } let successor = match successor_json { Some(path) => { let raw = fs::read(&path) @@ -385,5 +530,91 @@ fn main() -> Result<()> { ); Ok(()) } + Command::PublishEpoch { + epoch, + source_dir, + from_r2, + chunk_r2_prefix, + publish_r2_prefix, + staging_dir, + zstd_level, + successor_json, + handoff_command, + verify_catalog_json, + catalog_db, + catalog_generation, + catalog_prefix, + cleanup_r2_chunks, + cleanup_local_chunks_dir, + min_free_disk_gib, + } => { + ensure!( + source_dir.is_some() || from_r2, + "specify either --source-dir or --from-r2" + ); + let chunk_r2 = if from_r2 || cleanup_r2_chunks { + Some(R2Settings::from_env(chunk_r2_prefix)?) + } else { + None + }; + let publish_r2 = R2Settings::from_env(Some(publish_r2_prefix))?; + let successor = match successor_json { + Some(path) => { + let raw = fs::read(&path) + .with_context(|| format!("read successor {}", path.display()))?; + Some( + serde_json::from_slice::(&raw) + .with_context(|| format!("parse successor {}", path.display()))?, + ) + } + None => None, + }; + let catalog = match catalog_db { + Some(path) => { + let generation = catalog_generation + .context("--catalog-generation is required with --catalog-db")?; + let prefix = catalog_prefix + .or_else(|| chunk_r2.as_ref().map(|r| r.prefix.clone())) + .context("--catalog-prefix is required with --catalog-db")?; + Some(CatalogOptions { + path, + generation, + prefix, + }) + } + None => None, + }; + + let report = graduate_epoch(&GraduateEpochConfig { + epoch, + source_dir, + chunk_r2, + publish_r2, + staging_dir, + zstd_level, + successor, + handoff_command, + verify_catalog_json, + catalog, + cleanup_r2_chunks, + cleanup_local_chunks_dir, + min_free_disk_gib, + telegram: TelegramConfig::from_env(), + })?; + + eprintln!( + "published epoch {}: blocks={}, uploaded_files={}, ready={}, handoff_invoked={}, catalog_verified={}, catalog_rows_removed={}, r2_chunks_deleted={}, local_epoch_dir_removed={}", + report.epoch, + report.compaction.blocks, + report.uploaded_files, + report.ready_key, + report.handoff_invoked, + report.catalog_verified, + report.catalog_rows_removed, + report.r2_chunk_objects_deleted, + report.local_epoch_dir_removed, + ); + Ok(()) + } } } diff --git a/blockzilla/finalized-ledger/src/r2.rs b/blockzilla/finalized-ledger/src/r2.rs index c79640a8..e9f1dbaa 100644 --- a/blockzilla/finalized-ledger/src/r2.rs +++ b/blockzilla/finalized-ledger/src/r2.rs @@ -17,6 +17,7 @@ use blockzilla_finalized_chunks::{ CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, CHUNK_MANIFEST_FILE, ChunkManifestV1, ChunkSource, chunk_dir_name, }; +use bytes::Bytes; use chrono::Utc; use reqwest::Method; use reqwest::blocking::{Body, Client, Response}; @@ -32,7 +33,8 @@ pub const R2_PREFIX_ENV: &str = "R2_PREFIX"; pub const R2_REGION_ENV: &str = "R2_REGION"; const DEFAULT_REGION: &str = "auto"; -const PART_SIZE: u64 = 128 * 1024 * 1024; +/// 32 MiB multipart part size keeps peak upload RAM modest on co-located hosts. +const PART_SIZE: u64 = 32 * 1024 * 1024; const UNSIGNED_PAYLOAD: &str = "UNSIGNED-PAYLOAD"; const PAYLOAD_SHA256: &str = "x-amz-content-sha256"; const OBJECT_SHA256: &str = "x-amz-meta-blockzilla-sha256"; @@ -177,8 +179,10 @@ impl R2Client { } if expected_len <= PART_SIZE { - let bytes = std::fs::read(path) - .with_context(|| format!("read local file {}", path.display()))?; + let bytes = Bytes::from( + std::fs::read(path) + .with_context(|| format!("read local file {}", path.display()))?, + ); let actual_sha = hex::encode(Sha256::digest(&bytes)); ensure!( actual_sha == expected_sha256, @@ -198,7 +202,7 @@ impl R2Client { key, &BTreeMap::new(), &headers, - &bytes, + bytes, 1024 * 1024, )?; ensure!( @@ -230,6 +234,104 @@ impl R2Client { }) } + /// Upload an in-memory verified object (e.g. `GETBLOCK-EPOCH-READY.json`) + /// idempotently and confirm length, SHA-256 metadata, and ETag via HEAD. + pub fn put_bytes_verified( + &self, + key: &str, + bytes: Bytes, + content_type: &str, + ) -> Result { + let expected_len = bytes.len() as u64; + let expected_sha256 = hex::encode(Sha256::digest(&bytes)); + if let Some((remote_len, remote_etag, remote_sha)) = self.head_object(key)? { + ensure!( + remote_len == expected_len, + "remote object {key} has length {remote_len}, expected {expected_len}" + ); + if let Some(sha) = remote_sha { + ensure!( + sha == expected_sha256, + "remote object {key} SHA-256 metadata {sha} differs from {expected_sha256}" + ); + } + return Ok(UploadedObject { + key: key.to_owned(), + etag: remote_etag, + length: remote_len, + }); + } + let headers = BTreeMap::from([ + ("content-type".to_owned(), content_type.to_owned()), + (PAYLOAD_SHA256.to_owned(), expected_sha256.clone()), + (OBJECT_SHA256.to_owned(), expected_sha256.clone()), + ]); + let resp = self.request_buffered( + Method::PUT, + key, + &BTreeMap::new(), + &headers, + bytes, + 1024 * 1024, + )?; + ensure!( + resp.status == 200, + "PUT {key} returned HTTP {}", + resp.status + ); + let (remote_len, remote_etag, remote_sha) = self + .head_object(key)? + .with_context(|| format!("uploaded object {key} missing on HEAD"))?; + ensure!( + remote_len == expected_len, + "uploaded object {key} HEAD length {remote_len} != {expected_len}" + ); + if let Some(sha) = remote_sha { + ensure!( + sha == expected_sha256, + "uploaded object {key} HEAD SHA-256 {sha} != {expected_sha256}" + ); + } + Ok(UploadedObject { + key: key.to_owned(), + etag: remote_etag, + length: remote_len, + }) + } + + /// Idempotently delete a single R2 object (`204`, `200`, or `404` all succeed). + pub fn delete_object(&self, key: &str) -> Result<()> { + let resp = self.request_buffered( + Method::DELETE, + key, + &BTreeMap::new(), + &BTreeMap::new(), + Bytes::new(), + 64 * 1024, + )?; + ensure!( + matches!(resp.status, 200 | 204 | 404), + "DELETE {key} returned HTTP {}", + resp.status + ); + Ok(()) + } + + /// Delete every R2 object under `key_prefix`. Returns the count of deleted keys. + pub fn delete_prefix(&self, key_prefix: &str) -> Result { + ensure!( + !key_prefix.trim().is_empty() && key_prefix.ends_with('/'), + "refusing to delete R2 prefix '{key_prefix}' without trailing slash" + ); + let keys = self.list_keys(key_prefix)?; + let mut deleted = 0usize; + for key in &keys { + self.delete_object(key)?; + deleted += 1; + } + Ok(deleted) + } + fn upload_multipart( &self, path: &Path, @@ -247,7 +349,7 @@ impl R2Client { key, &init_params, &init_headers, - &[], + Bytes::new(), 1024 * 1024, )?; ensure!( @@ -263,72 +365,95 @@ impl R2Client { .context("multipart response missing UploadId")? .to_owned(); - let file = File::open(path)?; - let mut parts: Vec<(u32, String)> = Vec::new(); - let mut offset = 0u64; - let mut part_number = 1u32; - while offset < total_len { - let size = PART_SIZE.min(total_len - offset) as usize; - let mut buf = vec![0u8; size]; - file.read_exact_at(&mut buf, offset)?; - let params = BTreeMap::from([ - ("partNumber".to_owned(), part_number.to_string()), - ("uploadId".to_owned(), upload_id.clone()), - ]); - let headers = BTreeMap::from([ + let upload_result = (|| -> Result<()> { + let file = File::open(path)?; + let mut parts: Vec<(u32, String)> = Vec::new(); + let mut offset = 0u64; + let mut part_number = 1u32; + while offset < total_len { + let size = PART_SIZE.min(total_len - offset) as usize; + let mut buf = vec![0u8; size]; + file.read_exact_at(&mut buf, offset)?; + let body = Bytes::from(buf); + let params = BTreeMap::from([ + ("partNumber".to_owned(), part_number.to_string()), + ("uploadId".to_owned(), upload_id.clone()), + ]); + let headers = BTreeMap::from([ + ( + "content-type".to_owned(), + "application/octet-stream".to_owned(), + ), + (PAYLOAD_SHA256.to_owned(), hex::encode(Sha256::digest(&body))), + ]); + let resp = self.request_buffered( + Method::PUT, + key, + ¶ms, + &headers, + body, + 1024 * 1024, + )?; + ensure!( + resp.status == 200, + "upload part {part_number} of {key} returned HTTP {}", + resp.status + ); + let etag = quote_etag(header_value(&resp.headers, "etag", "upload part")?); + parts.push((part_number, etag)); + offset += size as u64; + part_number += 1; + } + + let mut xml = String::from(""); + for (number, etag) in &parts { + xml.push_str(&format!( + "{number}{etag}" + )); + } + xml.push_str(""); + let complete_body = Bytes::from(xml.into_bytes()); + let complete_params = BTreeMap::from([("uploadId".to_owned(), upload_id.clone())]); + let complete_headers = BTreeMap::from([ + ("content-type".to_owned(), "application/xml".to_owned()), ( - "content-type".to_owned(), - "application/octet-stream".to_owned(), + PAYLOAD_SHA256.to_owned(), + hex::encode(Sha256::digest(&complete_body)), ), - (PAYLOAD_SHA256.to_owned(), hex::encode(Sha256::digest(&buf))), ]); let resp = self.request_buffered( - Method::PUT, + Method::POST, key, - ¶ms, - &headers, - &buf, + &complete_params, + &complete_headers, + complete_body, 1024 * 1024, )?; ensure!( resp.status == 200, - "upload part {part_number} of {key} returned HTTP {}", + "complete multipart {key} returned HTTP {}", resp.status ); - let etag = quote_etag(header_value(&resp.headers, "etag", "upload part")?); - parts.push((part_number, etag)); - offset += size as u64; - part_number += 1; - } + Ok(()) + })(); - let mut xml = String::from(""); - for (number, etag) in &parts { - xml.push_str(&format!( - "{number}{etag}" - )); + if upload_result.is_err() { + // Best-effort AbortMultipartUpload so R2 does not retain orphaned parts. + let _ = self.abort_multipart(key, &upload_id); } - xml.push_str(""); - let complete_params = BTreeMap::from([("uploadId".to_owned(), upload_id)]); - let complete_headers = BTreeMap::from([ - ("content-type".to_owned(), "application/xml".to_owned()), - ( - PAYLOAD_SHA256.to_owned(), - hex::encode(Sha256::digest(xml.as_bytes())), - ), - ]); - let resp = self.request_buffered( - Method::POST, + upload_result + } + + fn abort_multipart(&self, key: &str, upload_id: &str) -> Result<()> { + let params = BTreeMap::from([("uploadId".to_owned(), upload_id.to_owned())]); + let _ = self.request_buffered( + Method::DELETE, key, - &complete_params, - &complete_headers, - xml.as_bytes(), - 1024 * 1024, + ¶ms, + &BTreeMap::new(), + Bytes::new(), + 64 * 1024, )?; - ensure!( - resp.status == 200, - "complete multipart {key} returned HTTP {}", - resp.status - ); Ok(()) } @@ -338,7 +463,7 @@ impl R2Client { key, &BTreeMap::new(), &BTreeMap::new(), - &[], + Bytes::new(), 64 * 1024, )?; if resp.status == 404 { @@ -374,7 +499,7 @@ impl R2Client { "", ¶ms, &BTreeMap::new(), - &[], + Bytes::new(), MAX_SMALL_RESPONSE_BYTES, )?; ensure!( @@ -410,7 +535,7 @@ impl R2Client { key, &BTreeMap::new(), &BTreeMap::new(), - &[], + Bytes::new(), max_bytes, )?; ensure!( @@ -422,7 +547,13 @@ impl R2Client { } pub fn open_stream(&self, key: &str) -> Result> { - let resp = self.send_with_retry(Method::GET, key, &BTreeMap::new(), &BTreeMap::new(), &[])?; + let resp = self.send_with_retry( + Method::GET, + key, + &BTreeMap::new(), + &BTreeMap::new(), + Bytes::new(), + )?; let status = resp.status().as_u16(); ensure!(status == 200, "GET stream {key} returned HTTP {status}"); Ok(Box::new(resp)) @@ -434,7 +565,7 @@ impl R2Client { key: &str, params: &BTreeMap, headers: &BTreeMap, - body: &[u8], + body: Bytes, max_response_bytes: usize, ) -> Result { let resp = self.send_with_retry(method.clone(), key, params, headers, body)?; @@ -461,11 +592,11 @@ impl R2Client { key: &str, params: &BTreeMap, headers: &BTreeMap, - body: &[u8], + body: Bytes, ) -> Result { let mut last_err = None; for attempt in 1..=ATTEMPTS { - match self.send_once(method.clone(), key, params, headers, body) { + match self.send_once(method.clone(), key, params, headers, body.clone()) { Ok(resp) => return Ok(resp), Err(err) => { last_err = Some(err); @@ -484,7 +615,7 @@ impl R2Client { key: &str, params: &BTreeMap, headers: &BTreeMap, - body: &[u8], + body: Bytes, ) -> Result { let now = Utc::now(); let date = now.format("%Y%m%d").to_string(); @@ -542,7 +673,7 @@ impl R2Client { } let mut req = self.client.request(method.clone(), &url); if !body.is_empty() { - req = req.body(Body::from(body.to_vec())); + req = req.body(Body::from(body)); } for (name, value) in &signed { req = req.header( diff --git a/blockzilla/finalized-ledger/src/recovery.rs b/blockzilla/finalized-ledger/src/recovery.rs index f3833b06..a0ca3d3b 100644 --- a/blockzilla/finalized-ledger/src/recovery.rs +++ b/blockzilla/finalized-ledger/src/recovery.rs @@ -20,7 +20,8 @@ use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail, ensure}; use blockzilla_finalized_chunks::{ CHUNK_BUNDLES_FILE, CHUNK_INDEX_FILE, CHUNK_MANIFEST_FILE, ChunkCatalogWriter, ChunkManifestV1, - ChunkStorageMode, DEGRADED_SOURCE_RPC_ONLY, SealedChunk, chunk_dir_name, epoch_for_slot, + ChunkStorageMode, DEGRADED_SOURCE_RPC_ONLY, SLOTS_PER_EPOCH, SealedChunk, chunk_dir_name, + epoch_for_slot, epoch_slot_range, }; use chrono::Utc; use serde::{Deserialize, Serialize}; @@ -36,6 +37,12 @@ use crate::rpc_fallback; pub const DEFAULT_GAP_RECOVERY_POLL_INTERVAL: Duration = Duration::from_secs(2); pub const DEFAULT_GAP_RECOVERY_TIMEOUT: Duration = Duration::from_secs(30 * 60); pub const DEFAULT_FALLBACK_RPC_TIMEOUT: Duration = Duration::from_secs(30); +/// Default cap on peer shred recovery span (1 epoch = 432,000 slots). +/// Multi-day/multi-week outages above this cap fail fast to CAR backfill. +pub const DEFAULT_MAX_LOCAL_RECOVERY_SLOTS: u64 = SLOTS_PER_EPOCH; +/// Default cap on degraded RPC `getBlock` fallback span (16,384 slots ≈ ~1.8h). +/// Prevents issuing millions of sequential RPC calls during multi-day outages. +pub const DEFAULT_MAX_RPC_FALLBACK_SLOTS: u64 = 16_384; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -63,6 +70,10 @@ pub struct GapRecoveryConfig { pub fallback_policy: GapFallbackPolicy, pub fallback_rpc_url: Option, pub fallback_rpc_timeout: Duration, + /// Maximum slot span attempted via Agave shred recovery (`0` disables cap). + pub max_local_recovery_slots: u64, + /// Maximum slot span attempted via degraded RPC fallback (`0` disables cap). + pub max_rpc_fallback_slots: u64, pub telegram: TelegramConfig, } @@ -77,6 +88,8 @@ impl Default for GapRecoveryConfig { fallback_policy: GapFallbackPolicy::WaitForCar, fallback_rpc_url: None, fallback_rpc_timeout: DEFAULT_FALLBACK_RPC_TIMEOUT, + max_local_recovery_slots: DEFAULT_MAX_LOCAL_RECOVERY_SLOTS, + max_rpc_fallback_slots: DEFAULT_MAX_RPC_FALLBACK_SLOTS, telegram: TelegramConfig::from_env(), } } @@ -121,10 +134,33 @@ pub enum GapRecoveryOutcome { }, FailedWithFallback { receipt_path: PathBuf, + receipt_paths: Vec, receipt: GapFailureReceipt, }, } +/// Split an inclusive slot gap `[gap_start..=gap_end]` into per-epoch slices +/// `(epoch, ep_start, ep_end)` so multi-day or multi-week outages write a +/// durable failure receipt into every affected `epoch-N/` directory. +pub fn split_gap_by_epoch(gap_start: u64, gap_end: u64) -> Vec<(u64, u64, u64)> { + if gap_start > gap_end { + return Vec::new(); + } + let mut slices = Vec::new(); + let mut cursor = gap_start; + while cursor <= gap_end { + let epoch = epoch_for_slot(cursor); + let (_, epoch_end) = epoch_slot_range(epoch).unwrap_or((cursor, gap_end)); + let slice_end = gap_end.min(epoch_end); + slices.push((epoch, cursor, slice_end)); + if slice_end == u64::MAX { + break; + } + cursor = slice_end + 1; + } + slices +} + pub fn gap_receipt_path(output_dir: &Path, gap_start: u64, gap_end: u64) -> PathBuf { let epoch = epoch_for_slot(gap_start); output_dir @@ -158,95 +194,142 @@ pub async fn recover_restart_gap( evict_local_payloads: bool, config: GapRecoveryConfig, ) -> GapRecoveryOutcome { - let epoch = epoch_for_slot(gap_start); + let epoch_slices = split_gap_by_epoch(gap_start, gap_end); + let first_epoch = epoch_for_slot(gap_start); + let last_epoch = epoch_for_slot(gap_end); + let epoch_label = if first_epoch == last_epoch { + format!("epoch {first_epoch}") + } else { + format!("epochs {first_epoch}..={last_epoch} ({} epochs)", epoch_slices.len()) + }; let gap_slots = gap_end.saturating_sub(gap_start).saturating_add(1); let detected_at_utc = Utc::now().to_rfc3339(); eprintln!( - "gap-recovery: detected restart gap epoch-{epoch} slots {gap_start}..={gap_end} ({gap_slots} slots); live draining continues immediately while parallel recovery runs" + "gap-recovery: detected restart gap {epoch_label} slots {gap_start}..={gap_end} ({gap_slots} slots); live draining continues immediately while parallel recovery runs" ); - // Step 1: Attempt local historical shred recovery via Agave admin.rpc + optional replay command. - let (failure_reason, last_status) = match try_local_recovery( - gap_start, - gap_end, - &output_dir, - chunk_slots, - &r2_settings, - &catalog_writer, - evict_local_payloads, - &config, - ) - .await + // Step 1: Attempt local historical shred recovery via Agave admin.rpc + optional replay command + // unless the gap exceeds `max_local_recovery_slots` (e.g. multi-day/week outage). + let (failure_reason, last_status) = if config.max_local_recovery_slots > 0 + && gap_slots > config.max_local_recovery_slots { - Ok((chunks_published, recovery_status)) => { - eprintln!( - "gap-recovery: SUCCEEDED locally for epoch-{epoch} slots {gap_start}..={gap_end} (published {chunks_published} canonical chunks)" - ); - let _ = notify::send_alert( - &config.telegram, - format!( - "✅ Blockzilla gap recovery succeeded locally: epoch {epoch} slots {gap_start}..={gap_end} ({chunks_published} canonical chunks)" - ), - ) - .await; - return GapRecoveryOutcome::LocallyRebuilt { - chunks_published, - recovery_status, - }; + ( + format!( + "gap spans {gap_slots} slots across {epoch_label}, exceeding max_local_recovery_slots ({}); skipping peer shred recovery (CAR backfill required)", + config.max_local_recovery_slots + ), + None, + ) + } else { + match try_local_recovery( + gap_start, + gap_end, + &output_dir, + chunk_slots, + &r2_settings, + &catalog_writer, + evict_local_payloads, + &config, + ) + .await + { + Ok((chunks_published, recovery_status)) => { + eprintln!( + "gap-recovery: SUCCEEDED locally for {epoch_label} slots {gap_start}..={gap_end} (published {chunks_published} canonical chunks)" + ); + let _ = notify::send_alert( + &config.telegram, + format!( + "✅ Blockzilla gap recovery succeeded locally: {epoch_label} slots {gap_start}..={gap_end} ({chunks_published} canonical chunks)" + ), + ) + .await; + return GapRecoveryOutcome::LocallyRebuilt { + chunks_published, + recovery_status, + }; + } + Err((reason, status)) => (reason, status), } - Err((reason, status)) => (reason, status), }; - // Step 2: FAILURE PATH — log error, write durable receipt, and notify Telegram! + // Step 2: FAILURE PATH — log error, write durable per-epoch receipts across + // EVERY missed epoch, and send ONE concise summary alert to Telegram! eprintln!( - "ERROR: gap-recovery FAILED for epoch-{epoch} slots {gap_start}..={gap_end} ({gap_slots} slots): {failure_reason}; fallback={:?}", + "ERROR: gap-recovery FAILED for {epoch_label} slots {gap_start}..={gap_end} ({gap_slots} slots): {failure_reason}; fallback={:?}", config.fallback_policy ); - let receipt_path = gap_receipt_path(&output_dir, gap_start, gap_end); - let mut receipt = GapFailureReceipt { - version: 1, - epoch, - gap_start_slot: gap_start, - gap_end_slot: gap_end, - gap_slots, - reason: failure_reason.clone(), - historical_recovery_status: last_status, - fallback_policy: config.fallback_policy, - fallback_status: GapFallbackStatus::WaitingForCar, - rpc_chunks_sealed: Vec::new(), - telegram_notified: false, - detected_at_utc: detected_at_utc.clone(), - updated_at_utc: detected_at_utc, + let rpc_capped = config.fallback_policy == GapFallbackPolicy::RpcGetBlock + && config.max_rpc_fallback_slots > 0 + && gap_slots > config.max_rpc_fallback_slots; + + let effective_reason = if rpc_capped { + format!( + "{failure_reason}; skipping RPC fallback because gap ({gap_slots} slots) exceeds max_rpc_fallback_slots ({}) — CAR backfill required", + config.max_rpc_fallback_slots + ) + } else { + failure_reason.clone() }; - if let Err(err) = write_receipt_atomic(&receipt_path, &receipt) { - eprintln!( - "ERROR: failed to write gap failure receipt {}: {err:#}", - receipt_path.display() - ); + let mut per_epoch_receipts: Vec<(PathBuf, GapFailureReceipt)> = epoch_slices + .iter() + .map(|&(ep, ep_start, ep_end)| { + let path = gap_receipt_path(&output_dir, ep_start, ep_end); + let ep_slots = ep_end.saturating_sub(ep_start).saturating_add(1); + let receipt = GapFailureReceipt { + version: 1, + epoch: ep, + gap_start_slot: ep_start, + gap_end_slot: ep_end, + gap_slots: ep_slots, + reason: effective_reason.clone(), + historical_recovery_status: last_status.clone(), + fallback_policy: config.fallback_policy, + fallback_status: GapFallbackStatus::WaitingForCar, + rpc_chunks_sealed: Vec::new(), + telegram_notified: false, + detected_at_utc: detected_at_utc.clone(), + updated_at_utc: detected_at_utc.clone(), + }; + (path, receipt) + }) + .collect(); + + for (path, receipt) in &per_epoch_receipts { + if let Err(err) = write_receipt_atomic(path, receipt) { + eprintln!( + "ERROR: failed to write gap failure receipt {}: {err:#}", + path.display() + ); + } } let fallback_label = match config.fallback_policy { GapFallbackPolicy::WaitForCar => "wait_for_car (CAR required before epoch compaction)", + GapFallbackPolicy::RpcGetBlock if rpc_capped => { + "rpc_get_block SKIPPED (exceeds --max-rpc-fallback-slots cap); waiting for CAR" + } GapFallbackPolicy::RpcGetBlock => { "rpc_get_block (attempting degraded RPC backfill; CAR still required before epoch compaction)" } }; let alert_text = format!( - "🚨 Blockzilla gap recovery FAILED: epoch {epoch} slots {gap_start}..={gap_end} ({gap_slots} slots) — {failure_reason} | fallback: {fallback_label}" + "🚨 Blockzilla gap recovery FAILED: {epoch_label} slots {gap_start}..={gap_end} ({gap_slots} slots) — {effective_reason} | fallback: {fallback_label}" ); - receipt.telegram_notified = notify::send_alert(&config.telegram, alert_text).await; - receipt.updated_at_utc = Utc::now().to_rfc3339(); - let _ = write_receipt_atomic(&receipt_path, &receipt); - - // Step 3: Execute configured fallback policy. - if config.fallback_policy == GapFallbackPolicy::RpcGetBlock { - let rpc_url = config - .fallback_rpc_url - .clone() - .unwrap_or_default(); + let notified = notify::send_alert(&config.telegram, alert_text).await; + let updated = Utc::now().to_rfc3339(); + for (path, receipt) in &mut per_epoch_receipts { + receipt.telegram_notified = notified; + receipt.updated_at_utc = updated.clone(); + let _ = write_receipt_atomic(path, receipt); + } + + // Step 3: Execute configured RPC fallback policy if within slot cap. + if config.fallback_policy == GapFallbackPolicy::RpcGetBlock && !rpc_capped { + let rpc_url = config.fallback_rpc_url.clone().unwrap_or_default(); let out_clone = output_dir.clone(); let rpc_timeout = config.fallback_rpc_timeout; let backfill_res = tokio::task::spawn_blocking(move || { @@ -267,12 +350,16 @@ pub async fn recover_restart_gap( match backfill_res { Ok(sealed_chunks) => { let mut publish_err = None; - let mut sealed_names = Vec::with_capacity(sealed_chunks.len()); + let mut sealed_by_epoch: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); for sealed in &sealed_chunks { - sealed_names.push(chunk_dir_name( - sealed.manifest.start_slot, - sealed.manifest.end_slot, - )); + sealed_by_epoch + .entry(sealed.manifest.epoch) + .or_default() + .push(chunk_dir_name( + sealed.manifest.start_slot, + sealed.manifest.end_slot, + )); if let Err(err) = publish_chunk( sealed, r2_settings.as_ref(), @@ -286,61 +373,91 @@ pub async fn recover_restart_gap( } } if let Some(err) = publish_err { - receipt.fallback_status = GapFallbackStatus::RpcFallbackFailed; - receipt.reason = format!( - "{}; RPC fallback publish failed: {err:#}", - receipt.reason - ); + let err_msg = format!("RPC fallback publish failed: {err:#}"); + for (_, receipt) in &mut per_epoch_receipts { + receipt.fallback_status = GapFallbackStatus::RpcFallbackFailed; + receipt.reason = format!("{}; {err_msg}", receipt.reason); + } eprintln!( "ERROR: gap-recovery RPC fallback publish failed for {gap_start}..={gap_end}: {err:#}" ); let _ = notify::send_alert( &config.telegram, format!( - "🚨 Blockzilla RPC fallback FAILED for epoch {epoch} slots {gap_start}..={gap_end}: {err:#} — waiting for CAR" + "🚨 Blockzilla RPC fallback FAILED for {epoch_label} slots {gap_start}..={gap_end}: {err:#} — waiting for CAR" ), ) .await; } else { - receipt.fallback_status = - GapFallbackStatus::RpcBackfilledDegradedWaitingForCar; - receipt.rpc_chunks_sealed = sealed_names; + let total_chunks = sealed_chunks.len(); + for (_, receipt) in &mut per_epoch_receipts { + receipt.fallback_status = + GapFallbackStatus::RpcBackfilledDegradedWaitingForCar; + receipt.rpc_chunks_sealed = sealed_by_epoch + .remove(&receipt.epoch) + .unwrap_or_default(); + } eprintln!( - "WARN: gap-recovery sealed {} degraded RPC chunks ({DEGRADED_SOURCE_RPC_ONLY}) for {gap_start}..={gap_end}; getBlock can serve them temporarily, but epoch compaction will refuse until CAR replaces them", - receipt.rpc_chunks_sealed.len() + "WARN: gap-recovery sealed {total_chunks} degraded RPC chunks ({DEGRADED_SOURCE_RPC_ONLY}) for {gap_start}..={gap_end}; getBlock can serve them temporarily, but epoch compaction will refuse until CAR replaces them" ); let _ = notify::send_alert( &config.telegram, format!( - "⚠️ Blockzilla RPC degraded backfill complete for epoch {epoch} slots {gap_start}..={gap_end} ({} chunks, source={DEGRADED_SOURCE_RPC_ONLY}); CAR still required before epoch compaction", - receipt.rpc_chunks_sealed.len() + "⚠️ Blockzilla RPC degraded backfill complete for {epoch_label} slots {gap_start}..={gap_end} ({total_chunks} chunks, source={DEGRADED_SOURCE_RPC_ONLY}); CAR still required before epoch compaction" ), ) .await; } } Err(err) => { - receipt.fallback_status = GapFallbackStatus::RpcFallbackFailed; - receipt.reason = format!("{}; RPC fallback failed: {err:#}", receipt.reason); + for (_, receipt) in &mut per_epoch_receipts { + receipt.fallback_status = GapFallbackStatus::RpcFallbackFailed; + receipt.reason = format!("{}; RPC fallback failed: {err:#}", receipt.reason); + } eprintln!( "ERROR: gap-recovery RPC fallback failed for {gap_start}..={gap_end}: {err:#}" ); let _ = notify::send_alert( &config.telegram, format!( - "🚨 Blockzilla RPC fallback FAILED for epoch {epoch} slots {gap_start}..={gap_end}: {err:#} — waiting for CAR" + "🚨 Blockzilla RPC fallback FAILED for {epoch_label} slots {gap_start}..={gap_end}: {err:#} — waiting for CAR" ), ) .await; } } - receipt.updated_at_utc = Utc::now().to_rfc3339(); - let _ = write_receipt_atomic(&receipt_path, &receipt); + let updated = Utc::now().to_rfc3339(); + for (path, receipt) in &mut per_epoch_receipts { + receipt.updated_at_utc = updated.clone(); + let _ = write_receipt_atomic(path, receipt); + } } + let receipt_paths: Vec = per_epoch_receipts.iter().map(|(p, _)| p.clone()).collect(); + let (primary_path, primary_receipt) = per_epoch_receipts.into_iter().next().unwrap_or_else(|| { + let path = gap_receipt_path(&output_dir, gap_start, gap_end); + let receipt = GapFailureReceipt { + version: 1, + epoch: first_epoch, + gap_start_slot: gap_start, + gap_end_slot: gap_end, + gap_slots, + reason: effective_reason, + historical_recovery_status: last_status, + fallback_policy: config.fallback_policy, + fallback_status: GapFallbackStatus::WaitingForCar, + rpc_chunks_sealed: Vec::new(), + telegram_notified: notified, + detected_at_utc: detected_at_utc.clone(), + updated_at_utc: detected_at_utc, + }; + (path, receipt) + }); + GapRecoveryOutcome::FailedWithFallback { - receipt_path, - receipt, + receipt_path: primary_path, + receipt_paths, + receipt: primary_receipt, } } diff --git a/blockzilla/finalized-ledger/src/tests.rs b/blockzilla/finalized-ledger/src/tests.rs index d00619d0..32cb98bd 100644 --- a/blockzilla/finalized-ledger/src/tests.rs +++ b/blockzilla/finalized-ledger/src/tests.rs @@ -288,6 +288,12 @@ fn handle_http_conn( "HTTP/1.1 200 OK\r\nETag: {etag}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" )?; } + "DELETE" => { + objects.lock().unwrap().remove(&key); + stream.write_all( + b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + )?; + } "HEAD" => { let guard = objects.lock().unwrap(); if let Some(obj) = guard.get(&key) { @@ -579,6 +585,9 @@ async fn end_to_end_drain_r2_catalog_evict_purge_and_streaming_compact() { gap_recovery: GapRecoveryConfig::default(), stall_alert_after: None, stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, shutdown: None, }) .await @@ -1030,6 +1039,8 @@ async fn restart_gap_drains_live_immediately_and_wait_for_car_writes_receipt_and fallback_policy: GapFallbackPolicy::WaitForCar, fallback_rpc_url: None, fallback_rpc_timeout: Duration::from_secs(5), + max_local_recovery_slots: crate::recovery::DEFAULT_MAX_LOCAL_RECOVERY_SLOTS, + max_rpc_fallback_slots: crate::recovery::DEFAULT_MAX_RPC_FALLBACK_SLOTS, telegram: TelegramConfig { bot_token: secret_token.into(), chat_id: "-100999".into(), @@ -1038,6 +1049,9 @@ async fn restart_gap_drains_live_immediately_and_wait_for_car_writes_receipt_and }, stall_alert_after: None, stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, shutdown: None, }) .await @@ -1278,6 +1292,8 @@ async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_ale fallback_policy: GapFallbackPolicy::RpcGetBlock, fallback_rpc_url: Some(rpc_server.url.clone()), fallback_rpc_timeout: Duration::from_secs(5), + max_local_recovery_slots: crate::recovery::DEFAULT_MAX_LOCAL_RECOVERY_SLOTS, + max_rpc_fallback_slots: crate::recovery::DEFAULT_MAX_RPC_FALLBACK_SLOTS, telegram: TelegramConfig { bot_token: "123:TESTTOKEN".into(), chat_id: "-100123".into(), @@ -1286,6 +1302,9 @@ async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_ale }, stall_alert_after: None, stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, shutdown: None, }) .await @@ -1532,6 +1551,9 @@ async fn catchup_stall_alerts_telegram_and_sends_recovery_when_max_root_advances }, stall_alert_after: Some(Duration::from_millis(80)), stall_repeat_interval: Duration::from_secs(30), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, shutdown: Some(shutdown.clone()), }) .await @@ -1757,6 +1779,9 @@ async fn mid_run_validator_restart_reloads_source_and_triggers_parallel_gap_reco }, stall_alert_after: None, stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, shutdown: Some(shutdown.clone()), }) .await @@ -1813,6 +1838,9 @@ async fn fatal_drain_error_sends_telegram_alert_before_exiting() { }, stall_alert_after: None, stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, shutdown: None, }) .await @@ -1823,3 +1851,292 @@ async fn fatal_drain_error_sends_telegram_alert_before_exiting() { assert_eq!(tg_reqs.len(), 1); assert!(tg_reqs[0].1.contains("FATAL"), "req: {}", tg_reqs[0].1); } + +#[tokio::test] +async fn multi_epoch_outage_writes_per_epoch_receipts_and_caps_rpc_fallback() { + let root = tempfile::tempdir().unwrap(); + let output_dir = root.path().join("chunks"); + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + let rpc_called = Arc::new(AtomicBool::new(false)); + let rpc_called_srv = rpc_called.clone(); + let rpc_server = MockHttpJsonServer::start(move |_path, _body| { + rpc_called_srv.store(true, Ordering::Relaxed); + (500, "must not be called above cap".into()) + }); + + // Multi-epoch outage spanning epoch 1 tail, all of epoch 2, and epoch 3 head (~432,020 slots). + let gap_start = SLOTS_PER_EPOCH * 2 - 10; + let gap_end = SLOTS_PER_EPOCH * 3 + 9; + + let outcome = crate::recovery::recover_restart_gap( + gap_start, + gap_end, + output_dir.clone(), + 4_096, + 1, + None, + None, + false, + GapRecoveryConfig { + admin_ledger_dir: None, + fallback_policy: GapFallbackPolicy::RpcGetBlock, + fallback_rpc_url: Some(rpc_server.url.clone()), + max_local_recovery_slots: 100_000, + max_rpc_fallback_slots: 16_384, + telegram: TelegramConfig { + bot_token: "123:MULTI".into(), + chat_id: "-10099".into(), + api_base_url: tg_server.url.clone(), + }, + ..GapRecoveryConfig::default() + }, + ) + .await; + + assert!( + !rpc_called.load(Ordering::Relaxed), + "RPC fallback must not be called when gap exceeds max_rpc_fallback_slots" + ); + + let receipt_paths = match outcome { + crate::recovery::GapRecoveryOutcome::FailedWithFallback { receipt_paths, .. } => { + receipt_paths + } + other => panic!("expected FailedWithFallback, got {other:?}"), + }; + assert_eq!( + receipt_paths.len(), + 3, + "must emit one failure receipt in each affected epoch directory (epochs 1, 2, 3)" + ); + + let mut seen_epochs = Vec::new(); + for path in &receipt_paths { + assert!(path.is_file(), "receipt missing at {}", path.display()); + let receipt: GapFailureReceipt = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + seen_epochs.push(receipt.epoch); + assert_eq!(receipt.fallback_status, GapFallbackStatus::WaitingForCar); + assert!(receipt.reason.contains("max_local_recovery_slots")); + assert!(receipt.reason.contains("max_rpc_fallback_slots")); + assert!(receipt.telegram_notified); + } + assert_eq!(seen_epochs, vec![1, 2, 3]); + + // Exactly ONE concise Telegram summary alert (not 3 spam alerts). + let tg_reqs = tg_server.requests.lock().unwrap(); + assert_eq!(tg_reqs.len(), 1); + assert!(tg_reqs[0].1.contains("epochs 1..=3")); +} + +#[tokio::test] +async fn startup_crash_recovery_sweeps_stale_temps_and_publishes_unregistered_local_chunk() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let output_dir = root.path().join("finalized-chunks"); + let catalog_path = root.path().join("chunk_catalog.sqlite"); + let s0 = SLOTS_PER_EPOCH; + + // 1. Simulate a locally sealed chunk [s0..=s0+3] where the process crashed + // BEFORE uploading to R2 or registering in `chunk_catalog.sqlite`, PLUS a + // stale `.chunk-tmp-crashed` directory left by SIGKILL. + let stale_tmp = output_dir.join("epoch-1").join(".chunk-tmp-crashed"); + std::fs::create_dir_all(&stale_tmp).unwrap(); + std::fs::write(stale_tmp.join("partial.bin"), b"junk").unwrap(); + + let payload = ArchiveBlockPayloadV1 { + slot: s0, + parent_slot: s0 - 1, + blockhash: [0x71; 32], + previous_blockhash: [0x70; 32], + block_time: Some(1_700_000_000), + block_height: Some(10), + consensus_block_id: [0x72; 32], + markers: vec![], + rewards_proto: vec![], + entries: vec![ArchiveEntry { + num_hashes: 1, + hash: [0x71; 32], + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }; + let encoded = blockzilla_finalized_chunks::encode_archive_payload(&payload, 1).unwrap(); + let mut builder = + blockzilla_finalized_chunks::ChunkBuilder::create_default(&output_dir, s0, s0 + 3).unwrap(); + builder.add_block(&encoded).unwrap(); + builder.add_skip(s0 + 1).unwrap(); + builder.add_skip(s0 + 2).unwrap(); + builder.add_skip(s0 + 3).unwrap(); + let sealed = builder.finish().unwrap(); + + // 2. Live bridge sits at max_root = s0 + 5 (so no new chunk seals after s0+3). + let (bridge_stop, bridge_handle) = + spawn_mock_live_bridge_at_tip(&bridge_sock, s0, HashMap::new(), s0 + 5); + let r2_server = MockR2Server::start("blockzilla-crash-test"); + let r2_settings = r2_server.settings("finalized-chunks/mainnet"); + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: true, + poll_interval: Duration::from_millis(20), + r2: Some(r2_settings), + catalog: Some(CatalogOptions { + path: catalog_path.clone(), + generation: "gen-crash-1".into(), + prefix: "finalized-chunks/mainnet".into(), + }), + evict_local_payloads: true, + purge: None, + gap_recovery: GapRecoveryConfig::default(), + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: None, + shutdown: None, + }) + .await + .expect("run_drain crash repair"); + + assert_eq!(summary.stale_temps_swept, 1); + assert!(!stale_tmp.exists(), "stale .chunk-tmp dir must be removed"); + assert_eq!(summary.unpublished_chunks_repaired, 1); + assert_eq!(r2_server.objects.lock().unwrap().len(), 5); + assert!( + !sealed.dir.join(blockzilla_finalized_chunks::CHUNK_BUNDLES_FILE).exists(), + "bulk payload must be evicted after crash-repair R2 upload + catalog commit" + ); + + let lookup = ChunkCatalogReader::lookup( + &catalog_path.canonicalize().unwrap(), + "gen-crash-1", + "finalized-chunks/mainnet", + s0, + ) + .unwrap() + .unwrap(); + assert!(matches!( + lookup, + ChunkCatalogLookup::ProducedBlock { + storage_mode: ChunkStorageMode::R2, + .. + } + )); + + bridge_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); +} + +#[tokio::test] +async fn low_disk_space_guard_refuses_sealing_and_alerts_telegram() { + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let output_dir = root.path().join("finalized-chunks"); + let s0 = SLOTS_PER_EPOCH; + + let (bridge_stop, bridge_handle) = + spawn_mock_live_bridge_at_tip(&bridge_sock, s0, HashMap::new(), s0 + 20); + let tg_server = MockHttpJsonServer::start(|_path, _body| (200, "{\"ok\":true}".into())); + + // Require an impossibly large free-space floor (10 billion GiB) to trigger the guard! + let err = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: true, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: None, + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig { + telegram: TelegramConfig { + bot_token: "123:DISK".into(), + chat_id: "-10077".into(), + api_base_url: tg_server.url.clone(), + }, + ..GapRecoveryConfig::default() + }, + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 10_000_000_000, + slot_pace: Duration::ZERO, + auto_graduate: None, + shutdown: None, + }) + .await + .unwrap_err(); + + assert!(err.to_string().contains("LOW DISK SPACE"), "err: {err:#}"); + let tg_reqs = tg_server.requests.lock().unwrap(); + assert_eq!(tg_reqs.len(), 1); + assert!(tg_reqs[0].1.contains("LOW DISK SPACE")); + + bridge_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); +} + +#[test] +fn r2_put_bytes_delete_prefix_and_catalog_admission_verification() { + let r2_server = MockR2Server::start("blockzilla-grad-test"); + let settings = r2_server.settings("finalized-chunks/mainnet"); + let client = crate::r2::R2Client::new(settings).unwrap(); + + let key1 = "finalized-chunks/mainnet/epoch-5/chunk-a/chunk.manifest.json"; + let key2 = "finalized-chunks/mainnet/epoch-5/chunk-b/chunk.manifest.json"; + let other_epoch_key = "finalized-chunks/mainnet/epoch-6/chunk-a/chunk.manifest.json"; + client + .put_bytes_verified(key1, bytes::Bytes::from_static(b"{\"a\":1}"), "application/json") + .unwrap(); + client + .put_bytes_verified(key2, bytes::Bytes::from_static(b"{\"b\":2}"), "application/json") + .unwrap(); + client + .put_bytes_verified( + other_epoch_key, + bytes::Bytes::from_static(b"{\"c\":3}"), + "application/json", + ) + .unwrap(); + + let deleted = client + .delete_prefix("finalized-chunks/mainnet/epoch-5/") + .unwrap(); + assert_eq!(deleted, 2); + assert!(client.head_object(key1).unwrap().is_none()); + assert!(client.head_object(key2).unwrap().is_none()); + assert!(client.head_object(other_epoch_key).unwrap().is_some()); + + // Verify catalog.json admission check accepts admitted epoch and rejects missing epoch. + let dir = tempfile::tempdir().unwrap(); + let catalog_json = dir.path().join("catalog.json"); + std::fs::write( + &catalog_json, + r#"{"version":1,"source_prefix":"compact-v2/test","generation":"g1","epochs":[{"epoch":1095},{"epoch":1096}]}"#, + ) + .unwrap(); + crate::graduate::verify_epoch_in_catalog_json(&catalog_json, 1096).unwrap(); + assert!(crate::graduate::verify_epoch_in_catalog_json(&catalog_json, 1097).is_err()); +} From 56f5398ac2461dddedc0af13b5bea6d1c98a2aca Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 22:34:15 +0100 Subject: [PATCH 6/9] fix(get-block,finalized-ledger): prefer admitted archive over recent ring, retry auto-graduation, and snap fresh snapshot starts --- blockzilla/finalized-ledger/src/drain.rs | 317 ++++++++++++++--- blockzilla/finalized-ledger/src/main.rs | 5 +- blockzilla/finalized-ledger/src/tests.rs | 322 ++++++++++++++++++ .../get-block/resolver/src/finalized.rs | 44 +-- .../get-block/resolver/src/http_tests.rs | 52 +++ 5 files changed, 664 insertions(+), 76 deletions(-) diff --git a/blockzilla/finalized-ledger/src/drain.rs b/blockzilla/finalized-ledger/src/drain.rs index 8ed72912..00ddeb37 100644 --- a/blockzilla/finalized-ledger/src/drain.rs +++ b/blockzilla/finalized-ledger/src/drain.rs @@ -4,7 +4,7 @@ //! payloads, and optionally triggers Agave's `admin.rpc` `blockstorePurge` //! strictly behind a safety tail. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -40,6 +40,20 @@ pub const MIN_PURGE_SAFETY_TAIL: u64 = 300; pub const DEFAULT_PURGE_SAFETY_TAIL: u64 = 512; pub const DEFAULT_STALL_ALERT_SECS: u64 = 600; pub const DEFAULT_STALL_REPEAT_SECS: u64 = 1_800; +pub const DEFAULT_GRADUATE_RETRY_SECS: u64 = 60; +pub const SUCCESSOR_FILE: &str = "successor.json"; +pub const GRADUATED_MARKER_FILE: &str = "graduated.json"; + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +struct GraduatedEpochMarker { + epoch: u64, + ready_key: String, + blocks: u64, + uploaded_files: usize, + catalog_verified: bool, + catalog_rows_removed: usize, + r2_chunk_objects_deleted: usize, +} #[derive(Clone, Debug)] pub struct CatalogOptions { @@ -64,6 +78,8 @@ pub struct AutoGraduateOptions { pub verify_catalog_json: Option, pub cleanup_r2_chunks: bool, pub cleanup_local_chunks: bool, + /// Minimum backoff before retrying a failed background graduation attempt. + pub retry_interval: Duration, } #[derive(Clone, Debug)] @@ -330,8 +346,9 @@ async fn run_drain_inner(config: DrainConfig) -> Result { let mut next_slot = determine_saved_next_slot(&config, catalog_writer.as_ref()).await?; let mut recovery_tasks: Vec> = Vec::new(); - let mut graduate_tasks: Vec>> = Vec::new(); - let mut triggered_graduations: BTreeSet = BTreeSet::new(); + let mut graduate_tasks: Vec<(u64, JoinHandle>)> = Vec::new(); + let mut in_flight_graduations: BTreeSet = BTreeSet::new(); + let mut graduate_retry_after: BTreeMap = BTreeMap::new(); let mut stall_tracker = StallTracker::new(config.stall_alert_after, config.stall_repeat_interval); let mut low_disk_active = false; @@ -340,7 +357,21 @@ async fn run_drain_inner(config: DrainConfig) -> Result { loop { reap_finished_recovery_tasks(&mut recovery_tasks, &mut summary).await; - reap_finished_graduate_tasks(&mut graduate_tasks, &mut summary).await; + reap_finished_graduate_tasks( + &mut graduate_tasks, + &mut in_flight_graduations, + &mut graduate_retry_after, + &config, + &mut summary, + ) + .await; + schedule_pending_graduations( + &config, + r2_settings.as_ref(), + &mut in_flight_graduations, + &graduate_retry_after, + &mut graduate_tasks, + ); if shutdown_requested(&config) { break; } @@ -373,8 +404,16 @@ async fn run_drain_inner(config: DrainConfig) -> Result { let slot_cursor = match next_slot { Some(slot) => slot, None => { - next_slot = Some(status.lowest_slot); - status.lowest_slot + let snapped = + initial_canonical_start_slot(status.lowest_slot, config.chunk_slots)?; + if snapped != status.lowest_slot { + eprintln!( + "fresh drain init: snapping lowest_slot={} up to next canonical chunk boundary {snapped} (avoids missing snapshot parent_blockhash)", + status.lowest_slot + ); + } + next_slot = Some(snapped); + snapped } }; @@ -394,8 +433,10 @@ async fn run_drain_inner(config: DrainConfig) -> Result { // Detect restart/prune gaps BOTH on startup AND mid-run if Agave restarts // from a newer snapshot while `drain-chunks` is already running! let current_slot = if slot_cursor < status.lowest_slot { + let resume_slot = + initial_canonical_start_slot(status.lowest_slot, config.chunk_slots)?; let gap_start = slot_cursor; - let gap_end = status.lowest_slot - 1; + let gap_end = resume_slot - 1; let mut recovery_cfg = config.gap_recovery.clone(); if recovery_cfg.admin_ledger_dir.is_none() { recovery_cfg.admin_ledger_dir = @@ -414,8 +455,8 @@ async fn run_drain_inner(config: DrainConfig) -> Result { )); recovery_tasks.push(handle); summary.gap_recovery_triggered = true; - next_slot = Some(status.lowest_slot); - status.lowest_slot + next_slot = Some(resume_slot); + resume_slot } else { slot_cursor }; @@ -626,15 +667,16 @@ async fn run_drain_inner(config: DrainConfig) -> Result { next_slot = Some(advanced_slot); // When the first produced block of a new epoch seals, persist - // `epoch-/successor.json` automatically and—if explicitly armed - // via `--auto-graduate-epochs`—spawn background Compact V2 graduation - // for `prev_epoch` without stalling live chunk draining. + // `epoch-/successor.json` automatically and then trigger + // `schedule_pending_graduations` (decoupled from `!successor_path.exists()` + // so failed or restarted graduations retry cleanly until `graduated.json` + // is written or the local epoch directory is cleaned up). if sealed.manifest.epoch > 0 && sealed.manifest.block_count > 0 { let prev_epoch = sealed.manifest.epoch - 1; let successor_path = config .output_dir .join(format!("epoch-{prev_epoch}")) - .join("successor.json"); + .join(SUCCESSOR_FILE); if !successor_path.exists() && let Ok(Some(successor)) = extract_first_produced_successor(&sealed.index_bytes, prev_epoch) @@ -651,39 +693,14 @@ async fn run_drain_inner(config: DrainConfig) -> Result { successor_path.display() ); } - if let Some(grad_opts) = &config.auto_graduate - && triggered_graduations.insert(prev_epoch) - { - let grad_cfg = GraduateEpochConfig { - epoch: prev_epoch, - source_dir: if r2_settings.is_some() { - None - } else { - Some(config.output_dir.clone()) - }, - chunk_r2: r2_settings.clone(), - publish_r2: grad_opts.publish_r2.clone(), - staging_dir: grad_opts.staging_dir.clone(), - zstd_level: grad_opts.zstd_level, - successor: Some(successor), - handoff_command: grad_opts.handoff_command.clone(), - verify_catalog_json: grad_opts.verify_catalog_json.clone(), - catalog: config.catalog.clone(), - cleanup_r2_chunks: grad_opts.cleanup_r2_chunks, - cleanup_local_chunks_dir: grad_opts - .cleanup_local_chunks - .then(|| config.output_dir.clone()), - min_free_disk_gib: config.min_free_disk_gib, - telegram: config.gap_recovery.telegram.clone(), - }; - eprintln!( - "auto-graduate: spawning background Compact V2 graduation for epoch {prev_epoch}" - ); - graduate_tasks.push(tokio::task::spawn_blocking(move || { - graduate::graduate_epoch(&grad_cfg) - })); - } } + schedule_pending_graduations( + &config, + r2_settings.as_ref(), + &mut in_flight_graduations, + &graduate_retry_after, + &mut graduate_tasks, + ); } stall_tracker @@ -698,8 +715,15 @@ async fn run_drain_inner(config: DrainConfig) -> Result { for handle in recovery_tasks { record_recovery_outcome(handle.await, &mut summary); } - for handle in graduate_tasks { - record_graduate_outcome(handle.await, &mut summary); + for (epoch, handle) in graduate_tasks { + record_graduate_outcome( + epoch, + handle.await, + &mut in_flight_graduations, + &mut graduate_retry_after, + &config, + &mut summary, + ); } summary.stall_alerts_sent = stall_tracker.stall_alerts_sent; summary.stall_recoveries_sent = stall_tracker.stall_recoveries_sent; @@ -707,6 +731,154 @@ async fn run_drain_inner(config: DrainConfig) -> Result { Ok(summary) } +/// Snap an unaligned snapshot-boundary `lowest_slot` UP to the next canonical +/// epoch-aligned chunk start so fresh initialization (or post-restart resume) +/// never attempts to read the snapshot boundary block whose `parent_blockhash` +/// lies outside Agave's RocksDB Blockstore. +pub(crate) fn initial_canonical_start_slot(lowest_slot: u64, chunk_slots: u64) -> Result { + let epoch = epoch_for_slot(lowest_slot); + let (epoch_start, _) = epoch_slot_range(epoch)?; + if (lowest_slot - epoch_start) % chunk_slots == 0 { + return Ok(lowest_slot); + } + let window_end = chunk_window_end(lowest_slot, chunk_slots)?; + window_end + .checked_add(1) + .context("initial canonical start slot overflow") +} + +/// Discover closed epochs under `output_dir` that have a persisted +/// `successor.json` anchor and have NOT yet written a `graduated.json` marker. +fn pending_graduation_epochs(output_dir: &Path) -> Result> { + if !output_dir.is_dir() { + return Ok(Vec::new()); + } + let mut pending = Vec::new(); + for entry in fs::read_dir(output_dir)? { + let path = entry?.path(); + if !path.is_dir() { + continue; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { + continue; + }; + let Some(epoch_str) = name.strip_prefix("epoch-") else { + continue; + }; + let Ok(epoch) = epoch_str.parse::() else { + continue; + }; + let successor_path = path.join(SUCCESSOR_FILE); + let graduated_path = path.join(GRADUATED_MARKER_FILE); + if successor_path.is_file() && !graduated_path.is_file() { + pending.push((epoch, successor_path)); + } + } + pending.sort_by_key(|(epoch, _)| *epoch); + Ok(pending) +} + +fn schedule_pending_graduations( + config: &DrainConfig, + r2_settings: Option<&R2Settings>, + in_flight: &mut BTreeSet, + retry_after: &BTreeMap, + graduate_tasks: &mut Vec<(u64, JoinHandle>)>, +) { + let Some(grad_opts) = &config.auto_graduate else { + return; + }; + let pending = match pending_graduation_epochs(&config.output_dir) { + Ok(list) => list, + Err(err) => { + eprintln!("WARN: failed to scan pending epoch graduations: {err:#}"); + return; + } + }; + let now = Instant::now(); + for (epoch, successor_path) in pending { + if in_flight.contains(&epoch) { + continue; + } + if retry_after.get(&epoch).is_some_and(|when| now < *when) { + continue; + } + let raw = match fs::read(&successor_path) { + Ok(bytes) => bytes, + Err(err) => { + eprintln!( + "WARN: failed to read {} for epoch {epoch}: {err:#}", + successor_path.display() + ); + continue; + } + }; + let successor: EpochHandoffSuccessor = match serde_json::from_slice(&raw) { + Ok(parsed) => parsed, + Err(err) => { + eprintln!( + "WARN: failed to parse {} for epoch {epoch}: {err:#}", + successor_path.display() + ); + continue; + } + }; + let grad_cfg = GraduateEpochConfig { + epoch, + source_dir: if r2_settings.is_some() { + None + } else { + Some(config.output_dir.clone()) + }, + chunk_r2: r2_settings.cloned(), + publish_r2: grad_opts.publish_r2.clone(), + staging_dir: grad_opts.staging_dir.clone(), + zstd_level: grad_opts.zstd_level, + successor: Some(successor), + handoff_command: grad_opts.handoff_command.clone(), + verify_catalog_json: grad_opts.verify_catalog_json.clone(), + catalog: config.catalog.clone(), + cleanup_r2_chunks: grad_opts.cleanup_r2_chunks, + cleanup_local_chunks_dir: grad_opts + .cleanup_local_chunks + .then(|| config.output_dir.clone()), + min_free_disk_gib: config.min_free_disk_gib, + telegram: config.gap_recovery.telegram.clone(), + }; + in_flight.insert(epoch); + eprintln!( + "auto-graduate: spawning background Compact V2 graduation for epoch {epoch}" + ); + graduate_tasks.push(( + epoch, + tokio::task::spawn_blocking(move || graduate::graduate_epoch(&grad_cfg)), + )); + } +} + +fn write_graduated_marker_atomic(output_dir: &Path, report: &GraduationReport) -> Result<()> { + let epoch_dir = output_dir.join(format!("epoch-{}", report.epoch)); + if !epoch_dir.is_dir() { + // Already cleaned up by `--graduate-cleanup-local-chunks`; nothing to mark. + return Ok(()); + } + let marker = GraduatedEpochMarker { + epoch: report.epoch, + ready_key: report.ready_key.clone(), + blocks: report.compaction.blocks, + uploaded_files: report.uploaded_files, + catalog_verified: report.catalog_verified, + catalog_rows_removed: report.catalog_rows_removed, + r2_chunk_objects_deleted: report.r2_chunk_objects_deleted, + }; + let path = epoch_dir.join(GRADUATED_MARKER_FILE); + let tmp = path.with_extension("json.tmp"); + let bytes = serde_json::to_vec_pretty(&marker)?; + fs::write(&tmp, bytes)?; + fs::rename(&tmp, &path)?; + Ok(()) +} + fn build_account_client(config: &DrainConfig, source: &SourceIdentity) -> Result { AccountClient::new( &config.native_socket, @@ -777,14 +949,24 @@ async fn sleep_or_shutdown(config: &DrainConfig, duration: Duration) -> bool { } async fn reap_finished_graduate_tasks( - tasks: &mut Vec>>, + tasks: &mut Vec<(u64, JoinHandle>)>, + in_flight: &mut BTreeSet, + retry_after: &mut BTreeMap, + config: &DrainConfig, summary: &mut DrainSummary, ) { let mut i = 0; while i < tasks.len() { - if tasks[i].is_finished() { - let handle = tasks.swap_remove(i); - record_graduate_outcome(handle.await, summary); + if tasks[i].1.is_finished() { + let (epoch, handle) = tasks.swap_remove(i); + record_graduate_outcome( + epoch, + handle.await, + in_flight, + retry_after, + config, + summary, + ); } else { i += 1; } @@ -792,16 +974,43 @@ async fn reap_finished_graduate_tasks( } fn record_graduate_outcome( + epoch: u64, result: std::result::Result, tokio::task::JoinError>, + in_flight: &mut BTreeSet, + retry_after: &mut BTreeMap, + config: &DrainConfig, summary: &mut DrainSummary, ) { + in_flight.remove(&epoch); + let backoff = config + .auto_graduate + .as_ref() + .map(|g| g.retry_interval) + .unwrap_or_else(|| Duration::from_secs(DEFAULT_GRADUATE_RETRY_SECS)); match result { - Ok(Ok(report)) => summary.epochs_graduated.push(report.epoch), + Ok(Ok(report)) => { + retry_after.remove(&epoch); + if let Err(err) = write_graduated_marker_atomic(&config.output_dir, &report) { + eprintln!( + "WARN: failed to persist graduated.json for epoch {}: {err:#}", + report.epoch + ); + } + summary.epochs_graduated.push(report.epoch); + } Ok(Err(err)) => { - eprintln!("ERROR: background auto-graduation failed: {err:#}"); + retry_after.insert(epoch, Instant::now() + backoff); + eprintln!( + "ERROR: background auto-graduation failed for epoch {epoch} (will retry in {:?}): {err:#}", + backoff + ); } Err(join_err) => { - eprintln!("ERROR: background auto-graduation task panicked: {join_err}"); + retry_after.insert(epoch, Instant::now() + backoff); + eprintln!( + "ERROR: background auto-graduation task panicked for epoch {epoch} (will retry in {:?}): {join_err}", + backoff + ); } } } diff --git a/blockzilla/finalized-ledger/src/main.rs b/blockzilla/finalized-ledger/src/main.rs index aef7b331..7e4247da 100644 --- a/blockzilla/finalized-ledger/src/main.rs +++ b/blockzilla/finalized-ledger/src/main.rs @@ -26,8 +26,8 @@ use blockzilla_finalized_chunks::{ }; use blockzilla_finalized_ledger::disk::{self, DEFAULT_MIN_FREE_DISK_GIB}; use blockzilla_finalized_ledger::drain::{ - AutoGraduateOptions, CatalogOptions, DEFAULT_PURGE_SAFETY_TAIL, DEFAULT_STALL_ALERT_SECS, - DEFAULT_STALL_REPEAT_SECS, DrainConfig, PurgeOptions, run_drain, + AutoGraduateOptions, CatalogOptions, DEFAULT_GRADUATE_RETRY_SECS, DEFAULT_PURGE_SAFETY_TAIL, + DEFAULT_STALL_ALERT_SECS, DEFAULT_STALL_REPEAT_SECS, DrainConfig, PurgeOptions, run_drain, }; use blockzilla_finalized_ledger::graduate::{GraduateEpochConfig, graduate_epoch}; use blockzilla_finalized_ledger::notify::{self, TelegramConfig}; @@ -347,6 +347,7 @@ fn main() -> Result<()> { verify_catalog_json: graduate_verify_catalog_json, cleanup_r2_chunks: graduate_cleanup_r2_chunks, cleanup_local_chunks: graduate_cleanup_local_chunks, + retry_interval: Duration::from_secs(DEFAULT_GRADUATE_RETRY_SECS), }) } else { None diff --git a/blockzilla/finalized-ledger/src/tests.rs b/blockzilla/finalized-ledger/src/tests.rs index 32cb98bd..ec897e5d 100644 --- a/blockzilla/finalized-ledger/src/tests.rs +++ b/blockzilla/finalized-ledger/src/tests.rs @@ -2140,3 +2140,325 @@ fn r2_put_bytes_delete_prefix_and_catalog_admission_verification() { crate::graduate::verify_epoch_in_catalog_json(&catalog_json, 1096).unwrap(); assert!(crate::graduate::verify_epoch_in_catalog_json(&catalog_json, 1097).is_err()); } + +#[test] +fn initial_canonical_start_slot_snaps_mid_chunk_snapshot_boundary_up() { + use crate::drain::initial_canonical_start_slot; + // Genesis and exact canonical boundaries stay unchanged. + assert_eq!(initial_canonical_start_slot(0, 4096).unwrap(), 0); + assert_eq!( + initial_canonical_start_slot(476_496_000, 4096).unwrap(), + 476_496_000 + ); + assert_eq!( + initial_canonical_start_slot(476_631_168, 4096).unwrap(), + 476_631_168 + ); + // Live bz-2 snapshot boundary: lowest_slot=476_627_910 (1 slot past snapshot + // 476_627_909 where parent_blockhash is absent) snaps up to canonical 476_631_168. + assert_eq!( + initial_canonical_start_slot(476_627_910, 4096).unwrap(), + 476_631_168 + ); + // Last slot of epoch 1103 snaps cleanly to exact epoch 1104 start. + assert_eq!( + initial_canonical_start_slot(476_927_999, 4096).unwrap(), + 476_928_000 + ); +} + +#[tokio::test] +async fn auto_graduate_retries_after_handoff_failure_and_persists_graduated_marker() { + use crate::drain::{AutoGraduateOptions, GRADUATED_MARKER_FILE, SUCCESSOR_FILE}; + use blockzilla_finalized_chunks::{ + ChunkCatalogBinding, ChunkCatalogWriter, EpochHandoffSuccessor, TailBlockhash, + }; + + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let output_dir = root.path().join("finalized-chunks"); + let catalog_path = root.path().join("chunk_catalog.sqlite"); + let archive_catalog_json = root.path().join("catalog.json"); + let attempts_file = root.path().join("handoff-attempts.txt"); + + // Seed a complete epoch-1 chunk [SLOTS_PER_EPOCH..=2*SLOTS_PER_EPOCH-1] + // with produced blocks at the start and end of epoch 1 plus an ALREADY-EXISTING + // `epoch-1/successor.json` (simulating a drain-chunks restart or prior failed + // graduation where `successor.json` already exists on disk). + let epoch = 1u64; + let first_slot = SLOTS_PER_EPOCH; + let last_slot = 2 * SLOTS_PER_EPOCH - 1; + let first_block = ArchiveBlockPayloadV1 { + slot: first_slot, + parent_slot: first_slot - 1, + blockhash: [0x11; 32], + previous_blockhash: [0x10; 32], + block_time: Some(1_700_000_000), + block_height: Some(10), + consensus_block_id: [0x12; 32], + markers: vec![], + rewards_proto: vec![], + entries: vec![ArchiveEntry { + num_hashes: 1, + hash: [0x11; 32], + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }; + let last_block = ArchiveBlockPayloadV1 { + slot: last_slot, + parent_slot: first_slot, + blockhash: [0x22; 32], + previous_blockhash: [0x11; 32], + block_time: Some(1_700_000_100), + block_height: Some(11), + consensus_block_id: [0x23; 32], + markers: vec![], + rewards_proto: vec![], + entries: vec![ArchiveEntry { + num_hashes: 1, + hash: [0x22; 32], + tx_count: 0, + signature_count: 0, + }], + shredding: vec![ArchiveShredGroup { + entry_end_idx: 1, + shred_end_idx: 1, + }], + transactions: vec![], + }; + let enc_first = blockzilla_finalized_chunks::encode_archive_payload(&first_block, 1).unwrap(); + let enc_last = blockzilla_finalized_chunks::encode_archive_payload(&last_block, 1).unwrap(); + + // Seed all canonical 4096-slot chunks of epoch 1 and register them in SQLite + // catalog so we can verify cleanup happens ONLY after retry succeeds. + { + let mut writer = ChunkCatalogWriter::open_or_create( + &catalog_path, + ChunkCatalogBinding { + version: 1, + generation: "gen-grad-retry".into(), + prefix: "finalized-chunks/test".into(), + }, + ) + .unwrap(); + let mut cursor = first_slot; + while cursor <= last_slot { + let chunk_end = blockzilla_finalized_chunks::chunk_window_end(cursor, 4096).unwrap(); + let mut builder = blockzilla_finalized_chunks::ChunkBuilder::create_default( + &output_dir, + cursor, + chunk_end, + ) + .unwrap(); + if cursor == first_slot { + builder.set_previous_tail(vec![TailBlockhash { + slot: first_slot - 1, + blockhash: bs58::encode([0x10; 32]).into_string(), + }]); + } + for s in cursor..=chunk_end { + if s == first_slot { + builder.add_block(&enc_first).unwrap(); + } else if s == last_slot { + builder.add_block(&enc_last).unwrap(); + } else { + builder.add_skip(s).unwrap(); + } + } + let sealed = builder.finish().unwrap(); + let bundles_path = sealed + .dir + .join(blockzilla_finalized_chunks::CHUNK_BUNDLES_FILE) + .canonicalize() + .unwrap(); + writer + .register_chunk( + &sealed.manifest, + &sealed.index_bytes, + ChunkStorageMode::Local, + bundles_path.to_str().unwrap(), + None, + ) + .unwrap(); + cursor = chunk_end + 1; + } + } + + // Write `epoch-1/successor.json` BEFORE starting `run_drain`. + let epoch2_start = 2 * SLOTS_PER_EPOCH; + let successor = EpochHandoffSuccessor { + slot: epoch2_start, + parent_slot: last_slot, + blockhash: bs58::encode([0x33; 32]).into_string(), + previous_blockhash: bs58::encode([0x22; 32]).into_string(), + }; + let successor_path = output_dir + .join(format!("epoch-{epoch}")) + .join(SUCCESSOR_FILE); + std::fs::write(&successor_path, serde_json::to_vec_pretty(&successor).unwrap()).unwrap(); + + // Handoff command that FAILS on attempt #1 (simulating transient NATIVE_RECENT + // or timer race) and SUCCEEDS on attempt #2, writing epoch 1 into catalog.json. + std::fs::write( + &archive_catalog_json, + r#"{"version":1,"source_prefix":"compact-v2/test","generation":"g1","epochs":[]}"#, + ) + .unwrap(); + let handoff_cmd = format!( + "n=$(cat '{attempts}' 2>/dev/null || echo 0); n=$((n+1)); echo $n > '{attempts}'; \ + if [ \"$n\" -lt 2 ]; then echo 'transient handoff error' >&2; exit 1; fi; \ + printf '{{\"version\":1,\"source_prefix\":\"compact-v2/test\",\"generation\":\"g1\",\"epochs\":[{{\"epoch\":1}}]}}' > '{cat}'", + attempts = attempts_file.display(), + cat = archive_catalog_json.display(), + ); + + let r2_server = MockR2Server::start("blockzilla-grad-retry-test"); + let publish_r2 = r2_server.settings("compact-v2/test"); + + // Live bridge sits at epoch-2 start with max_root < next chunk so no new + // chunks seal; continuous loop stays alive just long enough for attempt #1 + // (fail) + retry backoff + attempt #2 (succeed). + let (bridge_stop, bridge_handle) = spawn_mock_live_bridge_at_tip( + &bridge_sock, + epoch2_start, + HashMap::new(), + epoch2_start + 1, + ); + let shutdown = Arc::new(AtomicBool::new(false)); + let shutdown_watcher = shutdown.clone(); + let graduated_marker = output_dir + .join(format!("epoch-{epoch}")) + .join(GRADUATED_MARKER_FILE); + let marker_watch = graduated_marker.clone(); + let stopper = tokio::spawn(async move { + for _ in 0..200 { + if marker_watch.is_file() { + tokio::time::sleep(Duration::from_millis(50)).await; + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + shutdown_watcher.store(true, Ordering::Relaxed); + }); + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: None, + once: false, + poll_interval: Duration::from_millis(25), + r2: None, + catalog: Some(CatalogOptions { + path: catalog_path.clone(), + generation: "gen-grad-retry".into(), + prefix: "finalized-chunks/test".into(), + }), + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig::default(), + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: Some(AutoGraduateOptions { + publish_r2: publish_r2.clone(), + staging_dir: root.path().join("staging"), + zstd_level: 1, + handoff_command: Some(handoff_cmd.clone()), + verify_catalog_json: Some(archive_catalog_json.clone()), + cleanup_r2_chunks: false, + cleanup_local_chunks: false, + retry_interval: Duration::from_millis(25), + }), + shutdown: Some(shutdown), + }) + .await + .expect("run_drain auto-graduate retry"); + stopper.await.unwrap(); + + assert_eq!(summary.epochs_graduated, vec![epoch]); + assert!( + graduated_marker.is_file(), + "graduated.json marker must be written after successful retry" + ); + let attempts_after_first: u32 = std::fs::read_to_string(&attempts_file) + .unwrap() + .trim() + .parse() + .unwrap(); + assert_eq!(attempts_after_first, 2); + + // Chunk catalog row for epoch 1 must now be pruned. + let lookup_after = ChunkCatalogReader::lookup( + &catalog_path.canonicalize().unwrap(), + "gen-grad-retry", + "finalized-chunks/test", + first_slot, + ) + .unwrap(); + assert!(lookup_after.is_none()); + + // Restarting `run_drain` again with `graduated.json` present MUST NOT + // re-trigger graduation (idempotent). + let second_summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: None, + once: true, + poll_interval: Duration::from_millis(25), + r2: None, + catalog: Some(CatalogOptions { + path: catalog_path.clone(), + generation: "gen-grad-retry".into(), + prefix: "finalized-chunks/test".into(), + }), + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig::default(), + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + auto_graduate: Some(AutoGraduateOptions { + publish_r2, + staging_dir: root.path().join("staging"), + zstd_level: 1, + handoff_command: Some(handoff_cmd), + verify_catalog_json: Some(archive_catalog_json), + cleanup_r2_chunks: false, + cleanup_local_chunks: false, + retry_interval: Duration::from_millis(25), + }), + shutdown: None, + }) + .await + .expect("second run_drain idempotency"); + assert!(second_summary.epochs_graduated.is_empty()); + let attempts_after_second: u32 = std::fs::read_to_string(&attempts_file) + .unwrap() + .trim() + .parse() + .unwrap(); + assert_eq!(attempts_after_second, 2); + + bridge_stop.store(true, Ordering::Relaxed); + bridge_handle.join().unwrap(); +} diff --git a/blockzilla/get-block/resolver/src/finalized.rs b/blockzilla/get-block/resolver/src/finalized.rs index 4fba48ed..75d13954 100644 --- a/blockzilla/get-block/resolver/src/finalized.rs +++ b/blockzilla/get-block/resolver/src/finalized.rs @@ -63,6 +63,17 @@ pub(super) async fn block( let _permit = permit; let clock = Clock::start()?; let result = (|| -> Result<_> { + // Check verified, admitted historical archive epochs FIRST: once a + // closed epoch is admitted in `catalog.json`, serving it from + // ARCHIVE is canonical, immutable-cacheable, and guarantees + // `archive_index_handoff.py`'s probe(z) never hits NATIVE_RECENT + // while the last slot of the closed epoch is still in the native ring. + let pending = catalog.pending(slot)?; + if pending.is_some() { + let hash = catalog.archived_blockhash(slot)?; + ensure!(hash.is_some(), "archive_hash_unavailable"); + return Ok((None, None, Some((pending, hash)), None, None)); + } let (found, native_unavailable) = match recent.read_finalized_by_slot(slot) { Ok(found) => (found, false), Err(error) if error.is::() => (None, true), @@ -73,31 +84,14 @@ pub(super) async fn block( } else { None }; - let archive = if found.is_none() && native_archive.is_none() { - let pending = catalog.pending(slot)?; - let hash = if pending.is_some() { - catalog.archived_blockhash(slot)? - } else { - None - }; - ensure!( - pending.is_none() || hash.is_some(), - "archive_hash_unavailable" - ); - Some((pending, hash)) - } else { - None - }; - let chunk = if archive.as_ref().is_some_and(|(source, _)| source.is_none()) { + let chunk = if found.is_none() && native_archive.is_none() { recent .chunk_archive(slot) .map_err(|_| anyhow::anyhow!("chunk_archive_unavailable"))? } else { None }; - let ledger = if archive.as_ref().is_some_and(|(source, _)| source.is_none()) - && chunk.is_none() - { + let ledger = if found.is_none() && native_archive.is_none() && chunk.is_none() { recent.ledger_compact(slot).map_err(|error| { if error.to_string() == "ledger_not_rooted" { error @@ -109,15 +103,25 @@ pub(super) async fn block( None }; if native_unavailable + && found.is_none() + && native_archive.is_none() && chunk.is_none() && ledger.is_none() - && matches!(archive, Some((None, None))) { // The checked feed reported failed health, and the independently // available local readers supplied no block. The archive is // still a possible source. Errors above never enter this path. return Err(ArchiveLookupRequired.into()); } + let archive = if found.is_none() + && native_archive.is_none() + && chunk.is_none() + && ledger.is_none() + { + Some((None, None)) + } else { + None + }; Ok((found, native_archive, archive, chunk, ledger)) })(); Ok((result, clock.finish()?)) diff --git a/blockzilla/get-block/resolver/src/http_tests.rs b/blockzilla/get-block/resolver/src/http_tests.rs index 005a79cd..8f05ed49 100644 --- a/blockzilla/get-block/resolver/src/http_tests.rs +++ b/blockzilla/get-block/resolver/src/http_tests.rs @@ -1473,3 +1473,55 @@ async fn finalized_slot_http_serves_r2_chunk_locator_local_chunk_bundle_and_prov assert_eq!(bytes(response).await, bundle_bytes); } } + +#[tokio::test] +async fn admitted_archive_precedes_recent_native_ring_in_finalized_endpoint() { + // Regression test: when a closed epoch is admitted in `catalog.json` while + // its last slot (here slot 100) is STILL retained in the 4,096-bank native + // ring (`recent`), `/v1/finalized/:slot` MUST return the admitted ARCHIVE + // locator (`not_cached` with `source` + `x-bz-recent-blockhash`) instead of + // `recent`, so `archive_index_handoff.py`'s probe(z) deterministically hits + // ARCHIVE. + struct AdmittedSlot100Catalog; + impl ResolutionCatalog for AdmittedSlot100Catalog { + fn source_prefix(&self) -> &str { + PREFIX + } + fn generation(&self) -> &str { + GEN + } + fn pending(&self, slot: u64) -> Result> { + Ok((slot == 100).then(pending)) + } + fn has_epoch(&self, epoch: u64) -> bool { + epoch == 0 + } + fn archived_blockhash(&self, slot: u64) -> Result> { + Ok((slot == 100).then_some([100; 32])) + } + fn resolve(&self, _: &ResolveRequestV1) -> Result { + anyhow::bail!("unexpected resolve call") + } + } + + let f = crate::recent::tests::fixture(); + // Confirm slot 100 IS present in the healthy native ring. + assert!(f.client.read_finalized_by_slot(100).unwrap().is_some()); + let app = router_with_recent( + Arc::new(AdmittedSlot100Catalog), + TOKEN, + 0, + 2, + Some(Arc::new(f.client)), + ) + .unwrap(); + let response = app.oneshot(get_request("/v1/finalized/100")).await.unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!(response.headers()["x-bz-foundation-result"], "not_cached"); + assert_eq!( + response.headers()["x-bz-recent-blockhash"], + crate::recent::encode_hash(&[100; 32]) + ); + let value: serde_json::Value = serde_json::from_slice(&bytes(response).await).unwrap(); + assert_eq!(value["source"], serde_json::to_value(pending()).unwrap()); +} From edd6de5dae5580a2ecc5760c3df6cc3b482afeaa Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 22:42:02 +0100 Subject: [PATCH 7/9] fix(finalized-ledger,resolver): short-circuit admitted archive skips and add snapshot safety margin --- blockzilla/finalized-ledger/src/drain.rs | 63 ++++++++++++++----- blockzilla/finalized-ledger/src/main.rs | 1 + blockzilla/finalized-ledger/src/tests.rs | 49 +++++++++++---- .../get-block/resolver/src/chunk_archive.rs | 8 ++- .../get-block/resolver/src/finalized.rs | 23 +++++-- .../get-block/resolver/src/http_tests.rs | 33 ++++++++++ blockzilla/get-block/wrangler.example.toml | 5 ++ 7 files changed, 145 insertions(+), 37 deletions(-) diff --git a/blockzilla/finalized-ledger/src/drain.rs b/blockzilla/finalized-ledger/src/drain.rs index 00ddeb37..45ea8948 100644 --- a/blockzilla/finalized-ledger/src/drain.rs +++ b/blockzilla/finalized-ledger/src/drain.rs @@ -112,6 +112,11 @@ pub struct DrainConfig { /// Optional per-block pacing delay during bridge reads to limit NVMe/CPU /// contention with co-located services during backlog catchup. pub slot_pace: Duration, + /// Minimum slots skipped past a non-genesis snapshot boundary `lowest_slot` + /// before snapping up to a canonical chunk start (default 512 in CLI) so + /// `get_archive_block(S)` never hits `ParentUnavailable` across skip runs + /// and `start_slot == epoch_start` has >= 300 ancestor blocks in Blockstore. + pub snapshot_safety_margin: u64, /// Optional opt-in automatic epoch graduation triggered when chunk 0 of /// `epoch + 1` seals a produced block. Disabled by default so canary nodes /// never publish to production Compact V2 prefixes unless explicitly armed. @@ -404,12 +409,15 @@ async fn run_drain_inner(config: DrainConfig) -> Result { let slot_cursor = match next_slot { Some(slot) => slot, None => { - let snapped = - initial_canonical_start_slot(status.lowest_slot, config.chunk_slots)?; + let snapped = initial_canonical_start_slot( + status.lowest_slot, + config.chunk_slots, + config.snapshot_safety_margin, + )?; if snapped != status.lowest_slot { eprintln!( - "fresh drain init: snapping lowest_slot={} up to next canonical chunk boundary {snapped} (avoids missing snapshot parent_blockhash)", - status.lowest_slot + "fresh drain init: snapping lowest_slot={} up to next canonical chunk boundary {snapped} (safety_margin={} avoids missing snapshot parent/ancestor blockhashes)", + status.lowest_slot, config.snapshot_safety_margin, ); } next_slot = Some(snapped); @@ -432,9 +440,15 @@ async fn run_drain_inner(config: DrainConfig) -> Result { // Detect restart/prune gaps BOTH on startup AND mid-run if Agave restarts // from a newer snapshot while `drain-chunks` is already running! - let current_slot = if slot_cursor < status.lowest_slot { - let resume_slot = - initial_canonical_start_slot(status.lowest_slot, config.chunk_slots)?; + let snapshot_boundary_hit = config.snapshot_safety_margin > 0 + && status.lowest_slot > 0 + && slot_cursor == status.lowest_slot; + let current_slot = if slot_cursor < status.lowest_slot || snapshot_boundary_hit { + let resume_slot = initial_canonical_start_slot( + status.lowest_slot, + config.chunk_slots, + config.snapshot_safety_margin, + )?; let gap_start = slot_cursor; let gap_end = resume_slot - 1; let mut recovery_cfg = config.gap_recovery.clone(); @@ -548,7 +562,10 @@ async fn run_drain_inner(config: DrainConfig) -> Result { &mut client, ) .await - && rechecked.lowest_slot > current_slot + && (rechecked.lowest_slot > current_slot + || (config.snapshot_safety_margin > 0 + && rechecked.lowest_slot > 0 + && rechecked.lowest_slot == current_slot)) { eprintln!( "WARN: validator jumped to lowest_slot={} mid-chunk ({current_slot}..={end_slot}): {err:#}; handing off to parallel gap recovery", @@ -731,17 +748,29 @@ async fn run_drain_inner(config: DrainConfig) -> Result { Ok(summary) } -/// Snap an unaligned snapshot-boundary `lowest_slot` UP to the next canonical -/// epoch-aligned chunk start so fresh initialization (or post-restart resume) -/// never attempts to read the snapshot boundary block whose `parent_blockhash` -/// lies outside Agave's RocksDB Blockstore. -pub(crate) fn initial_canonical_start_slot(lowest_slot: u64, chunk_slots: u64) -> Result { - let epoch = epoch_for_slot(lowest_slot); +/// Snap a snapshot-boundary `lowest_slot` UP to a canonical epoch-aligned chunk +/// start that sits at least `safety_margin` slots past `lowest_slot` (except +/// genesis `lowest_slot == 0`), so fresh initialization and post-restart resume +/// never hit `ParentUnavailable` across skip runs and `start_slot == epoch_start` +/// always has >= 300 ancestor blocks in Blockstore for +/// `get_ancestor_blockhashes(first_rooted, 300)`. +pub(crate) fn initial_canonical_start_slot( + lowest_slot: u64, + chunk_slots: u64, + safety_margin: u64, +) -> Result { + if lowest_slot == 0 { + return Ok(0); + } + let min_safe = lowest_slot + .checked_add(safety_margin) + .context("initial canonical start safety margin overflow")?; + let epoch = epoch_for_slot(min_safe); let (epoch_start, _) = epoch_slot_range(epoch)?; - if (lowest_slot - epoch_start) % chunk_slots == 0 { - return Ok(lowest_slot); + if (min_safe - epoch_start) % chunk_slots == 0 { + return Ok(min_safe); } - let window_end = chunk_window_end(lowest_slot, chunk_slots)?; + let window_end = chunk_window_end(min_safe, chunk_slots)?; window_end .checked_add(1) .context("initial canonical start slot overflow") diff --git a/blockzilla/finalized-ledger/src/main.rs b/blockzilla/finalized-ledger/src/main.rs index 7e4247da..0777029d 100644 --- a/blockzilla/finalized-ledger/src/main.rs +++ b/blockzilla/finalized-ledger/src/main.rs @@ -398,6 +398,7 @@ fn main() -> Result<()> { stall_repeat_interval: Duration::from_secs(stall_repeat_secs.max(1)), min_free_disk_gib, slot_pace: Duration::from_millis(slot_pace_ms), + snapshot_safety_margin: purge_safety_tail.max(DEFAULT_PURGE_SAFETY_TAIL), auto_graduate, shutdown: None, }))?; diff --git a/blockzilla/finalized-ledger/src/tests.rs b/blockzilla/finalized-ledger/src/tests.rs index ec897e5d..3364dbb3 100644 --- a/blockzilla/finalized-ledger/src/tests.rs +++ b/blockzilla/finalized-ledger/src/tests.rs @@ -587,6 +587,7 @@ async fn end_to_end_drain_r2_catalog_evict_purge_and_streaming_compact() { stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: None, }) @@ -1051,6 +1052,7 @@ async fn restart_gap_drains_live_immediately_and_wait_for_car_writes_receipt_and stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: None, }) @@ -1304,6 +1306,7 @@ async fn restart_gap_rpc_fallback_seals_degraded_chunk_blocks_compaction_and_ale stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: None, }) @@ -1553,6 +1556,7 @@ async fn catchup_stall_alerts_telegram_and_sends_recovery_when_max_root_advances stall_repeat_interval: Duration::from_secs(30), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: Some(shutdown.clone()), }) @@ -1781,6 +1785,7 @@ async fn mid_run_validator_restart_reloads_source_and_triggers_parallel_gap_reco stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: Some(shutdown.clone()), }) @@ -1840,6 +1845,7 @@ async fn fatal_drain_error_sends_telegram_alert_before_exiting() { stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: None, }) @@ -2007,6 +2013,7 @@ async fn startup_crash_recovery_sweeps_stale_temps_and_publishes_unregistered_lo stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: None, }) @@ -2083,6 +2090,7 @@ async fn low_disk_space_guard_refuses_sealing_and_alerts_telegram() { stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 10_000_000_000, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: None, shutdown: None, }) @@ -2143,26 +2151,41 @@ fn r2_put_bytes_delete_prefix_and_catalog_admission_verification() { #[test] fn initial_canonical_start_slot_snaps_mid_chunk_snapshot_boundary_up() { - use crate::drain::initial_canonical_start_slot; - // Genesis and exact canonical boundaries stay unchanged. - assert_eq!(initial_canonical_start_slot(0, 4096).unwrap(), 0); + use crate::drain::{DEFAULT_PURGE_SAFETY_TAIL, initial_canonical_start_slot}; + let margin = DEFAULT_PURGE_SAFETY_TAIL; // 512 slots (>= 300 ancestor blocks + skips) + + // Genesis stays at 0 even with a non-zero safety margin. + assert_eq!(initial_canonical_start_slot(0, 4096, margin).unwrap(), 0); + // Zero-margin exact canonical boundaries stay unchanged. assert_eq!( - initial_canonical_start_slot(476_496_000, 4096).unwrap(), - 476_496_000 + initial_canonical_start_slot(476_631_168, 4096, 0).unwrap(), + 476_631_168 ); assert_eq!( - initial_canonical_start_slot(476_631_168, 4096).unwrap(), - 476_631_168 + initial_canonical_start_slot(476_927_999, 4096, 0).unwrap(), + 476_928_000 ); - // Live bz-2 snapshot boundary: lowest_slot=476_627_910 (1 slot past snapshot - // 476_627_909 where parent_blockhash is absent) snaps up to canonical 476_631_168. + // Live bz-2 snapshot boundary: lowest_slot=476_627_910 + 512 = 476_628_422 + // snaps up to canonical 476_631_168 (3,258 slots of parent headroom). assert_eq!( - initial_canonical_start_slot(476_627_910, 4096).unwrap(), + initial_canonical_start_slot(476_627_910, 4096, margin).unwrap(), 476_631_168 ); - // Last slot of epoch 1103 snaps cleanly to exact epoch 1104 start. + // Exact chunk boundary snapshot (476_631_168) MUST advance to the next chunk + // (476_635_264) so `get_archive_block(476_631_168)` cannot hit ParentUnavailable. + assert_eq!( + initial_canonical_start_slot(476_631_168, 4096, margin).unwrap(), + 476_635_264 + ); + // Snapshot < 512 slots before epoch 1104 start (476_928_000) MUST advance past + // epoch_start so `get_ancestor_blockhashes(first_rooted, 300)` cannot fail. + assert_eq!( + initial_canonical_start_slot(476_927_900, 4096, margin).unwrap(), + 476_932_096 + ); + // Snapshot exactly 512 slots before epoch 1104 start lands cleanly on 476_928_000. assert_eq!( - initial_canonical_start_slot(476_927_999, 4096).unwrap(), + initial_canonical_start_slot(476_928_000 - margin, 4096, margin).unwrap(), 476_928_000 ); } @@ -2373,6 +2396,7 @@ async fn auto_graduate_retries_after_handoff_failure_and_persists_graduated_mark stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: Some(AutoGraduateOptions { publish_r2: publish_r2.clone(), staging_dir: root.path().join("staging"), @@ -2437,6 +2461,7 @@ async fn auto_graduate_retries_after_handoff_failure_and_persists_graduated_mark stall_repeat_interval: Duration::from_secs(60), min_free_disk_gib: 0, slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, auto_graduate: Some(AutoGraduateOptions { publish_r2, staging_dir: root.path().join("staging"), diff --git a/blockzilla/get-block/resolver/src/chunk_archive.rs b/blockzilla/get-block/resolver/src/chunk_archive.rs index eaa7e62a..9181d49d 100644 --- a/blockzilla/get-block/resolver/src/chunk_archive.rs +++ b/blockzilla/get-block/resolver/src/chunk_archive.rs @@ -223,7 +223,9 @@ pub(crate) mod tests { ) -> (PathBuf, u64, Vec) { let chunks_root = root.join("chunks"); let catalog_path = root.join("chunk_catalog.sqlite"); - let slot = SLOTS_PER_EPOCH; + // Use epoch 2 so tests that share `MockCatalog` (which admits epoch 1) + // exercise `chunk_archive` on an unadmitted/active epoch just like production. + let slot = 2 * SLOTS_PER_EPOCH; let payload = ArchiveBlockPayloadV1 { slot, parent_slot: slot - 1, @@ -262,7 +264,7 @@ pub(crate) mod tests { match mode { ChunkStorageMode::R2 => { let key = format!( - "{prefix}/epoch-1/{}/{CHUNK_BUNDLES_FILE}", + "{prefix}/epoch-2/{}/{CHUNK_BUNDLES_FILE}", chunk_dir_name(slot, slot + 2) ); writer @@ -360,7 +362,7 @@ pub(crate) mod tests { // Tampering with local bundle bytes must fail closed! let bundles_file = dir .path() - .join("chunks/epoch-1") + .join("chunks/epoch-2") .join(chunk_dir_name(slot, slot + 2)) .join(CHUNK_BUNDLES_FILE); let mut tampered = std::fs::read(&bundles_file).unwrap(); diff --git a/blockzilla/get-block/resolver/src/finalized.rs b/blockzilla/get-block/resolver/src/finalized.rs index 75d13954..21d2c76a 100644 --- a/blockzilla/get-block/resolver/src/finalized.rs +++ b/blockzilla/get-block/resolver/src/finalized.rs @@ -68,11 +68,24 @@ pub(super) async fn block( // ARCHIVE is canonical, immutable-cacheable, and guarantees // `archive_index_handoff.py`'s probe(z) never hits NATIVE_RECENT // while the last slot of the closed epoch is still in the native ring. - let pending = catalog.pending(slot)?; - if pending.is_some() { - let hash = catalog.archived_blockhash(slot)?; - ensure!(hash.is_some(), "archive_hash_unavailable"); - return Ok((None, None, Some((pending, hash)), None, None)); + // Likewise, if the epoch is already admitted and `pending(slot)` is + // None, the slot was skipped in that closed epoch — short-circuit to + // `ChunkOutcome::Skipped` (404 unavailable) in O(1) RAM without + // falling through to `recent`, `chunk_archive`, or `ledger_compact`. + if catalog.has_epoch(slot / crate::catalog::SLOTS) { + let pending = catalog.pending(slot)?; + if pending.is_some() { + let hash = catalog.archived_blockhash(slot)?; + ensure!(hash.is_some(), "archive_hash_unavailable"); + return Ok((None, None, Some((pending, hash)), None, None)); + } + return Ok(( + None, + None, + None, + Some(crate::chunk_archive::ChunkOutcome::Skipped), + None, + )); } let (found, native_unavailable) = match recent.read_finalized_by_slot(slot) { Ok(found) => (found, false), diff --git a/blockzilla/get-block/resolver/src/http_tests.rs b/blockzilla/get-block/resolver/src/http_tests.rs index 8f05ed49..a1eaca12 100644 --- a/blockzilla/get-block/resolver/src/http_tests.rs +++ b/blockzilla/get-block/resolver/src/http_tests.rs @@ -878,6 +878,9 @@ async fn cancelling_native_http_keeps_its_blocking_permit(finalized_by_slot: boo fn archived_blockhash(&self, slot: u64) -> Result> { Ok((slot == SLOT).then_some([5; 32])) } + fn has_epoch(&self, epoch: u64) -> bool { + epoch == SLOT / crate::catalog::SLOTS + } fn resolve(&self, _: &ResolveRequestV1) -> Result { anyhow::bail!("resolution is not part of this recent-read test") } @@ -1525,3 +1528,33 @@ async fn admitted_archive_precedes_recent_native_ring_in_finalized_endpoint() { let value: serde_json::Value = serde_json::from_slice(&bytes(response).await).unwrap(); assert_eq!(value["source"], serde_json::to_value(pending()).unwrap()); } + +#[tokio::test] +async fn skipped_slot_in_admitted_archive_epoch_short_circuits_without_ledger_helper() { + // Regression test: for a skipped slot (pending == None) inside an already + // admitted ARCHIVE epoch (`has_epoch(epoch) == true`), `/v1/finalized/:slot` + // MUST return 404 unavailable immediately in O(1) RAM without falling through + // to `ledger_compact` (spawning the helper subprocess) or enqueueing a bogus + // archive miss. + for native_failed in [false, true] { + let (app, _native, directory, config) = ledger_app("emit", 1000, native_failed); + let skipped_slot = SLOT + 1; // Same admitted epoch 1 as SLOT, not in index. + let response = app + .oneshot(get_request(&format!("/v1/finalized/{skipped_slot}"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!(response.headers()["x-bz-foundation-result"], "unavailable"); + assert_eq!(response.headers()["x-bz-foundation-cache"], "BYPASS"); + let value: serde_json::Value = serde_json::from_slice(&bytes(response).await).unwrap(); + assert_eq!(value["reason"], "unavailable"); + assert!( + !config.ledger.join("helper.pid").exists(), + "admitted archive skipped slot must never spawn ledger_compact helper" + ); + assert!( + !directory.path().join("epoch-misses/epoch-1").exists(), + "admitted archive skipped slot must never enqueue an archive miss" + ); + } +} diff --git a/blockzilla/get-block/wrangler.example.toml b/blockzilla/get-block/wrangler.example.toml index d81ae588..e7418e5b 100644 --- a/blockzilla/get-block/wrangler.example.toml +++ b/blockzilla/get-block/wrangler.example.toml @@ -30,6 +30,11 @@ BZ_R2_BUCKET_BINDING = "BZ_ARCHIVE_BUCKET" # BZ_INDEX_MIRROR_BUCKET_BINDING = "BZ_RESOLUTION" # BZ_INDEX_MIRROR_PREFIX = "index-mirror/compact-v2/blockzilla-20261004" +# Optional finalized-ledger ChunkBundle serving (requires both vars together and +# a matching chunk_archive entry in blockzilla-resolution-service's recent-config). +# BZ_FOUNDATION_CHUNK_GENERATION = "bz2-chunks-v1" +# BZ_FOUNDATION_CHUNK_PREFIX = "finalized-chunks-canary/bz2" + [[r2_buckets]] binding = "BZ_ARCHIVE_BUCKET" bucket_name = "replace-with-archive-bucket" From 3268300b5d2ef3606b7f66c386c1b1ebbfe879aa Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 23:37:39 +0100 Subject: [PATCH 8/9] fix(finalized-ledger): retry transient BudgetExceeded and bridge timeouts per slot --- blockzilla/finalized-ledger/src/drain.rs | 111 +++++++++++----- blockzilla/finalized-ledger/src/tests.rs | 156 +++++++++++++++++++++++ 2 files changed, 235 insertions(+), 32 deletions(-) diff --git a/blockzilla/finalized-ledger/src/drain.rs b/blockzilla/finalized-ledger/src/drain.rs index 45ea8948..6f32eb65 100644 --- a/blockzilla/finalized-ledger/src/drain.rs +++ b/blockzilla/finalized-ledger/src/drain.rs @@ -14,10 +14,10 @@ use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail, ensure}; use base64::{Engine, engine::general_purpose::STANDARD}; use blockzilla_account_bridge_protocol::{ - ArchiveBlockEnvelope, ArchiveBlockPayloadV1, MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, - MAX_SLOT_STATES_RANGE, SlotStateCode, + ArchiveBlockEnvelope, ArchiveBlockPayloadV1, BridgeErrorCode, + MAX_ARCHIVE_PAYLOAD_UNCOMPRESSED_BYTES, MAX_SLOT_STATES_RANGE, SlotStateCode, }; -use blockzilla_account_client::{AccountClient, ClientOptions, SourceIdentity}; +use blockzilla_account_client::{AccountClient, ClientOptions, Error as BridgeClientError, SourceIdentity}; use blockzilla_finalized_chunks::{ CHUNK_BUNDLES_FILE, CHUNK_COUNTS_FILE, CHUNK_EXTRAS_FILE, CHUNK_INDEX_FILE, CHUNK_MANIFEST_FILE, ChunkBuilder, ChunkCatalogBinding, ChunkCatalogWriter, ChunkIndexV1, @@ -1260,6 +1260,51 @@ fn highest_local_chunk_end(root: &Path) -> Result> { Ok(highest) } +const BRIDGE_READ_MAX_RETRIES: usize = 5; +const BRIDGE_READ_INITIAL_BACKOFF: Duration = Duration::from_millis(200); + +fn is_transient_bridge_error(err: &BridgeClientError) -> bool { + match err { + BridgeClientError::Timeout => true, + BridgeClientError::Remote(remote) => remote.code == BridgeErrorCode::BudgetExceeded, + BridgeClientError::Io(io_err) => matches!( + io_err.kind(), + std::io::ErrorKind::TimedOut + | std::io::ErrorKind::WouldBlock + | std::io::ErrorKind::Interrupted + | std::io::ErrorKind::ConnectionReset + | std::io::ErrorKind::BrokenPipe + | std::io::ErrorKind::UnexpectedEof + ), + _ => false, + } +} + +async fn retry_bridge_read(op_label: &str, mut f: F) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let mut backoff = BRIDGE_READ_INITIAL_BACKOFF; + for attempt in 0..=BRIDGE_READ_MAX_RETRIES { + match f().await { + Ok(val) => return Ok(val), + Err(err) if attempt < BRIDGE_READ_MAX_RETRIES && is_transient_bridge_error(&err) => { + eprintln!( + "WARN: transient bridge error during {op_label} (attempt {}/{}): {err}; retrying in {:?}", + attempt + 1, + BRIDGE_READ_MAX_RETRIES + 1, + backoff + ); + tokio::time::sleep(backoff).await; + backoff = (backoff.saturating_mul(2)).min(Duration::from_secs(4)); + } + Err(err) => return Err(err).with_context(|| op_label.to_owned()), + } + } + unreachable!("retry loop always returns") +} + async fn seal_chunk_from_bridge( client: &AccountClient, output_dir: &Path, @@ -1268,10 +1313,10 @@ async fn seal_chunk_from_bridge( zstd_level: i32, slot_pace: Duration, ) -> Result { - let slot_states = client - .get_slot_states(start_slot, end_slot) - .await - .with_context(|| format!("get_slot_states({start_slot}..={end_slot})"))?; + let slot_states = retry_bridge_read(&format!("get_slot_states({start_slot}..={end_slot})"), || { + client.get_slot_states(start_slot, end_slot) + }) + .await?; let expected_len = usize::try_from(end_slot - start_slot + 1)?; ensure!( slot_states.states.len() == expected_len, @@ -1290,10 +1335,10 @@ async fn seal_chunk_from_bridge( .position(|state| *state == SlotStateCode::RootedFull) { let first_rooted = start_slot + first_offset as u64; - let ancestors = client - .get_ancestor_blockhashes(first_rooted, 300) - .await - .with_context(|| format!("get_ancestor_blockhashes({first_rooted})"))?; + let ancestors = retry_bridge_read(&format!("get_ancestor_blockhashes({first_rooted})"), || { + client.get_ancestor_blockhashes(first_rooted, 300) + }) + .await?; let tail = ancestors .into_iter() .map(|a| TailBlockhash { @@ -1312,10 +1357,10 @@ async fn seal_chunk_from_bridge( if !slot_pace.is_zero() { tokio::time::sleep(slot_pace).await; } - let envelope = client - .get_archive_block(slot, None) - .await - .with_context(|| format!("get_archive_block({slot})"))?; + let envelope = retry_bridge_read(&format!("get_archive_block({slot})"), || { + client.get_archive_block(slot, None) + }) + .await?; let payload = decode_archive_envelope(slot, &envelope)?; let encoded = encode_archive_payload(&payload, zstd_level)?; builder.add_block(&encoded)?; @@ -1324,17 +1369,18 @@ async fn seal_chunk_from_bridge( let carrier = slot .checked_add(REWARD_SLOT_DISTANCE) .context("carrier slot overflow")?; - let carrier_info = client - .inspect_slot(carrier, true) - .await - .with_context(|| format!("inspect carrier slot {carrier}"))?; + let carrier_info = + retry_bridge_read(&format!("inspect carrier slot {carrier}"), || { + client.inspect_slot(carrier, true) + }) + .await?; let carrier_markers = decode_optional_markers(&carrier_info.markers_base64)?; let chain = if check::hole_uses_parent_chain(slot, carrier_markers.as_deref())? { - client - .inspect_slot(slot, false) - .await - .with_context(|| format!("inspect hole slot {slot}"))? - .chain_relation + retry_bridge_read(&format!("inspect hole slot {slot}"), || { + client.inspect_slot(slot, false) + }) + .await? + .chain_relation } else { None }; @@ -1342,20 +1388,21 @@ async fn seal_chunk_from_bridge( builder.add_skip(slot)?; } SlotStateCode::NonRoot => { - let slot_info = client - .inspect_slot(slot, false) - .await - .with_context(|| format!("inspect non-root slot {slot}"))?; + let slot_info = retry_bridge_read(&format!("inspect non-root slot {slot}"), || { + client.inspect_slot(slot, false) + }) + .await?; let chain = slot_info .chain_relation .with_context(|| format!("non-root slot {slot} missing chain_relation"))?; let carrier = slot .checked_add(REWARD_SLOT_DISTANCE) .context("carrier slot overflow")?; - let carrier_info = client - .inspect_slot(carrier, true) - .await - .with_context(|| format!("inspect carrier slot {carrier}"))?; + let carrier_info = + retry_bridge_read(&format!("inspect carrier slot {carrier}"), || { + client.inspect_slot(carrier, true) + }) + .await?; let carrier_markers = decode_optional_markers(&carrier_info.markers_base64)?; check::classify_abandoned_fork(slot, chain, carrier_markers.as_deref())?; builder.add_abandoned_fork(slot)?; diff --git a/blockzilla/finalized-ledger/src/tests.rs b/blockzilla/finalized-ledger/src/tests.rs index 3364dbb3..bd60e81a 100644 --- a/blockzilla/finalized-ledger/src/tests.rs +++ b/blockzilla/finalized-ledger/src/tests.rs @@ -2487,3 +2487,159 @@ async fn auto_graduate_retries_after_handoff_failure_and_persists_graduated_mark bridge_stop.store(true, Ordering::Relaxed); bridge_handle.join().unwrap(); } + +#[tokio::test] +async fn drain_retries_transient_budget_exceeded_per_slot() { + use blockzilla_account_bridge_protocol::BridgeErrorCode; + use std::sync::atomic::AtomicUsize; + + let root = tempfile::Builder::new() + .tempdir_in(std::env::temp_dir().canonicalize().unwrap()) + .unwrap(); + let bridge_sock = root.path().join("bridge.sock"); + let output_dir = root.path().join("finalized-chunks"); + + let s0 = SLOTS_PER_EPOCH + 4; // non-epoch-start canonical chunk boundary + let parent_bh = [0x60; 32]; + let bh0 = [0x61; 32]; + let env0 = make_envelope(s0, s0 - 1, bh0, parent_bh, [0xa1; 64], parent_bh); + + let budget_failures = Arc::new(AtomicUsize::new(0)); + let budget_failures_srv = budget_failures.clone(); + let stop = Arc::new(AtomicBool::new(false)); + let stop_srv = stop.clone(); + let listener = UnixListener::bind(&bridge_sock).unwrap(); + listener.set_nonblocking(true).unwrap(); + let handle = thread::spawn(move || { + while !stop_srv.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let req = read_request(&mut stream).unwrap(); + let resp = match &req.operation { + Operation::GetLedgerStatus => Response::ok( + &req, + source_identity(), + ResponseData::GetLedgerStatus { + status: LedgerStatus { + lowest_slot: s0 - 1, + lowest_cleanup_slot: s0 - 1, + max_root: s0 + 11, + highest_slot: Some(s0 + 11), + }, + }, + ), + Operation::GetSlotStates { + start_slot, + end_slot, + } => { + let states = (*start_slot..=*end_slot) + .map(|s| { + if s == s0 { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + } + }) + .collect(); + Response::ok( + &req, + source_identity(), + ResponseData::GetSlotStates { + states: SlotStates { + start_slot: *start_slot, + end_slot: *end_slot, + states, + }, + }, + ) + } + Operation::InspectSlot { + slot, + include_markers, + } => Response::ok( + &req, + source_identity(), + ResponseData::InspectSlot { + inspection: SlotInspection { + slot: *slot, + state: if *include_markers { + SlotStateCode::RootedFull + } else { + SlotStateCode::Absent + }, + parent_slot: (*include_markers).then(|| *slot - 1), + blockhash: (*include_markers).then(|| hash_b58(0x62)), + chain_relation: (!*include_markers).then_some( + SlotChainRelation::JumpsOver { next_root: s0 + 4 }, + ), + markers_base64: None, + }, + }, + ), + Operation::GetArchiveBlock { slot, .. } if *slot == s0 => { + let prev = budget_failures_srv.fetch_add(1, Ordering::Relaxed); + if prev < 2 { + Response::error( + &req, + source_identity(), + BridgeErrorCode::BudgetExceeded, + "native block read budget exceeded", + ) + } else { + Response::ok( + &req, + source_identity(), + ResponseData::GetArchiveBlock { + block: env0.clone(), + }, + ) + } + } + other => panic!("unexpected op {other:?}"), + }; + write_response(&mut stream, &resp).unwrap(); + } + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }); + + let summary = run_drain(DrainConfig { + native_socket: bridge_sock.clone(), + source: source_identity(), + source_json_path: None, + client_timeout: Duration::from_secs(5), + output_dir: output_dir.clone(), + chunk_slots: 4, + zstd_level: 1, + start_slot: Some(s0), + once: true, + poll_interval: Duration::from_millis(20), + r2: None, + catalog: None, + evict_local_payloads: false, + purge: None, + gap_recovery: GapRecoveryConfig::default(), + stall_alert_after: None, + stall_repeat_interval: Duration::from_secs(60), + min_free_disk_gib: 0, + slot_pace: Duration::ZERO, + snapshot_safety_margin: 0, + auto_graduate: None, + shutdown: None, + }) + .await + .expect("chunk must seal after transient BudgetExceeded retries"); + + assert_eq!(summary.chunks_sealed, 1); + assert_eq!(summary.blocks_sealed, 1); + assert_eq!(summary.skips_sealed, 3); + assert_eq!(budget_failures.load(Ordering::Relaxed), 3); + + stop.store(true, Ordering::Relaxed); + handle.join().unwrap(); +} From 23b49fe0a10c7563ec7541e75114095d933ef96d Mon Sep 17 00:00:00 2001 From: augustin Date: Wed, 2 Dec 2026 23:42:55 +0100 Subject: [PATCH 9/9] style: apply rustfmt 1.98.1 formatting --- .../get-block/src/worker/foundation_first.rs | 4 +++- .../blockzilla-archive-v2/src/v2/wire_rewrite.rs | 14 +++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/blockzilla/get-block/src/worker/foundation_first.rs b/blockzilla/get-block/src/worker/foundation_first.rs index b9f4b616..4f977df1 100644 --- a/blockzilla/get-block/src/worker/foundation_first.rs +++ b/blockzilla/get-block/src/worker/foundation_first.rs @@ -1736,7 +1736,9 @@ mod tests { let bh_str = std::str::from_utf8(&bh_buf[..bh_len]).unwrap().to_owned(); let mut prev_buf = [0u8; 44]; let prev_len = five8::encode_32(&[0x11; 32], &mut prev_buf) as usize; - let prev_str = std::str::from_utf8(&prev_buf[..prev_len]).unwrap().to_owned(); + let prev_str = std::str::from_utf8(&prev_buf[..prev_len]) + .unwrap() + .to_owned(); let valid = ChunkBundleLocatorV1 { version: 1, diff --git a/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs b/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs index fe7d0f0b..70c132e3 100644 --- a/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs +++ b/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs @@ -4653,8 +4653,13 @@ mod tests { #[test] fn hot_v1_message_and_nonce_blockhash_promotion_round_trip() { - use blockzilla_compact::{CompactMessageHeader, CompactTransactionConfig, OwnedCompactRecentBlockhash}; - use crate::{ArchiveV2HotInstruction, ArchiveV2HotInstructionData, ArchiveV2HotMessagePayload, ArchiveV2HotV1Message}; + use crate::{ + ArchiveV2HotInstruction, ArchiveV2HotInstructionData, ArchiveV2HotMessagePayload, + ArchiveV2HotV1Message, + }; + use blockzilla_compact::{ + CompactMessageHeader, CompactTransactionConfig, OwnedCompactRecentBlockhash, + }; struct PromoteVisitor { target_nonce: [u8; 32], @@ -4726,7 +4731,10 @@ mod tests { wincode::config::deserialize(&output, wincode_leb128_config()).unwrap(); match decoded { ArchiveV2HotMessagePayload::V1(v1) => { - assert_eq!(v1.account_keys, vec![CompactPubkey::Id(101), CompactPubkey::Id(102)]); + assert_eq!( + v1.account_keys, + vec![CompactPubkey::Id(101), CompactPubkey::Id(102)] + ); assert!(matches!( v1.recent_blockhash, OwnedCompactRecentBlockhash::Id(-7)