Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion blockzilla/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ blockzilla-program-logs = { path = "../../crates/parser/blockzilla-program-logs"
blockzilla-registry = { path = "../../crates/compact-v2/blockzilla-registry", default-features = false, version = "0.2.0" }
anyhow = "1.0.104"
bincode = "1.3.3"
bs58 = "0.5.1"
# Allocation-free base58 and integer text for the token dump rows.
five8 = "1.0.0"
itoa = "1.0.18"
Expand All @@ -58,6 +57,7 @@ wincode = { version = "=0.6.1", features = ["derive"] }
zstd = "0.14.0"

[dev-dependencies]
bs58 = "0.5.1"
tempfile = "3.27.0"

[lints]
Expand Down
5 changes: 1 addition & 4 deletions blockzilla/cli/src/archive_v2/direct_agave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,7 @@ fn validate(r: &Receipt) -> Result<()> {
"unsupported Agave source revision"
);
for value in [&r.genesis_hash, &r.node_identity] {
ensure!(
bs58::decode(value).into_vec()?.len() == 32,
"invalid source identity"
);
five8::decode_32(value, &mut [0; 32]).context("invalid source identity")?;
}
ensure!(
(1..=4096).contains(&r.blocks.len()) && r.start_slot < r.end_slot_exclusive,
Expand Down
16 changes: 11 additions & 5 deletions blockzilla/cli/src/dump_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ pub(crate) struct DumpTokensArgs {
}

fn parse_mint(value: &str) -> Result<[u8; 32], String> {
bs58::decode(value)
.into_vec()
.map_err(|error| format!("Invalid base58 mint: {error}"))?
.try_into()
.map_err(|_| "A mint must decode to exactly 32 bytes".into())
let mut mint = [0; 32];
five8::decode_32(value, &mut mint).map_err(|error| match error {
five8::DecodeError::InvalidChar(_) => format!("Invalid base58 mint: {error}"),
_ => "A mint must decode to exactly 32 bytes".into(),
})?;
Ok(mint)
}

/// Output buffer for standard output. The sink flushes once per accepted
Expand Down Expand Up @@ -391,6 +392,11 @@ mod tests {
fn mint_parser_requires_exact_public_key_length() {
assert!(parse_mint("bad!").is_err());
assert!(parse_mint("1").is_err());
assert!(parse_mint(&"1".repeat(33)).is_err());
assert_eq!(
parse_mint(&bs58::encode([255; 32]).into_string()).unwrap(),
[255; 32]
);
assert_eq!(
parse_mint("11111111111111111111111111111111").unwrap(),
[0; 32]
Expand Down
44 changes: 18 additions & 26 deletions blockzilla/get-block/src/transaction_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,10 @@ pub fn encode_transaction(
let mut output = Vec::new();
push_short_len(&mut output, signatures.len())?;
for signature in signatures {
append_base58(&mut output, signature, 64)?;
let text = signature.as_str().ok_or_else(invalid_base58)?;
let mut bytes = [0; 64];
five8::decode_64(text, &mut bytes).map_err(|_| invalid_base58())?;
output.extend_from_slice(&bytes);
}
if version.as_u64() == Some(0) {
output.push(0x80);
Expand Down Expand Up @@ -486,13 +489,11 @@ pub fn encode_transaction(
.ok_or_else(invalid)?;
push_short_len(&mut output, keys.len())?;
for key in keys {
append_base58(&mut output, key, 32)?;
output.extend_from_slice(&decode_base58_key(key)?);
}
append_base58(
&mut output,
output.extend_from_slice(&decode_base58_key(
message.get("recentBlockhash").ok_or_else(invalid)?,
32,
)?;
)?);
let instructions = message
.get("instructions")
.and_then(Value::as_array)
Expand Down Expand Up @@ -528,11 +529,9 @@ pub fn encode_transaction(
.ok_or_else(invalid)?;
push_short_len(&mut output, lookups.len())?;
for lookup in lookups {
append_base58(
&mut output,
output.extend_from_slice(&decode_base58_key(
lookup.get("accountKey").ok_or_else(invalid)?,
32,
)?;
)?);
append_indices(
&mut output,
lookup.get("writableIndexes").ok_or_else(invalid)?,
Expand All @@ -549,22 +548,15 @@ pub fn encode_transaction(
Ok(output)
}

fn append_base58(
output: &mut Vec<u8>,
value: &Value,
length: usize,
) -> Result<(), TransactionRpcError> {
let invalid = || TransactionRpcError::unavailable("archive contains an invalid base58 value");
let value = value
.as_str()
.filter(|value| value.len() <= 88)
.ok_or_else(invalid)?;
let bytes = bs58::decode(value).into_vec().map_err(|_| invalid())?;
if bytes.len() != length {
return Err(invalid());
}
output.extend(bytes);
Ok(())
fn invalid_base58() -> TransactionRpcError {
TransactionRpcError::unavailable("archive contains an invalid base58 value")
}

fn decode_base58_key(value: &Value) -> Result<[u8; 32], TransactionRpcError> {
let text = value.as_str().ok_or_else(invalid_base58)?;
let mut bytes = [0; 32];
five8::decode_32(text, &mut bytes).map_err(|_| invalid_base58())?;
Ok(bytes)
}

fn append_indices(output: &mut Vec<u8>, value: &Value) -> Result<(), TransactionRpcError> {
Expand Down
22 changes: 11 additions & 11 deletions blockzilla/get-block/src/worker/foundation_first/finalized.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ pub(crate) struct LedgerCompactMetadata {
impl LedgerCompactMetadata {
pub(crate) fn hashes(&self) -> std::result::Result<([u8; 32], [u8; 32]), String> {
let hash = |text: &str| -> std::result::Result<[u8; 32], String> {
let bytes: [u8; 32] = bs58::decode(text)
.into_vec()
.map_err(|_| "invalid ledger block hash")?
.try_into()
.map_err(|_| "invalid ledger block hash length")?;
if bytes == [0; 32] || bs58::encode(bytes).into_string() != text {
let mut bytes = [0; 32];
five8::decode_32(text, &mut bytes).map_err(|error| match error {
five8::DecodeError::InvalidChar(_) => "invalid ledger block hash",
_ => "invalid ledger block hash length",
})?;
if bytes == [0; 32] {
return Err("noncanonical ledger block hash".into());
}
Ok(bytes)
Expand Down Expand Up @@ -184,11 +184,11 @@ fn validate_metadata(
expected_source: &RecentSource,
sha: &[u8; 32],
) -> std::result::Result<(), String> {
let expected_hash: [u8; 32] = bs58::decode(&metadata.blockhash)
.into_vec()
.map_err(|_| "invalid finalized blockhash")?
.try_into()
.map_err(|_| "invalid finalized blockhash length")?;
let mut expected_hash = [0; 32];
five8::decode_32(&metadata.blockhash, &mut expected_hash).map_err(|error| match error {
five8::DecodeError::InvalidChar(_) => "invalid finalized blockhash",
_ => "invalid finalized blockhash length",
})?;
metadata.validate(
&RecentRequest {
slot,
Expand Down
13 changes: 5 additions & 8 deletions blockzilla/get-block/src/worker/foundation_first/recent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,14 +451,11 @@ fn cursor_parts(cursor: &str) -> std::result::Result<(&str, u64, &str), String>
}

fn hash(text: &str) -> std::result::Result<[u8; 32], String> {
let bytes: [u8; 32] = bs58::decode(text)
.into_vec()
.map_err(|_| "invalid compact block hash")?
.try_into()
.map_err(|_| "compact block hash must have 32 bytes")?;
if base58_32(&bytes) != text {
return Err("compact block hash is not canonical".into());
}
let mut bytes = [0; 32];
five8::decode_32(text, &mut bytes).map_err(|error| match error {
five8::DecodeError::InvalidChar(_) => "invalid compact block hash",
_ => "compact block hash must have 32 bytes",
})?;
Ok(bytes)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
//! `OrderedBlockPublisher`.

mod indexed_tokens;
mod registry_cache;

use registry_cache::{RegistryPageResolver, SharedRegistryPages};

use std::{
cell::Cell,
Expand Down Expand Up @@ -143,7 +146,8 @@ impl CompactV2RegistryReadPolicy {
pub enum CompactV2ParallelRegistryMode {
/// One complete immutable registry is shared across all workers.
SharedFull,
/// Each used worker has its own bounded eight-chunk LRU cache.
/// Each worker uses a bounded cache. Sources with cheap positional reads
/// also share smaller pages across workers.
SparseWorkerCache,
/// Indexed token output resolves keys through one bounded consumer cache.
SparseConsumerCache,
Expand All @@ -166,9 +170,7 @@ pub struct CompactV2ParallelRegistryReceipt {
pub prefetch_read_calls: u64,
/// Source bytes used by the one-pass complete-registry prefetch.
pub prefetch_read_bytes: u64,
/// Exact shared payload for `SharedFull`; a checked worst-case retained
/// worker-cache payload for `SparseWorkerCache`, or one consumer cache for
/// `SparseConsumerCache`.
/// Maximum retained registry payload across the shared and local caches.
pub resident_bound_bytes: u64,
}

Expand Down Expand Up @@ -696,6 +698,10 @@ impl<S: RangeSource> CompactV2InstructionSource<S> {
let (shared_registry, mut registry_receipt) = self
.parallel_registry_for_scan(start, end, request, requested_transactions, config)
.map_err(source_error)?;
let registry_pages = shared_registry
.is_none()
.then(|| SharedRegistryPages::for_scan(&self.reader, request))
.flatten();
let read_signatures = request.include_primary_signatures;
let mut signature_scan =
ContiguousSignatureScan::new(&self.reader, start..end, read_signatures);
Expand All @@ -718,6 +724,8 @@ impl<S: RangeSource> CompactV2InstructionSource<S> {
|_| {
let mut worker = ParallelProjectionWorker::new(shared_registry.clone());
worker.context.query_keys = Arc::clone(&query_keys);
worker.context.registry_pages =
registry_pages.clone().map(RegistryPageResolver::new);
Ok::<_, CompactV2ParallelScanError>(worker)
},
|worker, _row_number, block| {
Expand Down Expand Up @@ -910,16 +918,20 @@ impl<S: RangeSource> CompactV2InstructionSource<S> {
registry_receipt.mode,
CompactV2ParallelRegistryMode::SparseWorkerCache
) {
registry_receipt.resident_bound_bytes = u64::try_from(pipeline.effective_workers)
.ok()
.and_then(|workers| {
workers.checked_mul(COMPACT_V2_QUERY_REGISTRY_RETAINED_KEY_BYTES as u64)
})
.ok_or_else(|| {
source_error(CompactV2InstructionSourceError::Invalid(
"sparse registry resident bound overflow".into(),
))
})?;
registry_receipt.resident_bound_bytes = if let Some(pages) = registry_pages {
pages.retained_key_bytes(pipeline.effective_workers)
} else {
u64::try_from(pipeline.effective_workers)
.ok()
.and_then(|workers| {
workers.checked_mul(COMPACT_V2_QUERY_REGISTRY_RETAINED_KEY_BYTES as u64)
})
.ok_or_else(|| {
source_error(CompactV2InstructionSourceError::Invalid(
"sparse registry resident bound overflow".into(),
))
})?
};
}

let signature_io = signature_scan.finish().map_err(source_error)?;
Expand Down Expand Up @@ -3255,6 +3267,7 @@ struct ExactContext {
output_pool: blockzilla_model::projection_pool::ProjectionPool,
query_keys: Arc<BoundQueryKeys>,
shared_registry: Option<Arc<SharedRegistry>>,
registry_pages: Option<RegistryPageResolver>,
registry_chunks: HashMap<u32, Vec<[u8; 32]>>,
registry_lru: VecDeque<u32>,
vote_hashes_loaded: bool,
Expand Down Expand Up @@ -3309,6 +3322,7 @@ impl ExactContext {
fn retain_shared_registry(&mut self, registry: Arc<SharedRegistry>) {
self.registry_chunks.clear();
self.registry_lru.clear();
self.registry_pages = None;
self.shared_registry = Some(registry);
}

Expand Down Expand Up @@ -3375,6 +3389,9 @@ impl ExactContext {
))
});
}
if let Some(pages) = &mut self.registry_pages {
return pages.resolve(reader, id, &mut self.io);
}
let zero_based = usize::try_from(id - 1).map_err(|_| {
CompactV2InstructionSourceError::Invalid("registry ID exceeds address space".into())
})?;
Expand Down Expand Up @@ -7852,6 +7869,35 @@ pub(crate) mod tests {
);
}

#[test]
fn parallel_local_projection_shares_registry_reads_and_preserves_output() {
let fixture = indexer_fixture(12);
let local = crate::PinnedLocalRangeSource::new(fixture.directory.path());
let reader = open_trusted_test_reader(local);
let registry_bytes = u64::from(reader.registry_entries()) * REGISTRY_KEY_BYTES as u64;
let mut source = CompactV2InstructionSource::new(reader, FIRST_SLOT).unwrap();
let mut reference =
CompactV2InstructionSource::new(fixture.trusted_reader(), FIRST_SLOT).unwrap();
let request = ScanRequest::token_balances_only().allow_unverified_source();
let config = CompactV2ParallelScanConfig {
max_full_registry_bytes: 0,
..CompactV2ParallelScanConfig::new(4)
};

let (expected, baseline) = plain_scan_bytes(&mut reference, &request, config);
let baseline = baseline.unwrap();
let (output, receipt) = plain_scan_bytes(&mut source, &request, config);
let receipt = receipt.unwrap();
assert_eq!(output, expected);
assert!(
baseline.scan.io.source_read_bytes.unwrap() > fixture.compressed_bytes + registry_bytes
);
assert_eq!(
receipt.scan.io.source_read_bytes,
Some(fixture.compressed_bytes + registry_bytes)
);
}

#[test]
fn parallel_scans_keep_a_loaded_registry_for_later_scans() {
let fixture = indexer_fixture(12);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,19 +225,21 @@ impl<S: RangeSource> CompactV2InstructionSource<S> {
let (shared_registry, mut registry_receipt) = self
.parallel_registry_for_scan(start, end, request, requested_transactions, config)
.map_err(source_error)?;
let mut context = ExactContext::with_shared_registry(shared_registry);
if matches!(
registry_receipt.mode,
CompactV2ParallelRegistryMode::SparseWorkerCache
) {
registry_receipt.mode = CompactV2ParallelRegistryMode::SparseConsumerCache;
registry_receipt.resident_bound_bytes =
COMPACT_V2_QUERY_REGISTRY_RETAINED_KEY_BYTES as u64;
if let Some(pages) = SharedRegistryPages::for_scan(&self.reader, request) {
registry_receipt.resident_bound_bytes = pages.retained_key_bytes(1);
context.registry_pages = Some(RegistryPageResolver::new(pages));
}
}
let reader = &self.reader;
let mut resolver = ConsumerResolver {
reader,
context: ExactContext::with_shared_registry(shared_registry),
};
let mut resolver = ConsumerResolver { reader, context };
let projected_bytes_current = AtomicU64::new(0);
let max_projected_block_bytes = AtomicU64::new(0);
let max_projected_batch_bytes = AtomicU64::new(0);
Expand Down
Loading