diff --git a/Cargo.lock b/Cargo.lock index b3a21a34..81a85105 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -447,13 +447,7 @@ name = "blockzilla-dump-examples" version = "0.2.0" dependencies = [ "anyhow", - "blockzilla-compact-v2-reader", - "blockzilla-model", - "bs58", - "clap 4.6.6", - "five8", - "itoa", - "serde_json", + "blockzilla", ] [[package]] diff --git a/README.md b/README.md index 315ca35b..dc1364c7 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,14 @@ RUSTFLAGS="-C target-cpu=native" cargo run --locked -p blockzilla -- \ stream --epoch 200 --max-blocks 5 ``` -This reads five block rows from the public sample archive. No API key is needed. +This reads five block rows from the public Foundation archive. No API key is needed. Use `--help` to see the commands, or start with the [small examples](examples). ## In this repository | Component | Purpose | | --- | --- | -| [CLI](blockzilla/cli) | Stream, inspect, dump tokens and build archives | +| [CLI](blockzilla/cli) | Stream, inspect, dump tokens, wallets and programs, and build archives | | [Compact V2](crates/compact-v2) | Block format, archive layout and readers | | [Zillastream](zillastream) | Capture Agave blocks and deliver a live stream | | [getBlock](blockzilla/get-block) | Serve recent and archived blocks | diff --git a/blockzilla/cli/Cargo.toml b/blockzilla/cli/Cargo.toml index cca25a24..9fe88205 100644 --- a/blockzilla/cli/Cargo.toml +++ b/blockzilla/cli/Cargo.toml @@ -36,6 +36,7 @@ blockzilla-primitives = { path = "../../crates/blockzilla-primitives", default-f blockzilla-program-logs = { path = "../../crates/parser/blockzilla-program-logs", default-features = false, version = "0.2.0" } blockzilla-registry = { path = "../../crates/compact-v2/blockzilla-registry", default-features = false, version = "0.2.0" } anyhow = "1.0.104" +bs58 = "0.5.1" bincode = "1.3.3" # Allocation-free base58 and integer text for the token dump rows. five8 = "1.0.0" @@ -57,7 +58,6 @@ wincode = { version = "=0.6.1", features = ["derive"] } zstd = "0.14.0" [dev-dependencies] -bs58 = "0.5.1" tempfile = "3.27.0" [lints] diff --git a/blockzilla/cli/README.md b/blockzilla/cli/README.md index ef24f194..6db63c72 100644 --- a/blockzilla/cli/README.md +++ b/blockzilla/cli/README.md @@ -6,7 +6,9 @@ The core command tree contains: | Command | Purpose | | --- | --- | | `stream` | Read an archive epoch as ordered JSON block summaries. | -| `dump-tokens` | Export recorded token balances as JSON Lines. | +| `token-dump` | Export recorded token balances as JSON Lines. | +| `wallet-dump` | Export transactions that one wallet signed. | +| `program-dump` | Export recorded outer and inner calls of one program. | | `inspect` | Show an archive's admitted identity and range. | | `compare-sdk-rpc` | Compare a saved SDK capture with finalized RPC blocks. | | `build-direct-agave-compact` | Build compact blocks from a complete native callback batch. | @@ -14,13 +16,32 @@ The core command tree contains: ```sh cargo run --locked -p blockzilla -- --help blockzilla stream --epoch 900 --max-blocks 5 -blockzilla dump-tokens --epoch 900 --max-blocks 100 > token-balances.jsonl +blockzilla token-dump --epoch 200 --max-blocks 20 --mint EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v > usdc.jsonl +blockzilla token-dump --archive-url https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-1094 --epoch 1094 --mint EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v +blockzilla wallet-dump --epoch 1094 --key WALLET +blockzilla program-dump --epoch 1094 --key PROGRAM blockzilla inspect --epoch 900 ``` +`token-dump` takes `--epoch`, `--origin`, `--archive-url`, `--s3-region`, +`--cache-root`, `--archive-dir`, `--source-id`, `--read-concurrency`, +`--threads`, `--first-block`, `--max-blocks`, and `--mint`. With no +`--archive-url`, `--origin`, or `--archive-dir`, it reads the public Foundation +directory +`https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-`. +It writes one JSON line per recorded token balance. Each line includes the +transaction signature. The command stops when execution status or token data +is missing. +`wallet-dump` and `program-dump` take the same arguments as the example +binaries in `examples/`. Omit `--archive-url` to read the public Foundation archive at +`https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-`. +The cache defaults to `.blockzilla-cache` in the current directory. Give a +local epoch directory instead of `--archive-url` to read a local build. `--key` +selects a required signer or a program. `wallet-dump` and `program-dump` +require `--key`. These commands read archives only. + For a local archive, supply `--archive-dir /absolute/archive/path` and a stable -`--source-id`. The `stream`, `dump-tokens` and `inspect` commands use the same -archive source options. Output goes to stdout; progress goes to stderr. +`--source-id`. Output goes to stdout; progress goes to stderr. The native worker uses this unchanged command contract: @@ -39,7 +60,7 @@ their separate tools. Archive integrity and signature checks remain available through the reader SDK. The combined live-capture and archive-backfill token example is a product -acceptance target. The current `dump-tokens` command reads archives only. +acceptance target. The current `token-dump` command reads archives only. ## Compare SDK output with RPC diff --git a/examples/src/lib.rs b/blockzilla/cli/src/archive_dump.rs similarity index 64% rename from examples/src/lib.rs rename to blockzilla/cli/src/archive_dump.rs index 1a25f3f4..4d540c85 100644 --- a/examples/src/lib.rs +++ b/blockzilla/cli/src/archive_dump.rs @@ -4,8 +4,7 @@ use blockzilla_compact_v2_reader::{ archive::{CompactV2Archive, CompactV2LocalDescriptor}, }; use blockzilla_model::{ - ArchiveInstructionSource, BlockSink, BlockView, Error, ExecutionStatus, RecordedTokenBalance, - ScanRequest, TokenBalanceSide, + ArchiveInstructionSource, BlockSink, BlockView, Error, ExecutionStatus, ScanRequest, }; use clap::Parser; use std::{ @@ -16,30 +15,33 @@ use std::{ #[derive(Clone, Copy)] pub enum Kind { - Token, Wallet, Program, } -#[derive(Parser)] -struct Args { - /// Local Compact V2 epoch directory. Omit it when `--url` is set. + +#[derive(clap::Args)] +pub struct Args { + /// Local Compact V2 epoch directory. Omit it when `--archive-url` is set. archive: Option, #[arg(long)] epoch: u64, /// Stable identifier of this immutable local archive generation. #[arg(long)] source_id: Option, - /// Stream a public HTTPS epoch directory instead of a local one, for - /// example `https://archive.example/compact-v2/build/epoch-200`. + /// Public HTTPS epoch directory. Omit it to read + /// `https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-` + /// for the selected epoch. #[arg(long)] - url: Option, - /// Private cache directory for the network reader's control files. - #[arg(long, requires = "url")] + archive_url: Option, + /// Cache directory for the network reader's control files. The default is + /// `.blockzilla-cache` in the current directory. A relative path is + /// resolved from the current directory. + #[arg(long, conflicts_with = "archive")] cache_dir: Option, /// Sign requests for a private S3-compatible bucket in this region (`auto` /// for Cloudflare R2). Credentials come from AWS_ACCESS_KEY_ID, /// AWS_SECRET_ACCESS_KEY and the optional AWS_SESSION_TOKEN. - #[arg(long, requires = "url")] + #[arg(long, requires = "archive_url")] s3_region: Option, /// First block row of the scan. #[arg(long, default_value_t = 0)] @@ -47,7 +49,7 @@ struct Args { /// Maximum number of block rows to scan. #[arg(long)] max_blocks: Option, - /// Token mint, required signer, or invoked program in base58. + /// Required signer or invoked program in base58. #[arg(long)] key: Option, /// Parallel decode workers. The default is the number of logical CPUs. @@ -55,14 +57,14 @@ struct Args { #[arg(long)] workers: Option, /// Concurrent HTTPS range requests for a network archive. - #[arg(long, requires = "url")] + #[arg(long, conflicts_with = "archive")] http_requests: Option, /// Target size of one HTTPS range request, in MiB. - #[arg(long, requires = "url")] + #[arg(long, conflicts_with = "archive")] http_range_mib: Option, /// Concurrent block reads for a local archive. Use several on a NAS or /// disk array; 1 reads one range at a time. - #[arg(long, default_value_t = 1, conflicts_with = "url")] + #[arg(long, default_value_t = 1, conflicts_with = "archive_url")] read_concurrency: usize, /// Print the scan receipt with pipeline timings to standard error. #[arg(long)] @@ -84,38 +86,20 @@ impl Rows { /// Append the rows of one block to `out`. fn block(&self, block: &BlockView<'_>, out: &mut Vec) { let slot = block.header.slot; + let key = self.key.expect("validated before scan"); for tx in block.transaction_views() { - match self.kind { - Kind::Token => { - for row in tx.token_balances { - // The scan request already selects the mint. Keep the - // check so a source without mint selection prints the - // same rows. Rows with an unknown mint stay visible. - if self.key.is_some() && row.mint.is_some() && row.mint != self.key { - continue; - } - token_row(out, slot, tx.header.tx_index, tx.header.status, row); - } - } - Kind::Wallet | Kind::Program => { - let key = self.key.expect("validated before scan"); - let matched = match self.kind { - Kind::Wallet => tx.required_signers.contains(&key), - Kind::Program => { - tx.instructions.iter().any(|ix| ix.program_id == Some(key)) - } - Kind::Token => unreachable!(), - }; - if matched { - transaction_row( - out, - slot, - tx.header.tx_index, - tx.header.status, - tx.primary_signature, - ); - } - } + let matched = match self.kind { + Kind::Wallet => tx.required_signers.contains(&key), + Kind::Program => tx.instructions.iter().any(|ix| ix.program_id == Some(key)), + }; + if matched { + transaction_row( + out, + slot, + tx.header.tx_index, + tx.header.status, + tx.primary_signature, + ); } } } @@ -125,19 +109,6 @@ fn number(out: &mut Vec, value: impl itoa::Integer) { out.extend_from_slice(itoa::Buffer::new().format(value).as_bytes()); } -/// A JSON string with the base58 key, or `null`. -fn key_32(out: &mut Vec, key: Option<&[u8; 32]>) { - let Some(key) = key else { - out.extend_from_slice(b"null"); - return; - }; - let mut text = [0u8; five8::BASE58_ENCODED_32_MAX_LEN]; - let length = usize::from(five8::encode_32(key, &mut text)); - out.push(b'"'); - out.extend_from_slice(&text[..length]); - out.push(b'"'); -} - fn key_64(out: &mut Vec, key: Option<&[u8; 64]>) { let Some(key) = key else { out.extend_from_slice(b"null"); @@ -161,37 +132,6 @@ fn status(out: &mut Vec, status: ExecutionStatus) { } } -/// One token balance row. Keys are in the sorted order that a -/// `serde_json::json!` object prints, so the bytes equal the earlier output. -fn token_row( - out: &mut Vec, - slot: u64, - tx_index: u32, - execution: ExecutionStatus, - row: &RecordedTokenBalance, -) { - out.extend_from_slice(b"{\"account_index\":"); - number(out, row.account_index); - out.extend_from_slice(b",\"amount\":\""); - number(out, row.amount); - out.extend_from_slice(b"\",\"decimals\":"); - number(out, row.decimals); - out.extend_from_slice(b",\"mint\":"); - key_32(out, row.mint.as_ref()); - out.extend_from_slice(b",\"owner\":"); - key_32(out, row.owner.as_ref()); - out.extend_from_slice(match row.side { - TokenBalanceSide::Pre => b",\"side\":\"Pre\",\"slot\":", - TokenBalanceSide::Post => b",\"side\":\"Post\",\"slot\":", - }); - number(out, slot); - out.extend_from_slice(b",\"status\":"); - status(out, execution); - out.extend_from_slice(b",\"tx_index\":"); - number(out, tx_index); - out.extend_from_slice(b"}\n"); -} - fn transaction_row( out: &mut Vec, slot: u64, @@ -227,8 +167,28 @@ impl BlockSink for Sink { } } +#[derive(Parser)] +struct ExampleCommand { + #[command(flatten)] + args: Args, +} + +fn absolute_cache_dir(cache_dir: Option) -> Result { + let path = cache_dir.unwrap_or_else(|| PathBuf::from(".blockzilla-cache")); + if path.is_absolute() { + Ok(path) + } else { + Ok(std::env::current_dir()?.join(path)) + } +} + +/// Parse the example binary's arguments and run one dump. pub fn run(kind: Kind) -> Result<()> { - let args = Args::parse(); + execute(kind, ExampleCommand::parse().args) +} + +/// Run one dump with arguments already parsed by `blockzilla`. +pub fn execute(kind: Kind, args: Args) -> Result<()> { let key = args .key .map(|value| -> Result<[u8; 32]> { @@ -238,11 +198,12 @@ pub fn run(kind: Kind) -> Result<()> { .map_err(|_| anyhow::anyhow!("key must contain 32 bytes")) }) .transpose()?; - if !matches!(kind, Kind::Token) { - anyhow::ensure!(key.is_some(), "--key is required"); - } + anyhow::ensure!(key.is_some(), "--key is required"); let local = args.archive.is_some(); - let mut archive = match (args.archive, args.url) { + let mut archive = match (args.archive, args.archive_url) { + (Some(_), Some(_)) => { + bail!("give either a local ARCHIVE directory or --archive-url, not both") + } (Some(directory), None) => CompactV2Archive::open_local_with_read_concurrency( &directory, CompactV2LocalDescriptor::mainnet( @@ -252,33 +213,25 @@ pub fn run(kind: Kind) -> Result<()> { )?, args.read_concurrency, )?, - (None, Some(url)) => { - let cache_dir = args - .cache_dir - .context("--cache-dir is required with --url")?; + (None, archive_url) => { + let archive_url = archive_url.unwrap_or_else(|| crate::public_epoch_url(args.epoch)); + let cache_dir = absolute_cache_dir(args.cache_dir)?; + eprintln!("Source: {archive_url}"); match args.s3_region { Some(region) => { let signer = S3SigV4Signer::new(S3Credentials::from_env()?, region)?; CompactV2Archive::open_signed_epoch_url( - &url, + &archive_url, args.epoch, cache_dir, std::sync::Arc::new(signer), )? } - None => CompactV2Archive::open_epoch_url(&url, args.epoch, cache_dir)?, + None => CompactV2Archive::open_epoch_url(&archive_url, args.epoch, cache_dir)?, } } - _ => bail!("give either a local ARCHIVE directory or --url, not both"), }; let mut request = match kind { - // Token rows print no signature and no signer, so the request reads - // neither. With a mint, the reader skips other rows before it - // resolves their owner and token program. Unknown mints stay selected. - Kind::Token => match key { - Some(mint) => ScanRequest::token_balances_only().with_token_balances_for([mint]), - None => ScanRequest::token_balances_only(), - }, // The reader keeps only the selected signer in each signer list, so // it does not resolve every other signer key. Kind::Wallet => ScanRequest::all() @@ -372,26 +325,6 @@ mod tests { use blockzilla_model::CoverageReason; use serde_json::json; - /// The JSON the example printed before the hand-written writer. - fn reference_token_row( - slot: u64, - tx_index: u32, - status: ExecutionStatus, - row: &RecordedTokenBalance, - ) -> Vec { - let mut bytes = serde_json::to_vec(&json!({ - "slot": slot, "tx_index": tx_index, - "status": format!("{:?}", status), - "side": format!("{:?}", row.side), "account_index": row.account_index, - "mint": row.mint.map(|v| bs58::encode(v).into_string()), - "owner": row.owner.map(|v| bs58::encode(v).into_string()), - "amount": row.amount.to_string(), "decimals": row.decimals - })) - .unwrap(); - bytes.push(b'\n'); - bytes - } - fn reference_transaction_row( slot: u64, tx_index: u32, @@ -452,35 +385,72 @@ mod tests { } #[test] - fn token_rows_match_the_json_macro_output_byte_for_byte() { - let keys = keys(); - let mut output = Vec::new(); - let mut expected = Vec::new(); - for (index, status) in statuses().into_iter().enumerate() { - for (position, key) in keys.iter().enumerate() { - let row = RecordedTokenBalance { - side: if position % 2 == 0 { - TokenBalanceSide::Pre - } else { - TokenBalanceSide::Post - }, - balance_index: position as u32, - account_index: [0, 1, 255, u32::MAX][position % 4], - mint: (position % 5 != 0).then_some(*key), - owner: (position % 3 != 0).then(|| keys[(position + 7) % keys.len()]), - token_program: None, - amount: [0, 1, 10, u64::MAX, 1_000_000_007][position % 5], - decimals: [0, 6, 9, u8::MAX][position % 4], - }; - let slot = [0, 86_604_091, u64::MAX][index % 3]; - let tx_index = [0, 72, u32::MAX][position % 3]; - expected.extend(reference_token_row(slot, tx_index, status, &row)); - token_row(&mut output, slot, tx_index, status, &row); - } - } + fn example_command_accepts_the_local_and_https_forms() { + let local = ExampleCommand::try_parse_from([ + "wallet-dump", + "/data/epoch-900", + "--epoch", + "900", + "--source-id", + "my-generation", + "--key", + "WALLET", + "--workers", + "4", + ]) + .unwrap(); + assert_eq!(local.args.epoch, 900); assert_eq!( - String::from_utf8(output).unwrap(), - String::from_utf8(expected).unwrap() + local.args.archive.as_deref(), + Some(PathBuf::from("/data/epoch-900").as_path()) + ); + assert_eq!(local.args.source_id.as_deref(), Some("my-generation")); + assert_eq!(local.args.key.as_deref(), Some("WALLET")); + assert_eq!(local.args.workers, Some(4)); + + let remote = ExampleCommand::try_parse_from([ + "wallet-dump", + "--archive-url", + "https://archive.example/compact-v2/build/epoch-200", + "--epoch", + "200", + "--cache-dir", + "/var/cache/blockzilla", + "--s3-region", + "auto", + "--max-blocks", + "10", + ]) + .unwrap(); + assert!(remote.args.archive.is_none()); + assert_eq!(remote.args.epoch, 200); + assert_eq!(remote.args.max_blocks.unwrap().get(), 10); + assert_eq!(remote.args.s3_region.as_deref(), Some("auto")); + + let foundation = + ExampleCommand::try_parse_from(["wallet-dump", "--epoch", "1094"]).unwrap(); + assert!(foundation.args.archive.is_none()); + assert!(foundation.args.archive_url.is_none()); + assert!(foundation.args.cache_dir.is_none()); + assert_eq!( + crate::public_epoch_url(1094), + "https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-1094" + ); + + assert!( + ExampleCommand::try_parse_from([ + "wallet-dump", + "/data/epoch-200", + "--archive-url", + "https://archive.example/epoch-200", + "--epoch", + "200", + "--cache-dir", + "/var/cache/blockzilla", + "--read-concurrency", + "6", + ]) + .is_err() ); } diff --git a/blockzilla/cli/src/lib.rs b/blockzilla/cli/src/lib.rs new file mode 100644 index 00000000..4b257cdd --- /dev/null +++ b/blockzilla/cli/src/lib.rs @@ -0,0 +1,14 @@ +//! Shared archive dump commands for the `blockzilla` binary and the example bins. + +/// Public Foundation Compact V2 bucket. Objects for one epoch live in +/// `{PUBLIC_ARCHIVE_BASE}/epoch-/`. +pub const PUBLIC_ARCHIVE_BASE: &str = + "https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004"; + +/// Epoch directory on the public Foundation bucket. +pub fn public_epoch_url(epoch: u64) -> String { + format!("{PUBLIC_ARCHIVE_BASE}/epoch-{epoch}") +} + +#[doc(hidden)] +pub mod archive_dump; diff --git a/blockzilla/cli/src/main.rs b/blockzilla/cli/src/main.rs index 81e1e033..2ae0d1bf 100644 --- a/blockzilla/cli/src/main.rs +++ b/blockzilla/cli/src/main.rs @@ -8,10 +8,10 @@ use std::path::PathBuf; mod archive_v2; mod compare_sdk_rpc; -mod dump_tokens; mod first_seen_finalization; mod progress; mod stream; +mod token_dump; use progress::{ProgressTracker, file_nonempty}; pub const BUFFER_SIZE: usize = 256 << 20; @@ -37,7 +37,11 @@ enum Commands { /// Stream an archive epoch as ordered JSON block summaries. Stream(stream::StreamArgs), /// Export recorded token balances from an archive epoch. - DumpTokens(dump_tokens::DumpTokensArgs), + TokenDump(token_dump::TokenDumpArgs), + /// Export transactions that the selected wallet signed. + WalletDump(blockzilla::archive_dump::Args), + /// Export recorded outer and inner calls of one program. + ProgramDump(blockzilla::archive_dump::Args), /// Show the admitted identity and range of an archive epoch. Inspect { #[command(flatten)] @@ -62,7 +66,13 @@ fn main() -> Result<()> { match Cli::parse().command { Commands::CompareSdkRpc(args) => compare_sdk_rpc::run(args), Commands::Stream(args) => stream::run(args), - Commands::DumpTokens(args) => dump_tokens::run(args), + Commands::TokenDump(args) => token_dump::run(args), + Commands::WalletDump(args) => { + blockzilla::archive_dump::execute(blockzilla::archive_dump::Kind::Wallet, args) + } + Commands::ProgramDump(args) => { + blockzilla::archive_dump::execute(blockzilla::archive_dump::Kind::Program, args) + } Commands::Inspect { source } => { let archive = stream::open(&source)?; println!("{}", serde_json::to_string_pretty(archive.identity())?); @@ -129,6 +139,43 @@ mod cli_tests { )); } + #[test] + fn archive_dump_commands_use_the_example_arguments() { + for (name, expected) in [("wallet-dump", "wallet"), ("program-dump", "program")] { + let cli = Cli::try_parse_from([ + "blockzilla", + name, + "/data/epoch-900", + "--epoch", + "900", + "--source-id", + "my-generation", + "--key", + "WALLET", + ]) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let actual = match cli.command { + Commands::WalletDump(_) => "wallet", + Commands::ProgramDump(_) => "program", + _ => "other", + }; + assert_eq!(actual, expected, "{name}"); + } + assert!(Cli::try_parse_from(["blockzilla", "dump-tokens", "--epoch", "1094"]).is_err()); + let cli = Cli::try_parse_from([ + "blockzilla", + "token-dump", + "--epoch", + "1094", + "--max-blocks", + "20", + "--mint", + "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + ]) + .unwrap(); + assert!(matches!(cli.command, Commands::TokenDump(_))); + } + #[test] fn removed_application_and_source_commands_are_not_core_commands() { for command in [ diff --git a/blockzilla/cli/src/stream.rs b/blockzilla/cli/src/stream.rs index 3bd678bc..627e3ede 100644 --- a/blockzilla/cli/src/stream.rs +++ b/blockzilla/cli/src/stream.rs @@ -11,8 +11,6 @@ use blockzilla_compact_v2_reader::archive::{ use clap::Args; use serde::Serialize; -const DEFAULT_ORIGIN: &str = "https://blockzilla-archive-samples-v1.cheron-augustin.workers.dev"; - #[derive(Args, Debug)] pub(crate) struct StreamArgs { #[command(flatten)] @@ -21,13 +19,14 @@ pub(crate) struct StreamArgs { #[derive(Args, Debug)] pub(crate) struct EpochSourceArgs { - /// Epoch to read. The public source supplies selected sample epochs. + /// Epoch to read from the public Foundation archive. #[arg(long)] pub epoch: u64, - /// Compatible HTTPS archive origin. Defaults to the public sample source. + /// Compatible HTTPS archive origin. Omit it to read the public Foundation bucket. #[arg(long, env = "BLOCKZILLA_ORIGIN", conflicts_with = "archive_dir")] pub origin: Option, - /// Public HTTPS epoch directory, such as https://archive.example.com/epoch-N. + /// Public HTTPS epoch directory. Omit `--archive-url` and `--origin` to read + /// `https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-`. #[arg(long, env = "BLOCKZILLA_ARCHIVE_URL", conflicts_with_all = ["origin", "archive_dir"])] pub archive_url: Option, /// Sign requests to --archive-url for a private S3-compatible bucket in this @@ -150,11 +149,15 @@ pub(crate) fn open(args: &EpochSourceArgs) -> Result { None => CompactV2Archive::open_epoch_url(epoch_url, args.epoch, cache_root), } .with_context(|| format!("Cannot open epoch {} at {epoch_url}", args.epoch))? - } else { - let origin = args.origin.as_deref().unwrap_or(DEFAULT_ORIGIN); + } else if let Some(origin) = args.origin.as_deref() { eprintln!("Source: {origin}\nPreparing archive index and key registry..."); CompactV2Archive::open(origin, args.epoch, cache_root) .with_context(|| format!("Cannot open epoch {} at {origin}", args.epoch))? + } else { + let epoch_url = blockzilla::public_epoch_url(args.epoch); + eprintln!("Source: {epoch_url}\nPreparing archive index and key registry..."); + CompactV2Archive::open_epoch_url(&epoch_url, args.epoch, cache_root) + .with_context(|| format!("Cannot open epoch {} at {epoch_url}", args.epoch))? } }; Ok(archive) diff --git a/blockzilla/cli/src/dump_tokens.rs b/blockzilla/cli/src/token_dump.rs similarity index 65% rename from blockzilla/cli/src/dump_tokens.rs rename to blockzilla/cli/src/token_dump.rs index 86863a93..04c54ef2 100644 --- a/blockzilla/cli/src/dump_tokens.rs +++ b/blockzilla/cli/src/token_dump.rs @@ -2,23 +2,61 @@ use std::{ io::{self, BufWriter, Write}, + num::NonZeroU32, + path::PathBuf, time::Instant, }; use anyhow::{Context, Result}; use blockzilla_compact_v2_reader::archive::{ - ArchiveInstructionSource, BlockSink, BlockView, QueryError, QueryResult, + ArchiveInstructionSource, BlockSink, BlockView, CompactV2Archive, CompactV2LocalDescriptor, + CompactV2ParallelScanConfig, QueryError, QueryResult, ScanRequest, }; use blockzilla_model::{ExecutionStatus, TokenBalanceCoverage, TokenBalanceSide}; use clap::Args; use sha2::{Digest, Sha256}; -use crate::stream::{self, EpochSourceArgs}; - #[derive(Args, Debug)] -pub(crate) struct DumpTokensArgs { - #[command(flatten)] - pub source: EpochSourceArgs, +pub(crate) struct TokenDumpArgs { + /// Epoch to read from the public Foundation archive. + #[arg(long)] + pub epoch: u64, + /// Compatible HTTPS archive origin. Omit it to read the public Foundation bucket. + #[arg(long, env = "BLOCKZILLA_ORIGIN", conflicts_with = "archive_dir")] + pub origin: Option, + /// Public HTTPS epoch directory. Omit `--archive-url` and `--origin` to read + /// `https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-`. + #[arg(long, env = "BLOCKZILLA_ARCHIVE_URL", conflicts_with_all = ["origin", "archive_dir"])] + pub archive_url: Option, + /// Sign requests to --archive-url for a private S3-compatible bucket in this + /// region (`auto` for Cloudflare R2). Credentials come from + /// AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and the optional + /// AWS_SESSION_TOKEN. + #[arg(long, requires = "archive_url")] + pub s3_region: Option, + /// Cache directory. Relative paths are resolved from the current directory. + #[arg(long, default_value = ".blockzilla-cache")] + pub cache_root: PathBuf, + /// Read this local epoch directory instead of the HTTPS source. + #[arg(long, requires = "source_id")] + pub archive_dir: Option, + /// Stable ID for a local archive build. Change it when you replace that build. + #[arg(long, requires = "archive_dir")] + pub source_id: Option, + /// Concurrent block reads for --archive-dir. Use several on a NAS or disk + /// array; 1 reads one range at a time. + #[arg(long, default_value_t = 1, requires = "archive_dir", value_parser = clap::value_parser!(u16).range(1..=64))] + pub read_concurrency: u16, + /// Decode workers (1 through 64). + #[arg(long, default_value_t = 4, value_parser = clap::value_parser!(u16).range(1..=64))] + pub threads: u16, + /// First block row to read. Use the next row after a saved checkpoint to + /// resume a dump. + #[arg(long, default_value_t = 0)] + pub first_block: u32, + /// Read at most this many block rows. Omit to read all admitted rows. + #[arg(long)] + pub max_blocks: Option, /// Select one base58 mint. Unknown mint identities remain visible as null. #[arg(long, value_parser = parse_mint)] pub mint: Option<[u8; 32]>, @@ -67,6 +105,18 @@ impl TokenSink { self.output.write_all(text.as_bytes()) } + /// A JSON string with the base58 transaction signature, or `null`. + fn signature(&mut self, signature: Option<&[u8; 64]>) -> io::Result<()> { + let Some(signature) = signature else { + return self.output.write_all(b"null"); + }; + let mut text = [0u8; five8::BASE58_ENCODED_64_MAX_LEN]; + let length = usize::from(five8::encode_64(signature, &mut text)); + self.output.write_all(b"\"")?; + self.output.write_all(&text[..length])?; + self.output.write_all(b"\"") + } + /// A JSON string with the base58 key, or `null`. fn key(&mut self, key: Option<&[u8; 32]>) -> io::Result<()> { let Some(key) = key else { @@ -88,6 +138,7 @@ impl TokenSink { block_ordinal: u32, slot: u64, tx_index: u32, + signature: Option<&[u8; 64]>, status: &'static [u8], balance: &blockzilla_model::RecordedTokenBalance, ) -> io::Result<()> { @@ -99,6 +150,8 @@ impl TokenSink { self.number(slot)?; self.output.write_all(b",\"tx_index\":")?; self.number(tx_index)?; + self.output.write_all(b",\"signature\":")?; + self.signature(signature)?; self.output.write_all(b",\"execution_status\":\"")?; self.output.write_all(status)?; self.output.write_all(match balance.side { @@ -148,6 +201,7 @@ impl BlockSink for TokenSink { block.header.block_ordinal, block.header.slot, tx.header.tx_index, + tx.primary_signature, status, balance, ) @@ -168,12 +222,84 @@ impl BlockSink for TokenSink { } } -pub(crate) fn run(args: DumpTokensArgs) -> Result<()> { +fn open(args: &TokenDumpArgs) -> Result { + eprintln!("Opening epoch {}...", args.epoch); + let archive = if let Some(root) = &args.archive_dir { + let root = std::fs::canonicalize(&root) + .with_context(|| format!("Cannot open archive directory {}", root.display()))?; + let source_id = args + .source_id + .as_deref() + .context("Local reads require --source-id")?; + let descriptor = CompactV2LocalDescriptor::mainnet(args.epoch, source_id)?; + CompactV2Archive::open_local_with_read_concurrency( + root, + descriptor, + usize::from(args.read_concurrency), + )? + } else { + let cache_root = if args.cache_root.is_absolute() { + args.cache_root.clone() + } else { + std::env::current_dir()?.join(&args.cache_root) + }; + if let Some(epoch_url) = &args.archive_url { + eprintln!("Source: {epoch_url}\nPreparing archive index and key registry..."); + match &args.s3_region { + Some(region) => { + let signer = blockzilla_compact_v2_reader::S3SigV4Signer::new( + blockzilla_compact_v2_reader::S3Credentials::from_env()?, + region.as_str(), + )?; + CompactV2Archive::open_signed_epoch_url( + epoch_url, + args.epoch, + cache_root, + std::sync::Arc::new(signer), + ) + } + None => CompactV2Archive::open_epoch_url(epoch_url, args.epoch, cache_root), + } + .with_context(|| format!("Cannot open epoch {} at {epoch_url}", args.epoch))? + } else if let Some(origin) = args.origin.as_deref() { + eprintln!("Source: {origin}\nPreparing archive index and key registry..."); + CompactV2Archive::open(origin, args.epoch, cache_root) + .with_context(|| format!("Cannot open epoch {} at {origin}", args.epoch))? + } else { + let epoch_url = blockzilla::public_epoch_url(args.epoch); + eprintln!("Source: {epoch_url}\nPreparing archive index and key registry..."); + CompactV2Archive::open_epoch_url(&epoch_url, args.epoch, cache_root) + .with_context(|| format!("Cannot open epoch {} at {epoch_url}", args.epoch))? + } + }; + Ok(archive) +} + +fn parallel_config(args: &TokenDumpArgs) -> CompactV2ParallelScanConfig { + let mut config = CompactV2ParallelScanConfig::new(usize::from(args.threads)); + if args.archive_dir.is_some() + && args.read_concurrency > 1 + && let Some(input) = config.network_input.as_mut() + { + input.workers = usize::from(args.read_concurrency); + } + config +} + +fn request(archive: &CompactV2Archive, args: &TokenDumpArgs) -> Result { + Ok(match (args.first_block, args.max_blocks) { + (0, None) => ScanRequest::all(), + (first_block, limit) => ScanRequest::bounded( + archive.bounded_range(first_block, limit.unwrap_or(NonZeroU32::MAX))?, + ), + }) +} + +pub(crate) fn run(args: TokenDumpArgs) -> Result<()> { let started = Instant::now(); - let mut archive = stream::open(&args.source)?; - let request = stream::request(&archive, &args.source)? + let mut archive = open(&args)?; + let request = request(&archive, &args)? .without_instructions() - .without_primary_signatures() .without_required_signers(); let request = match args.mint { Some(mint) => request.with_token_balances_for([mint]), @@ -190,7 +316,7 @@ pub(crate) fn run(args: DumpTokensArgs) -> Result<()> { &source_id, ); let receipt = archive - .scan_ordered_parallel(&request, &mut sink, stream::parallel_config(&args.source)) + .scan_ordered_parallel(&request, &mut sink, parallel_config(&args)) .context("Token dump stopped; output can contain an incomplete prefix")?; sink.output.flush().context("flush token dump output")?; archive.verify_local_unchanged()?; @@ -226,7 +352,7 @@ mod tests { ), cpi_coverage: CpiCoverage::NotRecorded, }, - primary_signature: None, + primary_signature: Some([5; 64]), required_signers: Vec::new(), instructions: Vec::new(), token_balance_coverage: TokenBalanceCoverage::Complete, @@ -255,6 +381,7 @@ mod tests { block_ordinal: u32, slot: u64, tx_index: u32, + signature: Option, execution_status: &'static str, side: TokenBalanceSide, balance_index: u32, @@ -281,6 +408,9 @@ mod tests { key }; let text = |key: Option<[u8; 32]>| key.map(|key| bs58::encode(key).into_string()); + let signature_text = |signature: Option<[u8; 64]>| { + signature.map(|signature| bs58::encode(signature).into_string()) + }; for source_id in ["source-test", "a\"b\\c\u{1}"] { let mut sink = TokenSink::new(Vec::new(), source_id); let mut expected = Vec::new(); @@ -299,6 +429,12 @@ mod tests { amount: [0, 1, u64::MAX, 123_456_789][index as usize % 4], decimals: [0, 6, 9, u8::MAX][index as usize % 4], }; + let signature = (index % 4 != 0).then(|| { + let mut signature = [0u8; 64]; + signature[..32].copy_from_slice(&key(index)); + signature[32..].copy_from_slice(&key(index + 7)); + signature + }); let (status, status_text) = if index % 3 == 0 { (&b"failed"[..], "failed") } else { @@ -318,6 +454,7 @@ mod tests { block_ordinal: ordinal, slot, tx_index, + signature: signature_text(signature), execution_status: status_text, side: balance.side, balance_index: balance.balance_index, @@ -331,8 +468,16 @@ mod tests { ) .unwrap(); expected.push(b'\n'); - sink.row(epoch, ordinal, slot, tx_index, status, &balance) - .unwrap(); + sink.row( + epoch, + ordinal, + slot, + tx_index, + signature.as_ref(), + status, + &balance, + ) + .unwrap(); } assert_eq!( String::from_utf8(sink.output).unwrap(), @@ -361,6 +506,7 @@ mod tests { let row: serde_json::Value = serde_json::from_slice(&sink.output).unwrap(); assert_eq!(row["amount"], u64::MAX.to_string()); assert_eq!(row["mint"], serde_json::Value::Null); + assert_eq!(row["signature"], bs58::encode([5; 64]).into_string()); assert_eq!(row["execution_status"], "failed"); assert_eq!(row["balance_index"], 9); assert_eq!(row["account_index"], 4); diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/examples/read_epoch.rs b/crates/compact-v2/blockzilla-compact-v2-reader/examples/read_epoch.rs index 94a7c9ff..8638d467 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/examples/read_epoch.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/examples/read_epoch.rs @@ -1,8 +1,10 @@ -//! Read blocks from the public Blockzilla archive through Cloudflare. +//! Read blocks from the public Foundation Compact V2 archive. //! //! Run from the workspace root: //! cargo run --locked -p blockzilla-compact-v2-reader --features http \ //! --example read_epoch -- +//! +//! The default epoch is 200. Its directory is on the public Foundation bucket. use std::{error::Error, num::NonZeroU32}; @@ -11,7 +13,8 @@ use blockzilla_compact_v2_reader::archive::{ }; use solana_signature::Signature; -const ARCHIVE: &str = "https://blockzilla-archive-samples-v1.cheron-augustin.workers.dev"; +const ARCHIVE_BASE: &str = + "https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004"; fn main() -> Result<(), Box> { let mut args = std::env::args().skip(1); @@ -21,7 +24,8 @@ fn main() -> Result<(), Box> { // START read-epoch let cache = std::env::current_dir()?.join(".blockzilla-cache"); - let mut archive = CompactV2Archive::open(ARCHIVE, epoch, cache)?; + let epoch_url = format!("{ARCHIVE_BASE}/epoch-{epoch}"); + let mut archive = CompactV2Archive::open_epoch_url(&epoch_url, epoch, &cache)?; let range = archive.bounded_range(0, max_blocks)?; let request = ScanRequest::bounded(range); diff --git a/examples/Cargo.toml b/examples/Cargo.toml index fd9c0e81..60a30d82 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -6,25 +6,18 @@ rust-version.workspace = true license.workspace = true publish = false autobins = false + [dependencies] anyhow = "1.0.104" -# `CompactV2Archive` (local and HTTPS epochs) is behind the reader's `http` feature. -blockzilla-compact-v2-reader = { path = "../crates/compact-v2/blockzilla-compact-v2-reader", features = ["http"] } -blockzilla-model = { path = "../crates/blockzilla-model" } -bs58 = "0.5.1" -clap = { version = "4.6.6", features = ["derive"] } -# Allocation-free base58 and integer text for the row writers. -five8 = "1.0.0" -itoa = "1.0.18" -serde_json = "1.0.151" -[[bin]] -name = "token-dump" -path = "token-dump.rs" +blockzilla = { path = "../blockzilla/cli" } + [[bin]] name = "wallet-dump" path = "wallet-dump.rs" + [[bin]] name = "program-dump" path = "program-dump.rs" + [lints] workspace = true diff --git a/examples/README.md b/examples/README.md index a92803e6..ab939cd7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,18 +1,28 @@ # Small archive examples -Run one example with a local Compact V2 epoch directory, `--epoch`, and an -immutable `--source-id`. `--key` selects a mint, required signer, or program. -For example: +`wallet-dump` and `program-dump` read the same archive. +Token balances use `blockzilla token-dump`. +Omit `--archive-url` on these two commands to read the public Foundation directory for +the selected epoch. Epoch 1094 is +`https://pub-97348740d6ef467aa2f1b4b62daa98dc.r2.dev/compact-v2/blockzilla-20261004/epoch-1094`. +The cache defaults to `.blockzilla-cache` in the current directory. +`--key` selects a required signer or a program. ```sh -cargo run --release -p blockzilla-dump-examples --bin wallet-dump -- /data/epoch-900 --epoch 900 --source-id my-generation --key WALLET +blockzilla wallet-dump --epoch 1094 --key WALLET +blockzilla program-dump --epoch 1094 --key PROGRAM ``` -To stream an epoch over HTTPS instead, give `--url` with the epoch directory -and a private `--cache-dir` for the index and key registry: +The same arguments work through the example binary: ```sh -cargo run --release -p blockzilla-dump-examples --bin token-dump -- --url https://archive.example/compact-v2/build/epoch-200 --epoch 200 --cache-dir /var/cache/blockzilla +cargo run --release -p blockzilla-dump-examples --bin wallet-dump -- --epoch 1094 --key WALLET +``` + +A local epoch directory uses a path instead of `--archive-url`: + +```sh +blockzilla wallet-dump /data/epoch-900 --epoch 900 --source-id my-generation --key WALLET ``` For a private S3-compatible bucket, such as Cloudflare R2 through its S3 API, @@ -22,20 +32,16 @@ signs each request with SigV4 and reads the credentials from `AWS_SESSION_TOKEN`. It never prints them: ```sh -cargo run --release -p blockzilla-dump-examples --bin token-dump -- --url https://ACCOUNT.r2.cloudflarestorage.com/BUCKET/PREFIX/epoch-200 --s3-region auto --epoch 200 --cache-dir /var/cache/blockzilla +blockzilla wallet-dump --archive-url https://ACCOUNT.r2.cloudflarestorage.com/BUCKET/PREFIX/epoch-200 --s3-region auto --epoch 200 --cache-dir /var/cache/blockzilla --key WALLET ``` `wallet-dump` reports transactions signed by the selected wallet. It does not claim all transactions that affect the wallet. `program-dump` includes recorded -outer and inner calls and requires complete CPI coverage. `token-dump` reports -recorded balance rows; it does not claim a complete current account snapshot. +outer and inner calls and requires complete CPI coverage. These are archive examples. The live plus archive backfill acceptance case remains a separate target; these commands do not implement it yet. -Token rows with unavailable mint identity remain visible as null, even when a -mint filter is selected. They are not treated as confirmed non-matches. - ## Speed options - `--first-block N` and `--max-blocks N` select a block-row range. To resume @@ -55,8 +61,6 @@ mint filter is selected. They are not treated as confirmed non-matches. Output is written with one call per block and is flushed after each block. Each dump asks the reader only for the facts it prints: -- `token-dump` reads no signatures and no signers - (`ScanRequest::token_balances_only`). - `wallet-dump` selects one signer (`with_required_signer`), so other signer keys are not resolved. - `program-dump` reads program identities without instruction data or diff --git a/examples/program-dump.rs b/examples/program-dump.rs index 07745125..c658a144 100644 --- a/examples/program-dump.rs +++ b/examples/program-dump.rs @@ -1,3 +1,3 @@ fn main() -> anyhow::Result<()> { - blockzilla_dump_examples::run(blockzilla_dump_examples::Kind::Program) + blockzilla::archive_dump::run(blockzilla::archive_dump::Kind::Program) } diff --git a/examples/token-dump.rs b/examples/token-dump.rs deleted file mode 100644 index d09e530a..00000000 --- a/examples/token-dump.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() -> anyhow::Result<()> { - blockzilla_dump_examples::run(blockzilla_dump_examples::Kind::Token) -} diff --git a/examples/wallet-dump.rs b/examples/wallet-dump.rs index 291c7bb5..39ddd5a6 100644 --- a/examples/wallet-dump.rs +++ b/examples/wallet-dump.rs @@ -1,3 +1,3 @@ fn main() -> anyhow::Result<()> { - blockzilla_dump_examples::run(blockzilla_dump_examples::Kind::Wallet) + blockzilla::archive_dump::run(blockzilla::archive_dump::Kind::Wallet) } diff --git a/zillastream/README.md b/zillastream/README.md index 7a65cff8..09ce8888 100644 --- a/zillastream/README.md +++ b/zillastream/README.md @@ -30,7 +30,7 @@ Live source identity and control events remain distinct from finalized archive identity. Backfill must not invent processed events or expired native cursors. Missing coverage stops with an explicit gap. The acceptance criteria are in the [first stable release requirements](../RELEASE.md#first-stable-release). -The existing archive-only `dump-tokens` command does not implement this target +The existing archive-only `token-dump` command does not implement this target yet. The full Agave fork, patch code and Agave regression tests stay in the fork