diff --git a/Cargo.lock b/Cargo.lock index 7a97a63..990be9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3289,7 +3289,7 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "e3-bfv-client" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "anyhow", "e3-fhe-params", @@ -3338,7 +3338,7 @@ dependencies = [ [[package]] name = "e3-ciphernode-config" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy-primitives", "anyhow", @@ -3353,7 +3353,7 @@ dependencies = [ [[package]] name = "e3-committee" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "anyhow", "serde", @@ -3362,7 +3362,7 @@ dependencies = [ [[package]] name = "e3-committee-hash" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy", "hex", @@ -3372,7 +3372,7 @@ dependencies = [ [[package]] name = "e3-crypto" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "aes-gcm", "anyhow", @@ -3391,7 +3391,7 @@ dependencies = [ [[package]] name = "e3-data-availability" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -3417,7 +3417,7 @@ dependencies = [ [[package]] name = "e3-entrypoint" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "actix-web", "anyhow", @@ -3436,7 +3436,7 @@ dependencies = [ [[package]] name = "e3-evm" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy", "anyhow", @@ -3455,7 +3455,7 @@ dependencies = [ [[package]] name = "e3-evm-config" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy-primitives", "anyhow", @@ -3466,7 +3466,7 @@ dependencies = [ [[package]] name = "e3-evm-contracts" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy-contract", "alloy-json-abi", @@ -3477,7 +3477,7 @@ dependencies = [ [[package]] name = "e3-evm-transactions" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy", ] @@ -3485,7 +3485,7 @@ dependencies = [ [[package]] name = "e3-fhe-params" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -3588,13 +3588,14 @@ version = "0.20.0-dev.3" dependencies = [ "alloy-primitives", "alloy-signer", + "async-trait", + "bincode", "e3-blobs", "e3-protocol", "e3-utils", "futures", "libp2p", "serde", - "serde_bytes", "sha2 0.10.9", "tempfile", "thiserror 1.0.69", @@ -3605,7 +3606,7 @@ dependencies = [ [[package]] name = "e3-polynomial" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "num-bigint 0.5.1", "num-integer", @@ -3617,7 +3618,7 @@ dependencies = [ [[package]] name = "e3-polynomial-fhe" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "e3-polynomial", "fhe-math", @@ -3642,7 +3643,7 @@ dependencies = [ [[package]] name = "e3-safe" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "ark-bn254 0.5.0", "ark-ff 0.5.0", @@ -3669,7 +3670,7 @@ dependencies = [ [[package]] name = "e3-trbfv" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "anyhow", "bincode", @@ -3693,7 +3694,7 @@ dependencies = [ [[package]] name = "e3-utils" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "anyhow", "bincode", @@ -3709,7 +3710,7 @@ dependencies = [ [[package]] name = "e3-utils-derive" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "hex", "proc-macro2", @@ -3720,7 +3721,7 @@ dependencies = [ [[package]] name = "e3-zk-config" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "ark-bn254 0.5.0", "ark-ff 0.5.0", @@ -3739,7 +3740,7 @@ dependencies = [ [[package]] name = "e3-zk-prover" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "acir", "alloy", @@ -3785,7 +3786,7 @@ dependencies = [ [[package]] name = "e3-zk-witness" version = "0.20.0-dev.3" -source = "git+https://github.com/theinterfold/interfold?rev=31cd408ea5131de7e700ae3438aecea9000b45bf#31cd408ea5131de7e700ae3438aecea9000b45bf" +source = "git+https://github.com/theinterfold/interfold?rev=caae224b1296e329c2857b46056ed2a1214fff78#caae224b1296e329c2857b46056ed2a1214fff78" dependencies = [ "anyhow", "ark-bn254 0.5.0", diff --git a/Cargo.toml b/Cargo.toml index bdac70f..362a1dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,24 +29,24 @@ e3-jobs = { version = "0.20.0-dev.3", path = "./crates/ciphernode/jobs" } e3-journal = { version = "0.20.0-dev.3", path = "./crates/state/journal" } e3-p2p = { version = "0.20.0-dev.3", path = "./crates/ciphernode/p2p" } # Shared crates, pinned to one commit of theinterfold/interfold. Bump `rev` on every line together. -e3-bfv-client = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-ciphernode-config = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-committee = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-committee-hash = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-crypto = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-entrypoint = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-data-availability = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-evm = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-evm-contracts = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-evm-transactions = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-fhe-params = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-polynomial = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-polynomial-fhe = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-trbfv = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-utils = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-zk-config = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-zk-prover = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } -e3-zk-witness = { git = "https://github.com/theinterfold/interfold", rev = "31cd408ea5131de7e700ae3438aecea9000b45bf" } +e3-bfv-client = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-ciphernode-config = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-committee = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-committee-hash = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-crypto = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-entrypoint = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-data-availability = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-evm = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-evm-contracts = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-evm-transactions = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-fhe-params = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-polynomial = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-polynomial-fhe = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-trbfv = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-utils = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-zk-config = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-zk-prover = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } +e3-zk-witness = { git = "https://github.com/theinterfold/interfold", rev = "caae224b1296e329c2857b46056ed2a1214fff78" } # External crates, as in theinterfold/interfold. @@ -74,7 +74,6 @@ rand = "=0.9.5" rand_core = "=0.9.5" rayon = "=1.10.0" serde = { version = "=1.0.228", features = ["derive"] } -serde_bytes = "=0.11.19" serde_json = "=1.0.145" sha2 = "=0.10.9" tempfile = "=3.20.0" diff --git a/crates/ciphernode/chain/src/reader.rs b/crates/ciphernode/chain/src/reader.rs index c3b4508..0fccc6a 100644 --- a/crates/ciphernode/chain/src/reader.rs +++ b/crates/ciphernode/chain/src/reader.rs @@ -13,7 +13,10 @@ use e3_protocol::{ node::{ChainEvent, ChainFact, CommitteeRequest, CommitteeSeed}, UnixSecs, }; -use futures::{stream::BoxStream, StreamExt}; +use futures::{ + stream::{self, BoxStream}, + StreamExt, TryStreamExt, +}; use std::collections::BTreeSet; use std::future::Future; use std::time::Duration; @@ -258,13 +261,35 @@ impl Reader { self.contracts.randomness.extend(providers); self.contracts.slashing.extend(managers); }; - let mut events = Vec::new(); - for decoded in decoded { - match decoded { - Decoded::Fact(event) => events.push(event), - Decoded::Read(read) => events.extend(Self::read(&self.rpc, read, confirmed).await?), + let mut read_items = Vec::new(); + let mut slots: Vec> = Vec::with_capacity(decoded.len()); + for (index, item) in decoded.into_iter().enumerate() { + match item { + Decoded::Fact(event) => slots.push(Some(event)), + Decoded::Read(read) => { + slots.push(None); + read_items.push((index, read)); + } } } + if read_items.len() == 1 { + let (index, read) = read_items.pop().expect("len == 1"); + slots[index] = Self::read(&self.rpc, read, confirmed).await?; + } else if !read_items.is_empty() { + const MAX_CONCURRENT_READS: usize = 8; + let rpc = &self.rpc; + let resolved: Vec<(usize, Option)> = stream::iter(read_items) + .map(|(index, read)| async move { + Ok::<_, RpcError>((index, Self::read(rpc, read, confirmed).await?)) + }) + .buffer_unordered(MAX_CONCURRENT_READS) + .try_collect() + .await?; + for (index, event) in resolved { + slots[index] = event; + } + } + let events: Vec = slots.into_iter().flatten().collect(); self.next = to + 1; Ok(events) } @@ -388,12 +413,15 @@ impl Reader { attestation, owner_cap, } => { - let sortition = answer(rpc.sortition(e3.number, block)).await?; + let (sortition, dkg_window) = tokio::try_join!( + answer(rpc.sortition(e3.number, block)), + answer(rpc.dkg_window(e3.number, block)), + )?; let request = CommitteeRequest { time, ticket_price: sortition.ticket_price, owner_cap, - dkg_window: answer(rpc.dkg_window(e3.number, block)).await?, + dkg_window, }; let fact = ChainFact::E3Requested { e3, @@ -412,9 +440,13 @@ impl Reader { e3, members, } => { + let (deadlines, window) = tokio::try_join!( + answer(rpc.deadlines(e3.number, block)), + answer(rpc.dkg_window(e3.number, block)), + )?; let dkg = DkgTiming { - deadline: answer(rpc.deadlines(e3.number, block)).await?.dkg, - window: answer(rpc.dkg_window(e3.number, block)).await?, + deadline: deadlines.dkg, + window, finalized_block: at.block, }; (at, time, ChainFact::CommitteeFinalized { e3, members, dkg }) diff --git a/crates/ciphernode/chain/src/rpc.rs b/crates/ciphernode/chain/src/rpc.rs index 35ba665..3edfd94 100644 --- a/crates/ciphernode/chain/src/rpc.rs +++ b/crates/ciphernode/chain/src/rpc.rs @@ -15,18 +15,50 @@ use alloy_primitives::{Address, B256, U256}; use e3_evm::log_window::is_range_limit_error; use e3_evm_contracts::{IBondingRegistry, ICiphernodeRegistry, IInterfold}; use e3_protocol::{node::LogPosition, UnixSecs}; -use futures::{future::try_join_all, ready, stream::BoxStream, Stream, StreamExt}; +use futures::{ + ready, + stream::{self, BoxStream}, + Stream, StreamExt, TryStreamExt, +}; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, pin::Pin, + sync::{Arc, Mutex, PoisonError}, task::{Context, Poll}, }; +const MAX_CACHED_BLOCK_TIMES: usize = 4_096; +const MAX_CONCURRENT_RPC: usize = 16; + +#[derive(Default)] +struct BlockTimeCache { + times: HashMap, + order: VecDeque, +} + +impl BlockTimeCache { + fn get(&self, block: u64) -> Option { + self.times.get(&block).copied() + } + + fn insert(&mut self, block: u64, time: UnixSecs) { + if self.times.insert(block, time).is_none() { + self.order.push_back(block); + } + while self.order.len() > MAX_CACHED_BLOCK_TIMES { + if let Some(oldest) = self.order.pop_front() { + self.times.remove(&oldest); + } + } + } +} + /// A chain node over JSON-RPC. #[derive(Clone)] pub struct ChainNode

{ provider: P, contracts: Contracts, + timestamps: Arc>, } impl

ChainNode

{ @@ -34,6 +66,7 @@ impl

ChainNode

{ Self { provider, contracts, + timestamps: Arc::new(Mutex::new(BlockTimeCache::default())), } } } @@ -85,7 +118,57 @@ impl Rpc for ChainNode

{ false => LogsError::Failed(error), } })?; + let mut times: BTreeMap = BTreeMap::new(); + let mut missing: BTreeSet = BTreeSet::new(); + { + let cache = self + .timestamps + .lock() + .unwrap_or_else(PoisonError::into_inner); + for log in &logs { + let (Some(block), Some(_), Some(_)) = + (log.block_number, log.log_index, log.transaction_hash) + else { + return Err(RpcError("a log without its block position".into()).into()); + }; + if let Some(time) = log.block_timestamp { + times.insert(block, time); + } else if let Some(time) = cache.get(block) { + times.insert(block, time); + } else if !times.contains_key(&block) { + missing.insert(block); + } + } + } + + if !missing.is_empty() { + let fetched: Vec<(u64, UnixSecs)> = + stream::iter(missing) + .map(|block| async move { + Ok::<_, RpcError>((block, self.block_time(block).await?)) + }) + .buffer_unordered(MAX_CONCURRENT_RPC) + .try_collect() + .await?; + let mut cache = self + .timestamps + .lock() + .unwrap_or_else(PoisonError::into_inner); + for (block, time) in fetched { + cache.insert(block, time); + times.insert(block, time); + } + } else if !times.is_empty() { + let mut cache = self + .timestamps + .lock() + .unwrap_or_else(PoisonError::into_inner); + for (&block, &time) in × { + cache.insert(block, time); + } + } + let mut raw = Vec::with_capacity(logs.len()); for log in logs { let (Some(block), Some(log_index), Some(transaction)) = @@ -93,11 +176,10 @@ impl Rpc for ChainNode

{ else { return Err(RpcError("a log without its block position".into()).into()); }; - let time = match log.block_timestamp.or_else(|| times.get(&block).copied()) { - Some(time) => time, - None => self.block_time(block).await?, - }; - times.insert(block, time); + let time = log + .block_timestamp + .or_else(|| times.get(&block).copied()) + .ok_or_else(|| RpcError(format!("missing timestamp for block {block}").into()))?; raw.push(RawLog { address: log.address(), topics: log.topics().to_vec(), @@ -118,18 +200,12 @@ impl Rpc for ChainNode

{ async fn sortition(&self, e3: U256, block: u64) -> Result { let registry = ICiphernodeRegistry::new(self.contracts.registry, &self.provider); let at = BlockId::number(block); - let request = registry - .getSortitionRequest(e3) - .block(at) - .call() - .await - .map_err(RpcError::new)?; - let seed = registry - .sortitionSeed(e3) - .block(at) - .call() - .await - .map_err(RpcError::new)?; + let req_call = registry.getSortitionRequest(e3).block(at); + let seed_call = registry.sortitionSeed(e3).block(at); + let (request, seed) = tokio::try_join!( + async { req_call.call().await.map_err(RpcError::new) }, + async { seed_call.call().await.map_err(RpcError::new) }, + )?; Ok(Sortition { ticket_price: request.ticketPrice, committee_deadline: secs(request.committeeDeadline), @@ -177,11 +253,19 @@ impl Rpc for ChainNode

{ at: UnixSecs, ) -> Result, RpcError> { let bonding = IBondingRegistry::new(self.contracts.bonding, &self.provider); - let reads = operators.iter().map(|operator| { - let read = bonding.eligibilityAt(*operator, U256::from(at)); - async move { read.call().await.map(|answer| (*operator, answer.active)) } - }); - let answers = try_join_all(reads).await.map_err(RpcError::new)?; + let reads: Vec<_> = operators + .iter() + .copied() + .map(|operator| { + let read = bonding.eligibilityAt(operator, U256::from(at)); + async move { read.call().await.map(|answer| (operator, answer.active)) } + }) + .collect(); + let answers: Vec<(Address, bool)> = stream::iter(reads) + .buffer_unordered(MAX_CONCURRENT_RPC) + .try_collect() + .await + .map_err(RpcError::new)?; Ok(answers .into_iter() .filter_map(|(operator, active)| active.then_some(operator)) diff --git a/crates/ciphernode/chain/src/wallet.rs b/crates/ciphernode/chain/src/wallet.rs index 0c81240..efe33e1 100644 --- a/crates/ciphernode/chain/src/wallet.rs +++ b/crates/ciphernode/chain/src/wallet.rs @@ -97,13 +97,19 @@ impl Unmined { Some((*nonce, *pending)) } + #[cfg(test)] fn insert(&mut self, nonce: u64, pending: Pending) -> io::Result<()> { self.sends.insert(nonce, pending); self.save() } + async fn insert_async(&mut self, nonce: u64, pending: Pending) -> io::Result<()> { + self.sends.insert(nonce, pending); + self.save_async().await + } + /// Forgets the send at `nonce` if it still carries `call`. - fn landed(&mut self, nonce: u64, call: &B256) -> io::Result<()> { + async fn landed_async(&mut self, nonce: u64, call: &B256) -> io::Result<()> { match self .sends .get(&nonce) @@ -111,13 +117,14 @@ impl Unmined { { true => { self.sends.remove(&nonce); - self.save() + self.save_async().await } false => Ok(()), } } /// Forgets the sends whose nonces the chain used, `mined` being the account's mined count. + #[cfg(test)] fn forget_mined(&mut self, mined: u64) -> io::Result<()> { let before = self.sends.len(); self.sends.retain(|nonce, _| *nonce >= mined); @@ -127,17 +134,40 @@ impl Unmined { } } - fn save(&self) -> io::Result<()> { - let partial = self.path.with_extension("partial"); - let mut file = fs::File::create(&partial)?; - file.write_all(&serde_json::to_vec(&self.sends)?)?; - file.sync_all()?; - fs::rename(&partial, &self.path)?; - match self.path.parent().filter(|dir| !dir.as_os_str().is_empty()) { - Some(dir) => fs::File::open(dir)?.sync_all(), - None => Ok(()), + async fn forget_mined_async(&mut self, mined: u64) -> io::Result<()> { + let before = self.sends.len(); + self.sends.retain(|nonce, _| *nonce >= mined); + match self.sends.len() == before { + true => Ok(()), + false => self.save_async().await, } } + + #[cfg(test)] + fn save(&self) -> io::Result<()> { + let bytes = serde_json::to_vec(&self.sends)?; + write_atomic(&self.path, &bytes) + } + + async fn save_async(&self) -> io::Result<()> { + let bytes = serde_json::to_vec(&self.sends)?; + let path = self.path.clone(); + tokio::task::spawn_blocking(move || write_atomic(&path, &bytes)) + .await + .map_err(|e| io::Error::other(e.to_string()))? + } +} + +fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> { + let partial = path.with_extension("partial"); + let mut file = fs::File::create(&partial)?; + file.write_all(bytes)?; + file.sync_data()?; + fs::rename(&partial, path)?; + match path.parent().filter(|dir| !dir.as_os_str().is_empty()) { + Some(dir) => fs::File::open(dir)?.sync_all(), + None => Ok(()), + } } mod fees { @@ -300,7 +330,8 @@ impl Wallet

{ // Kept before the broadcast, as for any send. nonces .unmined - .insert(nonce, pending) + .insert_async(nonce, pending) + .await .map_err(RpcError::new)?; match self .provider @@ -334,13 +365,24 @@ fn revert_of(error: TransportFailure) -> Result Account for Wallet

{ async fn estimate(&self, call: &Call) -> Result { + let request = self.request(call); + if self.confirmations == 0 { + return match self + .provider + .estimate_gas(request) + .block(BlockId::latest()) + .await + { + Ok(gas) => Ok(Estimate::Gas(gas)), + Err(error) => Ok(Estimate::Reverts(revert_of(error)?)), + }; + } let head = self .provider .get_block_number() .await .map_err(RpcError::new)?; let confirmed = BlockId::number(head.saturating_sub(self.confirmations)); - let request = self.request(call); if let Err(error) = self.provider.call(request.clone()).block(confirmed).await { return Ok(Estimate::Reverts(revert_of(error)?)); } @@ -388,6 +430,62 @@ impl Account for Wallet

{ }) } + async fn key_chunks( + &self, + first: &KeyChunk, + count: u16, + ) -> Option, RpcError>> { + let result = async { + let head = self + .provider + .get_block_number() + .await + .map_err(RpcError::new)?; + let filter = Filter::new() + .address(first.registry) + .event_signature(CommitteePublicKeyChunkPublished::SIGNATURE_HASH) + .topic1(B256::from(first.e3)) + .topic2(self.provider.default_signer_address().into_word()) + .topic3(first.candidate) + .from_block(first.since) + .to_block(head); + let logs = self + .provider + .get_logs(&filter) + .await + .map_err(RpcError::new)?; + let mut oldest: HashMap = HashMap::new(); + for log in &logs { + let Ok(event) = log.log_decode::() else { + continue; + }; + let index = event.inner.data.chunkIndex; + let Some(block) = log.block_number else { + continue; + }; + if index < count { + oldest + .entry(index) + .and_modify(|prev| *prev = (*prev).min(block)) + .or_insert(block); + } + } + let confirmed_head = head.saturating_sub(self.confirmations); + let mut map = HashMap::with_capacity(usize::from(count)); + for index in 0..count { + let state = match oldest.get(&index).copied() { + None => OnChain::Absent, + Some(block) if block <= confirmed_head => OnChain::Confirmed, + Some(_) => OnChain::Unconfirmed, + }; + map.insert(index, state); + } + Ok(map) + } + .await; + Some(result) + } + /// Fees are estimated before the nonce is chosen, so the turn only signs and broadcasts. An /// RPC node's pending count can miss a transaction that another node behind the same endpoint /// accepted a moment ago, so a new nonce also skips the ones this process sent recently. The @@ -409,7 +507,11 @@ impl Account for Wallet

{ .latest() .await .map_err(RpcError::new)?; - nonces.unmined.forget_mined(mined).map_err(RpcError::new)?; + nonces + .unmined + .forget_mined_async(mined) + .await + .map_err(RpcError::new)?; let replaced = nonces.unmined.of(&key); let send = match replaced { Some((nonce, earlier)) => replacement( @@ -447,7 +549,8 @@ impl Account for Wallet

{ // this process can stop before the answer. nonces .unmined - .insert(send.nonce, unmined) + .insert_async(send.nonce, unmined) + .await .map_err(RpcError::new)?; let request = self .request(call) @@ -464,7 +567,8 @@ impl Account for Wallet

{ nonces.sent.remove(&send.nonce); nonces .unmined - .landed(send.nonce, &key) + .landed_async(send.nonce, &key) + .await .map_err(RpcError::new)?; } return Err(RpcError::new(error)); @@ -478,7 +582,11 @@ impl Account for Wallet

{ .await .map_err(RpcError::new)?; let mut nonces = self.nonces.lock().await; - nonces.unmined.landed(nonce, &key).map_err(RpcError::new)?; + nonces + .unmined + .landed_async(nonce, &key) + .await + .map_err(RpcError::new)?; Ok(receipt.status()) } @@ -499,7 +607,11 @@ impl Account for Wallet

{ .latest() .await .map_err(RpcError::new)?; - nonces.unmined.forget_mined(mined).map_err(RpcError::new)?; + nonces + .unmined + .forget_mined_async(mined) + .await + .map_err(RpcError::new)?; let unsent: BTreeSet = nonces .unmined .sends diff --git a/crates/ciphernode/chain/src/writer.rs b/crates/ciphernode/chain/src/writer.rs index bde5870..9bc5aae 100644 --- a/crates/ciphernode/chain/src/writer.rs +++ b/crates/ciphernode/chain/src/writer.rs @@ -21,8 +21,9 @@ use e3_protocol::{ node::{Submission, Transaction}, proof::{verifier_calldata, ZkProof}, }; +use futures::{stream, StreamExt}; use reverts::{Reading, Verdict}; -use std::{fmt::Display, future::Future, iter, time::Duration}; +use std::{collections::HashMap, fmt::Display, future::Future, iter, time::Duration}; use tracing::{debug, info, warn}; /// What the shared bindings do not carry. @@ -129,6 +130,16 @@ pub trait Account { fn key_chunk(&self, chunk: &KeyChunk) -> impl Future> + Send; + /// Optional batch read of chunks `0..count` for `first`'s candidate in a single log scan. + /// Returning `None` falls back to per-chunk [`Account::key_chunk`] calls. + fn key_chunks( + &self, + _first: &KeyChunk, + _count: u16, + ) -> impl Future, RpcError>>> + Send { + async { None } + } + /// Counts `call` as driven, by a sender that still sends it, for as long as the result lives. fn drive(&self, call: &Call) -> impl Send + '_; @@ -172,13 +183,78 @@ impl Writer { } /// Sends `submission`'s calls in order, each until the chain says it is finished; a call the - /// chain can no longer take ends the submission. The node stops the calls of an E3 it no longer - /// owes. + /// chain can no longer take ends the submission. Key chunks are checked in a single log scan + /// and submitted concurrently when the account supports batched chunk reads. The node stops + /// the calls of an E3 it no longer owes. pub async fn submit(&self, submission: &Submission) -> Result<(), WriteError> { let blobs = self.blobs.of(submission.e3); - for step in calls(&self.contracts, &blobs, submission)? { - if deliver(&self.account, &submission.e3, &step).await == Delivered::Obsolete { - break; + let steps = calls(&self.contracts, &blobs, submission)?; + let first_chunk_pos = steps + .iter() + .position(|step| step.chunk.is_some()) + .unwrap_or(steps.len()); + let (ordered, chunk_steps) = steps.split_at(first_chunk_pos); + for step in ordered { + if deliver(&self.account, &submission.e3, step).await == Delivered::Obsolete { + return Ok(()); + } + } + if chunk_steps.is_empty() { + return Ok(()); + } + let first_chunk = chunk_steps[0] + .chunk + .as_ref() + .expect("chunk_steps starts at a chunk"); + let count = u16::try_from(chunk_steps.len()).unwrap_or(u16::MAX); + match self.account.key_chunks(first_chunk, count).await { + Some(batch_result) => { + let statuses = match batch_result { + Ok(map) => Some(map), + Err(error) => { + warn!( + e3 = %submission.e3, %error, + "the chain's chunks could not be read; sending" + ); + None + } + }; + const MAX_CONCURRENT_CHUNKS: usize = 8; + stream::iter(chunk_steps) + .for_each_concurrent(MAX_CONCURRENT_CHUNKS, |step| { + let initial = statuses.as_ref().and_then(|map| { + step.chunk + .as_ref() + .map(|c| map.get(&c.index).copied().unwrap_or(OnChain::Absent)) + }); + async move { + if initial == Some(OnChain::Confirmed) { + if let Some(chunk) = &step.chunk { + info!( + e3 = %submission.e3, call = step.call.label, index = chunk.index, + "nothing to send: the chain has it already" + ); + } + return; + } + let skip_first_chunk_read = initial == Some(OnChain::Absent); + let _ = deliver_with_hint( + &self.account, + &submission.e3, + step, + skip_first_chunk_read, + ) + .await; + } + }) + .await; + } + None => { + for step in chunk_steps { + if deliver(&self.account, &submission.e3, step).await == Delivered::Obsolete { + break; + } + } } } Ok(()) @@ -224,16 +300,26 @@ pub async fn acknowledge(account: &A, call: &Call) -> bool { /// `of` names what the call is for, in logs. async fn deliver(account: &A, of: &(dyn Display + Sync), step: &Step) -> Delivered { + deliver_with_hint(account, of, step, false).await +} + +async fn deliver_with_hint( + account: &A, + of: &(dyn Display + Sync), + step: &Step, + mut skip_chunk_read: bool, +) -> Delivered { let (label, mut wait) = (step.call.label, FIRST_RETRY); // Driven through the waits between attempts too, so the account frees no nonce of a call that // still goes out. let _driving = account.drive(&step.call); loop { - match attempt(account, of, step).await { + match attempt(account, of, step, skip_chunk_read).await { Ok(Some(delivered)) => return delivered, Ok(None) => {} Err(error) => warn!(%of, call = label, %error, "the attempt failed"), } + skip_chunk_read = false; tokio::time::sleep(wait).await; wait = (wait * 2).min(LONGEST_RETRY); } @@ -244,24 +330,27 @@ async fn attempt( account: &A, of: &(dyn Display + Sync), step: &Step, + skip_chunk_read: bool, ) -> Result, RpcError> { let call = &step.call; - if let Some(chunk) = &step.chunk { - match account.key_chunk(chunk).await { - Ok(OnChain::Confirmed) => { - info!( - %of, call = call.label, index = chunk.index, - "nothing to send: the chain has it already" - ); - return Ok(Some(Delivered::Done)); + if !skip_chunk_read { + if let Some(chunk) = &step.chunk { + match account.key_chunk(chunk).await { + Ok(OnChain::Confirmed) => { + info!( + %of, call = call.label, index = chunk.index, + "nothing to send: the chain has it already" + ); + return Ok(Some(Delivered::Done)); + } + Ok(OnChain::Unconfirmed) => return Ok(None), + Ok(OnChain::Absent) => {} + // Finding out must not hold up the key: a repeated chunk costs only gas. + Err(error) => warn!( + %of, call = call.label, %error, + "the chain's chunks could not be read; sending" + ), } - Ok(OnChain::Unconfirmed) => return Ok(None), - Ok(OnChain::Absent) => {} - // Finding out must not hold up the key: a repeated chunk costs only gas. - Err(error) => warn!( - %of, call = call.label, %error, - "the chain's chunks could not be read; sending" - ), } } let gas = match account.estimate(call).await? { diff --git a/crates/ciphernode/engine/src/lib.rs b/crates/ciphernode/engine/src/lib.rs index 53da8a6..4ea0562 100644 --- a/crates/ciphernode/engine/src/lib.rs +++ b/crates/ciphernode/engine/src/lib.rs @@ -40,6 +40,27 @@ pub struct Step { pub answers: Option, } +/// One operation inside [`Engine::apply_batch`]. +pub enum BatchOp { + /// Step the machine with `input`, optionally answering a prior effect in the same commit. + Step { + now: UnixSecs, + input: I, + answers: Option, + }, + /// Acknowledge a previously emitted durable effect without stepping the machine. + Ack(EffectKey), +} + +/// A batch of steps, acknowledgments, and optional final snapshot committed in one transaction. +#[derive(Default)] +pub struct BatchCommit { + pub steps: Vec, + pub acks: Vec, + /// When present, captures the state after step `seq` (typically the final step in `steps`). + pub snapshot: Option<(u64, Vec)>, +} + /// What a store holds when the engine opens it. #[derive(Clone, Debug, Default)] pub struct Stored { @@ -57,6 +78,19 @@ pub trait Store { fn acknowledge(&mut self, key: EffectKey) -> Result<(), StoreError>; /// Keeps `snapshot` as the state after step `seq`, the last one committed. fn checkpoint(&mut self, seq: u64, snapshot: Vec) -> Result<(), StoreError>; + /// Commits a batch of steps and acknowledgments atomically (one transaction / one fsync). + fn commit_batch(&mut self, batch: BatchCommit) -> Result<(), StoreError> { + for step in batch.steps { + self.commit(step)?; + } + for key in batch.acks { + self.acknowledge(key)?; + } + if let Some((seq, snapshot)) = batch.snapshot { + self.checkpoint(seq, snapshot)?; + } + Ok(()) + } } #[derive(Debug, thiserror::Error)] @@ -177,6 +211,76 @@ impl Engine { self.step(now, input, Some(key)) } + /// Apply a batch of steps and acknowledgments in a single durable store commit. + /// + /// On error the engine is consumed because in-memory state may be ahead of the store, matching + /// [`Self::apply`]. + pub fn apply_batch(mut self, ops: I) -> Result, Error> + where + I: IntoIterator>, + { + let mut batch = BatchCommit::default(); + let mut all_pending = Vec::new(); + let mut seq = self.next_seq; + let mut steps_applied = 0u64; + + for op in ops { + match op { + BatchOp::Step { + now, + input, + answers, + } => { + let entry = bincode::serialize(&Entry { now, input: &input })?; + let effects = self.machine.step(now, input); + let mut encoded = Vec::new(); + for (index, effect) in effects.into_iter().enumerate() { + let key = EffectKey { + seq, + index: index as u32, + }; + if M::is_durable_effect(&effect) { + encoded.push((key, bincode::serialize(&effect)?)); + } + all_pending.push(Pending { key, effect }); + } + batch.steps.push(Step { + seq, + entry, + effects: encoded, + snapshot: None, + answers, + }); + seq += 1; + steps_applied += 1; + } + BatchOp::Ack(key) => { + batch.acks.push(key); + } + } + } + + if batch.steps.is_empty() && batch.acks.is_empty() { + return Ok((self, all_pending)); + } + + let snapshot_due = + steps_applied > 0 && self.steps_since_snapshot + steps_applied >= self.snapshot_every; + if snapshot_due { + let last_seq = seq - 1; + batch.snapshot = Some((last_seq, bincode::serialize(&self.machine)?)); + } + + self.store.commit_batch(batch)?; + self.next_seq = seq; + self.steps_since_snapshot = if snapshot_due { + 0 + } else { + self.steps_since_snapshot + steps_applied + }; + Ok((self, all_pending)) + } + fn step( mut self, now: UnixSecs, @@ -199,6 +303,7 @@ impl Engine { .collect(); let encoded = pending .iter() + .filter(|p| M::is_durable_effect(&p.effect)) .map(|p| Ok((p.key, bincode::serialize(&p.effect)?))) .collect::>()?; let snapshot_due = self.steps_since_snapshot + 1 >= self.snapshot_every; @@ -436,4 +541,36 @@ mod tests { assert_eq!(restarted.machine().total, 1); assert_eq!(pending.len(), 1); } + + #[test] + fn apply_batch_commits_steps_acks_and_snapshot_atomically() { + let store = MemoryStore::default(); + let (engine, _) = Engine::open(store.clone(), Tally::default(), 3).unwrap(); + let (engine, first) = engine.apply(1, TallyInput::Add(1)).unwrap(); + let (engine, batched) = engine + .apply_batch([ + BatchOp::Ack(first[0].key), + BatchOp::Step { + now: 2, + input: TallyInput::Add(2), + answers: None, + }, + BatchOp::Step { + now: 3, + input: TallyInput::Add(3), + answers: None, + }, + ]) + .unwrap(); + assert_eq!(batched.len(), 2); + drop(engine); + + let stored = store.read().unwrap(); + assert_eq!(stored.snapshot.as_ref().map(|(seq, _)| *seq), Some(3)); + assert!(stored.journal.is_empty()); + let (restarted, pending) = Engine::open(store, Tally::default(), 3).unwrap(); + assert_eq!(restarted.machine().total, 6); + let values: Vec = pending.into_iter().map(|p| p.effect).collect(); + assert_eq!(values, vec![3, 6]); + } } diff --git a/crates/ciphernode/engine/src/memory.rs b/crates/ciphernode/engine/src/memory.rs index b6c92b7..6c345fa 100644 --- a/crates/ciphernode/engine/src/memory.rs +++ b/crates/ciphernode/engine/src/memory.rs @@ -4,7 +4,7 @@ // without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. -use crate::{EffectKey, Step, Store, StoreError, Stored}; +use crate::{BatchCommit, EffectKey, Step, Store, StoreError, Stored}; use std::collections::BTreeMap; use std::sync::{Arc, Mutex, MutexGuard}; @@ -67,4 +67,25 @@ impl Store for MemoryStore { self.inner().snapshot = Some((seq, snapshot)); Ok(()) } + + fn commit_batch(&mut self, batch: BatchCommit) -> Result<(), StoreError> { + let mut inner = self.inner(); + for step in batch.steps { + inner.journal.insert(step.seq, step.entry); + inner.outbox.extend(step.effects); + if let Some(key) = step.answers { + inner.outbox.remove(&key); + } + if let Some(snapshot) = step.snapshot { + inner.snapshot = Some((step.seq, snapshot)); + } + } + for key in batch.acks { + inner.outbox.remove(&key); + } + if let Some((seq, snapshot)) = batch.snapshot { + inner.snapshot = Some((seq, snapshot)); + } + Ok(()) + } } diff --git a/crates/ciphernode/jobs/src/accusation.rs b/crates/ciphernode/jobs/src/accusation.rs index 16c6412..a0f1949 100644 --- a/crates/ciphernode/jobs/src/accusation.rs +++ b/crates/ciphernode/jobs/src/accusation.rs @@ -12,7 +12,7 @@ use e3_protocol::{ node::CryptoParams, }; -impl Jobs<'_, B> { +impl Jobs<'_, B, S> { pub(crate) fn run_accusation( &self, params: &CryptoParams, diff --git a/crates/ciphernode/jobs/src/decryption.rs b/crates/ciphernode/jobs/src/decryption.rs index 072c5a8..1f4d9b9 100644 --- a/crates/ciphernode/jobs/src/decryption.rs +++ b/crates/ciphernode/jobs/src/decryption.rs @@ -8,7 +8,9 @@ //! T+1 members' shares (C7), with the current node's library calls. use crate::{ - placeholder, proofs, proofs::Prover, trbfv, Blobs, JobError, Jobs, SealedDecryptionKey, + placeholder, + proofs::{self, Priority, Prover}, + trbfv, Blobs, JobError, Jobs, SealedDecryptionKey, }; use alloy_primitives::{Address, B256, U256}; use e3_bfv_client::compute_ct_commitment_with_params; @@ -36,8 +38,8 @@ use e3_trbfv::{ use e3_utils::utility_types::ArcBytes; use e3_zk_config::{CircuitName, CircuitVariant, MAX_MSG_NON_ZERO_COEFFS, MESSAGE_COEFF_BYTE_LEN}; use e3_zk_prover::{ - prove_decryption_aggregation_jobs, DecryptedSharesAggregationCircuit, DecryptionAggregationJob, - Provable, ThresholdShareDecryptionCircuit, + generate_c6_fold_step, prove_decryption_aggregator_with_c6_fold, + DecryptedSharesAggregationCircuit, Provable, ThresholdShareDecryptionCircuit, }; use e3_zk_witness::{ compute_threshold_decryption_share_commitment, @@ -46,12 +48,64 @@ use e3_zk_witness::{ share_decryption::ShareDecryptionCircuitData, }, }; -use fhe::bfv::Ciphertext; +use fhe::bfv::{BfvParameters, Ciphertext}; use fhe_traits::DeserializeParametrized; -use rayon::prelude::*; -use std::collections::BTreeMap; +use std::{ + collections::{BTreeMap, HashMap, VecDeque}, + sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Mutex, OnceLock, PoisonError, + }, + thread, +}; + +const CT_COMMITMENT_CACHE_CAP: usize = 64; + +#[derive(Default)] +struct CtCommitmentCache { + map: HashMap<(B256, B256), Option>, + order: VecDeque<(B256, B256)>, +} + +impl CtCommitmentCache { + fn get_or_compute( + &mut self, + config: B256, + ciphertext_hash: B256, + ciphertext: &[u8], + threshold: &Arc, + ) -> Option { + let key = (config, ciphertext_hash); + if let Some(&cached) = self.map.get(&key) { + return cached; + } + let value = compute_ct_commitment_with_params(ciphertext, threshold) + .ok() + .map(B256::from); + if self.map.len() >= CT_COMMITMENT_CACHE_CAP { + if let Some(oldest) = self.order.pop_front() { + self.map.remove(&oldest); + } + } + self.map.insert(key, value); + self.order.push_back(key); + value + } +} + +fn cached_ct_commitment( + config: B256, + ciphertext_hash: B256, + ciphertext: &[u8], + threshold: &Arc, +) -> Option { + static CACHE: OnceLock> = OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(CtCommitmentCache::default())); + let mut guard = cache.lock().unwrap_or_else(PoisonError::into_inner); + guard.get_or_compute(config, ciphertext_hash, ciphertext, threshold) +} -impl Jobs<'_, B> { +impl Jobs<'_, B, S> { pub(crate) fn run_decryption( &self, params: &CryptoParams, @@ -101,21 +155,23 @@ impl Jobs<'_, B> { let sensitive = |bytes: &Vec| { SensitiveBytes::new(bytes.clone(), self.cipher).map_err(JobError::crypto) }; - let response = calculate_decryption_share( - self.cipher, - CalculateDecryptionShareRequest { - name: "decryption share".to_owned(), - trbfv_config: trbfv::config(params)?, - ciphertexts: ciphertexts.clone(), - sk_poly_sum: sensitive(&key.sk_poly_sum)?, - es_poly_sum: key - .es_poly_sum - .iter() - .map(sensitive) - .collect::>()?, - }, - ) - .map_err(JobError::crypto)?; + let response = self.check_pool.install(|| { + calculate_decryption_share( + self.cipher, + CalculateDecryptionShareRequest { + name: "decryption share".to_owned(), + trbfv_config: trbfv::config(params)?, + ciphertexts: ciphertexts.clone(), + sk_poly_sum: sensitive(&key.sk_poly_sum)?, + es_poly_sum: key + .es_poly_sum + .iter() + .map(sensitive) + .collect::>()?, + }, + ) + .map_err(JobError::crypto) + })?; let shares: Vec = response .d_share_poly .iter() @@ -165,31 +221,79 @@ impl Jobs<'_, B> { return Err(JobError::crypto("the decryption key has no smudging noise")); } let domain = split_decryption_domain(domain); - ciphertexts - .par_iter() - .zip(shares) - .enumerate() - .map(|(index, (ciphertext, share))| { - // One smudging-noise sum serves every ciphertext. - let noise = &key.es_poly_sum[index % key.es_poly_sum.len()]; - let data = ShareDecryptionCircuitData { - ciphertext: Ciphertext::from_bytes(ciphertext, &threshold) - .map_err(JobError::crypto)?, - s: s.clone(), - e: poly(noise)?, - d_share: poly(share)?, - domain_hi: domain.hi, - domain_lo: domain.lo, - }; - let work = format!("c6-{index}"); - self.prove( - prover, - params, - ThresholdShareDecryptionCircuit, - &config, - &data, - &work, - ) + let prove_one = |index: usize| -> Result { + let ciphertext = &ciphertexts[index]; + let share = &shares[index]; + // One smudging-noise sum serves every ciphertext. + let noise = &key.es_poly_sum[index % key.es_poly_sum.len()]; + let data = ShareDecryptionCircuitData { + ciphertext: Ciphertext::from_bytes(ciphertext, &threshold) + .map_err(JobError::crypto)?, + s: s.clone(), + e: poly(noise)?, + d_share: poly(share)?, + domain_hi: domain.hi, + domain_lo: domain.lo, + }; + let work = format!("c6-{index}"); + self.prove( + prover, + params, + ThresholdShareDecryptionCircuit, + &config, + &data, + &work, + ) + }; + if ciphertexts.len() <= 1 { + return (0..ciphertexts.len()).map(prove_one).collect(); + } + let next = AtomicUsize::new(0); + let failed = AtomicBool::new(false); + let first_err: Mutex> = Mutex::new(None); + let results: Vec>> = + (0..ciphertexts.len()).map(|_| Mutex::new(None)).collect(); + let workers = prover.max_concurrent().min(ciphertexts.len()).max(1); + thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + while !failed.load(Ordering::Acquire) { + let index = next.fetch_add(1, Ordering::Relaxed); + if index >= ciphertexts.len() { + break; + } + match prove_one(index) { + Ok(proof) => { + *results[index] + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(proof); + } + Err(error) => { + failed.store(true, Ordering::Release); + let mut slot = + first_err.lock().unwrap_or_else(PoisonError::into_inner); + if slot.is_none() { + *slot = Some(error); + } + break; + } + } + } + }); + } + }); + if let Some(error) = first_err + .into_inner() + .unwrap_or_else(PoisonError::into_inner) + { + return Err(error); + } + results + .into_iter() + .map(|slot| { + slot.into_inner() + .unwrap_or_else(PoisonError::into_inner) + .ok_or_else(|| JobError::crypto("missing C6 proof")) }) .collect() } @@ -229,11 +333,20 @@ impl Jobs<'_, B> { { return Ok(false); } - for ((share, c6), ciphertext) in - message.shares.iter().zip(&message.c6).zip(&ciphertexts) - { + let threshold = trbfv::threshold_params(params)?; + let ct_commitment = if ciphertexts.len() == 1 { + cached_ct_commitment(params.config, ciphertext.hash, &ciphertexts[0], &threshold) + } else { + None + }; + for ((share, c6), ct) in message.shares.iter().zip(&message.c6).zip(&ciphertexts) { let share = self.blobs.get(share)?; - if !self.c6_binds(params, &c6.proof, ciphertext, &share, domain, anchor)? { + let ct_commit = ct_commitment.or_else(|| { + compute_ct_commitment_with_params(ct, &threshold) + .ok() + .map(B256::from) + }); + if !self.c6_binds(params, &c6.proof, ct_commit, &share, domain, anchor)? { return Ok(false); } } @@ -248,7 +361,7 @@ impl Jobs<'_, B> { &self, params: &CryptoParams, c6: &ZkProof, - ciphertext: &[u8], + ciphertext: Option, share: &[u8], domain: B256, anchor: KeyAnchor, @@ -260,9 +373,6 @@ impl Jobs<'_, B> { let in_domain = limbs .into_iter() .all(|(name, limb)| field(name) == Some(B256::from(U256::from(limb)))); - let ciphertext = compute_ct_commitment_with_params(ciphertext, &threshold) - .ok() - .map(B256::from); let d_native_bit = e3_zk_config::threshold::share_decryption::Configs::new(&threshold) .map_err(JobError::crypto)? .bits @@ -306,12 +416,14 @@ impl Jobs<'_, B> { Ok((party, polys)) }) .collect::, JobError>>()?; - let response = calculate_threshold_decryption(CalculateThresholdDecryptionRequest { - trbfv_config: trbfv::config(params)?, - d_share_polys, - ciphertexts: self.ciphertexts(ciphertext)?, - }) - .map_err(JobError::crypto)?; + let response = self.check_pool.install(|| { + calculate_threshold_decryption(CalculateThresholdDecryptionRequest { + trbfv_config: trbfv::config(params)?, + d_share_polys, + ciphertexts: self.ciphertexts(ciphertext)?, + }) + .map_err(JobError::crypto) + })?; let mut plaintext = response .plaintext .first() @@ -336,6 +448,9 @@ impl Jobs<'_, B> { /// The proof `publishPlaintextOutput` verifies: C7, that the T+1 members' shares of the first /// ciphertext combine into the plaintext, folded with their C6 proofs. + /// + /// C7 and the sequential C6 fold chain are mutually independent and run concurrently across + /// `ProveGate` slots, with every intermediate step checkpointed in `blobs.kept`. fn prove_plaintext( &self, prover: &Prover<'_>, @@ -347,7 +462,7 @@ impl Jobs<'_, B> { let threshold = trbfv::threshold_params(params)?; let mut d_share_polys = Vec::new(); let mut reconstructing_parties = Vec::new(); - let mut c6 = Vec::new(); + let mut c6_refs = Vec::new(); for (member, message) in shares { let (Some(share), Some(proof)) = (message.shares.first(), message.c6.first()) else { return Err(JobError::crypto( @@ -360,13 +475,14 @@ impl Jobs<'_, B> { ); // The circuit numbers parties from one. reconstructing_parties.push(trbfv::party(committee, *member)? + 1); - c6.push(proofs::load( - &self.blobs, - &proof.proof, - proofs::circuit(ProofType::C6ThresholdShareDecryption), - )?); + c6_refs.push(&proof.proof); + } + if c6_refs.is_empty() { + return Err(JobError::crypto( + "C6 fold requires at least one inner proof", + )); } - let c7 = DecryptedSharesAggregationCircuitData { + let c7_data = DecryptedSharesAggregationCircuitData { d_share_polys, reconstructing_parties, message_vec: e3_bfv_client::decode_bytes_to_vec_u64(plaintext) @@ -377,28 +493,113 @@ impl Jobs<'_, B> { params.committee_size, ) .map_err(JobError::crypto)?; - let (work, artifacts) = (self.work("c7"), self.artifacts(params)?); - // C7 takes the variant the decryption aggregation verifies inside it. - let c7 = prover.proving(|zk| { - let variant = CircuitVariant::Default; - DecryptedSharesAggregationCircuit - .prove_with_variant(zk, &config, &c7, &work, variant, &artifacts) - })?; - let slots: Vec = (0..c6.len() as u32).collect(); - let job = DecryptionAggregationJob { - c6_inner_proofs: &c6, - c6_slot_indices: &slots, - c7_proof: &c7, - }; - let (work, artifacts) = (self.work("decryption"), self.artifacts(params)?); - let proofs = prover.proving(|zk| { - let slots = c6.len(); - prove_decryption_aggregation_jobs(zk, slots, &[job], committee, &work, &artifacts) - })?; - let proof = proofs - .first() - .ok_or(JobError::crypto("no decryption aggregation proof"))?; - proofs::store(&self.blobs, proof) + let artifacts = self.artifacts(params)?; + let c6_total_slots = c6_refs.len(); + + let (c7_res, c6_fold_res) = thread::scope(|scope| { + let c7_handle = scope.spawn(|| { + let mut c7_inputs = vec![params.config, alloy_primitives::keccak256(plaintext)]; + for proof in &c6_refs { + c7_inputs.push(proof.data.hash); + } + let c7_key = proofs::step_key(self.scope, "c7", &c7_inputs); + let work = self.work("c7"); + // C7 takes the variant the decryption aggregation verifies inside it. + proofs::prove_kept_step(&self.blobs, prover, c7_key, Priority::Foreground, |zk| { + DecryptedSharesAggregationCircuit.prove_with_variant( + zk, + &config, + &c7_data, + &work, + CircuitVariant::Default, + &artifacts, + ) + }) + }); + + let c6_handle = scope.spawn(|| -> Result<(ZkProof, CircuitName), JobError> { + let mut prior: Option<(ZkProof, CircuitName)> = None; + for (step, inner_zk) in c6_refs.iter().enumerate() { + let slot = step as u32; + let prior_hash = prior + .as_ref() + .map(|(p, _)| p.data.hash) + .unwrap_or(B256::ZERO); + let key = proofs::step_key( + self.scope, + &format!("c6-fold-{step}-{c6_total_slots}"), + &[params.config, prior_hash, inner_zk.data.hash], + ); + let work = self.work(&format!("decryption-c6fold-{step}")); + let prior_ref = prior.as_ref(); + let next = proofs::prove_kept_step( + &self.blobs, + prover, + key, + Priority::Foreground, + |zk| { + let inner_loaded = proofs::load( + &self.blobs, + inner_zk, + proofs::circuit(ProofType::C6ThresholdShareDecryption), + ) + .map_err(|e| e.to_string())?; + let prior_loaded = prior_ref + .map(|(p, circuit)| proofs::load(&self.blobs, p, *circuit)) + .transpose() + .map_err(|e| e.to_string())?; + generate_c6_fold_step( + zk, + &inner_loaded, + prior_loaded.as_ref(), + slot, + c6_total_slots, + &work, + &artifacts, + ) + .map_err(|e| e.to_string()) + }, + )?; + let circuit = if step == 0 { + CircuitName::C6FoldKernel + } else { + CircuitName::C6Fold + }; + prior = Some((next, circuit)); + } + prior.ok_or_else(|| JobError::crypto("missing C6 fold proof")) + }); + + ( + c7_handle.join().expect("c7 worker panicked"), + c6_handle.join().expect("c6 fold worker panicked"), + ) + }); + + let c7_zk = c7_res?; + let (c6_fold_zk, c6_fold_circuit) = c6_fold_res?; + let agg_key = proofs::step_key( + self.scope, + "decryption-agg", + &[params.config, c6_fold_zk.data.hash, c7_zk.data.hash], + ); + let work = self.work("decryption-decagg-0"); + proofs::prove_kept_step(&self.blobs, prover, agg_key, Priority::Foreground, |zk| { + let c6_fold = proofs::load(&self.blobs, &c6_fold_zk, c6_fold_circuit) + .map_err(|e| e.to_string())?; + let c7 = proofs::load(&self.blobs, &c7_zk, CircuitName::DecryptedSharesAggregation) + .map_err(|e| e.to_string())?; + prove_decryption_aggregator_with_c6_fold( + zk, + &c6_fold, + c6_total_slots, + &c7, + committee, + &work, + &artifacts, + ) + .map_err(|e| e.to_string()) + }) } /// The ciphertext blob holds the bytes the chain's content hash names: one serialized diff --git a/crates/ciphernode/jobs/src/dkg.rs b/crates/ciphernode/jobs/src/dkg.rs index 8d3741e..c1e8546 100644 --- a/crates/ciphernode/jobs/src/dkg.rs +++ b/crates/ciphernode/jobs/src/dkg.rs @@ -9,8 +9,10 @@ //! current node. use crate::{ - placeholder, proofs, proofs::Prover, trbfv, Blobs, JobError, Jobs, OwnShareRows, - RecipientCiphertexts, SealedDecryptionKey, + placeholder, + proofs::{self, Priority, Prover}, + trbfv, Attempt, BlobStore, Blobs, JobError, Jobs, OwnShareRows, Prefolds, RecipientCiphertexts, + SealedDecryptionKey, }; use alloy_primitives::{keccak256, Address, B256}; use e3_crypto::SensitiveBytes; @@ -24,7 +26,7 @@ use e3_protocol::{ }, node::CryptoParams, proof::{ProofType, SignedProof, ZkProof}, - BlobRef, SealedRef, + BlobRef, E3Id, SealedRef, }; use e3_trbfv::{ calculate_decryption_key::{calculate_decryption_key, CalculateDecryptionKeyRequest}, @@ -43,10 +45,10 @@ use e3_trbfv::{ }; use e3_zk_config::{CircuitName, CircuitVariant, DkgInputType}; use e3_zk_prover::{ - extract_node_fold_agg_commits, generate_nodes_fold_step, prove_dkg_aggregation, - prove_node_dkg_fold, DkgAggregationInput, DkgShareDecryptionCircuit, NodeDkgFoldInput, - PkAggregationCircuit, PkCircuit, PkGenerationCircuit, Provable, ShareComputationCircuit, - ShareEncryptionCircuit, + extract_node_fold_agg_commits, generate_c3_fold_step, generate_nodes_fold_step, + prove_c2ab_fold, prove_c3ab_fold, prove_c4ab_fold, prove_dkg_aggregation, + prove_node_fold_final, DkgAggregationInput, DkgShareDecryptionCircuit, PkAggregationCircuit, + PkCircuit, PkGenerationCircuit, Provable, ShareComputationCircuit, ShareEncryptionCircuit, }; use e3_zk_witness::{ compute_dkg_pk_commitment_from_public_key_bytes, compute_pk_commitment_from_keyshare_bytes, @@ -65,9 +67,53 @@ use fhe_traits::{DeserializeParametrized, FheEncoder, Serialize}; use ndarray::Array2; use num_bigint::BigInt; use rayon::prelude::*; -use std::{collections::BTreeMap, sync::Arc}; +use std::{ + collections::{BTreeMap, VecDeque}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Condvar, Mutex, PoisonError, + }, + thread, +}; + +struct PrefoldDoneGuard { + prefolds: Arc, + e3: E3Id, + done: Arc<(Mutex, Condvar)>, +} + +impl Drop for PrefoldDoneGuard { + fn drop(&mut self) { + self.prefolds.mark_finished(self.e3, &self.done); + } +} + +enum MakeSharesTask { + C1(PkGenerationCircuitData), + C2a(ShareComputationCircuitData), + C2b(ShareComputationCircuitData), + C3 { + recipient_index: usize, + is_c3a: bool, + slot: usize, + row: usize, + witness: Box, + }, +} -impl Jobs<'_, B> { +enum MakeSharesOutput { + C1(ZkProof), + C2a(ZkProof), + C2b(ZkProof), + C3 { + recipient_index: usize, + is_c3a: bool, + row: usize, + proof: ZkProof, + }, +} + +impl Jobs<'_, B, S> { pub(crate) fn run_dkg( &self, params: &CryptoParams, @@ -228,37 +274,40 @@ impl Jobs<'_, B> { let config = trbfv::config(params)?; let dkg = trbfv::dkg_params(params)?; let mut rng = self.rng("shares")?; - let generated = gen_pk_share_and_sk_sss( - &mut rng, - self.cipher, - GenPkShareAndSkSssRequest { - trbfv_config: config.clone(), - crp: trbfv::crp(params)?, - lambda: trbfv::lambda(params)?, - num_ciphertexts: trbfv::ciphertexts(params)?, - }, - ) - .map_err(JobError::crypto)?; - let smudging = gen_esi_sss( - &mut rng, - self.cipher, - GenEsiSssRequest { - trbfv_config: config, - e_sm_raw: generated.e_sm_raw.clone(), - }, - ) - .map_err(JobError::crypto)?; - let sk_sss = generated - .sk_sss - .clone() - .decrypt(self.cipher) + let (generated, sk_sss, esi_sss) = self.check_pool.install(|| { + let generated = gen_pk_share_and_sk_sss( + &mut rng, + self.cipher, + GenPkShareAndSkSssRequest { + trbfv_config: config.clone(), + crp: trbfv::crp(params)?, + lambda: trbfv::lambda(params)?, + num_ciphertexts: trbfv::ciphertexts(params)?, + }, + ) .map_err(JobError::crypto)?; - let esi_sss: Vec<_> = smudging - .esi_sss - .into_iter() - .map(|shares| shares.decrypt(self.cipher)) - .collect::>() + let smudging = gen_esi_sss( + &mut rng, + self.cipher, + GenEsiSssRequest { + trbfv_config: config, + e_sm_raw: generated.e_sm_raw.clone(), + }, + ) .map_err(JobError::crypto)?; + let sk_sss = generated + .sk_sss + .clone() + .decrypt(self.cipher) + .map_err(JobError::crypto)?; + let esi_sss: Vec<_> = smudging + .esi_sss + .into_iter() + .map(|shares| shares.decrypt(self.cipher)) + .collect::>() + .map_err(JobError::crypto)?; + Ok::<_, JobError>((generated, sk_sss, esi_sss)) + })?; let own_public = PublicKey::from_bytes(&self.blobs.get(own_key)?, &dkg).map_err(JobError::crypto)?; @@ -273,18 +322,21 @@ impl Jobs<'_, B> { .collect::, JobError>>()?; let slots: Vec = (0..committee.len()).collect(); let encrypt = |purpose: String, secret| { - BfvEncryptedShares::encrypt_all_extended_for_share_indices( - secret, - &recipient_keys, - &slots, - &dkg, - &mut self.rng(&purpose)?, - Some(party), - ) - .map_err(JobError::crypto) + let mut purpose_rng = self.rng(&purpose)?; + self.check_pool.install(|| { + BfvEncryptedShares::encrypt_all_extended_for_share_indices( + secret, + &recipient_keys, + &slots, + &dkg, + &mut purpose_rng, + Some(party), + ) + .map_err(JobError::crypto) + }) }; - let (sk_encrypted, sk_witnesses) = encrypt("sk encryption".into(), &sk_sss)?; - let (esi_encrypted, esi_witnesses): (Vec<_>, Vec<_>) = esi_sss + let (sk_encrypted, mut sk_witnesses) = encrypt("sk encryption".into(), &sk_sss)?; + let (esi_encrypted, mut esi_witnesses): (Vec<_>, Vec<_>) = esi_sss .iter() .enumerate() .map(|(index, shares)| encrypt(format!("esi encryption {index}"), shares)) @@ -292,105 +344,296 @@ impl Jobs<'_, B> { .into_iter() .unzip(); - let c3_config = - e3_zk_config::dkg::share_encryption::Configs::new(&dkg).map_err(JobError::crypto)?; - let recipients = || { - committee - .par_iter() - .enumerate() - .filter(|(_, member)| **member != dealer) - .map(|(slot, member)| { - let ciphertexts = RecipientCiphertexts { - sk: sk_encrypted - .clone_share(slot) - .ok_or(JobError::crypto("no share for a slot"))?, - esi: esi_encrypted - .iter() - .map(|shares| { - shares - .clone_share(slot) - .ok_or(JobError::crypto("no share for a slot")) - }) - .collect::>()?, - }; - let bytes = bincode::serialize(&ciphertexts).map_err(JobError::crypto)?; - let shares = match keys.contains_key(member) { - true => Some(self.blobs.put(&bytes)?), - false => None, - }; - // C3: each share row's ciphertext encrypts that row under the recipient's key. - let prove = - |proof_type: ProofType, row: usize, witness: &BfvEncryptionWitness| { - let Some(prover) = self.prover() else { - return placeholder::proof(&self.blobs, proof_type, &bytes); + // Serialize and store every recipient's ciphertexts first so `sk_encrypted` and + // `esi_encrypted` can be dropped before proving begins. + let other_members: Vec<(usize, Address)> = committee + .iter() + .enumerate() + .filter(|(_, member)| **member != dealer) + .map(|(slot, member)| (slot, *member)) + .collect(); + let keep_bytes = self.prover().is_none(); + let recipient_blobs: Vec<(Option, Option>)> = + self.check_pool.install(|| { + other_members + .par_iter() + .map(|(slot, member)| { + let ciphertexts = RecipientCiphertexts { + sk: sk_encrypted + .clone_share(*slot) + .ok_or(JobError::crypto("no share for a slot"))?, + esi: esi_encrypted + .iter() + .map(|shares| { + shares + .clone_share(*slot) + .ok_or(JobError::crypto("no share for a slot")) + }) + .collect::>()?, + }; + let bytes = bincode::serialize(&ciphertexts).map_err(JobError::crypto)?; + let shares = match keys.contains_key(member) { + true => Some(self.blobs.put(&bytes)?), + false => None, + }; + Ok((shares, keep_bytes.then_some(bytes))) + }) + .collect::, JobError>>() + })?; + drop(sk_encrypted); + drop(esi_encrypted); + + let (recipients, c1, c2a, c2b) = if let Some(prover) = self.prover() { + let (c1_data, c2a_data, c2b_data, c1_config, c2_config) = + self.prepare_dealing_witnesses(params, &generated, &sk_sss, &esi_sss)?; + let c3_config = e3_zk_config::dkg::share_encryption::Configs::new(&dkg) + .map_err(JobError::crypto)?; + + let mut tasks = VecDeque::new(); + tasks.push_back(MakeSharesTask::C1(c1_data)); + tasks.push_back(MakeSharesTask::C2a(c2a_data)); + tasks.push_back(MakeSharesTask::C2b(c2b_data)); + + let mut c3a_counts = vec![0usize; other_members.len()]; + let mut c3b_counts = vec![0usize; other_members.len()]; + for (recipient_index, (slot, _)) in other_members.iter().enumerate() { + let sk_rows = std::mem::take(&mut sk_witnesses[*slot]); + c3a_counts[recipient_index] = sk_rows.len(); + for (row, witness) in sk_rows.into_iter().enumerate() { + tasks.push_back(MakeSharesTask::C3 { + recipient_index, + is_c3a: true, + slot: *slot, + row, + witness: Box::new(witness), + }); + } + let mut row = 0usize; + for esi in &mut esi_witnesses { + for witness in std::mem::take(&mut esi[*slot]) { + tasks.push_back(MakeSharesTask::C3 { + recipient_index, + is_c3a: false, + slot: *slot, + row, + witness: Box::new(witness), + }); + row += 1; + } + } + c3b_counts[recipient_index] = row; + } + drop(sk_witnesses); + drop(esi_witnesses); + + let worker_count = prover.max_concurrent().min(tasks.len()).max(1); + let queue = Mutex::new(tasks); + let outputs: Mutex> = Mutex::new(Vec::new()); + let first_err: Mutex> = Mutex::new(None); + let failed = AtomicBool::new(false); + + thread::scope(|scope| { + for _ in 0..worker_count { + scope.spawn(|| { + while !failed.load(Ordering::Acquire) { + let task = { + queue + .lock() + .unwrap_or_else(PoisonError::into_inner) + .pop_front() }; - let data = ShareEncryptionCircuitData { - plaintext: Plaintext::try_encode( - &witness.share_row, - Encoding::poly(), - &dkg, - ) - .map_err(JobError::crypto)?, - ciphertext: witness.ciphertext.clone(), - public_key: recipient_keys[slot].clone(), - u_rns: witness.u_rns.clone(), - e0_rns: witness.e0_rns.clone(), - e1_rns: witness.e1_rns.clone(), + let Some(task) = task else { + break; }; - let work = format!("{proof_type:?}-{slot}-{row}"); - self.prove( - prover, - params, - ShareEncryptionCircuit, - &c3_config, - &data, - &work, - ) - }; - let c3 = |proof_type, witnesses: Vec<&BfvEncryptionWitness>| { - witnesses - .into_par_iter() - .enumerate() - .map(|(row, witness)| prove(proof_type, row, witness)) - .collect::, _>>() - }; - let (c3a, c3b) = rayon::join( - || { - c3( - ProofType::C3aSkShareEncryption, - sk_witnesses[slot].iter().collect(), - ) - }, - || { - let rows = esi_witnesses.iter().flat_map(|esi| &esi[slot]); - c3(ProofType::C3bESmShareEncryption, rows.collect()) - }, - ); - Ok(( - *member, - RecipientShares { - shares, - c3a: c3a?, - c3b: c3b?, - }, - )) - }) - .collect::, JobError>>() - }; - let dealing = || match self.prover() { - Some(prover) => self.prove_dealing(prover, params, &generated, &sk_sss, &esi_sss), - None => { - let bound = - |proof_type| placeholder::proof(&self.blobs, proof_type, &generated.pk_share); - Ok(( - bound(ProofType::C1PkGeneration)?, - bound(ProofType::C2aSkShareComputation)?, - bound(ProofType::C2bESmShareComputation)?, - )) + let result = match task { + MakeSharesTask::C1(data) => self + .prove( + prover, + params, + PkGenerationCircuit, + &c1_config, + &data, + "c1", + ) + .map(MakeSharesOutput::C1), + MakeSharesTask::C2a(data) => self + .prove( + prover, + params, + ShareComputationCircuit, + &c2_config, + &data, + "c2a", + ) + .map(MakeSharesOutput::C2a), + MakeSharesTask::C2b(data) => self + .prove( + prover, + params, + ShareComputationCircuit, + &c2_config, + &data, + "c2b", + ) + .map(MakeSharesOutput::C2b), + MakeSharesTask::C3 { + recipient_index, + is_c3a, + slot, + row, + witness, + } => { + let proof_type = if is_c3a { + ProofType::C3aSkShareEncryption + } else { + ProofType::C3bESmShareEncryption + }; + let work = format!("{proof_type:?}-{slot}-{row}"); + let witness = *witness; + let built = Plaintext::try_encode( + &witness.share_row, + Encoding::poly(), + &dkg, + ) + .map_err(JobError::crypto) + .map(|plaintext| ShareEncryptionCircuitData { + plaintext, + ciphertext: witness.ciphertext, + public_key: recipient_keys[slot].clone(), + u_rns: witness.u_rns, + e0_rns: witness.e0_rns, + e1_rns: witness.e1_rns, + }); + built + .and_then(|data| { + self.prove( + prover, + params, + ShareEncryptionCircuit, + &c3_config, + &data, + &work, + ) + }) + .map(|proof| MakeSharesOutput::C3 { + recipient_index, + is_c3a, + row, + proof, + }) + } + }; + match result { + Ok(output) => { + outputs + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(output); + } + Err(error) => { + failed.store(true, Ordering::Release); + let mut slot = + first_err.lock().unwrap_or_else(PoisonError::into_inner); + if slot.is_none() { + *slot = Some(error); + } + break; + } + } + } + }); + } + }); + + if let Some(error) = first_err + .into_inner() + .unwrap_or_else(PoisonError::into_inner) + { + return Err(error); + } + + let mut c1 = None; + let mut c2a = None; + let mut c2b = None; + let mut c3a_slots: Vec>> = + c3a_counts.iter().map(|&n| vec![None; n]).collect(); + let mut c3b_slots: Vec>> = + c3b_counts.iter().map(|&n| vec![None; n]).collect(); + + for output in outputs.into_inner().unwrap_or_else(PoisonError::into_inner) { + match output { + MakeSharesOutput::C1(p) => c1 = Some(p), + MakeSharesOutput::C2a(p) => c2a = Some(p), + MakeSharesOutput::C2b(p) => c2b = Some(p), + MakeSharesOutput::C3 { + recipient_index, + is_c3a, + row, + proof, + } => { + if is_c3a { + c3a_slots[recipient_index][row] = Some(proof); + } else { + c3b_slots[recipient_index][row] = Some(proof); + } + } + } + } + + let mut recipients = BTreeMap::new(); + for (index, ((_, member), (shares, _))) in + other_members.iter().zip(recipient_blobs).enumerate() + { + let c3a = c3a_slots[index] + .drain(..) + .map(|p| p.ok_or_else(|| JobError::crypto("missing C3a proof"))) + .collect::, _>>()?; + let c3b = c3b_slots[index] + .drain(..) + .map(|p| p.ok_or_else(|| JobError::crypto("missing C3b proof"))) + .collect::, _>>()?; + recipients.insert(*member, RecipientShares { shares, c3a, c3b }); + } + let c1 = c1.ok_or_else(|| JobError::crypto("missing C1 proof"))?; + let c2a = c2a.ok_or_else(|| JobError::crypto("missing C2a proof"))?; + let c2b = c2b.ok_or_else(|| JobError::crypto("missing C2b proof"))?; + + // Speculatively pre-fold C2ab and C3a/C3b -> C3ab in the background only when the host + // has spare prover concurrency (`max_concurrent >= 2`). On a single-prover host, + // launching a multi-second fold before roster formation blocks foreground `C4` proofs + // and spends the only prover slot on non-roster observers until the roster forms. + if prover.max_concurrent() >= 2 { + self.spawn_dkg_prefold(params, committee, &c2a, &c2b, &recipients); } + + (recipients, c1, c2a, c2b) + } else { + let mut recipients = BTreeMap::new(); + for ((slot, member), (shares, bytes)) in other_members.iter().zip(recipient_blobs) { + let bytes = bytes.as_deref().unwrap_or(&[]); + let c3a = (0..sk_witnesses[*slot].len()) + .map(|_| { + placeholder::proof(&self.blobs, ProofType::C3aSkShareEncryption, bytes) + }) + .collect::, _>>()?; + let esi_rows: usize = esi_witnesses.iter().map(|esi| esi[*slot].len()).sum(); + let c3b = (0..esi_rows) + .map(|_| { + placeholder::proof(&self.blobs, ProofType::C3bESmShareEncryption, bytes) + }) + .collect::, _>>()?; + recipients.insert(*member, RecipientShares { shares, c3a, c3b }); + } + let bound = + |proof_type| placeholder::proof(&self.blobs, proof_type, &generated.pk_share); + ( + recipients, + bound(ProofType::C1PkGeneration)?, + bound(ProofType::C2aSkShareComputation)?, + bound(ProofType::C2bESmShareComputation)?, + ) }; - let (recipients, dealing) = rayon::join(recipients, dealing); - let (recipients, (c1, c2a, c2b)) = (recipients?, dealing?); + let pk_share = self.blobs.put(&generated.pk_share)?; let own = OwnShareRows { sk: sk_sss @@ -413,17 +656,89 @@ impl Jobs<'_, B> { }) } - /// C1: the public-key share comes from the secret key, its key error, and the smudging - /// noise. C2a and C2b: the Shamir shares of the secret key and of the smudging noise share - /// them. - fn prove_dealing( + fn spawn_dkg_prefold( + &self, + params: &CryptoParams, + committee: &[Address], + c2a: &ZkProof, + c2b: &ZkProof, + recipients: &BTreeMap, + ) { + let (Some(store), Some(circuits), Some(prefolds)) = + (self.blob_store, self.circuits.as_ref(), self.prefolds) + else { + return; + }; + let (cancel, stop_launching, done) = prefolds.register(self.e3); + let store = store.clone(); + let circuits = circuits.clone(); + let prefolds = Arc::clone(prefolds); + let e3 = self.e3; + let scope = self.scope; + let params = *params; + let committee = committee.to_vec(); + let c2a = c2a.clone(); + let c2b = c2b.clone(); + let c3a: BTreeMap> = recipients + .iter() + .map(|(member, shares)| (*member, shares.c3a.clone())) + .collect(); + let c3b: BTreeMap> = recipients + .iter() + .map(|(member, shares)| (*member, shares.c3b.clone())) + .collect(); + + let prefolds_thread = Arc::clone(&prefolds); + let done_thread = Arc::clone(&done); + let spawned = thread::Builder::new() + .name(format!("prefold-{}", e3.number)) + .spawn(move || { + let _guard = PrefoldDoneGuard { + prefolds: prefolds_thread, + e3, + done: done_thread, + }; + let attempt = Attempt { number: 0, cancel }; + let prover = circuits.for_attempt(&attempt); + let blobs = store.of(e3); + let _ = run_dkg_prefold_steps( + &blobs, + &prover, + scope, + e3, + ¶ms, + &committee, + &c2a, + &c2b, + &c3a, + &c3b, + Priority::Background, + Some(&stop_launching), + ); + }); + if spawned.is_err() { + prefolds.mark_finished(e3, &done); + } + } + + /// Build C1, C2a, and C2b witness data + circuit configs. + #[allow(clippy::type_complexity)] + fn prepare_dealing_witnesses( &self, - prover: &Prover<'_>, params: &CryptoParams, generated: &GenPkShareAndSkSssResponse, sk_sss: &SharedSecret, esi_sss: &[SharedSecret], - ) -> Result<(ZkProof, ZkProof, ZkProof), JobError> { + ) -> Result< + ( + PkGenerationCircuitData, + ShareComputationCircuitData, + ShareComputationCircuitData, + e3_zk_config::threshold::pk_generation::Configs, + e3_zk_config::dkg::share_computation::Configs, + ), + JobError, + > { let preset = trbfv::threshold_preset(params)?; let threshold = trbfv::threshold_params(params)?; let raw = |bytes: &SensitiveBytes| bytes.access_raw(self.cipher).map_err(JobError::crypto); @@ -471,34 +786,7 @@ impl Jobs<'_, B> { let c2_config = e3_zk_config::dkg::share_computation::Configs::new(preset, &threshold, committee) .map_err(JobError::crypto)?; - let (c1, (c2a, c2b)) = rayon::join( - || self.prove(prover, params, PkGenerationCircuit, &c1_config, &c1, "c1"), - || { - rayon::join( - || { - self.prove( - prover, - params, - ShareComputationCircuit, - &c2_config, - &c2a, - "c2a", - ) - }, - || { - self.prove( - prover, - params, - ShareComputationCircuit, - &c2_config, - &c2b, - "c2b", - ) - }, - ) - }, - ); - Ok((c1?, c2a?, c2b?)) + Ok((c1, c2a, c2b, c1_config, c2_config)) } /// Shares count when their C2 and C3 proofs hold, they decrypt under this node's C0 secret to @@ -610,13 +898,19 @@ impl Jobs<'_, B> { .iter() .map(|(dealer, blob)| Ok((*dealer, self.recipient_ciphertexts(blob)?))) .collect::, JobError>>()?; + let decrypted_rows: Vec = self.check_pool.install(|| { + let ciphertexts: Vec<&RecipientCiphertexts> = dealt.values().collect(); + ciphertexts + .par_iter() + .map(|ct| decrypt_shares(&secret, &dkg, ct)) + .collect::, JobError>>() + })?; let mut sk_collected = vec![own.sk.clone()]; let mut esi_collected: Vec> = own.esi.iter().map(|esi| vec![esi.clone()]).collect(); - for ciphertexts in dealt.values() { - let shares = decrypt_shares(&secret, &dkg, ciphertexts)?; - sk_collected.push(shares.sk); - for (collected, esi) in esi_collected.iter_mut().zip(shares.esi) { + for rows in decrypted_rows { + sk_collected.push(rows.sk); + for (collected, esi) in esi_collected.iter_mut().zip(rows.esi) { collected.push(esi); } } @@ -693,19 +987,24 @@ impl Jobs<'_, B> { let mut roster: Vec

= dealt.keys().copied().chain([member]).collect(); roster.sort(); let data = |share: fn(&RecipientCiphertexts) -> &BfvEncryptedShare, own: &ShamirShare| { - let honest_ciphertexts = roster - .iter() - .map(|dealer| { - let Some(dealt) = dealt.get(dealer) else { - return Ok(None); - }; - let ciphertexts = share(dealt).ciphertext_bytes().iter(); - ciphertexts - .map(|bytes| Ciphertext::from_bytes(bytes, dkg).map_err(JobError::crypto)) - .collect::>() - .map(Some) - }) - .collect::>()?; + let honest_ciphertexts = self.check_pool.install(|| { + roster + .par_iter() + .map(|dealer| { + let Some(dealt) = dealt.get(dealer) else { + return Ok(None); + }; + let ciphertexts = share(dealt).ciphertext_bytes(); + ciphertexts + .iter() + .map(|bytes| { + Ciphertext::from_bytes(bytes, dkg).map_err(JobError::crypto) + }) + .collect::>() + .map(Some) + }) + .collect::>() + })?; Ok::<_, JobError>(ShareDecryptionCircuitData { secret_key: secret.clone(), honest_ciphertexts, @@ -725,8 +1024,8 @@ impl Jobs<'_, B> { }, own_esi, )?; - let (c4a, c4b) = rayon::join( - || { + let (c4a, c4b) = thread::scope(|scope| { + let a = scope.spawn(|| { self.prove( prover, params, @@ -735,8 +1034,8 @@ impl Jobs<'_, B> { &c4a, "c4a", ) - }, - || { + }); + let b = scope.spawn(|| { self.prove( prover, params, @@ -745,8 +1044,12 @@ impl Jobs<'_, B> { &c4b, "c4b", ) - }, - ); + }); + ( + a.join().expect("c4a worker panicked"), + b.join().expect("c4b worker panicked"), + ) + }); Ok((c4a?, vec![c4b?])) } @@ -767,52 +1070,121 @@ impl Jobs<'_, B> { esm_agg_commit: keccak256(statements.repeat(2)), }); }; + // Hand over any remaining pre-fold steps to foreground priority while allowing any + // currently running background step to finish and share its result via single-flight. + if let Some(prefolds) = self.prefolds { + prefolds.pause_new_steps(self.e3); + } let size = params.committee_size.values(); let rows = trbfv::threshold_params(params)?.moduli().len(); - let load = |proof: &ZkProof, proof_type| { - proofs::load(&self.blobs, proof, proofs::circuit(proof_type)) - }; - // A C3 proof's slot is its recipient's party ID times the share rows, plus its row. - let c3 = |c3: &BTreeMap>, proof_type| { - let mut folded = (Vec::new(), Vec::new()); - for (recipient, row_proofs) in c3 { - let party = trbfv::party(committee, *recipient)?; - for (row, proof) in row_proofs.iter().enumerate() { - folded.0.push(load(proof, proof_type)?); - folded - .1 - .push(u32::try_from(party * rows + row).map_err(JobError::crypto)?); - } - } - Ok::<_, JobError>(folded) - }; - let (c3a, slots_a) = c3(&proofs.c3a, ProofType::C3aSkShareEncryption)?; - let (c3b, slots_b) = c3(&proofs.c3b, ProofType::C3bESmShareEncryption)?; let [c4b] = proofs.c4b.as_slice() else { return Err(JobError::crypto("the fold takes one smudging-noise C4")); }; - let input = NodeDkgFoldInput { - c0_proof: &load(&proofs.c0, ProofType::C0PkBfv)?, - c1_proof: &load(&proofs.c1, ProofType::C1PkGeneration)?, - c2a_proof: &load(&proofs.c2a, ProofType::C2aSkShareComputation)?, - c2b_proof: &load(&proofs.c2b, ProofType::C2bESmShareComputation)?, - c3a_inner_proofs: &c3a, - c3b_inner_proofs: &c3b, - c3_slot_indices_a: &slots_a, - c3_slot_indices_b: &slots_b, - c3_total_slots: size.n * rows, - c4a_proof: &load(&proofs.c4a, ProofType::C4aSkShareDecryption)?, - c4b_proof: &load(c4b, ProofType::C4bESmShareDecryption)?, - party_id: trbfv::party(committee, member)? as u64, - }; - let (work, artifacts) = (self.work("fold"), self.artifacts(params)?); - let fold = prover - .proving(|zk| prove_node_dkg_fold(zk, &input, &work, &artifacts))? - .proof; + let party_id = trbfv::party(committee, member)? as u64; + let artifacts = self.artifacts(params)?; + + let (prefold_res, c4ab_res) = thread::scope(|scope| { + let prefold = scope.spawn(|| { + run_dkg_prefold_steps( + &self.blobs, + prover, + self.scope, + self.e3, + params, + committee, + &proofs.c2a, + &proofs.c2b, + &proofs.c3a, + &proofs.c3b, + Priority::Foreground, + None, + ) + }); + let c4ab = scope.spawn(|| { + let c4ab_key = proofs::step_key( + self.scope, + "c4ab", + &[params.config, proofs.c4a.data.hash, c4b.data.hash], + ); + let work = self.work("fold-c4ab"); + proofs::prove_kept_step(&self.blobs, prover, c4ab_key, Priority::Foreground, |zk| { + let c4a_loaded = proofs::load( + &self.blobs, + &proofs.c4a, + proofs::circuit(ProofType::C4aSkShareDecryption), + ) + .map_err(|e| e.to_string())?; + let c4b_loaded = proofs::load( + &self.blobs, + c4b, + proofs::circuit(ProofType::C4bESmShareDecryption), + ) + .map_err(|e| e.to_string())?; + prove_c4ab_fold(zk, &c4a_loaded, &c4b_loaded, &work, &artifacts) + .map_err(|e| e.to_string()) + }) + }); + ( + prefold.join().expect("prefold worker panicked"), + c4ab.join().expect("c4ab worker panicked"), + ) + }); + + let (c2ab, c3ab) = prefold_res?.expect("foreground prefold runs to completion"); + let c4ab = c4ab_res?; + + let node_fold_key = proofs::step_key( + self.scope, + &format!("nodefold-{party_id}"), + &[ + params.config, + proofs.c0.data.hash, + proofs.c1.data.hash, + c2ab.data.hash, + c3ab.data.hash, + c4ab.data.hash, + ], + ); + let work = self.work("fold"); + let fold_zk = proofs::prove_kept_step( + &self.blobs, + prover, + node_fold_key, + Priority::Foreground, + |zk| { + let c0 = proofs::load(&self.blobs, &proofs.c0, proofs::circuit(ProofType::C0PkBfv)) + .map_err(|e| e.to_string())?; + let c1 = proofs::load( + &self.blobs, + &proofs.c1, + proofs::circuit(ProofType::C1PkGeneration), + ) + .map_err(|e| e.to_string())?; + let c2ab_loaded = proofs::load(&self.blobs, &c2ab, CircuitName::C2abFold) + .map_err(|e| e.to_string())?; + let c3ab_loaded = proofs::load(&self.blobs, &c3ab, CircuitName::C3abFold) + .map_err(|e| e.to_string())?; + let c4ab_loaded = proofs::load(&self.blobs, &c4ab, CircuitName::C4abFold) + .map_err(|e| e.to_string())?; + prove_node_fold_final( + zk, + &c0, + &c1, + &c2ab_loaded, + &c3ab_loaded, + &c4ab_loaded, + party_id, + &work, + &artifacts, + ) + .map_err(|e| e.to_string()) + }, + )?; + let fold = proofs::load(&self.blobs, &fold_zk, CircuitName::NodeFold)?; let (_, commits) = extract_node_fold_agg_commits(&fold, size.n, size.h, rows).map_err(JobError::crypto)?; Ok(NodeFold { - proof: proofs::store(&self.blobs, &fold)?, + proof: fold_zk, sk_agg_commit: B256::from(commits.sk_agg_commit), esm_agg_commit: B256::from(commits.esm_agg_commit), }) @@ -910,21 +1282,30 @@ impl Jobs<'_, B> { &slot.to_be_bytes(), ); }; - let fold = proofs::load(&self.blobs, fold, CircuitName::NodeFold)?; - // Slot 0 goes into the kernel on its own, so the accumulator of slot 1 is a kernel proof, - // which the step verifies with the kernel's key. Every later accumulator is a fold step's. - let previous = match slot { - 1 => CircuitName::NodesFoldKernel, - _ => CircuitName::NodesFold, - }; - let accumulator = accumulator - .map(|proof| proofs::load(&self.blobs, proof, previous)) - .transpose()?; + let acc_hash = accumulator.map(|p| p.data.hash).unwrap_or(B256::ZERO); + let key = proofs::step_key( + self.scope, + &format!("roster-fold-{slot}-{slots}"), + &[params.config, fold.data.hash, acc_hash], + ); let (work, artifacts) = ( self.work(&format!("roster-fold-{slot}")), self.artifacts(params)?, ); - let folded = prover.proving(|zk| { + proofs::prove_kept_step(&self.blobs, prover, key, Priority::Foreground, |zk| { + let fold = proofs::load(&self.blobs, fold, CircuitName::NodeFold) + .map_err(|e| e.to_string())?; + // Slot 0 goes into the kernel on its own, so the accumulator of slot 1 is a kernel + // proof, which the step verifies with the kernel's key. Every later accumulator is a + // fold step's. + let previous = match slot { + 1 => CircuitName::NodesFoldKernel, + _ => CircuitName::NodesFold, + }; + let accumulator = accumulator + .map(|proof| proofs::load(&self.blobs, proof, previous)) + .transpose() + .map_err(|e| e.to_string())?; generate_nodes_fold_step( zk, &fold, @@ -934,8 +1315,8 @@ impl Jobs<'_, B> { &work, &artifacts, ) - })?; - proofs::store(&self.blobs, &folded) + .map_err(|e| e.to_string()) + }) } /// Sum the roster's public-key shares into the committee key. Its proof, which @@ -952,13 +1333,15 @@ impl Jobs<'_, B> { ) -> Result { let bfv = trbfv::threshold_params(params)?; let crp = trbfv::crp_poly(params)?; - let shares = keyshares - .iter() - .map(|keyshare| { - let bytes = self.blobs.get(&keyshare.pk_share)?; - PublicKeyShare::deserialize(&bytes, &bfv, crp.clone()).map_err(JobError::crypto) - }) - .collect::, JobError>>()?; + let shares = self.check_pool.install(|| { + keyshares + .par_iter() + .map(|keyshare| { + let bytes = self.blobs.get(&keyshare.pk_share)?; + PublicKeyShare::deserialize(&bytes, &bfv, crp.clone()).map_err(JobError::crypto) + }) + .collect::, JobError>>() + })?; let pk0_shares = shares .iter() .map(|share| CrtPolynomial::from_fhe_polynomial(&share.p0_share())) @@ -978,37 +1361,50 @@ impl Jobs<'_, B> { let c5_config = e3_zk_config::threshold::pk_aggregation::Configs::new(&bfv, params.committee_size) .map_err(JobError::crypto)?; - let c5 = PkAggregationCircuitData { + let c5_data = PkAggregationCircuitData { public_key: key, pk0_shares, }; // C5 takes the variant the DKG aggregation verifies inside it. - let work = self.work("c5"); - let c5 = prover.proving(|zk| { - let variant = CircuitVariant::Default; - PkAggregationCircuit.prove_with_variant(zk, &c5_config, &c5, &work, variant, &artifacts) - })?; - let folds = folds - .iter() - .map(|fold| proofs::load(&self.blobs, &fold.proof, CircuitName::NodeFold)) - .collect::, _>>()?; - let accumulator = proofs::load(&self.blobs, accumulator, CircuitName::NodesFold)?; + let c5_key = proofs::step_key(self.scope, "c5", &[params.config, public_key.hash]); + let c5_work = self.work("c5"); + let c5_zk = + proofs::prove_kept_step(&self.blobs, prover, c5_key, Priority::Foreground, |zk| { + let variant = CircuitVariant::Default; + PkAggregationCircuit + .prove_with_variant(zk, &c5_config, &c5_data, &c5_work, variant, &artifacts) + })?; let party_ids = roster .iter() .map(|member| Ok(trbfv::party(committee, *member)? as u64)) .collect::, JobError>>()?; - let input = DkgAggregationInput { - node_fold_proofs: &folds, - nodes_fold_proof: Some(&accumulator), - c5_proof: &c5, - party_ids: &party_ids, - committee_addresses: committee, - }; - let (work, artifacts) = (self.work("dkg"), self.artifacts(params)?); - let proof = prover.proving(|zk| { - prove_dkg_aggregation(zk, &input, &work, &artifacts, params.committee_size) - })?; - let proof = proofs::store(&self.blobs, &proof)?; + let mut agg_inputs = vec![params.config, c5_zk.data.hash, accumulator.data.hash]; + for fold in folds { + agg_inputs.push(fold.proof.data.hash); + } + let dkg_key = proofs::step_key(self.scope, "dkg-agg", &agg_inputs); + let dkg_work = self.work("dkg"); + let proof = + proofs::prove_kept_step(&self.blobs, prover, dkg_key, Priority::Foreground, |zk| { + let c5 = proofs::load(&self.blobs, &c5_zk, CircuitName::PkAggregation) + .map_err(|e| e.to_string())?; + let folds = folds + .iter() + .map(|fold| proofs::load(&self.blobs, &fold.proof, CircuitName::NodeFold)) + .collect::, _>>() + .map_err(|e| e.to_string())?; + let accumulator = proofs::load(&self.blobs, accumulator, CircuitName::NodesFold) + .map_err(|e| e.to_string())?; + let input = DkgAggregationInput { + node_fold_proofs: &folds, + nodes_fold_proof: Some(&accumulator), + c5_proof: &c5, + party_ids: &party_ids, + committee_addresses: committee, + }; + prove_dkg_aggregation(zk, &input, &dkg_work, &artifacts, params.committee_size) + .map_err(|e| e.to_string()) + })?; let commitment = *proof.public_inputs.last().ok_or(JobError::crypto( "the DKG aggregation proof has no public inputs", ))?; @@ -1033,6 +1429,217 @@ impl Jobs<'_, B> { } } +/// Shared implementation of `C2abFold || (C3aFold chain || C3bFold chain) -> C3abFold` used by +/// both speculative background pre-folding (right after `MakeShares`) and foreground `FoldProofs`. +/// +/// Every step is individually checkpointed in `blobs.kept` and deduplicated via single-flight so +/// foreground `FoldProofs` immediately reuses completed steps and joins in-flight steps. +#[allow(clippy::too_many_arguments)] +fn run_dkg_prefold_steps( + blobs: &B, + prover: &Prover<'_>, + scope: B256, + e3: E3Id, + params: &CryptoParams, + committee: &[Address], + c2a: &ZkProof, + c2b: &ZkProof, + c3a: &BTreeMap>, + c3b: &BTreeMap>, + priority: Priority, + stop_launching: Option<&AtomicBool>, +) -> Result, JobError> { + let should_stop = || stop_launching.is_some_and(|flag| flag.load(Ordering::Acquire)); + if should_stop() { + return Ok(None); + } + let size = params.committee_size.values(); + let rows = trbfv::threshold_params(params)?.moduli().len(); + let total_slots = size.n * rows; + let artifacts = proofs::artifacts_dir(params)?; + + let collect_c3 = + |map: &BTreeMap>| -> Result, JobError> { + let mut items = Vec::new(); + for (recipient, row_proofs) in map { + let party = trbfv::party(committee, *recipient)?; + for (row, proof) in row_proofs.iter().enumerate() { + let slot = u32::try_from(party * rows + row).map_err(JobError::crypto)?; + items.push((slot, proof.clone())); + } + } + Ok(items) + }; + let c3a_items = collect_c3(c3a)?; + let c3b_items = collect_c3(c3b)?; + + let (c2ab_res, c3ab_res) = thread::scope(|s| { + let c2ab_handle = s.spawn(|| -> Result, JobError> { + if should_stop() { + return Ok(None); + } + let key = proofs::step_key( + scope, + "c2ab", + &[params.config, c2a.data.hash, c2b.data.hash], + ); + let work = proofs::work_dir(e3, "fold-c2ab"); + let proof = proofs::prove_kept_step(blobs, prover, key, priority, |zk| { + let c2a_loaded = proofs::load( + blobs, + c2a, + proofs::circuit(ProofType::C2aSkShareComputation), + ) + .map_err(|e| e.to_string())?; + let c2b_loaded = proofs::load( + blobs, + c2b, + proofs::circuit(ProofType::C2bESmShareComputation), + ) + .map_err(|e| e.to_string())?; + prove_c2ab_fold(zk, &c2a_loaded, &c2b_loaded, &work, &artifacts) + .map_err(|e| e.to_string()) + })?; + Ok(Some(proof)) + }); + + let c3ab_handle = s.spawn(|| -> Result, JobError> { + let (c3a_res, c3b_res) = thread::scope(|inner| { + let a = inner.spawn(|| { + run_c3_fold_chain( + blobs, + prover, + scope, + e3, + params.config, + "a", + &c3a_items, + total_slots, + &artifacts, + priority, + stop_launching, + ) + }); + let b = inner.spawn(|| { + run_c3_fold_chain( + blobs, + prover, + scope, + e3, + params.config, + "b", + &c3b_items, + total_slots, + &artifacts, + priority, + stop_launching, + ) + }); + ( + a.join().expect("c3a chain panicked"), + b.join().expect("c3b chain panicked"), + ) + }); + let (Some((c3a_folded, c3a_circuit)), Some((c3b_folded, c3b_circuit))) = + (c3a_res?, c3b_res?) + else { + return Ok(None); + }; + if should_stop() { + return Ok(None); + } + let key = proofs::step_key( + scope, + "c3ab", + &[params.config, c3a_folded.data.hash, c3b_folded.data.hash], + ); + let work = proofs::work_dir(e3, "fold-c3ab"); + let proof = proofs::prove_kept_step(blobs, prover, key, priority, |zk| { + let a_loaded = + proofs::load(blobs, &c3a_folded, c3a_circuit).map_err(|e| e.to_string())?; + let b_loaded = + proofs::load(blobs, &c3b_folded, c3b_circuit).map_err(|e| e.to_string())?; + prove_c3ab_fold(zk, &a_loaded, &b_loaded, &work, &artifacts) + .map_err(|e| e.to_string()) + })?; + Ok(Some(proof)) + }); + + ( + c2ab_handle.join().expect("c2ab thread panicked"), + c3ab_handle.join().expect("c3ab thread panicked"), + ) + }); + + match (c2ab_res?, c3ab_res?) { + (Some(c2ab), Some(c3ab)) => Ok(Some((c2ab, c3ab))), + _ => Ok(None), + } +} + +#[allow(clippy::too_many_arguments)] +fn run_c3_fold_chain( + blobs: &B, + prover: &Prover<'_>, + scope: B256, + e3: E3Id, + config: B256, + tag: &str, + items: &[(u32, ZkProof)], + total_slots: usize, + artifacts: &str, + priority: Priority, + stop_launching: Option<&AtomicBool>, +) -> Result, JobError> { + if items.is_empty() { + return Err(JobError::crypto( + "C3 fold requires at least one inner proof", + )); + } + let mut prior: Option<(ZkProof, CircuitName)> = None; + for (step, (slot, inner_zk)) in items.iter().enumerate() { + if stop_launching.is_some_and(|flag| flag.load(Ordering::Acquire)) { + return Ok(None); + } + let prior_hash = prior + .as_ref() + .map(|(p, _)| p.data.hash) + .unwrap_or(B256::ZERO); + let key = proofs::step_key( + scope, + &format!("c3-{tag}-{step}-{slot}-{total_slots}"), + &[config, prior_hash, inner_zk.data.hash], + ); + let work = proofs::work_dir(e3, &format!("fold-c3{tag}-{step}")); + let prior_ref = prior.as_ref(); + let next = proofs::prove_kept_step(blobs, prover, key, priority, |zk| { + let inner_loaded = proofs::load(blobs, inner_zk, CircuitName::ShareEncryption) + .map_err(|e| e.to_string())?; + let prior_loaded = prior_ref + .map(|(p, circuit)| proofs::load(blobs, p, *circuit)) + .transpose() + .map_err(|e| e.to_string())?; + generate_c3_fold_step( + zk, + &inner_loaded, + prior_loaded.as_ref(), + *slot, + total_slots, + &work, + artifacts, + ) + .map_err(|e| e.to_string()) + })?; + let circuit = if step == 0 { + CircuitName::C3FoldKernel + } else { + CircuitName::C3Fold + }; + prior = Some((next, circuit)); + } + Ok(prior) +} + /// A dealer's shares for this node, decrypted with its C0 secret key. fn decrypt_shares( key: &SecretKey, diff --git a/crates/ciphernode/jobs/src/lib.rs b/crates/ciphernode/jobs/src/lib.rs index 064cfa2..a982644 100644 --- a/crates/ciphernode/jobs/src/lib.rs +++ b/crates/ciphernode/jobs/src/lib.rs @@ -38,7 +38,14 @@ use rand_chacha::ChaCha20Rng; use rand_core::{OsRng, SeedableRng, TryRngCore}; use rayon::{ThreadPool, ThreadPoolBuilder}; use serde::{Deserialize, Serialize}; -use std::fmt::Display; +use std::{ + collections::HashMap, + fmt::Display, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Condvar, Mutex, PoisonError, + }, +}; use zeroize::Zeroizing; #[derive(Debug, thiserror::Error)] @@ -103,13 +110,146 @@ pub struct JobLimits { pub scope: B256, } +/// Boundary for running protocol jobs, implemented by [`JobRunner`]. +pub trait JobExecutor: Send + Sync + 'static { + fn run(&self, job: &Job, attempt: &Attempt) -> Result; + fn close(&self, e3: E3Id) -> std::io::Result<()>; + fn cancel_dkg_prefold(&self, _e3: E3Id) {} +} + +pub(crate) type DoneSignal = Arc<(Mutex, Condvar)>; +pub(crate) type PrefoldRegistration = (Cancel, Arc, DoneSignal); + +struct PrefoldSlot { + cancel: Cancel, + stop_launching: Arc, + done: DoneSignal, +} + +#[derive(Default)] +pub(crate) struct Prefolds { + entries: Mutex>, +} + +impl Prefolds { + /// Registers a new background pre-fold for `e3`, cancelling any prior one without blocking. + pub(crate) fn register(&self, e3: E3Id) -> PrefoldRegistration { + let cancel = Cancel::default(); + let stop_launching = Arc::new(AtomicBool::new(false)); + let done = Arc::new((Mutex::new(false), Condvar::new())); + let slot = PrefoldSlot { + cancel: cancel.clone(), + stop_launching: Arc::clone(&stop_launching), + done: Arc::clone(&done), + }; + if let Some(old) = self + .entries + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(e3, slot) + { + old.stop_launching.store(true, Ordering::Release); + old.cancel.cancel(); + } + (cancel, stop_launching, done) + } + + /// Signals a background pre-fold to let any in-flight `bb` step finish (so foreground + /// `FoldProofs` can join it via single-flight) but launch no further steps. + pub(crate) fn pause_new_steps(&self, e3: E3Id) { + if let Some(slot) = self + .entries + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(&e3) + { + slot.stop_launching.store(true, Ordering::Release); + } + } + + /// Immediately cancels any background pre-fold for `e3` without blocking the caller. + pub(crate) fn cancel(&self, e3: E3Id) { + if let Some(slot) = self + .entries + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(&e3) + { + slot.stop_launching.store(true, Ordering::Release); + slot.cancel.cancel(); + } + } + + /// Cancels any background pre-fold for `e3` and waits for its thread to finish before disk + /// cleanup removes the E3 work directory. + pub(crate) fn cancel_and_wait(&self, e3: E3Id) { + let slot = self + .entries + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(&e3); + if let Some(slot) = slot { + slot.stop_launching.store(true, Ordering::Release); + slot.cancel.cancel(); + let (lock, ready) = &*slot.done; + let mut finished = lock.lock().unwrap_or_else(PoisonError::into_inner); + while !*finished { + finished = ready.wait(finished).unwrap_or_else(PoisonError::into_inner); + } + } + } + + pub(crate) fn mark_finished(&self, e3: E3Id, done: &Arc<(Mutex, Condvar)>) { + let mut map = self.entries.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(slot) = map.get(&e3) { + if Arc::ptr_eq(&slot.done, done) { + map.remove(&e3); + } + } + drop(map); + let (lock, ready) = &**done; + let mut finished = lock.lock().unwrap_or_else(PoisonError::into_inner); + *finished = true; + ready.notify_all(); + } + + fn cancel_all_and_wait(&self) { + let slots: Vec = self + .entries + .lock() + .unwrap_or_else(PoisonError::into_inner) + .drain() + .map(|(_, slot)| slot) + .collect(); + for slot in &slots { + slot.stop_launching.store(true, Ordering::Release); + slot.cancel.cancel(); + } + for slot in slots { + let (lock, ready) = &*slot.done; + let mut finished = lock.lock().unwrap_or_else(PoisonError::into_inner); + while !*finished { + finished = ready.wait(finished).unwrap_or_else(PoisonError::into_inner); + } + } + } +} + pub struct JobRunner { blobs: S, cipher: Cipher, proofs: Proofs, - /// Every job runs here, so checks and cryptography together use at most its threads. - pool: ThreadPool, + /// Pure-CPU pool for fast verification checks and BFV math. Proving jobs run on the caller's + /// blocking thread and never park this pool while waiting on `ProveGate` or running `bb`. + check_pool: Arc, scope: B256, + prefolds: Arc, +} + +impl Drop for JobRunner { + fn drop(&mut self) { + self.prefolds.cancel_all_and_wait(); + } } impl JobRunner { @@ -119,23 +259,30 @@ impl JobRunner { proofs: Proofs, limits: JobLimits, ) -> Result { - let pool = ThreadPoolBuilder::new() + let check_pool = ThreadPoolBuilder::new() .num_threads(limits.threads.max(1)) - .thread_name(|index| format!("job-{index}")) + .thread_name(|index| format!("job-cpu-{index}")) .build() .map_err(JobError::crypto)?; Ok(Self { blobs, cipher, proofs, - pool, + check_pool: Arc::new(check_pool), scope: limits.scope, + prefolds: Arc::new(Prefolds::default()), }) } - /// Deletes the proving files of an E3 whose work ended. A proof still under way removes its - /// own files when it ends. + /// Cancels any speculative DKG pre-fold running in the background for `e3`. + pub fn cancel_dkg_prefold(&self, e3: E3Id) { + self.prefolds.cancel(e3); + } + + /// Deletes the proving files of an E3 whose work ended. Any background pre-fold for `e3` is + /// cancelled and joined first so it cannot write back into the removed directory. pub fn close(&self, e3: E3Id) -> std::io::Result<()> { + self.prefolds.cancel_and_wait(e3); match &self.proofs { Proofs::Circuits(circuits) => circuits.close(e3), #[cfg(any(test, feature = "testing"))] @@ -144,7 +291,10 @@ impl JobRunner { } pub fn run(&self, job: &Job, attempt: &Attempt) -> Result { - self.pool.install(|| { + if attempt.cancel.is_cancelled() { + return Err(JobError::Cancelled); + } + let execute = || { if attempt.cancel.is_cancelled() { return Err(JobError::Cancelled); } @@ -158,42 +308,75 @@ impl JobRunner { .run_accusation(&job.params, work) .map(WorkResult::Accusation), } - }) + }; + // Non-proving jobs (checks, accusations) run on `check_pool` so their parallel math and + // verification work is never starved by proving jobs waiting on `ProveGate`. + if job.work.proves() { + execute() + } else { + self.check_pool.install(execute) + } } fn jobs<'a>( &'a self, job: &Job, attempt: &'a Attempt, - ) -> Result>, JobError> { + ) -> Result, S>, JobError> { let encoded = bincode::serialize(job).map_err(JobError::crypto)?; + let (prover, circuits) = match &self.proofs { + Proofs::Circuits(circuits) => ( + Some(circuits.for_attempt(attempt)), + Some((**circuits).clone()), + ), + #[cfg(any(test, feature = "testing"))] + Proofs::Placeholder => (None, None), + }; Ok(Jobs { e3: job.e3, job: keccak256(encoded), scope: self.scope, blobs: self.blobs.of(job.e3), + blob_store: Some(&self.blobs), cipher: &self.cipher, - prover: match &self.proofs { - Proofs::Circuits(circuits) => Some(circuits.for_attempt(attempt)), - #[cfg(any(test, feature = "testing"))] - Proofs::Placeholder => None, - }, + prover, + circuits, + check_pool: &self.check_pool, + prefolds: Some(&self.prefolds), }) } } +impl JobExecutor for JobRunner { + fn run(&self, job: &Job, attempt: &Attempt) -> Result { + JobRunner::run(self, job, attempt) + } + + fn close(&self, e3: E3Id) -> std::io::Result<()> { + JobRunner::close(self, e3) + } + + fn cancel_dkg_prefold(&self, e3: E3Id) { + JobRunner::cancel_dkg_prefold(self, e3); + } +} + /// A job's view: the store of its E3, and the circuits as this attempt uses them. -struct Jobs<'a, B> { +struct Jobs<'a, B, S = MemoryBlobs> { e3: E3Id, /// The hash of the job, the same for every attempt and after a restart. job: B256, scope: B256, blobs: B, + blob_store: Option<&'a S>, cipher: &'a Cipher, prover: Option>, + circuits: Option, + check_pool: &'a ThreadPool, + prefolds: Option<&'a Arc>, } -impl Jobs<'_, B> { +impl Jobs<'_, B, S> { fn seal(&self, secret: &[u8]) -> Result { Ok(self.blobs.put_sealed(&self.sealed(secret)?)?) } diff --git a/crates/ciphernode/jobs/src/proofs.rs b/crates/ciphernode/jobs/src/proofs.rs index 62fe66d..084effa 100644 --- a/crates/ciphernode/jobs/src/proofs.rs +++ b/crates/ciphernode/jobs/src/proofs.rs @@ -20,8 +20,16 @@ use e3_zk_config::CircuitName; use e3_zk_prover::Proof; use e3_zk_prover::{Cancel, Provable, ZkProver}; use num_bigint::BigInt; -use rayon::{ThreadPool, ThreadPoolBuilder}; -use std::{collections::BTreeSet, fmt::Display, fs, io}; +use rayon::prelude::*; +use std::{ + collections::{BTreeSet, HashMap}, + fmt::Display, + fs, io, + sync::{Arc, Condvar, Mutex, PoisonError}, + time::Duration, +}; + +const WAIT_POLL: Duration = Duration::from_millis(25); pub enum Proofs { /// Proofs only the mock verifiers of a test deployment accept. @@ -30,44 +38,244 @@ pub enum Proofs { Circuits(Box), } +/// Priority on [`ProveGate`]: foreground protocol proofs always acquire permits before background +/// speculative pre-folding steps. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Priority { + Foreground, + Background, +} + +struct GateState { + active: usize, + high_waiters: usize, +} + +struct ProveGate { + max_concurrent: usize, + total_threads: usize, + state: Mutex, + ready: Condvar, +} + +struct Permit<'a> { + gate: &'a ProveGate, + threads: usize, +} + +impl Drop for Permit<'_> { + fn drop(&mut self) { + let mut state = self + .gate + .state + .lock() + .unwrap_or_else(PoisonError::into_inner); + state.active = state.active.saturating_sub(1); + self.gate.ready.notify_all(); + } +} + +impl ProveGate { + fn new(max_concurrent: usize, total_threads: usize) -> Self { + Self { + max_concurrent: max_concurrent.max(1), + total_threads: total_threads.max(1), + state: Mutex::new(GateState { + active: 0, + high_waiters: 0, + }), + ready: Condvar::new(), + } + } + + fn acquire<'a>(&'a self, priority: Priority, cancel: &Cancel) -> Result, JobError> { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + if priority == Priority::Foreground { + state.high_waiters += 1; + let result = loop { + if cancel.is_cancelled() { + state.high_waiters -= 1; + self.ready.notify_all(); + break Err(JobError::Cancelled); + } + if state.active < self.max_concurrent { + state.high_waiters -= 1; + state.active += 1; + let planned = (state.active + state.high_waiters).clamp(1, self.max_concurrent); + let threads = (self.total_threads / planned).max(1); + break Ok(Permit { + gate: self, + threads, + }); + } + let (guard, _) = self + .ready + .wait_timeout(state, WAIT_POLL) + .unwrap_or_else(PoisonError::into_inner); + state = guard; + }; + result + } else { + loop { + if cancel.is_cancelled() { + return Err(JobError::Cancelled); + } + if state.active < self.max_concurrent && state.high_waiters == 0 { + state.active += 1; + let planned = state.active.clamp(1, self.max_concurrent); + let threads = (self.total_threads / planned).max(1); + return Ok(Permit { + gate: self, + threads, + }); + } + let (guard, _) = self + .ready + .wait_timeout(state, WAIT_POLL) + .unwrap_or_else(PoisonError::into_inner); + state = guard; + } + } + } +} + +enum InFlightState { + Running, + Ready(ZkProof), + Failed, +} + +struct InFlight { + state: Mutex, + done: Condvar, +} + +impl InFlight { + fn new() -> Self { + Self { + state: Mutex::new(InFlightState::Running), + done: Condvar::new(), + } + } + + fn finish(&self, outcome: Option) { + let mut guard = self.state.lock().unwrap_or_else(PoisonError::into_inner); + *guard = match outcome { + Some(proof) => InFlightState::Ready(proof), + None => InFlightState::Failed, + }; + self.done.notify_all(); + } + + fn wait(&self, cancel: &Cancel) -> Result, JobError> { + let mut guard = self.state.lock().unwrap_or_else(PoisonError::into_inner); + loop { + match &*guard { + InFlightState::Ready(proof) => return Ok(Some(proof.clone())), + InFlightState::Failed => return Ok(None), + InFlightState::Running => { + if cancel.is_cancelled() { + return Err(JobError::Cancelled); + } + let (next, _) = self + .done + .wait_timeout(guard, WAIT_POLL) + .unwrap_or_else(PoisonError::into_inner); + guard = next; + } + } + } + } +} + +struct InFlightGuard<'a> { + map: &'a Mutex>>, + key: B256, + entry: Arc, + completed: bool, +} + +impl InFlightGuard<'_> { + fn complete(mut self, proof: ZkProof) { + self.completed = true; + self.map + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(&self.key); + self.entry.finish(Some(proof)); + } +} + +impl Drop for InFlightGuard<'_> { + fn drop(&mut self) { + if !self.completed { + self.map + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(&self.key); + self.entry.finish(None); + } + } +} + +struct CircuitsInner { + prover: ZkProver, + verify_threads: usize, + gate: ProveGate, + in_flight: Mutex>>, +} + /// The compiled circuits and `bb`. A proof and its witness can hold gigabytes under the secure -/// parameters, so proofs run on their own pool of `limit` threads: at most `limit` run at once. -/// A thread that waits for the pool keeps working for its own, and a proof's inner joins run on -/// this pool, so no proof waits for a thread that waits for it. +/// parameters, so proving runs behind a bounded priority gate of `limit` concurrent `bb` +/// invocations with dynamic per-proof thread allocation across the machine's thread budget. +#[derive(Clone)] pub struct Circuits { - prover: ZkProver, - pool: ThreadPool, + inner: Arc, } impl Circuits { - /// `threads` is how many threads each `bb` may use. + /// `threads` is how many threads each `bb` may use when `limit` run concurrently. pub fn new(prover: ZkProver, limit: usize, threads: usize) -> Result { - let pool = ThreadPoolBuilder::new() - .num_threads(limit.max(1)) - .thread_name(|index| format!("proof-{index}")) - .build() - .map_err(JobError::crypto)?; - let prover = prover.with_threads(threads); - Ok(Self { prover, pool }) + let total_threads = threads.max(1).saturating_mul(limit.max(1)); + Self::with_thread_budget(prover, limit, total_threads) + } + + /// `limit` is the maximum concurrent `bb` provers; `total_threads` is the total thread budget + /// dynamically divided across currently active/queued proofs so solo proofs use all threads. + pub fn with_thread_budget( + prover: ZkProver, + limit: usize, + total_threads: usize, + ) -> Result { + let total = total_threads.max(1); + let verify_threads = (total / 4).clamp(1, 2); + Ok(Self { + inner: Arc::new(CircuitsInner { + prover: prover.with_threads(verify_threads), + verify_threads, + gate: ProveGate::new(limit, total), + in_flight: Mutex::new(HashMap::new()), + }), + }) } /// The circuits as one attempt at a job uses them: it stops with the attempt's token, and /// after a failed attempt `bb` trades speed for a smaller memory peak. pub(crate) fn for_attempt<'a>(&'a self, attempt: &'a Attempt) -> Prover<'a> { - let zk = self.prover.with_cancel(attempt.cancel.clone()); + let zk = self.inner.prover.with_cancel(attempt.cancel.clone()); let zk = match attempt.number { 0 => zk, _ => zk.with_slow_low_memory(), }; Prover { zk, - pool: &self.pool, + inner: &self.inner, cancel: &attempt.cancel, } } pub(crate) fn close(&self, e3: E3Id) -> io::Result<()> { - match fs::remove_dir_all(self.prover.work_dir().join(directory(e3))) { + match fs::remove_dir_all(self.inner.prover.work_dir().join(directory(e3))) { Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), _ => Ok(()), } @@ -77,11 +285,15 @@ impl Circuits { /// One attempt's view of the circuits. pub(crate) struct Prover<'a> { zk: ZkProver, - pool: &'a ThreadPool, + inner: &'a CircuitsInner, cancel: &'a Cancel, } impl Prover<'_> { + pub(crate) fn max_concurrent(&self) -> usize { + self.inner.gate.max_concurrent + } + fn stop_if_cancelled(&self) -> Result<(), JobError> { match self.cancel.is_cancelled() { true => Err(JobError::Cancelled), @@ -95,21 +307,33 @@ impl Prover<'_> { result.map_err(JobError::crypto) } - /// Runs `prove` on the proof pool, once one of its threads is free. + /// Runs `prove` behind the priority proof gate at foreground priority. + #[cfg(test)] pub(crate) fn proving( &self, prove: impl FnOnce(&ZkProver) -> Result + Send, + ) -> Result { + self.proving_with_priority(Priority::Foreground, prove) + } + + /// Runs `prove` behind the priority proof gate, dynamically sizing `bb`'s thread count to the + /// live concurrency so solo proofs get the full budget while concurrent proofs share it cleanly. + pub(crate) fn proving_with_priority( + &self, + priority: Priority, + prove: impl FnOnce(&ZkProver) -> Result + Send, ) -> Result { self.stop_if_cancelled()?; - self.pool.install(|| { - self.stop_if_cancelled()?; - self.outcome(prove(&self.zk)) - }) + let permit = self.inner.gate.acquire(priority, self.cancel)?; + self.stop_if_cancelled()?; + let zk = self.zk.with_threads(permit.threads); + self.outcome(prove(&zk)) } fn verify(&self, proof: &Proof, work: &str, artifacts: &str) -> Result { self.stop_if_cancelled()?; - self.outcome(self.zk.verify_proof(proof, work, 0, artifacts)) + let zk = self.zk.with_threads(self.inner.verify_threads); + self.outcome(zk.verify_proof(proof, work, 0, artifacts)) } } @@ -125,11 +349,88 @@ fn settle( } /// Each E3's proofs run `bb` in a directory of its own, which goes when the E3's work ends. -fn directory(e3: E3Id) -> String { +pub(crate) fn directory(e3: E3Id) -> String { format!("{}-{}", e3.chain_id, e3.number) } -impl Jobs<'_, B> { +/// Deterministic work subdirectory for `name` under `e3`'s work directory. +pub(crate) fn work_dir(e3: E3Id, name: &str) -> String { + format!("{}/{name}", directory(e3)) +} + +/// Directory of compiled circuits for `params`. +pub(crate) fn artifacts_dir(params: &CryptoParams) -> Result { + let profile = trbfv::profile(params)?; + Ok(profile.artifacts_dir_for_committee(params.committee_size)?) +} + +/// Content-addressed checkpoint key for a single proof step. +pub(crate) fn step_key(scope: B256, label: &str, inputs: &[B256]) -> B256 { + let mut buf = Vec::with_capacity(32 + label.len() + inputs.len() * 32); + buf.extend_from_slice(scope.as_slice()); + buf.extend_from_slice(label.as_bytes()); + for input in inputs { + buf.extend_from_slice(input.as_slice()); + } + keccak256(&buf) +} + +/// Single-flight, checkpointed proving step shared between speculative background pre-folding +/// and foreground fold/aggregation jobs. +pub(crate) fn prove_kept_step( + blobs: &B, + prover: &Prover<'_>, + key: B256, + priority: Priority, + prove: impl FnOnce(&ZkProver) -> Result + Send, +) -> Result { + let mut prove = Some(prove); + loop { + prover.stop_if_cancelled()?; + if let Some(kept) = blobs.kept(&key)? { + return bincode::deserialize(&kept).map_err(JobError::crypto); + } + let existing = { + let mut map = prover + .inner + .in_flight + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(entry) = map.get(&key) { + Some(Arc::clone(entry)) + } else { + let entry = Arc::new(InFlight::new()); + map.insert(key, Arc::clone(&entry)); + drop(map); + let guard = InFlightGuard { + map: &prover.inner.in_flight, + key, + entry, + completed: false, + }; + if let Some(kept) = blobs.kept(&key)? { + let proof: ZkProof = bincode::deserialize(&kept).map_err(JobError::crypto)?; + guard.complete(proof.clone()); + return Ok(proof); + } + let prove_fn = prove.take().expect("single-flight runs closure once"); + let raw = prover.proving_with_priority(priority, prove_fn)?; + let proof = store(blobs, &raw)?; + let encoded = bincode::serialize(&proof).map_err(JobError::crypto)?; + blobs.keep(&key, &encoded)?; + guard.complete(proof.clone()); + return Ok(proof); + } + }; + if let Some(entry) = existing { + if let Some(proof) = entry.wait(prover.cancel)? { + return Ok(proof); + } + } + } +} + +impl Jobs<'_, B, S> { /// The circuits, or none where placeholders stand in. pub(crate) fn prover(&self) -> Option<&Prover<'_>> { self.prover.as_ref() @@ -149,15 +450,10 @@ impl Jobs<'_, B> { work: &str, ) -> Result { let key = self.proof_key(work); - if let Some(kept) = self.blobs.kept(&key)? { - return bincode::deserialize(&kept).map_err(JobError::crypto); - } let (work, artifacts) = (self.work(work), self.artifacts(params)?); - let proof = prover.proving(|zk| circuit.prove(zk, config, input, &work, &artifacts))?; - let proof = store(&self.blobs, &proof)?; - let encoded = bincode::serialize(&proof).map_err(JobError::crypto)?; - self.blobs.keep(&key, &encoded)?; - Ok(proof) + prove_kept_step(&self.blobs, prover, key, Priority::Foreground, |zk| { + circuit.prove(zk, config, input, &work, &artifacts) + }) } fn proof_key(&self, work: &str) -> B256 { @@ -175,13 +471,38 @@ impl Jobs<'_, B> { let artifacts = self.artifacts(params)?; // A message can repeat one proof to make the node verify it many times. let mut seen = BTreeSet::new(); - for (proof_type, proof) in proofs { - if !seen.insert((proof_type, proof)) { - continue; - } + let unique: Vec<(ProofType, &ZkProof)> = proofs + .into_iter() + .filter(|(proof_type, proof)| seen.insert((*proof_type, *proof))) + .collect(); + if unique.is_empty() { + return Ok(Verdict::Valid); + } + if unique.len() == 1 { + let (proof_type, proof) = unique[0]; let loaded = load(&self.blobs, proof, circuit(proof_type))?; - let valid = prover.verify(&loaded, &self.work("verify"), &artifacts)?; - if !valid { + if !prover.verify(&loaded, &self.work("verify"), &artifacts)? { + return Ok(Verdict::Fails(Fault { + proof_type, + proof: proof.clone(), + data_hash: self.data_hash(proof)?, + })); + } + return Ok(Verdict::Valid); + } + // Verify distinct proofs in parallel on the CPU check pool while returning the first + // failing proof in deterministic input order. + let results: Vec> = self.check_pool.install(|| { + unique + .par_iter() + .map(|(proof_type, proof)| { + let loaded = load(&self.blobs, proof, circuit(*proof_type))?; + prover.verify(&loaded, &self.work("verify"), &artifacts) + }) + .collect() + }); + for ((proof_type, proof), valid) in unique.into_iter().zip(results) { + if !valid? { return Ok(Verdict::Fails(Fault { proof_type, proof: proof.clone(), @@ -323,4 +644,50 @@ mod tests { ); assert_eq!(settle(Verdict::Valid, || Ok(true)).unwrap(), Verdict::Valid); } + + #[test] + fn foreground_proof_preempts_background_prefold_waiters() { + use std::{ + sync::{Arc, Barrier}, + thread, + }; + + let gate = Arc::new(ProveGate::new(1, 4)); + let cancel = Cancel::default(); + let holder = gate.acquire(Priority::Foreground, &cancel).unwrap(); + assert_eq!(holder.threads, 4); + + let bg_waiting = Arc::new(Barrier::new(2)); + let fg_waiting = Arc::new(Barrier::new(2)); + let order = Arc::new(Mutex::new(Vec::new())); + + let g1 = Arc::clone(&gate); + let b1 = Arc::clone(&bg_waiting); + let o1 = Arc::clone(&order); + let c1 = cancel.clone(); + let bg = thread::spawn(move || { + b1.wait(); + let _p = g1.acquire(Priority::Background, &c1).unwrap(); + o1.lock().unwrap().push("background"); + }); + bg_waiting.wait(); + thread::sleep(Duration::from_millis(15)); + + let g2 = Arc::clone(&gate); + let f2 = Arc::clone(&fg_waiting); + let o2 = Arc::clone(&order); + let c2 = cancel.clone(); + let fg = thread::spawn(move || { + f2.wait(); + let _p = g2.acquire(Priority::Foreground, &c2).unwrap(); + o2.lock().unwrap().push("foreground"); + }); + fg_waiting.wait(); + thread::sleep(Duration::from_millis(15)); + + drop(holder); + fg.join().unwrap(); + bg.join().unwrap(); + assert_eq!(*order.lock().unwrap(), vec!["foreground", "background"]); + } } diff --git a/crates/ciphernode/jobs/src/tests.rs b/crates/ciphernode/jobs/src/tests.rs index 3033a20..98d83ba 100644 --- a/crates/ciphernode/jobs/src/tests.rs +++ b/crates/ciphernode/jobs/src/tests.rs @@ -522,3 +522,151 @@ fn c3_proofs_must_name_this_node_s_key_and_its_rows() { missing.pop(); assert!(!checks(missing, rows_for(&c2b))); } + +#[test] +fn single_flight_prove_kept_step_runs_once_and_reuses_kept_cache() { + use crate::proofs::{prove_kept_step, Priority}; + use crate::Circuits; + use e3_utils::utility_types::ArcBytes; + use e3_zk_config::CircuitName; + use e3_zk_prover::{BBPath, Proof, ZkBackend, ZkProver}; + use std::{ + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Barrier, + }, + thread, + time::Duration, + }; + + let backend = ZkBackend::new( + BBPath::Custom("bb".into()), + "circuits".into(), + "work".into(), + ); + let circuits = Circuits::with_thread_budget(ZkProver::new(&backend), 2, 4).unwrap(); + let blobs = MemoryBlobs::default().of(E3); + let key = B256::repeat_byte(0x42); + let calls = Arc::new(AtomicUsize::new(0)); + let started = Arc::new(Barrier::new(2)); + + let (first, second) = thread::scope(|scope| { + let a = scope.spawn(|| { + let attempt = Attempt::default(); + let prover = circuits.for_attempt(&attempt); + prove_kept_step(&blobs, &prover, key, Priority::Background, |_| { + calls.fetch_add(1, Ordering::SeqCst); + started.wait(); + thread::sleep(Duration::from_millis(40)); + Ok::<_, JobError>(Proof::new( + CircuitName::C2abFold, + ArcBytes::from_bytes(b"proof-bytes"), + ArcBytes::from_bytes(&[7u8; 32]), + )) + }) + .unwrap() + }); + let b = scope.spawn(|| { + started.wait(); + let attempt = Attempt::default(); + let prover = circuits.for_attempt(&attempt); + prove_kept_step(&blobs, &prover, key, Priority::Foreground, |_| { + calls.fetch_add(1, Ordering::SeqCst); + Ok::<_, JobError>(Proof::new( + CircuitName::C2abFold, + ArcBytes::from_bytes(b"should-not-run"), + ArcBytes::from_bytes(&[9u8; 32]), + )) + }) + .unwrap() + }); + (a.join().unwrap(), b.join().unwrap()) + }); + + assert_eq!(first, second); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + // A subsequent lookup hits `blobs.kept` directly without running `prove`. + let attempt = Attempt::default(); + let prover = circuits.for_attempt(&attempt); + let third = prove_kept_step( + &blobs, + &prover, + key, + Priority::Foreground, + |_| -> Result { + calls.fetch_add(1, Ordering::SeqCst); + unreachable!("kept cache should satisfy repeat request") + }, + ) + .unwrap(); + assert_eq!(third, first); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn checks_are_not_starved_while_proof_gate_is_saturated() { + use crate::Circuits; + use e3_zk_prover::{BBPath, ZkBackend, ZkProver}; + use std::{ + sync::{Arc, Barrier}, + thread, + time::{Duration, Instant}, + }; + + let backend = ZkBackend::new( + BBPath::Custom("bb".into()), + "circuits".into(), + "work".into(), + ); + let circuits = Circuits::with_thread_budget(ZkProver::new(&backend), 1, 2).unwrap(); + let blobs = MemoryBlobs::default(); + let cipher = Cipher::from_password("node").await.unwrap(); + let runner = runner(blobs.clone(), cipher, 7); + let DkgWorkResult::EncryptionKeyMade(own) = dkg(&runner, DkgWork::MakeEncryptionKey) else { + panic!("expected encryption key"); + }; + + let saturated = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + let c1 = circuits.clone(); + let s1 = Arc::clone(&saturated); + let r1 = Arc::clone(&release); + let blocker = thread::spawn(move || { + let attempt = Attempt::default(); + let prover = c1.for_attempt(&attempt); + prover + .proving(|_| { + s1.wait(); + r1.wait(); + Ok::<_, JobError>(()) + }) + .unwrap(); + }); + + saturated.wait(); + let started = Instant::now(); + let checked = dkg( + &runner, + DkgWork::CheckEncryptionKey { + sender: Address::repeat_byte(1), + key: own.public, + proof: own.proof.clone(), + }, + ); + let elapsed = started.elapsed(); + release.wait(); + blocker.join().unwrap(); + + assert_eq!( + checked, + DkgWorkResult::EncryptionKeyChecked { + sender: Address::repeat_byte(1), + verdict: Verdict::Valid, + } + ); + assert!( + elapsed < Duration::from_secs(1), + "check took {elapsed:?} while prove gate was saturated" + ); +} diff --git a/crates/ciphernode/jobs/src/trbfv.rs b/crates/ciphernode/jobs/src/trbfv.rs index 17b818c..b95320f 100644 --- a/crates/ciphernode/jobs/src/trbfv.rs +++ b/crates/ciphernode/jobs/src/trbfv.rs @@ -19,8 +19,47 @@ use e3_trbfv::TrBFVConfig; use e3_utils::utility_types::ArcBytes; use fhe::{bfv::BfvParameters, mbfv::CommonRandomPoly}; use fhe_traits::Serialize as _; -use std::collections::HashSet; -use std::sync::Arc; +use std::{ + collections::{HashMap, HashSet}, + sync::{Arc, OnceLock, RwLock}, +}; + +struct CachedProfile { + threshold_params: Arc, + dkg_params: Arc, + encoded_threshold_params: ArcBytes, + crp_poly: CommonRandomPoly, + crp_bytes: ArcBytes, +} + +static PROFILE_CACHE: OnceLock>>> = OnceLock::new(); + +fn cached_profile(params: &CryptoParams) -> Result, JobError> { + let profile = profile(params)?; + let cache = PROFILE_CACHE.get_or_init(|| RwLock::new(HashMap::new())); + if let Ok(guard) = cache.read() { + if let Some(entry) = guard.get(&profile) { + return Ok(Arc::clone(entry)); + } + } + let threshold_params = BfvParamSet::from(profile.threshold_preset()).build_arc(); + let dkg_params = profile.dkg_parameters().build_arc(); + let encoded_threshold_params = ArcBytes::from_bytes(&encode_bfv_params(&threshold_params)); + let crp_poly = create_deterministic_crp_from_default_seed(&threshold_params); + let crp_bytes = ArcBytes::from_bytes(&crp_poly.to_bytes()); + let entry = Arc::new(CachedProfile { + threshold_params, + dkg_params, + encoded_threshold_params, + crp_poly, + crp_bytes, + }); + if let Ok(mut guard) = cache.write() { + Ok(Arc::clone(guard.entry(profile).or_insert(entry))) + } else { + Ok(entry) + } +} /// The crypto configurations this build admits, as the Interfold contract records them for a /// request: each admitted profile's ID for each committee size it supports, with its parameter set. @@ -51,19 +90,18 @@ pub(crate) fn threshold_preset(params: &CryptoParams) -> Result Result, JobError> { - Ok(BfvParamSet::from(profile(params)?.threshold_preset()).build_arc()) + Ok(Arc::clone(&cached_profile(params)?.threshold_params)) } pub(crate) fn dkg_params(params: &CryptoParams) -> Result, JobError> { - Ok(profile(params)?.dkg_parameters().build_arc()) + Ok(Arc::clone(&cached_profile(params)?.dkg_params)) } pub(crate) fn config(params: &CryptoParams) -> Result { let committee = params.committee_size.values(); - let threshold = threshold_params(params)?; - let encoded = encode_bfv_params(&threshold); + let cached = cached_profile(params)?; Ok(TrBFVConfig::new( - ArcBytes::from_bytes(&encoded), + cached.encoded_threshold_params.clone(), committee.n as u64, committee.threshold as u64, )) @@ -71,13 +109,11 @@ pub(crate) fn config(params: &CryptoParams) -> Result { /// Every party derives the same common random polynomial from a fixed seed, not the E3's. pub(crate) fn crp_poly(params: &CryptoParams) -> Result { - Ok(create_deterministic_crp_from_default_seed( - &threshold_params(params)?, - )) + Ok(cached_profile(params)?.crp_poly.clone()) } pub(crate) fn crp(params: &CryptoParams) -> Result { - Ok(ArcBytes::from_bytes(&crp_poly(params)?.to_bytes())) + Ok(cached_profile(params)?.crp_bytes.clone()) } pub(crate) fn lambda(params: &CryptoParams) -> Result { diff --git a/crates/ciphernode/node/src/effects.rs b/crates/ciphernode/node/src/effects.rs index 1a4ba8b..43c6b50 100644 --- a/crates/ciphernode/node/src/effects.rs +++ b/crates/ciphernode/node/src/effects.rs @@ -4,22 +4,22 @@ // without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. -//! Carries out the machine's effects. Each effect stays in the outbox until it is done: a job, a -//! signature or a fetch once its result is journaled, a gossip once it is published, a submission -//! once the writer finished it, and any effect the machine no longer owes. +//! Carries out the machine's effects. Each durable effect stays in the outbox until it is done: a +//! job, a signature or a fetch once its result is journaled, a gossip once it is published, a +//! submission once the writer finished it, and any effect the machine no longer owes. use crate::{ notes::NoteFeed, runtime::{now, Event}, }; -use alloy_primitives::keccak256; +use alloy_primitives::{keccak256, Bytes, B256}; use alloy_signer::SignerSync; use alloy_signer_local::PrivateKeySigner; use e3_blobs::BlobStore; use e3_chain::{Account, Rpc, Writer}; use e3_data_availability::{DataAvailabilityReader, DataReference}; use e3_engine::{EffectKey, Pending}; -use e3_jobs::{Attempt, Cancel, JobError, JobRunner}; +use e3_jobs::{Attempt, Cancel, JobError, JobExecutor, JobRunner}; use e3_p2p::Network; use e3_protocol::{ node::{ @@ -27,7 +27,7 @@ use e3_protocol::{ JobDone, Node, PeerMessage, Scope, Signed, Signing, Submission, }, wire::Envelope, - E3Id, + BlobRef, E3Id, }; use e3_utils::limited::Limited; use std::{ @@ -41,6 +41,21 @@ use tokio::{ }; use tracing::{debug, error, warn}; +/// Signing boundary for operator-owned hashes (protocol attestations, gossip envelopes). +pub(crate) trait OperatorSigner: Send + Sync + 'static { + fn sign_hash(&self, hash: &B256) -> Bytes; +} + +impl OperatorSigner for PrivateKeySigner { + fn sign_hash(&self, hash: &B256) -> Bytes { + self.sign_hash_sync(hash) + .expect("a local key signs any hash") + .as_bytes() + .to_vec() + .into() + } +} + /// A wait between attempts that doubles up to a limit. #[derive(Clone, Copy, Debug)] pub(crate) struct Backoff { @@ -117,11 +132,11 @@ impl Task { } } -pub(crate) struct Effects { +pub(crate) struct Effects, O = PrivateKeySigner> { pub(crate) rpc: Arc, - pub(crate) operator: PrivateKeySigner, + pub(crate) operator: O, pub(crate) blobs: B, - pub(crate) jobs: Arc>, + pub(crate) jobs: Arc, pub(crate) writer: Arc>, pub(crate) network: Arc, pub(crate) availability: Arc, @@ -136,11 +151,11 @@ pub(crate) struct Effects { } /// What `Effects` is made of. -pub(crate) struct EffectParts { +pub(crate) struct EffectParts, O = PrivateKeySigner> { pub(crate) rpc: Arc, - pub(crate) operator: PrivateKeySigner, + pub(crate) operator: O, pub(crate) blobs: B, - pub(crate) jobs: Arc>, + pub(crate) jobs: Arc, pub(crate) writer: Arc>, pub(crate) network: Arc, pub(crate) availability: Arc, @@ -150,14 +165,16 @@ pub(crate) struct EffectParts { pub(crate) proof_slots: usize, } -impl Effects +impl Effects where R: Rpc + Send + Sync + 'static, A: Account + Send + Sync + 'static, N: Network, B: BlobStore, + J: JobExecutor, + O: OperatorSigner, { - pub(crate) fn new(parts: EffectParts) -> Self { + pub(crate) fn new(parts: EffectParts) -> Self { Self { rpc: parts.rpc, operator: parts.operator, @@ -187,9 +204,10 @@ where now.push(Event::Result(key, self.sign(signing))); continue; } + // `Effect::Note` is non-durable (`Node::is_durable_effect == false`), so it is + // recorded directly to the note feed without a journal outbox round-trip. Effect::Note(note) => { self.notes.record(crate::runtime::now(), note); - now.push(Event::Done(key)); continue; } Effect::Gossip(message) => self.gossip(key, message), @@ -317,13 +335,7 @@ where let signatures = signing .hashes .iter() - .map(|hash| { - let signature = self - .operator - .sign_hash_sync(hash) - .expect("a local key signs any hash"); - signature.as_bytes().to_vec().into() - }) + .map(|hash| self.operator.sign_hash(hash)) .collect(); Input::Signed(Signed { e3: signing.e3, @@ -336,12 +348,11 @@ where let sent_at = now(); let signature = self .operator - .sign_hash_sync(&Envelope::signing_hash(&message, sent_at)) - .expect("a local key signs any hash"); + .sign_hash(&Envelope::signing_hash(&message, sent_at)); let envelope = Envelope { message, sent_at, - signature: signature.as_bytes().to_vec().into(), + signature, }; let (network, events) = (self.network.clone(), self.events.clone()); tokio::spawn(async move { @@ -416,19 +427,39 @@ where let mut backoff = Backoff::CIPHERTEXT; loop { match availability.retrieve(&reference).await { - Ok(bytes) if keccak256(&bytes) == fetch.data.hash => { - match blobs.put(fetch.e3, &bytes) { - Ok(blob) => { + Ok(bytes) => { + let store = blobs.clone(); + let e3 = fetch.e3; + let expected_hash = fetch.data.hash; + let stored = tokio::task::spawn_blocking(move || { + if keccak256(&bytes) != expected_hash { + return Ok(None); + } + let blob = BlobRef { + hash: expected_hash, + len: bytes.len() as u64, + }; + store.put_verified(e3, &blob, &bytes)?; + Ok::<_, e3_blobs::BlobError>(Some(blob)) + }) + .await; + match stored { + Ok(Ok(Some(blob))) => { let fetched = Input::Fetched(Fetched { e3: fetch.e3, blob }); let _ = events.send(Event::Result(key, fetched)).await; return; } - Err(failure) => { + Ok(Ok(None)) => { + warn!(e3 = %fetch.e3, "the availability layer sent other bytes") + } + Ok(Err(failure)) => { error!(e3 = %fetch.e3, %failure, "storing a ciphertext failed") } + Err(panic) => { + error!(e3 = %fetch.e3, %panic, "storing a ciphertext panicked") + } } } - Ok(_) => warn!(e3 = %fetch.e3, "the availability layer sent other bytes"), Err(failure) => { warn!(e3 = %fetch.e3, %failure, "fetching the ciphertext failed") } diff --git a/crates/ciphernode/node/src/preflight.rs b/crates/ciphernode/node/src/preflight.rs index e3cacd0..9fbcddb 100644 --- a/crates/ciphernode/node/src/preflight.rs +++ b/crates/ciphernode/node/src/preflight.rs @@ -245,11 +245,8 @@ async fn proofs(config: &Config, deadline: Instant) -> anyhow::Result<(Proofs, u status => return Err(Refused::ProverNotReady(format!("{status:?}")).into()), } } - let circuits = Circuits::new( - ZkProver::new(&backend), - capacity.proofs, - capacity.bb_threads, - )?; + let circuits = + Circuits::with_thread_budget(ZkProver::new(&backend), capacity.proofs, capacity.threads)?; Ok(( Proofs::Circuits(Box::new(circuits)), capacity.threads, diff --git a/crates/ciphernode/node/src/runtime.rs b/crates/ciphernode/node/src/runtime.rs index 9445f25..f7e1666 100644 --- a/crates/ciphernode/node/src/runtime.rs +++ b/crates/ciphernode/node/src/runtime.rs @@ -15,7 +15,7 @@ use alloy_signer_local::PrivateKeySigner; use e3_blobs::BlobStore; use e3_chain::{Account, Contracts, ReadError, Reader, Rpc, RpcError, Writer}; use e3_data_availability::DataAvailabilityReader; -use e3_engine::{EffectKey, Engine}; +use e3_engine::{BatchOp, EffectKey, Engine}; use e3_jobs::JobRunner; use e3_journal::Journal; use e3_p2p::{Inbox, Network}; @@ -35,6 +35,9 @@ use std::{ use tokio::{sync::mpsc, task::JoinSet, time::Instant}; use tracing::{debug, info, warn}; +/// Maximum queued events collapsed into a single atomic journal group-commit transaction. +const MAX_BATCH_OPS: usize = 128; + /// How long a failed chain read waits before it runs again. const RETRY_AFTER: Duration = Duration::from_secs(30); @@ -174,6 +177,7 @@ where let mut recovered = Some(recovered); sweep(&parts.blobs, engine.machine()); let mut admitted = engine.machine().admission(); + let mut admission_epoch = engine.machine().admission_epoch(); parts.network.admit(admitted.clone()); let (chain_id, start_block) = (settings.contracts.chain_id, settings.start_block); let from = engine @@ -203,6 +207,7 @@ where AbortOnDrop(tokio::spawn(serving)) }); let mut essential: JoinSet = JoinSet::new(); + let mut cleanup: JoinSet<()> = JoinSet::new(); let (heartbeat, poll, sender) = (parts.heartbeat, settings.poll_interval, events.clone()); let startup_timeout = settings.startup_timeout; essential.spawn(read_chain( @@ -252,6 +257,7 @@ where } let mut drained = false; loop { + while cleanup.try_join_next().is_some() {} let machine = engine.machine(); if machine.drained() && !drained { info!( @@ -261,7 +267,7 @@ where ); } drained = machine.drained(); - let event = match queue.pop_front() { + let first = match queue.pop_front() { Some(event) => event, None => tokio::select! { event = next_event(&mut receiver, engine.next_deadline()) => event?, @@ -291,84 +297,140 @@ where _ = board_update.tick() => { board.machine(engine.machine()); board.peers(effects.network.connected()); + board.adapter_stats( + effects.blobs.cache_stats(), + effects.network.stats(), + ); continue; } ended = essential.join_next() => return Err(ended_task(ended)), () = &mut stop => return Ok(engine), }, }; - let (input, answers) = match event { - Event::Input(input) => (input, None), - Event::Result(key, input) => (input, Some(key)), - Event::Done(key) => { - engine.acknowledge(key)?; + + if let Event::CaughtUp(listed) = first { + let machine = engine.machine(); + // The node's operators come from logs, so the chain shows whether it read them + // all. A chain node behind the journal cannot say yet. + let current = machine + .applied(chain_id) + .is_none_or(|at| at.block <= listed.block); + let read = machine.listed(chain_id); + if current && read != listed.operators { + return Err(NodeError::MissedRegistrations { + listed: listed.operators, + block: listed.block, + read, + start_block, + }); + } + let Some(recovered) = recovered.take() else { continue; + }; + let (owed, over): (Vec<_>, Vec<_>) = recovered + .into_iter() + .partition(|work| machine.owes(&work.effect.e3(), work.effect.scope())); + if !over.is_empty() { + let ops: Vec> = + over.into_iter().map(|work| BatchOp::Ack(work.key)).collect(); + let op_count = ops.len(); + let (next, _) = tokio::task::spawn_blocking(move || engine.apply_batch(ops)) + .await + .map_err(|e| NodeError::TaskPanicked("journal commit", e.to_string()))??; + engine = next; + board.record_batch(op_count); } - Event::CaughtUp(listed) => { - let machine = engine.machine(); - // The node's operators come from logs, so the chain shows whether it read them - // all. A chain node behind the journal cannot say yet. - let current = machine - .applied(chain_id) - .is_none_or(|at| at.block <= listed.block); - let read = machine.listed(chain_id); - if current && read != listed.operators { - return Err(NodeError::MissedRegistrations { - listed: listed.operators, - block: listed.block, - read, - start_block, - }); - } - let Some(recovered) = recovered.take() else { - continue; - }; - let (owed, over): (Vec<_>, Vec<_>) = recovered - .into_iter() - .partition(|work| machine.owes(&work.effect.e3(), work.effect.scope())); - for work in over { - engine.acknowledge(work.key)?; + queue.extend(effects.dispatch(owed)); + if !drain && engine.machine().draining() { + queue.push_back(Event::Input(Input::Drain(false))); + } + // The recovered calls go out again from here, so a call no one sends now is one + // the node no longer owes. + let keeper = keeper.clone(); + essential.spawn(async move { + match free_abandoned_nonces(|| keeper.free_abandoned()).await {} + }); + continue; + } + + // Group-commit all immediately ready events (from `queue` and `receiver`) in one + // atomic `redb` write transaction off the Tokio worker thread. Stop before any + // `Event::CaughtUp` so all preceding chain facts commit first. + let ts = now(); + let mut ops: Vec> = Vec::with_capacity(16); + push_batch_op(&mut ops, ts, first); + while ops.len() < MAX_BATCH_OPS { + match queue.front() { + Some(Event::CaughtUp(_)) | None => break, + Some(_) => { + let next = queue.pop_front().expect("checked front"); + push_batch_op(&mut ops, ts, next); } - queue.extend(effects.dispatch(owed)); - if !drain && engine.machine().draining() { - queue.push_back(Event::Input(Input::Drain(false))); + } + } + if !matches!(queue.front(), Some(Event::CaughtUp(_))) { + while ops.len() < MAX_BATCH_OPS { + match receiver.try_recv() { + Ok(Event::CaughtUp(listed)) => { + queue.push_front(Event::CaughtUp(listed)); + break; + } + Ok(next) => push_batch_op(&mut ops, ts, next), + Err(_) => break, } - // The recovered calls go out again from here, so a call no one sends now is one - // the node no longer owes. - let keeper = keeper.clone(); - essential.spawn(async move { - match free_abandoned_nonces(|| keeper.free_abandoned()).await {} - }); - continue; } - }; - debug!(input = %brief(&input), "applying"); + } + + let op_count = ops.len(); let working: BTreeSet = engine.machine().working().copied().collect(); - // The answer to an effect and the end of that effect are one commit, so a crash - // cannot leave an answered effect to run again. - let (next, pending) = match answers { - Some(key) => engine.answer(now(), input, key)?, - None => engine.apply(now(), input)?, - }; + let may_fold: BTreeSet = working + .iter() + .copied() + .filter(|e3| engine.machine().might_fold(e3)) + .collect(); + // The answers to effects and any newly emitted durable effects commit atomically in + // one journal transaction on the blocking pool. + let (next, pending) = tokio::task::spawn_blocking(move || engine.apply_batch(ops)) + .await + .map_err(|e| NodeError::TaskPanicked("journal commit", e.to_string()))??; engine = next; - // Before the step's effects go out: a peer can ask for what they announce at once. - let admission = engine.machine().admission(); - if admission != admitted { - effects.network.admit(admission.clone()); - admitted = admission; + board.record_batch(op_count); + + // Before the batch's effects go out: a peer can ask for what they announce at once. + let next_epoch = engine.machine().admission_epoch(); + if next_epoch != admission_epoch { + let admission = engine.machine().admission(); + if admission != admitted { + effects.network.admit(admission.clone()); + admitted = admission; + } + admission_epoch = next_epoch; } queue.extend(effects.dispatch(pending)); for key in effects.stop_ended(engine.machine()) { - engine.acknowledge(key)?; + queue.push_back(Event::Done(key)); + } + for e3 in &may_fold { + if !engine.machine().might_fold(e3) { + effects.jobs.cancel_dkg_prefold(*e3); + } } let still: BTreeSet<&E3Id> = engine.machine().working().collect(); for e3 in working.iter().filter(|e3| !still.contains(e3)) { - if let Err(error) = effects.blobs.close(*e3) { - warn!(%e3, %error, "deleting the blobs of ended work failed"); - } - if let Err(error) = effects.jobs.close(*e3) { - warn!(%e3, %error, "deleting the proving files of ended work failed"); - } + let e3 = *e3; + let blobs = effects.blobs.clone(); + let jobs = effects.jobs.clone(); + cleanup.spawn(async move { + let _ = tokio::task::spawn_blocking(move || { + if let Err(error) = blobs.close(e3) { + warn!(%e3, %error, "deleting the blobs of ended work failed"); + } + if let Err(error) = jobs.close(e3) { + warn!(%e3, %error, "deleting the proving files of ended work failed"); + } + }) + .await; + }); } } } @@ -378,13 +440,40 @@ where essential.abort_all(); effects.stop_all(); effects.stopped(JOB_STOP_LIMIT).await; + while cleanup.join_next().await.is_some() {} effects.network.close().await; // A clean stop leaves the state in one snapshot beside the outbox, which is all a later release // has to read. - outcome?.checkpoint()?; + let mut engine = outcome?; + tokio::task::spawn_blocking(move || engine.checkpoint()) + .await + .map_err(|e| NodeError::TaskPanicked("journal checkpoint", e.to_string()))??; Ok(()) } +fn push_batch_op(ops: &mut Vec>, now: UnixSecs, event: Event) { + match event { + Event::Input(input) => { + debug!(input = %brief(&input), "applying"); + ops.push(BatchOp::Step { + now, + input, + answers: None, + }); + } + Event::Result(key, input) => { + debug!(input = %brief(&input), "applying"); + ops.push(BatchOp::Step { + now, + input, + answers: Some(key), + }); + } + Event::Done(key) => ops.push(BatchOp::Ack(key)), + Event::CaughtUp(_) => unreachable!("CaughtUp is handled outside batch commit"), + } +} + /// The first E3 under a BFV profile this release does not run that has not ended, or that still /// has crypto or accusation work after its end, and why. Even a request the node only watches can /// give it a ticket, and then jobs that could not run here; a profile retires only once all its E3s diff --git a/crates/ciphernode/node/src/status.rs b/crates/ciphernode/node/src/status.rs index ee0c1d6..ec78a10 100644 --- a/crates/ciphernode/node/src/status.rs +++ b/crates/ciphernode/node/src/status.rs @@ -9,6 +9,8 @@ use crate::notes::{self, Entry}; use alloy_primitives::Address; +use e3_blobs::BlobCacheStats; +use e3_p2p::NetworkStats; use e3_protocol::{node::Node, UnixSecs}; use serde::Serialize; use std::{ @@ -32,6 +34,19 @@ const MAX_REQUEST_BYTES: usize = 8 * 1024; const ANSWER_LIMIT: Duration = Duration::from_secs(5); const RECENT_NOTES: usize = 50; +#[derive(Default)] +struct Metrics { + batches_committed: AtomicU64, + ops_applied: AtomicU64, + fsyncs_saved: AtomicU64, + blob_cache_hits: AtomicU64, + blob_cache_misses: AtomicU64, + p2p_direct_sent: AtomicU64, + p2p_gossip_sent: AtomicU64, + p2p_blob_batches_fetched: AtomicU64, + p2p_blob_batches_served: AtomicU64, +} + /// What the page shows, kept current by the node. #[derive(Clone)] pub(crate) struct Board { @@ -41,6 +56,7 @@ pub(crate) struct Board { read_to: Arc, peers: Arc, machine: Arc>, + metrics: Arc, } #[derive(Clone, Debug, Default, Serialize)] @@ -81,9 +97,93 @@ impl Board { read_to: Arc::default(), peers: Arc::default(), machine: Arc::default(), + metrics: Arc::default(), + } + } + + pub(crate) fn record_batch(&self, ops: usize) { + self.metrics + .batches_committed + .fetch_add(1, Ordering::Relaxed); + self.metrics + .ops_applied + .fetch_add(ops as u64, Ordering::Relaxed); + if ops > 1 { + self.metrics + .fsyncs_saved + .fetch_add((ops - 1) as u64, Ordering::Relaxed); } } + pub(crate) fn adapter_stats(&self, blobs: BlobCacheStats, network: NetworkStats) { + self.metrics + .blob_cache_hits + .store(blobs.hits, Ordering::Relaxed); + self.metrics + .blob_cache_misses + .store(blobs.misses, Ordering::Relaxed); + self.metrics + .p2p_direct_sent + .store(network.direct_sent, Ordering::Relaxed); + self.metrics + .p2p_gossip_sent + .store(network.gossip_sent, Ordering::Relaxed); + self.metrics + .p2p_blob_batches_fetched + .store(network.blob_batches_fetched, Ordering::Relaxed); + self.metrics + .p2p_blob_batches_served + .store(network.blob_batches_served, Ordering::Relaxed); + } + + fn prometheus(&self) -> String { + let m = &self.metrics; + let machine = self.lock(); + let held_e3s = machine.e3s.len(); + drop(machine); + format!( + "# TYPE interfold_chain_head gauge\n\ + interfold_chain_head {}\n\ + # TYPE interfold_chain_read_to gauge\n\ + interfold_chain_read_to {}\n\ + # TYPE interfold_peers_connected gauge\n\ + interfold_peers_connected {}\n\ + # TYPE interfold_held_e3s gauge\n\ + interfold_held_e3s {}\n\ + # TYPE interfold_journal_batches_total counter\n\ + interfold_journal_batches_total {}\n\ + # TYPE interfold_journal_ops_total counter\n\ + interfold_journal_ops_total {}\n\ + # TYPE interfold_journal_fsyncs_saved_total counter\n\ + interfold_journal_fsyncs_saved_total {}\n\ + # TYPE interfold_blob_cache_hits_total counter\n\ + interfold_blob_cache_hits_total {}\n\ + # TYPE interfold_blob_cache_misses_total counter\n\ + interfold_blob_cache_misses_total {}\n\ + # TYPE interfold_p2p_direct_sent_total counter\n\ + interfold_p2p_direct_sent_total {}\n\ + # TYPE interfold_p2p_gossip_sent_total counter\n\ + interfold_p2p_gossip_sent_total {}\n\ + # TYPE interfold_p2p_blob_batches_fetched_total counter\n\ + interfold_p2p_blob_batches_fetched_total {}\n\ + # TYPE interfold_p2p_blob_batches_served_total counter\n\ + interfold_p2p_blob_batches_served_total {}\n", + self.head.load(Ordering::Relaxed), + self.read_to.load(Ordering::Relaxed), + self.peers.load(Ordering::Relaxed), + held_e3s, + m.batches_committed.load(Ordering::Relaxed), + m.ops_applied.load(Ordering::Relaxed), + m.fsyncs_saved.load(Ordering::Relaxed), + m.blob_cache_hits.load(Ordering::Relaxed), + m.blob_cache_misses.load(Ordering::Relaxed), + m.p2p_direct_sent.load(Ordering::Relaxed), + m.p2p_gossip_sent.load(Ordering::Relaxed), + m.p2p_blob_batches_fetched.load(Ordering::Relaxed), + m.p2p_blob_batches_served.load(Ordering::Relaxed), + ) + } + pub(crate) fn chain_read(&self, head: u64, read_to: u64) { self.head.store(head, Ordering::Relaxed); self.read_to.store(read_to, Ordering::Relaxed); @@ -184,6 +284,13 @@ async fn answer(mut socket: TcpStream, board: Board, notes: PathBuf) -> std::io: } async fn respond(path: &[u8], board: &Board, notes: PathBuf) -> String { + if path == b"/metrics" { + return reply( + "200 OK", + "text/plain; version=0.0.4; charset=utf-8", + board.prometheus(), + ); + } let recent = tokio::task::spawn_blocking(move || recent_notes(¬es)) .await .unwrap_or_default(); @@ -339,6 +446,13 @@ mod tests { let status: serde_json::Value = serde_json::from_str(body).unwrap(); assert_eq!(status["peers"], 4); assert_eq!(status["notes"][0]["sequence"], 1); + let metrics = get(port, "GET /metrics HTTP/1.1\r\n\r\n").await; + assert!(metrics.starts_with("HTTP/1.1 200 OK"), "{metrics}"); + assert!(metrics.contains("interfold_peers_connected 4"), "{metrics}"); + assert!( + metrics.contains("interfold_journal_batches_total 0"), + "{metrics}" + ); } /// The page reads and changes nothing, whatever a client asks for. diff --git a/crates/ciphernode/p2p/Cargo.toml b/crates/ciphernode/p2p/Cargo.toml index 8c22acf..805b751 100644 --- a/crates/ciphernode/p2p/Cargo.toml +++ b/crates/ciphernode/p2p/Cargo.toml @@ -11,10 +11,11 @@ e3-blobs = { workspace = true } e3-protocol = { workspace = true } e3-utils = { workspace = true } alloy-primitives = { workspace = true } +async-trait = { workspace = true } +bincode = { workspace = true } futures = { workspace = true } libp2p = { workspace = true } serde = { workspace = true } -serde_bytes = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } diff --git a/crates/ciphernode/p2p/src/behaviour.rs b/crates/ciphernode/p2p/src/behaviour.rs index 2748de6..b47cf8c 100644 --- a/crates/ciphernode/p2p/src/behaviour.rs +++ b/crates/ciphernode/p2p/src/behaviour.rs @@ -7,7 +7,10 @@ //! Every libp2p setting of the node, in one place, each with its reason. use crate::{ - inbound_ip_limits::InboundIpLimits, peers::PeerBook, protocols::Protocols, serving::BlobRequest, + blob_codec::{BlobBatchCodec, DirectCodec}, + inbound_ip_limits::InboundIpLimits, + peers::PeerBook, + protocols::Protocols, }; use libp2p::{ connection_limits::{self, ConnectionLimits}, @@ -15,10 +18,9 @@ use libp2p::{ identify, identity::Keypair, kad::{self, store::MemoryStore, StoreInserts}, - request_response::{self, cbor, ProtocolSupport}, + request_response::{self, ProtocolSupport}, swarm::NetworkBehaviour, }; -use serde_bytes::ByteBuf; use sha2::{Digest, Sha256}; use std::{collections::HashSet, time::Duration}; @@ -26,16 +28,14 @@ use std::{collections::HashSet, time::Duration}; pub(crate) const MAX_ENVELOPE_BYTES: usize = 4 * 1024 * 1024; /// The largest blob a peer may send, above the old document limit of 26 MiB. pub(crate) const MAX_BLOB_BYTES: u64 = 32 * 1024 * 1024; -/// A blob's response carries CBOR framing on top of its bytes. -const RESPONSE_FRAMING: u64 = 64 * 1024; -/// A request names an E3, a hash and a proof. Anyone can open a stream and send this much before -/// the node knows who it is. -const MAX_BLOB_REQUEST_BYTES: u64 = 1024; /// How long a blob request may take, its wait for a place included: long enough for a dealer on /// the slowest supported uplink to reach the last of a large committee. const BLOB_REQUEST_TIMEOUT: Duration = Duration::from_secs(120); /// The blob requests that may run at once on one connection. const BLOB_STREAMS: usize = 8; +/// Direct pairwise messages are small envelopes and fall back to gossipsub quickly on timeout. +const DIRECT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +const DIRECT_STREAMS: usize = 16; /// The library's tick-based defaults (history, gossip windows) assume one second. const GOSSIP_HEARTBEAT: Duration = Duration::from_secs(1); /// Often enough to see a peer's new addresses, rarely enough not to cost anything. @@ -57,8 +57,10 @@ pub(crate) struct Behaviour { pub(crate) gossipsub: Gossipsub, pub(crate) identify: identify::Behaviour, pub(crate) kademlia: kad::Behaviour, - /// A request names the blob's E3 and hash: each E3 keeps its own copy of its blobs. - pub(crate) blobs: cbor::Behaviour>, + /// Batched binary blob transfers: each E3 keeps its own copy of its blobs. + pub(crate) blobs: request_response::Behaviour, + /// Direct pairwise delivery for recipient-targeted messages (e.g. DKG shares). + pub(crate) direct: request_response::Behaviour, } impl Behaviour { @@ -94,6 +96,7 @@ impl Behaviour { ), kademlia: kademlia(key, protocols), blobs: blobs(protocols, messages), + direct: direct(protocols, messages), }) } } @@ -154,19 +157,30 @@ fn kademlia(key: &Keypair, protocols: &Protocols) -> kad::Behaviour kademlia } -fn blobs(protocols: &Protocols, messages: bool) -> cbor::Behaviour> { - let codec = cbor::codec::Codec::default() - .set_request_size_maximum(MAX_BLOB_REQUEST_BYTES) - .set_response_size_maximum(MAX_BLOB_BYTES + RESPONSE_FRAMING); +fn blobs(protocols: &Protocols, messages: bool) -> request_response::Behaviour { let support = match messages { true => ProtocolSupport::Full, false => ProtocolSupport::Outbound, }; - cbor::Behaviour::with_codec( - codec, + request_response::Behaviour::with_codec( + BlobBatchCodec, [(protocols.blobs.clone(), support)], request_response::Config::default() .with_request_timeout(BLOB_REQUEST_TIMEOUT) .with_max_concurrent_streams(BLOB_STREAMS), ) } + +fn direct(protocols: &Protocols, messages: bool) -> request_response::Behaviour { + let support = match messages { + true => ProtocolSupport::Full, + false => ProtocolSupport::Outbound, + }; + request_response::Behaviour::with_codec( + DirectCodec, + [(protocols.direct.clone(), support)], + request_response::Config::default() + .with_request_timeout(DIRECT_REQUEST_TIMEOUT) + .with_max_concurrent_streams(DIRECT_STREAMS), + ) +} diff --git a/crates/ciphernode/p2p/src/blob_codec.rs b/crates/ciphernode/p2p/src/blob_codec.rs new file mode 100644 index 0000000..225a0cb --- /dev/null +++ b/crates/ciphernode/p2p/src/blob_codec.rs @@ -0,0 +1,278 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Compact binary codecs for batched blob transfers and direct pairwise messages. +//! +//! Avoiding CBOR and writing/reading raw blob bytes directly from `Arc<[u8]>` eliminates both +//! redundant framing overhead and extra multi-megabyte copies on the hot blob-transfer path. + +use crate::behaviour::{MAX_BLOB_BYTES, MAX_ENVELOPE_BYTES}; +use alloy_primitives::B256; +use async_trait::async_trait; +use e3_protocol::{wire::PeerProof, E3Id}; +use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use libp2p::{request_response, StreamProtocol}; +use serde::{Deserialize, Serialize}; +use std::{io, sync::Arc}; + +/// Maximum number of blobs requested in a single batched stream request. +pub(crate) const MAX_BATCH_BLOBS: usize = 16; +/// Soft target byte budget when grouping multiple blobs into a single batch request. +/// A single blob larger than this (up to [`MAX_BLOB_BYTES`]) still travels alone in a 1-item batch. +pub(crate) const MAX_BATCH_BYTES: u64 = 16 * 1024 * 1024; +/// Hard ceiling on a batch request envelope (E3Id + PeerProof + up to 16 hashes). +const MAX_BLOB_REQUEST_BYTES: usize = 4 * 1024; +/// Hard ceiling on total raw blob bytes inside one batch response. +const MAX_BATCH_RESPONSE_BYTES: u64 = MAX_BLOB_BYTES + MAX_BATCH_BYTES; +/// Hard ceiling on a serialized PeerProof inside a direct message. +const MAX_PROOF_BYTES: usize = 1024; + +/// A request for one or more public blobs of an E3, and the requester's proof of identity. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct BlobBatchRequest { + pub(crate) e3: E3Id, + pub(crate) hashes: Vec, + pub(crate) requester: PeerProof, +} + +/// Ordered responses corresponding 1-to-1 with [`BlobBatchRequest::hashes`]. +#[derive(Clone, Debug)] +pub(crate) struct BlobBatchResponse { + pub(crate) items: Vec>>, +} + +#[derive(Clone, Default)] +pub(crate) struct BlobBatchCodec; + +#[async_trait] +impl request_response::Codec for BlobBatchCodec { + type Protocol = StreamProtocol; + type Request = BlobBatchRequest; + type Response = BlobBatchResponse; + + async fn read_request(&mut self, _: &Self::Protocol, io: &mut T) -> io::Result + where + T: AsyncRead + Unpin + Send, + { + let len = read_u32(io).await? as usize; + if len == 0 || len > MAX_BLOB_REQUEST_BYTES { + return Err(invalid("blob request exceeds limit")); + } + let mut buf = vec![0u8; len]; + io.read_exact(&mut buf).await?; + let req: BlobBatchRequest = bincode::deserialize(&buf) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + if req.hashes.is_empty() || req.hashes.len() > MAX_BATCH_BLOBS { + return Err(invalid("blob batch count out of range")); + } + Ok(req) + } + + async fn read_response( + &mut self, + _: &Self::Protocol, + io: &mut T, + ) -> io::Result + where + T: AsyncRead + Unpin + Send, + { + let count = read_u16(io).await? as usize; + if count > MAX_BATCH_BLOBS { + return Err(invalid("blob response count exceeds limit")); + } + let mut items = Vec::with_capacity(count); + let mut total_bytes: u64 = 0; + for _ in 0..count { + let mut tag = [0u8; 1]; + io.read_exact(&mut tag).await?; + match tag[0] { + 0 => items.push(None), + 1 => { + let len = read_u32(io).await? as u64; + if len > MAX_BLOB_BYTES { + return Err(invalid("blob exceeds maximum size")); + } + total_bytes = total_bytes + .checked_add(len) + .filter(|&sum| sum <= MAX_BATCH_RESPONSE_BYTES) + .ok_or_else(|| invalid("blob batch response exceeds size limit"))?; + let mut buf = vec![0u8; len as usize]; + io.read_exact(&mut buf).await?; + items.push(Some(Arc::from(buf))); + } + _ => return Err(invalid("invalid blob item tag")), + } + } + Ok(BlobBatchResponse { items }) + } + + async fn write_request( + &mut self, + _: &Self::Protocol, + io: &mut T, + req: Self::Request, + ) -> io::Result<()> + where + T: AsyncWrite + Unpin + Send, + { + if req.hashes.is_empty() || req.hashes.len() > MAX_BATCH_BLOBS { + return Err(invalid("blob batch count out of range")); + } + let encoded = + bincode::serialize(&req).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + if encoded.len() > MAX_BLOB_REQUEST_BYTES { + return Err(invalid("blob request exceeds limit")); + } + io.write_all(&(encoded.len() as u32).to_be_bytes()).await?; + io.write_all(&encoded).await?; + io.close().await + } + + async fn write_response( + &mut self, + _: &Self::Protocol, + io: &mut T, + res: Self::Response, + ) -> io::Result<()> + where + T: AsyncWrite + Unpin + Send, + { + if res.items.len() > MAX_BATCH_BLOBS { + return Err(invalid("blob response count exceeds limit")); + } + io.write_all(&(res.items.len() as u16).to_be_bytes()) + .await?; + for item in res.items { + match item { + None => io.write_all(&[0u8]).await?, + Some(bytes) => { + let len = u32::try_from(bytes.len()) + .map_err(|_| invalid("blob exceeds u32 length"))?; + if len as u64 > MAX_BLOB_BYTES { + return Err(invalid("blob exceeds maximum size")); + } + let mut header = [0u8; 5]; + header[0] = 1; + header[1..5].copy_from_slice(&len.to_be_bytes()); + io.write_all(&header).await?; + io.write_all(&bytes).await?; + } + } + } + io.close().await + } +} + +/// A recipient-targeted signed envelope delivered directly to its recipient over QUIC. +#[derive(Clone, Debug)] +pub(crate) struct DirectMessage { + pub(crate) envelope: Vec, + pub(crate) sender_proof: PeerProof, +} + +/// Whether the recipient accepted and queued the direct message (`false` triggers gossip fallback). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DirectAck(pub(crate) bool); + +#[derive(Clone, Default)] +pub(crate) struct DirectCodec; + +#[async_trait] +impl request_response::Codec for DirectCodec { + type Protocol = StreamProtocol; + type Request = DirectMessage; + type Response = DirectAck; + + async fn read_request(&mut self, _: &Self::Protocol, io: &mut T) -> io::Result + where + T: AsyncRead + Unpin + Send, + { + let proof_len = read_u32(io).await? as usize; + if proof_len == 0 || proof_len > MAX_PROOF_BYTES { + return Err(invalid("direct sender proof exceeds limit")); + } + let mut proof_buf = vec![0u8; proof_len]; + io.read_exact(&mut proof_buf).await?; + let sender_proof: PeerProof = bincode::deserialize(&proof_buf) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + + let env_len = read_u32(io).await? as usize; + if env_len == 0 || env_len > MAX_ENVELOPE_BYTES { + return Err(invalid("direct envelope exceeds limit")); + } + let mut envelope = vec![0u8; env_len]; + io.read_exact(&mut envelope).await?; + Ok(DirectMessage { + envelope, + sender_proof, + }) + } + + async fn read_response( + &mut self, + _: &Self::Protocol, + io: &mut T, + ) -> io::Result + where + T: AsyncRead + Unpin + Send, + { + let mut ack = [0u8; 1]; + io.read_exact(&mut ack).await?; + Ok(DirectAck(ack[0] != 0)) + } + + async fn write_request( + &mut self, + _: &Self::Protocol, + io: &mut T, + req: Self::Request, + ) -> io::Result<()> + where + T: AsyncWrite + Unpin + Send, + { + let proof_buf = bincode::serialize(&req.sender_proof) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + if proof_buf.len() > MAX_PROOF_BYTES || req.envelope.len() > MAX_ENVELOPE_BYTES { + return Err(invalid("direct message exceeds limit")); + } + io.write_all(&(proof_buf.len() as u32).to_be_bytes()) + .await?; + io.write_all(&proof_buf).await?; + io.write_all(&(req.envelope.len() as u32).to_be_bytes()) + .await?; + io.write_all(&req.envelope).await?; + io.close().await + } + + async fn write_response( + &mut self, + _: &Self::Protocol, + io: &mut T, + res: Self::Response, + ) -> io::Result<()> + where + T: AsyncWrite + Unpin + Send, + { + io.write_all(&[u8::from(res.0)]).await?; + io.close().await + } +} + +async fn read_u16(io: &mut T) -> io::Result { + let mut buf = [0u8; 2]; + io.read_exact(&mut buf).await?; + Ok(u16::from_be_bytes(buf)) +} + +async fn read_u32(io: &mut T) -> io::Result { + let mut buf = [0u8; 4]; + io.read_exact(&mut buf).await?; + Ok(u32::from_be_bytes(buf)) +} + +fn invalid(msg: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, msg) +} diff --git a/crates/ciphernode/p2p/src/driver.rs b/crates/ciphernode/p2p/src/driver.rs index 4d992f0..7896d5b 100644 --- a/crates/ciphernode/p2p/src/driver.rs +++ b/crates/ciphernode/p2p/src/driver.rs @@ -9,13 +9,14 @@ use crate::{ behaviour::{Behaviour, BehaviourEvent, IDLE_CONNECTION, MAX_BLOB_BYTES}, + blob_codec::{BlobBatchRequest, BlobBatchResponse, DirectAck, DirectMessage}, fetcher::{Done, Fetcher, Wanted}, inbox::{inbox, Inbox, InboxWriter}, peers::{advertised, strip_peer_id, PeerBook}, protocols::{Protocols, Standing}, - serving::{BlobRequest, Serving}, + serving::Serving, transport::{DialGuard, RecentDials}, - Network, NetworkError, + Network, NetworkError, NetworkStats, }; use alloy_primitives::{Address, B256}; use e3_blobs::{BlobStore, MemoryBlobs}; @@ -35,11 +36,10 @@ use libp2p::{ swarm::{dial_opts::DialOpts, DialError, SwarmEvent}, Multiaddr, PeerId, Swarm, }; -use serde_bytes::ByteBuf; use std::{ collections::{BTreeSet, HashMap, HashSet, VecDeque}, sync::{ - atomic::{AtomicUsize, Ordering}, + atomic::{AtomicU64, AtomicUsize, Ordering}, Arc, }, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, @@ -51,6 +51,8 @@ use tracing::{debug, info, warn}; const MAX_COMMANDS: usize = 1_024; /// Messages whose senders a node remembers, to fetch their blobs from. const MAX_SOURCES: usize = 4_096; +/// Maximum distinct source peers tracked per message ID. +const MAX_SOURCES_PER_MESSAGE: usize = 8; /// The peers whose addresses the node remembers putting into Kademlia. const MAX_ADVERTISING_PEERS: usize = 1_024; /// A publish waits this long for a peer on the topic, as a node that just started has none. @@ -71,6 +73,25 @@ const DRAIN: Duration = Duration::from_secs(2); /// A log line that can repeat with every message comes at most this often. const WARN_EVERY: Duration = Duration::from_secs(60); +#[derive(Default)] +struct AtomicStats { + direct_sent: AtomicU64, + gossip_sent: AtomicU64, + blob_batches_fetched: AtomicU64, + blob_batches_served: AtomicU64, +} + +impl AtomicStats { + fn snapshot(&self) -> NetworkStats { + NetworkStats { + direct_sent: self.direct_sent.load(Ordering::Relaxed), + gossip_sent: self.gossip_sent.load(Ordering::Relaxed), + blob_batches_fetched: self.blob_batches_fetched.load(Ordering::Relaxed), + blob_batches_served: self.blob_batches_served.load(Ordering::Relaxed), + } + } +} + /// How a node joins its network. #[derive(Clone, Debug)] pub struct P2pConfig { @@ -121,6 +142,7 @@ pub struct P2p { peer: PeerId, listening: Vec, connected: Arc, + stats: Arc, } enum Command { @@ -194,8 +216,10 @@ impl P2p { let (served_writer, served) = mpsc::unbounded_channel(); let (stored_writer, stored) = mpsc::unbounded_channel(); let connected = Arc::new(AtomicUsize::new(0)); + let stats = Arc::new(AtomicStats::default()); let mut driver = Driver { connected: connected.clone(), + stats: stats.clone(), swarm, protocols, messages, @@ -206,8 +230,11 @@ impl P2p { recent_dials, sources: Recent::default(), advertised: Recent::default(), + verified_peers: HashMap::new(), + operator_peers: HashMap::new(), fetcher: Fetcher::default(), requests: HashMap::new(), + direct_pending: HashMap::new(), publishes: VecDeque::new(), serving: Serving::default(), served_writer, @@ -224,6 +251,7 @@ impl P2p { peer, listening, connected, + stats, }; Ok((p2p, reader)) } @@ -298,6 +326,10 @@ impl Network for P2p { self.connected.load(Ordering::Relaxed) } + fn stats(&self) -> NetworkStats { + self.stats.snapshot() + } + async fn close(&self) { let (done, closed) = oneshot::channel(); if self.commands.send(Command::Close { done }).await.is_ok() { @@ -336,6 +368,10 @@ impl Recent Option<&V> { self.entries.get(key) } + + fn get_mut(&mut self, key: &K) -> Option<&mut V> { + self.entries.get_mut(key) + } } struct PendingPublish { @@ -344,36 +380,35 @@ struct PendingPublish { done: Done, } -/// A member's request for a blob, on its way through the line. +/// A member's batched request for blobs, on its way through the line. struct Asked { e3: E3Id, - hash: B256, + hashes: Vec, member: Address, - channel: ResponseChannel>, + channel: ResponseChannel, } -/// A blob read for a member, ready to send. +/// A blob batch read for a member, ready to send. struct Served { request: InboundRequestId, - channel: ResponseChannel>, - bytes: Option, + channel: ResponseChannel, + response: BlobBatchResponse, } -/// What became of a blob that arrived. -enum Stored { - Kept, - /// The bytes were not the blob's: another peer may have the real ones. - Wrong, +/// What became of a blob batch that arrived. +enum BatchStored { + Done { kept: usize, retry: Vec }, Failed(String), } struct Driver { connected: Arc, + stats: Arc, swarm: Swarm, protocols: Protocols, /// Whether the node takes part in the network's messages; a bootstrap node does not. messages: bool, - /// The operator this node is, and its word for it, which every blob request shows. + /// The operator this node is, and its word for it, which every blob/direct request shows. proof: PeerProof, blobs: S, inbox: InboxWriter, @@ -384,16 +419,22 @@ struct Driver { sources: Recent, MAX_SOURCES>, /// The addresses of each peer that the node put into Kademlia from its last Identify. advertised: Recent, MAX_ADVERTISING_PEERS>, + /// Verified `(PeerId -> Operator)` cache for active connections, avoiding repeated ECDSA + /// verification on every blob/direct request and enabling direct pairwise routing. + verified_peers: HashMap, + operator_peers: HashMap, fetcher: Fetcher, - /// The read each request belongs to. + /// The read ticket each outbound blob batch request belongs to. requests: HashMap, + /// Outbound direct pairwise sends awaiting ack before optional gossipsub fallback. + direct_pending: HashMap, /// Publishes that found no peer on the topic yet. publishes: VecDeque, serving: Serving, served_writer: mpsc::UnboundedSender, served: mpsc::UnboundedReceiver, - stored_writer: mpsc::UnboundedSender<(u64, Stored)>, - stored: mpsc::UnboundedReceiver<(u64, Stored)>, + stored_writer: mpsc::UnboundedSender<(u64, BatchStored)>, + stored: mpsc::UnboundedReceiver<(u64, BatchStored)>, refused: Limited, } @@ -499,9 +540,93 @@ impl Driver { } } + fn record_verified_peer(&mut self, peer: PeerId, operator: Address) { + if let Some(prev) = self.verified_peers.insert(peer, operator) { + if prev != operator && self.operator_peers.get(&prev) == Some(&peer) { + self.operator_peers.remove(&prev); + } + } + self.operator_peers.insert(operator, peer); + } + + fn forget_verified_peer(&mut self, peer: &PeerId) { + if let Some(operator) = self.verified_peers.remove(peer) { + if self.operator_peers.get(&operator) == Some(peer) { + self.operator_peers.remove(&operator); + } + } + } + + fn verify_peer_proof(&mut self, peer: PeerId, proof: &PeerProof) -> bool { + if self.verified_peers.get(&peer) == Some(&proof.operator) { + return true; + } + if proof.holds_for(&peer.to_bytes()) { + self.record_verified_peer(peer, proof.operator); + return true; + } + false + } + + fn add_sources(&mut self, id: B256, candidates: impl IntoIterator) { + let book = &self.swarm.behaviour().peers; + let filtered: Vec = candidates + .into_iter() + .filter(|peer| !book.takes_no_messages(peer)) + .collect(); + if filtered.is_empty() { + return; + } + if let Some(existing) = self.sources.get_mut(&id) { + for peer in filtered { + if !existing.contains(&peer) && existing.len() < MAX_SOURCES_PER_MESSAGE { + existing.push(peer); + } + } + } else { + let mut peers = Vec::with_capacity(filtered.len().min(MAX_SOURCES_PER_MESSAGE)); + for peer in filtered { + if !peers.contains(&peer) && peers.len() < MAX_SOURCES_PER_MESSAGE { + peers.push(peer); + } + } + self.sources.insert(id, peers); + } + } + fn publish(&mut self, envelope: Envelope, done: Done) { + let bytes = envelope.encode(); + // Recipient-targeted messages (e.g. DKG shares) go directly over a single QUIC stream when + // the recipient's peer ID is already known and connected, falling back to gossipsub on any + // error or rejection. + if let Some(recipient) = envelope.message.recipient() { + if let Some(&peer) = self.operator_peers.get(&recipient) { + if self.swarm.is_connected(&peer) + && !self + .swarm + .behaviour() + .peers + .is_rejected(&peer, Instant::now()) + { + let req = DirectMessage { + envelope: bytes.clone(), + sender_proof: self.proof.clone(), + }; + let request_id = self.swarm.behaviour_mut().direct.send_request(&peer, req); + self.direct_pending.insert( + request_id, + PendingPublish { + bytes, + attempts: 0, + done, + }, + ); + return; + } + } + } let pending = PendingPublish { - bytes: envelope.encode(), + bytes, attempts: 0, done, }; @@ -521,6 +646,7 @@ impl Driver { .publish(topic, pending.bytes.clone()); match result { Ok(_) => { + self.stats.gossip_sent.fetch_add(1, Ordering::Relaxed); let _ = pending.done.send(Ok(())); } Err(PublishError::NoPeersSubscribedToTopic | PublishError::AllQueuesFull(_)) @@ -551,6 +677,7 @@ impl Driver { message, })) => self.on_gossip(propagation_source, message_id, message), SwarmEvent::Behaviour(BehaviourEvent::Blobs(event)) => self.on_blobs(event), + SwarmEvent::Behaviour(BehaviourEvent::Direct(event)) => self.on_direct_event(event), SwarmEvent::Behaviour(BehaviourEvent::Identify(identify::Event::Received { peer_id, info, @@ -574,12 +701,17 @@ impl Driver { SwarmEvent::ConnectionClosed { peer_id, connection_id, + num_established, .. - } => self - .swarm - .behaviour_mut() - .peers - .closed(peer_id, connection_id), + } => { + self.swarm + .behaviour_mut() + .peers + .closed(peer_id, connection_id); + if num_established == 0 { + self.forget_verified_peer(&peer_id); + } + } SwarmEvent::OutgoingConnectionError { peer_id, error: DialError::WrongPeerId { obtained, address }, @@ -655,18 +787,14 @@ impl Driver { let Some(peer_message) = opened.filter(|opened| admitted && opened.is_for(me)) else { return; }; - let mut peers: Vec = message.source.into_iter().collect(); - if !peers.contains(&propagation) { - peers.push(propagation); - } // A bootstrap peer offers no blobs. Who carried a message does not matter otherwise: its // signature says who wrote it, and refusing the first copy would make the network's own // duplicate filter drop the honest copies behind it. - let book = &self.swarm.behaviour().peers; - peers.retain(|peer| !book.takes_no_messages(peer)); - if !peers.is_empty() { - self.sources.insert(peer_message.id(), peers); + let mut peers: Vec = message.source.into_iter().collect(); + if !peers.contains(&propagation) { + peers.push(propagation); } + self.add_sources(peer_message.id(), peers); let sender = peer_message.sender; if !self.inbox.push(peer_message, message.data.len() as u64) { if let Some(held_back) = self.refused.pass() { @@ -675,6 +803,104 @@ impl Driver { } } + fn on_direct_event(&mut self, event: request_response::Event) { + match event { + request_response::Event::Message { + peer, + message: + request_response::Message::Request { + request, channel, .. + }, + .. + } => self.on_direct_request(peer, request, channel), + request_response::Event::Message { + message: + request_response::Message::Response { + request_id, + response, + }, + .. + } => { + let Some(pending) = self.direct_pending.remove(&request_id) else { + return; + }; + if response.0 { + self.stats.direct_sent.fetch_add(1, Ordering::Relaxed); + let _ = pending.done.send(Ok(())); + } else { + self.try_publish(pending); + } + } + request_response::Event::OutboundFailure { + request_id, error, .. + } => { + if let Some(pending) = self.direct_pending.remove(&request_id) { + debug!(%error, "direct message send failed; falling back to gossipsub"); + self.try_publish(pending); + } + } + request_response::Event::ResponseSent { .. } + | request_response::Event::InboundFailure { .. } => {} + } + } + + fn on_direct_request( + &mut self, + peer: PeerId, + request: DirectMessage, + channel: ResponseChannel, + ) { + let DirectMessage { + envelope: bytes, + sender_proof, + } = request; + if !self.verify_peer_proof(peer, &sender_proof) { + if let Some(held_back) = self.refused.pass() { + let operator = sender_proof.operator; + warn!(%peer, %operator, held_back, "a peer sent a direct message with an invalid identity proof"); + } + let _ = self + .swarm + .behaviour_mut() + .direct + .send_response(channel, DirectAck(false)); + self.refuse(peer); + return; + } + let wire_len = bytes.len() as u64; + let envelope = Envelope::decode(&bytes); + let is_fresh = envelope + .as_ref() + .is_some_and(|env| fresh(env.sent_at, unix_now())); + let opened = envelope.and_then(Envelope::open); + let me = self.proof.operator; + let admitted = is_fresh + && opened.as_ref().is_some_and(|msg| { + msg.sender == sender_proof.operator + && self.admission.borrow().senders.contains(&msg.sender) + && msg.is_for(me) + }); + let accepted = if admitted { + let peer_message = opened.expect("admitted implies opened"); + self.add_sources(peer_message.id(), [peer]); + let sender = peer_message.sender; + let queued = self.inbox.push(peer_message, wire_len); + if !queued { + if let Some(held_back) = self.refused.pass() { + warn!(%sender, held_back, "the node's inbox has no room for this sender"); + } + } + queued + } else { + false + }; + let _ = self + .swarm + .behaviour_mut() + .direct + .send_response(channel, DirectAck(accepted)); + } + /// Fetches the blobs `message` names that the store lacks. A fetch already on its way for the /// same message answers this caller too. fn fetch(&mut self, message: PeerMessage, done: Done) { @@ -692,13 +918,22 @@ impl Driver { let _ = done.send(Ok(())); return; } - let (Some(peers), true) = ( - self.sources.get(&id).cloned(), - missing.iter().all(|blob| blob.len <= MAX_BLOB_BYTES), - ) else { + let Some(mut peers) = self.sources.get(&id).cloned() else { let _ = done.send(Err(NetworkError::Unavailable)); return; }; + if !missing.iter().all(|blob| blob.len <= MAX_BLOB_BYTES) { + let _ = done.send(Err(NetworkError::Unavailable)); + return; + } + // Prefer the original publisher if its peer ID is already verified and connected. + if let Some(&publisher) = self.operator_peers.get(&message.sender) { + if !self.swarm.behaviour().peers.takes_no_messages(&publisher) + && !peers.contains(&publisher) + { + peers.insert(0, publisher); + } + } let wanted = Wanted { message, missing, @@ -710,19 +945,23 @@ impl Driver { fn start_reads(&mut self) { for read in self.fetcher.next_reads() { + let hashes = read.blobs.iter().map(|blob| blob.hash).collect(); let request = self.swarm.behaviour_mut().blobs.send_request( &read.peer, - BlobRequest { + BlobBatchRequest { e3: read.e3, - hash: read.hash, + hashes, requester: self.proof.clone(), }, ); + self.stats + .blob_batches_fetched + .fetch_add(1, Ordering::Relaxed); self.requests.insert(request, read.ticket); } } - fn on_blobs(&mut self, event: request_response::Event>) { + fn on_blobs(&mut self, event: request_response::Event) { match event { request_response::Event::Message { peer, @@ -745,19 +984,13 @@ impl Driver { let Some(read) = self.requests.remove(&request_id) else { return; }; - match response { - Some(bytes) => self.store(read, bytes.into_vec()), - None => { - self.fetcher.failed(read); - self.start_reads(); - } - } + self.store_batch(read, response); } request_response::Event::OutboundFailure { request_id, error, .. } => { if let Some(read) = self.requests.remove(&request_id) { - debug!(%error, "a blob request failed"); + debug!(%error, "a blob batch request failed"); self.fetcher.failed(read); self.start_reads(); } @@ -770,26 +1003,27 @@ impl Driver { } } - /// Takes a peer's request for a blob. Only a member of the blob's E3 gets an answer with + /// Takes a peer's batched request for blobs. Only a member of the blobs' E3 gets an answer with /// bytes. The claim costs nothing to check, so it comes first; a peer that claims a member it /// cannot prove to be is dropped, so a false claim costs it a new identity and connection. fn on_asked( &mut self, peer: PeerId, request: InboundRequestId, - asked: BlobRequest, - channel: ResponseChannel>, + asked: BlobBatchRequest, + channel: ResponseChannel, ) { - let BlobRequest { + let BlobBatchRequest { e3, - hash, + hashes, requester, } = asked; + let count = hashes.len(); if !self.may_read(e3, requester.operator) { - self.answer_nothing(channel); + self.answer_nothing(channel, count); return; } - if !requester.holds_for(&peer.to_bytes()) { + if !self.verify_peer_proof(peer, &requester) { if let Some(held_back) = self.refused.pass() { let operator = requester.operator; warn!(%peer, %operator, held_back, "a peer claimed to be a member it cannot prove to be"); @@ -800,13 +1034,15 @@ impl Driver { let member = requester.operator; let asked = Asked { e3, - hash, + hashes, member, channel, }; match self.serving.ask(request, member, asked) { Ok(()) => self.serve_next(), - Err(Asked { channel, .. }) => self.answer_nothing(channel), + Err(Asked { + channel, hashes, .. + }) => self.answer_nothing(channel, hashes.len()), } } @@ -818,35 +1054,43 @@ impl Driver { .is_some_and(|committee| committee.contains(&operator)) } - fn answer_nothing(&mut self, channel: ResponseChannel>) { - let _ = self - .swarm - .behaviour_mut() - .blobs - .send_response(channel, None); + fn answer_nothing(&mut self, channel: ResponseChannel, count: usize) { + let _ = self.swarm.behaviour_mut().blobs.send_response( + channel, + BlobBatchResponse { + items: vec![None; count], + }, + ); } - /// Starts the disk reads whose turn it is, off this task. A member can lose its seat while it + /// Starts the blob reads whose turn it is, off this task. A member can lose its seat while it /// waits in line, and then finds nothing. fn serve_next(&mut self) { while let Some((request, asked)) = self.serving.next_turn() { let Asked { e3, - hash, + hashes, member, channel, } = asked; let readable = self.may_read(e3, member); let (blobs, served) = (self.blobs.clone(), self.served_writer.clone()); + self.stats + .blob_batches_served + .fetch_add(1, Ordering::Relaxed); tokio::task::spawn_blocking(move || { - let bytes = readable - .then(|| blobs.serve(e3, &hash)) - .flatten() - .map(ByteBuf::from); + let items = if readable { + hashes + .into_iter() + .map(|hash| blobs.serve_shared(e3, &hash)) + .collect() + } else { + vec![None; hashes.len()] + }; let _ = served.send(Served { request, channel, - bytes, + response: BlobBatchResponse { items }, }); }); } @@ -856,48 +1100,71 @@ impl Driver { let Served { request, channel, - bytes, + response, } = served; self.serving.read(request); let blobs = &mut self.swarm.behaviour_mut().blobs; - if blobs.send_response(channel, bytes).is_err() { + if blobs.send_response(channel, response).is_err() { self.serving.end(request); self.serve_next(); } } - /// Checks and stores a blob off this task. A fetch that ended keeps nothing. - fn store(&mut self, read: u64, bytes: Vec) { - let Some((e3, blob)) = self.fetcher.expected(read) else { + /// Checks and stores a batch of blobs off this task with a single directory sync. + fn store_batch(&mut self, read: u64, response: BlobBatchResponse) { + let Some((e3, expected)) = self.fetcher.expected(read) else { self.fetcher.failed(read); self.start_reads(); return; }; let (blobs, stored) = (self.blobs.clone(), self.stored_writer.clone()); tokio::task::spawn_blocking(move || { - let outcome = if BlobRef::of(&bytes) != blob { - Stored::Wrong + if response.items.len() != expected.len() { + let _ = stored.send(( + read, + BatchStored::Done { + kept: 0, + retry: expected, + }, + )); + return; + } + let mut valid: Vec<(BlobRef, Arc<[u8]>)> = Vec::with_capacity(expected.len()); + let mut retry: Vec = Vec::new(); + for (want, got) in expected.into_iter().zip(response.items) { + match got { + Some(bytes) if BlobRef::of(&bytes) == want => valid.push((want, bytes)), + _ => retry.push(want), + } + } + let kept = valid.len(); + let outcome = if valid.is_empty() { + BatchStored::Done { kept: 0, retry } } else { - match blobs.put(e3, &bytes) { - Ok(_) => Stored::Kept, - Err(error) => Stored::Failed(error.to_string()), + let slices: Vec<(&BlobRef, &[u8])> = valid + .iter() + .map(|(reference, bytes)| (reference, &bytes[..])) + .collect(); + match blobs.put_verified_batch(e3, &slices) { + Ok(_) => BatchStored::Done { kept, retry }, + Err(error) => BatchStored::Failed(error.to_string()), } }; let _ = stored.send((read, outcome)); }); } - fn on_stored(&mut self, read: u64, stored: Stored) { + fn on_stored(&mut self, read: u64, stored: BatchStored) { match stored { - Stored::Kept => self.fetcher.stored(read), - Stored::Wrong => self.fetcher.failed(read), - Stored::Failed(error) => self.fetcher.abort(read, NetworkError::Store(error)), + BatchStored::Done { kept, retry } => self.fetcher.batch_done(read, kept, retry), + BatchStored::Failed(error) => self.fetcher.abort(read, NetworkError::Store(error)), } self.start_reads(); } /// Drops `peer`, and does not dial or keep it for a while. fn refuse(&mut self, peer: PeerId) { + self.forget_verified_peer(&peer); let behaviour = self.swarm.behaviour_mut(); behaviour.peers.reject(peer, Instant::now()); behaviour.kademlia.remove_peer(&peer); diff --git a/crates/ciphernode/p2p/src/driver/tests.rs b/crates/ciphernode/p2p/src/driver/tests.rs index 8799558..53659d2 100644 --- a/crates/ciphernode/p2p/src/driver/tests.rs +++ b/crates/ciphernode/p2p/src/driver/tests.rs @@ -657,3 +657,38 @@ async fn closing_ends_the_network() { .await .unwrap(); } + +/// Once operator-to-peer identity is learned (e.g. from Phase 1 C0 blob fetches), recipient-targeted +/// DKG shares route directly over QUIC without flooding the gossipsub mesh, and all share blobs +/// fetch in a single batched request. +#[tokio::test(flavor = "multi_thread")] +async fn shares_route_directly_and_batch_fetch_once_peer_operator_is_known() { + let [first, mut second, mut third] = network().await; + // Phase 1: third fetches first's key blobs, teaching first third's verified (PeerId <-> Operator). + let key_msg = key(&first, 1); + publish(&first, signed(key_msg.clone(), 1, 10)).await; + assert_eq!(received(&mut second).await, key_msg); + assert_eq!(received(&mut third).await, key_msg); + fetch(&third, key_msg).await.unwrap(); + + // Phase 2: first publishes shares addressed to third -> routed over direct/1. + let share_msg = shares(&first, 1, 3); + publish(&first, signed(share_msg.clone(), 1, 11)).await; + assert_eq!(received(&mut third).await, share_msg); + assert!( + first.p2p.stats().direct_sent >= 1, + "expected direct send, stats={:?}", + first.p2p.stats() + ); + + let before_batches = third.p2p.stats().blob_batches_fetched; + fetch(&third, share_msg.clone()).await.unwrap(); + let after_batches = third.p2p.stats().blob_batches_fetched; + assert_eq!( + after_batches - before_batches, + 1, + "all 6 share blobs should arrive in one batch request" + ); + assert!(share_msg.blobs().iter().all(|blob| third.blobs.has(blob))); + nothing(&mut second, Duration::from_secs(2)).await; +} diff --git a/crates/ciphernode/p2p/src/fetcher.rs b/crates/ciphernode/p2p/src/fetcher.rs index d62c55e..8af2a04 100644 --- a/crates/ciphernode/p2p/src/fetcher.rs +++ b/crates/ciphernode/p2p/src/fetcher.rs @@ -4,11 +4,14 @@ // without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. -//! Which blob to ask which peer for next. Reads run a few at a time: no peer gets more than its -//! share of them, and the sender with the fewest running goes next, so one member's message cannot -//! starve another's. A blob's bytes count only while its read runs. +//! Which blobs to ask which peer for next. Reads run a few batched streams at a time: no peer gets +//! more than its share of them, and the sender with the fewest running goes next, so one member's +//! message cannot starve another's. A batch's bytes count only while its read runs. -use crate::NetworkError; +use crate::{ + blob_codec::{MAX_BATCH_BLOBS, MAX_BATCH_BYTES}, + NetworkError, +}; use alloy_primitives::{Address, B256}; use e3_protocol::{ node::{PeerMessage, MAX_MESSAGE_BLOBS}, @@ -34,12 +37,12 @@ const MAX_MESSAGE_BYTES: u64 = 512 * 1024 * 1024; /// A fetch that long in the queue ends, and the sender's re-send starts another. const LONGEST_FETCH: Duration = Duration::from_secs(10 * 60); -/// One read to start. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// One batched read to start against a single peer. +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Read

{ pub(crate) ticket: u64, pub(crate) e3: E3Id, - pub(crate) hash: B256, + pub(crate) blobs: Vec, pub(crate) peer: P, } @@ -66,7 +69,8 @@ struct Fetch

{ struct Ticket

{ fetch: u64, sender: Address, - blob: BlobRef, + blobs: Vec, + bytes: u64, peer_index: usize, peer: P, } @@ -143,7 +147,8 @@ impl Fetcher

{ ); } - /// The reads to start now. Each is running until `stored` or `failed` names its ticket. + /// The batched reads to start now. Each is running until `batch_done`, `failed`, or `abort` + /// names its ticket. pub(crate) fn next_reads(&mut self) -> Vec> { let mut reads = Vec::new(); while self.tickets.len() < MAX_ACTIVE { @@ -151,18 +156,39 @@ impl Fetcher

{ break; }; let state = self.fetches.get_mut(&fetch).expect("just chosen"); - let (blob, peer_index) = state.waiting.pop_front().expect("it has a waiting blob"); + let (first_blob, peer_index) = + state.waiting.pop_front().expect("it has a waiting blob"); let peer = state.peers[peer_index]; let (e3, sender) = (state.e3, state.sender); + let mut batch = vec![first_blob]; + let mut batch_bytes = first_blob.len; + while batch.len() < MAX_BATCH_BLOBS { + let Some(&(next_blob, next_peer_index)) = state.waiting.front() else { + break; + }; + if next_peer_index != peer_index { + break; + } + let next_batch_bytes = batch_bytes.saturating_add(next_blob.len); + if next_batch_bytes > MAX_BATCH_BYTES + || self.active_bytes.saturating_add(next_batch_bytes) > MAX_ACTIVE_BYTES + { + break; + } + state.waiting.pop_front(); + batch.push(next_blob); + batch_bytes = next_batch_bytes; + } let ticket = self.next_ticket; self.next_ticket += 1; - self.active_bytes += blob.len; + self.active_bytes += batch_bytes; *self.per_peer.entry(peer).or_default() += 1; *self.per_sender.entry(sender).or_default() += 1; let running = Ticket { fetch, sender, - blob, + blobs: batch.clone(), + bytes: batch_bytes, peer_index, peer, }; @@ -170,7 +196,7 @@ impl Fetcher

{ reads.push(Read { ticket, e3, - hash: blob.hash, + blobs: batch, peer, }); } @@ -196,15 +222,15 @@ impl Fetcher

{ .map(|(number, _)| *number) } - /// The blob a running read asks for, while its fetch is on its way. - pub(crate) fn expected(&self, ticket: u64) -> Option<(E3Id, BlobRef)> { + /// The blobs a running batched read asks for, while its fetch is on its way. + pub(crate) fn expected(&self, ticket: u64) -> Option<(E3Id, Vec)> { let running = self.tickets.get(&ticket)?; - Some((self.fetches.get(&running.fetch)?.e3, running.blob)) + Some((self.fetches.get(&running.fetch)?.e3, running.blobs.clone())) } fn release(&mut self, ticket: u64) -> Option> { let running = self.tickets.remove(&ticket)?; - self.active_bytes -= running.blob.len; + self.active_bytes -= running.bytes; if let Some(count) = self.per_peer.get_mut(&running.peer) { *count -= 1; if *count == 0 { @@ -220,21 +246,44 @@ impl Fetcher

{ Some(running) } - /// The read's blob is in the store. - pub(crate) fn stored(&mut self, ticket: u64) { + /// Finishes a batched read: `kept` blobs were stored, and each blob in `retry` must be + /// requested from the next peer (or ends the fetch if no peer remains). + pub(crate) fn batch_done(&mut self, ticket: u64, kept: usize, retry: Vec) { let Some(running) = self.release(ticket) else { return; }; let Some(fetch) = self.fetches.get_mut(&running.fetch) else { return; }; - fetch.outstanding -= 1; + fetch.outstanding = fetch.outstanding.saturating_sub(kept); + if !retry.is_empty() { + let next = running.peer_index + 1; + if next < fetch.peers.len() { + for blob in retry.into_iter().rev() { + fetch.waiting.push_front((blob, next)); + } + } else { + self.finish(running.fetch, Err(NetworkError::Unavailable)); + return; + } + } if fetch.outstanding == 0 { self.finish(running.fetch, Ok(())); } } - /// The read's peer could not give the blob: the next one gets its turn, or the fetch ends. + /// Every blob in the read's batch was stored. + #[cfg(test)] + pub(crate) fn stored(&mut self, ticket: u64) { + let count = self + .tickets + .get(&ticket) + .map_or(0, |running| running.blobs.len()); + self.batch_done(ticket, count, Vec::new()); + } + + /// The read's peer could not give any blob in the batch: the next peer gets its turn, or the + /// fetch ends. pub(crate) fn failed(&mut self, ticket: u64) { let Some(running) = self.release(ticket) else { return; @@ -244,7 +293,9 @@ impl Fetcher

{ }; let next = running.peer_index + 1; if next < fetch.peers.len() { - fetch.waiting.push_front((running.blob, next)); + for blob in running.blobs.into_iter().rev() { + fetch.waiting.push_front((blob, next)); + } } else { self.finish(running.fetch, Err(NetworkError::Unavailable)); } @@ -371,6 +422,16 @@ mod tests { assert_eq!(next[0].peer, 7, "the sender with none running goes first"); } + #[test] + fn multiple_blobs_for_same_peer_are_batched_into_one_read() { + let mut fetcher = Fetcher::default(); + add(&mut fetcher, 1, 1, blobs(0, 8), vec![5]); + let reads = fetcher.next_reads(); + assert_eq!(reads.len(), 1); + assert_eq!(reads[0].blobs.len(), 8); + assert_eq!(reads[0].peer, 5); + } + #[test] fn bytes_count_only_while_a_read_runs() { let mut fetcher: Fetcher = Fetcher::default(); @@ -436,7 +497,7 @@ mod tests { Err(NetworkError::Unavailable) )); fetcher.stored(reads[0].ticket); - add(&mut fetcher, 2, 2, blobs(10, 8), vec![1, 2, 3, 4]); + add(&mut fetcher, 2, 2, blobs(10, 20), vec![1, 2, 3, 4]); assert_eq!(fetcher.next_reads().len(), MAX_ACTIVE_PER_PEER); } diff --git a/crates/ciphernode/p2p/src/inbox.rs b/crates/ciphernode/p2p/src/inbox.rs index 9c0f1d4..ed8d853 100644 --- a/crates/ciphernode/p2p/src/inbox.rs +++ b/crates/ciphernode/p2p/src/inbox.rs @@ -119,6 +119,11 @@ impl Inbox { } } + /// The next ready message without waiting, for draining bursts in a batch. + pub fn try_next(&self) -> Option { + self.shared.queues().pop() + } + /// Waits until the network stopped. pub async fn closed(&self) { loop { diff --git a/crates/ciphernode/p2p/src/lib.rs b/crates/ciphernode/p2p/src/lib.rs index c78ae3c..a7e2a3d 100644 --- a/crates/ciphernode/p2p/src/lib.rs +++ b/crates/ciphernode/p2p/src/lib.rs @@ -8,6 +8,7 @@ //! fetches from the message's publisher once its machine admits the message. mod behaviour; +mod blob_codec; mod driver; mod fetcher; mod inbound_ip_limits; @@ -26,6 +27,15 @@ use e3_protocol::{ }; use std::future::Future; +/// Lightweight operational counters for the network adapter. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct NetworkStats { + pub direct_sent: u64, + pub gossip_sent: u64, + pub blob_batches_fetched: u64, + pub blob_batches_served: u64, +} + /// What the node needs from the network. Inbound, an adapter delivers each peer message whose /// envelope opens and that is for this node, before it fetches any blob the message names. pub trait Network: Send + Sync + 'static { @@ -42,6 +52,11 @@ pub trait Network: Send + Sync + 'static { /// How many peers are connected now. fn connected(&self) -> usize; + /// Operational counters for metrics reporting. + fn stats(&self) -> NetworkStats { + NetworkStats::default() + } + /// Says goodbye to the peers, so they do not have to time out. fn close(&self) -> impl Future + Send; } diff --git a/crates/ciphernode/p2p/src/protocols.rs b/crates/ciphernode/p2p/src/protocols.rs index 3d33e4a..afa73f6 100644 --- a/crates/ciphernode/p2p/src/protocols.rs +++ b/crates/ciphernode/p2p/src/protocols.rs @@ -14,6 +14,7 @@ pub(crate) struct Protocols { pub(crate) identify: String, pub(crate) kademlia: StreamProtocol, pub(crate) blobs: StreamProtocol, + pub(crate) direct: StreamProtocol, } /// What a peer's Identify says about it. @@ -37,7 +38,8 @@ impl Protocols { topic: IdentTopic::new(format!("{prefix}/messages/2")), identify: format!("/{prefix}/identify/2"), kademlia: stream("kad/1.0.0"), - blobs: stream("blobs/1"), + blobs: stream("blobs/2"), + direct: stream("direct/1"), } } diff --git a/crates/ciphernode/p2p/src/serving.rs b/crates/ciphernode/p2p/src/serving.rs index 4727ae1..4e68677 100644 --- a/crates/ciphernode/p2p/src/serving.rs +++ b/crates/ciphernode/p2p/src/serving.rs @@ -12,27 +12,17 @@ //! read. use crate::fetcher::MAX_ACTIVE_PER_PEER; -use alloy_primitives::{Address, B256}; -use e3_protocol::{wire::PeerProof, E3Id}; -use serde::{Deserialize, Serialize}; +use alloy_primitives::Address; use std::{ collections::{HashMap, HashSet, VecDeque}, hash::Hash, }; -/// The blobs served at once, from the disk read until the peer has them. It is more than the most -/// faulty members a committee can tolerate. A member that stops reading holds its place only until -/// the request times out. +/// The blob batches served at once, from the disk read until the peer has them. It is more than +/// the most faulty members a committee can tolerate. A member that stops reading holds its place +/// only until the request times out. const MAX_SERVING: usize = 8; -/// A request for one public blob of an E3, and the requester's word for who it is. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub(crate) struct BlobRequest { - pub(crate) e3: E3Id, - pub(crate) hash: B256, - pub(crate) requester: PeerProof, -} - struct Waiting { id: Id, member: Address, diff --git a/crates/protocol/src/accusation/mod.rs b/crates/protocol/src/accusation/mod.rs index 9ebbefb..9fc9061 100644 --- a/crates/protocol/src/accusation/mod.rs +++ b/crates/protocol/src/accusation/mod.rs @@ -69,12 +69,33 @@ pub enum AccusationMessage { } impl AccusationMessage { + pub(crate) fn kind(&self) -> crate::node::Kind { + match self { + Self::Accuse { .. } => crate::node::Kind::Accusation, + Self::Vote(_) => crate::node::Kind::Vote, + } + } + pub(crate) fn blobs(&self) -> Vec { match self { Self::Accuse { proof, .. } => vec![proof.proof.data], Self::Vote(_) => Vec::new(), } } + + pub(crate) fn blob_count(&self) -> usize { + match self { + Self::Accuse { .. } => 1, + Self::Vote(_) => 0, + } + } + + pub(crate) fn blob_bytes(&self) -> u64 { + match self { + Self::Accuse { proof, .. } => proof.proof.data.len, + Self::Vote(_) => 0, + } + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -86,6 +107,14 @@ pub enum AccusationWork { }, } +impl AccusationWork { + pub(crate) fn name(&self) -> &'static str { + match self { + Self::Verify { .. } => "accusation: verify a proof", + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum AccusationWorkResult { Verified { diff --git a/crates/protocol/src/decryption/mod.rs b/crates/protocol/src/decryption/mod.rs index 47dc47d..c823ae4 100644 --- a/crates/protocol/src/decryption/mod.rs +++ b/crates/protocol/src/decryption/mod.rs @@ -48,11 +48,31 @@ pub struct SharesMessage { } impl DecryptionMessage { + pub(crate) fn kind(&self) -> crate::node::Kind { + let Self::Shares(_) = self; + crate::node::Kind::DecryptionShares + } + pub(crate) fn blobs(&self) -> Vec { let Self::Shares(message) = self; let proofs = message.c6.iter().map(|signed| signed.proof.data); message.shares.iter().copied().chain(proofs).collect() } + + pub(crate) fn blob_count(&self) -> usize { + let Self::Shares(message) = self; + message.shares.len() + message.c6.len() + } + + pub(crate) fn blob_bytes(&self) -> u64 { + let Self::Shares(message) = self; + message + .shares + .iter() + .map(|b| b.len) + .chain(message.c6.iter().map(|s| s.proof.data.len)) + .fold(0u64, u64::saturating_add) + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -84,6 +104,23 @@ pub enum DecryptionWork { }, } +impl DecryptionWork { + pub(crate) fn proves(&self) -> bool { + matches!( + self, + Self::MakeShares { .. } | Self::AggregatePlaintext { .. } + ) + } + + pub(crate) fn checks_a_member(&self) -> bool { + matches!(self, Self::CheckShares { .. }) + } + + pub(crate) fn name(&self) -> &'static str { + "decryption" + } +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum DecryptionWorkResult { SharesMade(OwnShares), @@ -91,6 +128,22 @@ pub enum DecryptionWorkResult { PlaintextMade(PlaintextPublication), } +impl DecryptionWorkResult { + pub(crate) fn answers_a_check(&self) -> bool { + matches!(self, Self::SharesChecked { .. }) + } + + pub(crate) fn fault(&self) -> Option<(Address, crate::accusation::Fault)> { + match self { + Self::SharesChecked { + member, + verdict: Verdict::Fails(fault), + } => Some((*member, fault.clone())), + _ => None, + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct OwnShares { pub shares: Vec, @@ -286,8 +339,14 @@ impl Decryption { now: UnixSecs, sender: Address, message: DecryptionMessage, + signatures_verified: bool, ) -> Vec { - if !self.admits(sender, &message) { + let admitted = if signatures_verified { + self.admits_state(sender, &message) + } else { + self.admits(sender, &message) + }; + if !admitted { return Vec::new(); } let DecryptionMessage::Shares(shares) = message; @@ -295,9 +354,7 @@ impl Decryption { self.advance(now) } - /// Whether this node takes `message` from `sender` now; it can tell before it fetches any blob - /// the message names. - pub(crate) fn admits(&self, sender: Address, message: &DecryptionMessage) -> bool { + fn admits_state(&self, sender: Address, message: &DecryptionMessage) -> bool { let DecryptionMessage::Shares(shares) = message; self.failure.is_none() && sender != self.me @@ -305,6 +362,13 @@ impl Decryption { && !self.shares.contains_key(&sender) && !shares.shares.is_empty() && shares.shares.len() == shares.c6.len() + } + + /// Whether this node takes `message` from `sender` now; it can tell before it fetches any blob + /// the message names. + pub(crate) fn admits(&self, sender: Address, message: &DecryptionMessage) -> bool { + let DecryptionMessage::Shares(shares) = message; + self.admits_state(sender, message) && shares.c6.iter().all(|proof| { proof.is_signed_by(sender, self.e3, ProofType::C6ThresholdShareDecryption) }) diff --git a/crates/protocol/src/decryption/tests.rs b/crates/protocol/src/decryption/tests.rs index 8455396..4df857d 100644 --- a/crates/protocol/src/decryption/tests.rs +++ b/crates/protocol/src/decryption/tests.rs @@ -77,7 +77,7 @@ fn deliver(decryption: &mut Decryption, now: UnixSecs, input: Input) -> Vec decryption.receive(now, sender, message), + }) => decryption.receive(now, sender, message, false), Input::Job(JobDone { result: WorkResult::Decryption(result), .. diff --git a/crates/protocol/src/dkg/aggregation.rs b/crates/protocol/src/dkg/aggregation.rs index e49cdfe..e9295bb 100644 --- a/crates/protocol/src/dkg/aggregation.rs +++ b/crates/protocol/src/dkg/aggregation.rs @@ -72,9 +72,12 @@ impl Default for Aggregation { } impl Dkg { + pub(super) fn admits_keyshare_state(&self, member: Address) -> bool { + self.counts_for_the_key(member) && !self.aggregation.keyshares.contains_key(&member) + } + pub(super) fn admits_keyshare(&self, member: Address, message: &KeyshareMessage) -> bool { - self.counts_for_the_key(member) - && !self.aggregation.keyshares.contains_key(&member) + self.admits_keyshare_state(member) && message .c1 .is_signed_by(member, self.e3, ProofType::C1PkGeneration) @@ -84,10 +87,12 @@ impl Dkg { self.aggregation.keyshares.insert(member, message); } + pub(super) fn admits_fold_state(&self, member: Address) -> bool { + self.counts_for_the_key(member) && !self.aggregation.folds.contains_key(&member) + } + pub(super) fn admits_fold(&self, member: Address, message: &NodeFoldMessage) -> bool { - self.counts_for_the_key(member) - && !self.aggregation.folds.contains_key(&member) - && self.attests(member, message) + self.admits_fold_state(member) && self.attests(member, message) } pub(super) fn receive_fold(&mut self, member: Address, message: NodeFoldMessage) { diff --git a/crates/protocol/src/dkg/decryption_key.rs b/crates/protocol/src/dkg/decryption_key.rs index 139014a..bc07a83 100644 --- a/crates/protocol/src/dkg/decryption_key.rs +++ b/crates/protocol/src/dkg/decryption_key.rs @@ -111,11 +111,7 @@ impl Dkg { effects } - pub(super) fn admits_decryption_key( - &self, - member: Address, - message: &DecryptionKeyMessage, - ) -> bool { + pub(super) fn admits_decryption_key_state(&self, member: Address) -> bool { let in_roster = self .roster_members() .is_none_or(|roster| roster.contains(&member)); @@ -123,7 +119,14 @@ impl Dkg { && member != self.me && self.is_member(member) && !self.decryption_keys.received.contains_key(&member) - && message.is_signed_by(member, self.e3) + } + + pub(super) fn admits_decryption_key( + &self, + member: Address, + message: &DecryptionKeyMessage, + ) -> bool { + self.admits_decryption_key_state(member) && message.is_signed_by(member, self.e3) } pub(super) fn receive_decryption_key( diff --git a/crates/protocol/src/dkg/keys.rs b/crates/protocol/src/dkg/keys.rs index 95ae297..144d281 100644 --- a/crates/protocol/src/dkg/keys.rs +++ b/crates/protocol/src/dkg/keys.rs @@ -25,11 +25,15 @@ pub(super) struct Keys { } impl Dkg { - pub(super) fn admits_key(&self, sender: Address, message: &KeyMessage) -> bool { + pub(super) fn admits_key_state(&self, sender: Address) -> bool { self.collecting_keys() && sender != self.me && self.is_member(sender) && !self.keys.received.contains_key(&sender) + } + + pub(super) fn admits_key(&self, sender: Address, message: &KeyMessage) -> bool { + self.admits_key_state(sender) && message .proof .is_signed_by(sender, self.e3, ProofType::C0PkBfv) diff --git a/crates/protocol/src/dkg/mod.rs b/crates/protocol/src/dkg/mod.rs index 9fd6199..67d76ea 100644 --- a/crates/protocol/src/dkg/mod.rs +++ b/crates/protocol/src/dkg/mod.rs @@ -161,6 +161,25 @@ impl Dealer { } impl DkgMessage { + pub(crate) fn kind(&self) -> crate::node::Kind { + match self { + Self::EncryptionKey(_) => crate::node::Kind::EncryptionKey, + Self::Shares(_) => crate::node::Kind::Shares, + Self::Ready(_) => crate::node::Kind::Ready, + Self::Roster(_) => crate::node::Kind::Roster, + Self::DecryptionKey(_) => crate::node::Kind::DecryptionKey, + Self::Keyshare(_) => crate::node::Kind::Keyshare, + Self::NodeFold(_) => crate::node::Kind::NodeFold, + } + } + + pub(crate) fn recipient(&self) -> Option

{ + match self { + Self::Shares(shares) => Some(shares.recipient), + _ => None, + } + } + pub(crate) fn blobs(&self) -> Vec { match self { Self::EncryptionKey(message) => vec![message.key, message.proof.proof.data], @@ -185,6 +204,38 @@ impl DkgMessage { Self::NodeFold(message) => vec![message.fold.proof.data], } } + + pub(crate) fn blob_count(&self) -> usize { + match self { + Self::EncryptionKey(_) | Self::Keyshare(_) => 2, + Self::Shares(message) => 4 + message.c3a.len() + message.c3b.len(), + Self::Ready(_) | Self::Roster(_) => 0, + Self::DecryptionKey(message) => 1 + message.c4b.len(), + Self::NodeFold(_) => 1, + } + } + + pub(crate) fn blob_bytes(&self) -> u64 { + match self { + Self::EncryptionKey(m) => m.key.len.saturating_add(m.proof.proof.data.len), + Self::Shares(m) => [ + m.pk_share.len, + m.shares.len, + m.c2a.proof.data.len, + m.c2b.proof.data.len, + ] + .into_iter() + .chain(m.c3a.iter().map(|s| s.proof.data.len)) + .chain(m.c3b.iter().map(|s| s.proof.data.len)) + .fold(0u64, u64::saturating_add), + Self::Ready(_) | Self::Roster(_) => 0, + Self::DecryptionKey(m) => std::iter::once(m.c4a.proof.data.len) + .chain(m.c4b.iter().map(|s| s.proof.data.len)) + .fold(0u64, u64::saturating_add), + Self::Keyshare(m) => m.pk_share.len.saturating_add(m.c1.proof.data.len), + Self::NodeFold(m) => m.fold.proof.data.len, + } + } } /// Work the DKG asks the job runner for. Jobs that need party IDs get the committee: a member's @@ -269,6 +320,45 @@ pub enum DkgWork { }, } +impl DkgWork { + pub(crate) fn proves(&self) -> bool { + matches!( + self, + Self::MakeEncryptionKey + | Self::MakeShares { .. } + | Self::MakeDecryptionKey { .. } + | Self::FoldProofs { .. } + | Self::FoldRoster { .. } + | Self::AggregateKey { .. } + ) + } + + pub(crate) fn checks_a_member(&self) -> bool { + matches!( + self, + Self::CheckEncryptionKey { .. } + | Self::CheckShares { .. } + | Self::CheckDecryptionKey { .. } + | Self::CheckKeyshare { .. } + ) + } + + pub(crate) fn name(&self) -> &'static str { + match self { + Self::MakeEncryptionKey => "dkg: make the encryption key", + Self::CheckEncryptionKey { .. } => "dkg: check an encryption key", + Self::MakeShares { .. } => "dkg: deal shares", + Self::CheckShares { .. } => "dkg: check a dealer's shares", + Self::MakeDecryptionKey { .. } => "dkg: make the decryption key", + Self::CheckDecryptionKey { .. } => "dkg: check a decryption key", + Self::FoldProofs { .. } => "dkg: fold this node's proofs", + Self::CheckKeyshare { .. } => "dkg: check a keyshare", + Self::FoldRoster { .. } => "dkg: fold a roster member's proof", + Self::AggregateKey { .. } => "dkg: aggregate the committee key", + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum DkgWorkResult { EncryptionKeyMade(OwnKey), @@ -283,6 +373,32 @@ pub enum DkgWorkResult { KeyAggregated(AggregatedKey), } +impl DkgWorkResult { + pub(crate) fn answers_a_check(&self) -> bool { + matches!( + self, + Self::EncryptionKeyChecked { .. } + | Self::SharesChecked { .. } + | Self::DecryptionKeyChecked { .. } + | Self::KeyshareChecked { .. } + ) + } + + pub(crate) fn fault(&self) -> Option<(Address, crate::accusation::Fault)> { + let (member, verdict) = match self { + Self::EncryptionKeyChecked { sender, verdict } => (sender, verdict), + Self::SharesChecked { dealer, verdict } => (dealer, verdict), + Self::DecryptionKeyChecked { member, verdict } + | Self::KeyshareChecked { member, verdict } => (member, verdict), + _ => return None, + }; + match verdict { + Verdict::Fails(fault) => Some((*member, fault.clone())), + Verdict::Valid | Verdict::Invalid => None, + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct AggregatedKey { pub public_key: BlobRef, @@ -501,11 +617,16 @@ impl Dkg { now: UnixSecs, sender: Address, message: DkgMessage, + signatures_verified: bool, ) -> Vec { if !self.running() { return Vec::new(); } - let admitted = self.admits(sender, &message); + let admitted = if signatures_verified { + self.admits_state(sender, &message) + } else { + self.admits(sender, &message) + }; let mut effects = match message { _ if !admitted => Vec::new(), DkgMessage::EncryptionKey(message) => self.receive_key(sender, message), @@ -529,6 +650,21 @@ impl Dkg { effects } + /// State-only admission check (without re-verifying inner ECDSA proof signatures), used when + /// `E3::receive` matches an exact message ID whose signatures already passed in `start_fetch`. + fn admits_state(&self, sender: Address, message: &DkgMessage) -> bool { + self.running() + && match message { + DkgMessage::EncryptionKey(_) => self.admits_key_state(sender), + DkgMessage::Shares(_) => self.admits_shares_state(sender), + DkgMessage::Ready(dealers) => self.admits_ready(sender, dealers), + DkgMessage::Roster(dealers) => self.admits_roster(sender, dealers), + DkgMessage::DecryptionKey(_) => self.admits_decryption_key_state(sender), + DkgMessage::Keyshare(_) => self.admits_keyshare_state(sender), + DkgMessage::NodeFold(_) => self.admits_fold_state(sender), + } + } + /// Whether this node takes `message` from `sender` now; it can tell before it fetches any blob /// the message names. pub(crate) fn admits(&self, sender: Address, message: &DkgMessage) -> bool { @@ -687,6 +823,12 @@ impl Dkg { !self.published && !matches!(self.phase, Phase::Failed(_)) } + /// Whether this node might still run `FoldProofs`: false once excluded from the roster as an + /// observer, failed, or once the committee key is published. + pub fn might_fold(&self) -> bool { + self.running() && !matches!(self.phase, Phase::Observing) + } + /// Every input ends here, since any of them can complete a roster or an aggregation. fn advance(&mut self, now: UnixSecs) -> Vec { let mut effects = self.advance_roster(now); diff --git a/crates/protocol/src/dkg/roster.rs b/crates/protocol/src/dkg/roster.rs index 7b0f8b6..c8d67d9 100644 --- a/crates/protocol/src/dkg/roster.rs +++ b/crates/protocol/src/dkg/roster.rs @@ -174,7 +174,7 @@ impl Dkg { let contains = |member: &Address| { self.ready .get(member) - .is_some_and(|ready| roster.iter().all(|dealer| ready.contains(dealer))) + .is_some_and(|ready| roster.iter().all(|dealer| ready_contains(ready, dealer))) }; self.is_live(&proposer) && roster.iter().all(|dealer| self.is_live(&dealer.member)) @@ -190,29 +190,121 @@ impl Dkg { /// receives only by chain facts: nodes that count votes at different times must not refuse /// each other's rosters and stop the same DKG. fn select_ready_roster(&self) -> Option> { - let reports: BTreeMap = self + let h = self.h(); + if h == 0 { + return Some(Vec::new()); + } + let mut entries: Vec<(Dealer, &[Dealer])> = self .ready .iter() .filter(|(reporter, _)| { self.is_live(reporter) && !self.rosters.failover.is_convicted(reporter) }) - .map(|(reporter, report)| (*reporter, report.as_slice())) - .collect(); - let candidates: Vec = reports - .iter() .filter_map(|(reporter, report)| { - report - .iter() - .find(|dealer| dealer.member == *reporter) - .copied() + let slice = report.as_slice(); + let own = slice + .binary_search_by_key(reporter, |d| d.member) + .ok() + .map(|idx| slice[idx])?; + Some((own, slice)) }) .collect(); - let mut selected = Vec::with_capacity(self.h()); - select(&reports, &candidates, self.h(), &mut selected).then_some(selected) + if entries.len() < h { + return None; + } + // `self.ready` is a BTreeMap keyed by Address, so `entries` is strictly ascending by member. + if entries.len() <= 128 { + select_bitmask(&entries, h) + } else { + let reports: BTreeMap = entries + .iter() + .map(|(dealer, report)| (dealer.member, *report)) + .collect(); + let candidates: Vec = entries.drain(..).map(|(dealer, _)| dealer).collect(); + let mut selected = Vec::with_capacity(h); + select_fallback(&reports, &candidates, h, &mut selected).then_some(selected) + } + } +} + +/// Ready reports are strictly ascending by `dealer.member`, so membership is O(log N). +fn ready_contains(ready: &[Dealer], dealer: &Dealer) -> bool { + ready + .binary_search_by_key(&dealer.member, |d| d.member) + .is_ok_and(|idx| ready[idx] == *dealer) +} + +/// Finds the lexicographically-first H-clique using bitmask adjacency and iterative (H-1)-core +/// pruning. Guarantees the exact same committee-order output as backtracking over sorted slices. +fn select_bitmask(entries: &[(Dealer, &[Dealer])], h: usize) -> Option> { + let n = entries.len(); + let mut adj = vec![0u128; n]; + for i in 0..n { + let (di, ri) = entries[i]; + for j in (i + 1)..n { + let (dj, rj) = entries[j]; + if ready_contains(ri, &dj) && ready_contains(rj, &di) { + adj[i] |= 1u128 << j; + adj[j] |= 1u128 << i; + } + } + } + + let min_deg = (h - 1) as u32; + let mut active: u128 = if n == 128 { + u128::MAX + } else { + (1u128 << n) - 1 + }; + loop { + let mut removed = 0u128; + let mut scan = active; + while scan != 0 { + let v = scan.trailing_zeros() as usize; + scan &= scan - 1; + if (adj[v] & active).count_ones() < min_deg { + removed |= 1u128 << v; + } + } + if removed == 0 { + break; + } + active &= !removed; + if (active.count_ones() as usize) < h { + return None; + } + } + + let mut chosen = Vec::with_capacity(h); + if search_clique(&adj, active, h, &mut chosen) { + Some(chosen.into_iter().map(|idx| entries[idx].0).collect()) + } else { + None + } +} + +fn search_clique(adj: &[u128], mut candidates: u128, h: usize, chosen: &mut Vec) -> bool { + let need = h - chosen.len(); + if need == 0 { + return true; + } + while (candidates.count_ones() as usize) >= need { + let v = candidates.trailing_zeros() as usize; + candidates &= candidates - 1; + let next = candidates & adj[v]; + if (next.count_ones() as usize) + 1 < need { + continue; + } + chosen.push(v); + if search_clique(adj, next, h, chosen) { + return true; + } + chosen.pop(); } + false } -fn select( +fn select_fallback( reports: &BTreeMap, candidates: &[Dealer], h: usize, @@ -226,17 +318,75 @@ fn select( return false; } let mutual = selected.iter().all(|dealer| { - reports[&candidate.member].contains(dealer) - && reports[&dealer.member].contains(candidate) + ready_contains(reports[&candidate.member], dealer) + && ready_contains(reports[&dealer.member], candidate) }); if !mutual { continue; } selected.push(*candidate); - if select(reports, &candidates[index + 1..], h, selected) { + if select_fallback(reports, &candidates[index + 1..], h, selected) { return true; } selected.pop(); } false } + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::B256; + + #[test] + fn bitmask_roster_selection_matches_fallback_on_adversarial_graphs() { + let n = 19usize; + let h = 14usize; + let dealers: Vec = (1..=n as u8) + .map(|i| Dealer { + member: Address::repeat_byte(i), + contribution: B256::repeat_byte(i), + }) + .collect(); + + // Near-clique with a planted clique at indices [1, 3, 5..17] and tricky missing edges. + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next_u64 = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + + for trial in 0..64 { + let mut lists: Vec> = vec![Vec::new(); n]; + let plant = trial % 2 == 0; + for (i, list) in lists.iter_mut().enumerate() { + list.push(dealers[i]); + for (j, &dealer) in dealers.iter().enumerate() { + if i == j { + continue; + } + let edge = + (plant && i >= 2 && j >= 2 && i < 16 && j < 16) || (next_u64() % 100) < 78; + if edge { + list.push(dealer); + } + } + list.sort_by_key(|d| d.member); + } + let entries: Vec<(Dealer, &[Dealer])> = dealers + .iter() + .zip(lists.iter()) + .map(|(d, l)| (*d, l.as_slice())) + .collect(); + let reports: BTreeMap = + entries.iter().map(|(d, l)| (d.member, *l)).collect(); + let mut expected = Vec::new(); + let expected = + select_fallback(&reports, &dealers, h, &mut expected).then_some(expected); + let actual = select_bitmask(&entries, h); + assert_eq!(actual, expected, "mismatch on trial {trial}"); + } + } +} diff --git a/crates/protocol/src/dkg/shares.rs b/crates/protocol/src/dkg/shares.rs index 369bfaf..8dc902d 100644 --- a/crates/protocol/src/dkg/shares.rs +++ b/crates/protocol/src/dkg/shares.rs @@ -216,14 +216,17 @@ impl Dkg { effects } - /// Shares can only be for a key this node has sent, so they count from then on. - /// Shares need this node's key to open. - pub(super) fn admits_shares(&self, dealer: Address, message: &SharesMessage) -> bool { + pub(super) fn admits_shares_state(&self, dealer: Address) -> bool { self.own_key().is_some() && dealer != self.me && self.is_member(dealer) && !self.shares.received.contains_key(&dealer) - && message.is_signed_by(dealer, self.e3) + } + + /// Shares can only be for a key this node has sent, so they count from then on. + /// Shares need this node's key to open. + pub(super) fn admits_shares(&self, dealer: Address, message: &SharesMessage) -> bool { + self.admits_shares_state(dealer) && message.is_signed_by(dealer, self.e3) } pub(super) fn receive_shares( diff --git a/crates/protocol/src/dkg/tests/decryption_key.rs b/crates/protocol/src/dkg/tests/decryption_key.rs index c79f2b1..a296449 100644 --- a/crates/protocol/src/dkg/tests/decryption_key.rs +++ b/crates/protocol/src/dkg/tests/decryption_key.rs @@ -70,10 +70,12 @@ fn a_roster_member_sums_the_other_roster_dealers_shares_and_binds_every_roster_c fn a_member_outside_the_roster_makes_no_decryption_key_but_checks_the_roster_s() { let [first, second, third] = ordered(); let mut node = verified_all(third); + assert!(node.might_fold(&e3(1))); node.step(NOW, ready(first, &[first, second, third], third)); node.step(NOW, ready(second, &[first, second, third], third)); let effects = node.step(NOW, roster(first, &[first, second], third)); assert_eq!(accepted(&node), Some(members(&[first, second]))); + assert!(!node.might_fold(&e3(1))); assert!(decryption_key_jobs(&effects).is_empty()); let effects = node.step(NOW, decryption_key(e3(1), first, first)); assert_eq!(checks_of_decryption_keys(&effects), members(&[first])); diff --git a/crates/protocol/src/e3.rs b/crates/protocol/src/e3.rs index 212ea38..c5abd5e 100644 --- a/crates/protocol/src/e3.rs +++ b/crates/protocol/src/e3.rs @@ -8,9 +8,9 @@ //! from the key's publication. use crate::{ - accusation::{Accusations, Fault, Slashing, Verdict}, - decryption::{Decryption, DecryptionWorkResult, Handover, PublishedKey}, - dkg::{AttestationContext, Dkg, DkgTiming, DkgWorkResult, KeyAnchor}, + accusation::{Accusations, Fault, Slashing}, + decryption::{Decryption, Handover, PublishedKey}, + dkg::{AttestationContext, Dkg, DkgTiming, KeyAnchor}, node::{ BlobFetch, Body, Classified, CommitteeRequest, CommitteeSeed, CryptoParams, DataRef, Effect, FetchFailed, Kind, Note, Noted, PeerMessage, Purpose, Stage, Submission, @@ -568,13 +568,13 @@ impl E3 { if !self.admits(now, message) { return Classified::Drop; } - if message.blobs().is_empty() { + if message.blob_count() == 0 { return Classified::Deliver; } let slot = (message.sender, message.body.kind()); match self.fetching.get(&slot) { None => Classified::Fetch, - Some(fetching) if fetching.id == message.id() && !fetching.running => Classified::Fetch, + Some(fetching) if !fetching.running && fetching.id == message.id() => Classified::Fetch, Some(_) => Classified::Drop, } } @@ -608,22 +608,36 @@ impl E3 { } } - pub(crate) fn receive(&mut self, now: UnixSecs, message: PeerMessage) -> Vec { + pub(crate) fn receive( + &mut self, + now: UnixSecs, + message: PeerMessage, + signatures_already_verified: bool, + ) -> Vec { let slot = (message.sender, message.body.kind()); - if self - .fetching - .get(&slot) - .is_some_and(|fetching| fetching.id == message.id()) - { - self.fetching.remove(&slot); - } + let fetched_verified = if self.fetching.contains_key(&slot) { + let id = message.id(); + if self + .fetching + .get(&slot) + .is_some_and(|fetching| fetching.id == id) + { + self.fetching.remove(&slot); + true + } else { + false + } + } else { + false + }; + let verified = signatures_already_verified || fetched_verified; let mut effects = match message.body { Body::Dkg(body) => match self.dkg_mut() { - Some(dkg) => dkg.receive(now, message.sender, body), + Some(dkg) => dkg.receive(now, message.sender, body, verified), None => Vec::new(), }, Body::Decryption(body) => match self.decryption_mut() { - Some(decryption) => decryption.receive(now, message.sender, body), + Some(decryption) => decryption.receive(now, message.sender, body, verified), None => Vec::new(), }, Body::Accusation(body) => match &mut self.accusations { @@ -639,7 +653,7 @@ impl E3 { if result.answers_a_check() { self.checks = self.checks.saturating_sub(1); } - let fault = fault_of(&result); + let fault = result.fault(); let mut effects = match result { WorkResult::Dkg(result) => match self.dkg_mut() { Some(dkg) => dkg.job_done(now, result), @@ -713,10 +727,13 @@ impl E3 { /// A member that H members found sending a failing proof aggregates no phase of the E3, so it /// cannot hold a phase for its budget; the chain's expulsion follows the slash later. fn hand_over_from_convicted(&mut self, now: UnixSecs) -> Vec { - let convicted: Vec
= match &self.accusations { - Some(accusations) => accusations.convicted().iter().copied().collect(), - None => return Vec::new(), + let Some(accusations) = &self.accusations else { + return Vec::new(); }; + if accusations.convicted().is_empty() { + return Vec::new(); + } + let convicted: Vec
= accusations.convicted().iter().copied().collect(); let mut effects = Vec::new(); for member in convicted { if let Some(dkg) = self.dkg_mut() { @@ -908,6 +925,11 @@ impl E3 { self.dkg.as_ref().is_some_and(Dkg::running) } + /// Whether this node's DKG might still run `FoldProofs`. + pub(crate) fn dkg_might_fold(&self) -> bool { + self.running() && self.dkg.as_ref().is_some_and(Dkg::might_fold) + } + fn dkg_mut(&mut self) -> Option<&mut Dkg> { let running = self.running(); self.dkg.as_mut().filter(|_| running) @@ -918,23 +940,3 @@ impl E3 { self.decryption.as_mut().filter(|_| running) } } - -/// The member and the failing proof that a check found, if any. -fn fault_of(result: &WorkResult) -> Option<(Address, Fault)> { - let (member, verdict) = match result { - WorkResult::Dkg(DkgWorkResult::EncryptionKeyChecked { sender, verdict }) => { - (sender, verdict) - } - WorkResult::Dkg(DkgWorkResult::SharesChecked { dealer, verdict }) => (dealer, verdict), - WorkResult::Dkg(DkgWorkResult::DecryptionKeyChecked { member, verdict }) - | WorkResult::Dkg(DkgWorkResult::KeyshareChecked { member, verdict }) - | WorkResult::Decryption(DecryptionWorkResult::SharesChecked { member, verdict }) => { - (member, verdict) - } - _ => return None, - }; - match verdict { - Verdict::Fails(fault) => Some((*member, fault.clone())), - Verdict::Valid | Verdict::Invalid => None, - } -} diff --git a/crates/protocol/src/hold.rs b/crates/protocol/src/hold.rs new file mode 100644 index 0000000..5e03814 --- /dev/null +++ b/crates/protocol/src/hold.rs @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Bounded hold for peer messages that arrive before the chain fact that lets the node judge them, +//! and bounded memory of ended E3 IDs. Both maintain O(1) in-memory indices while preserving the +//! exact bincode wire/snapshot layout of their underlying queues. + +use crate::{node::PeerMessage, E3Id, UnixSecs}; +use alloy_primitives::{Address, B256}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::collections::{HashMap, HashSet, VecDeque}; + +pub(crate) const HOLD_FOR: UnixSecs = 10 * 60; +pub(crate) const HOLD_PER_SENDER_MESSAGES: usize = 64; +const HOLD_PER_SENDER_BYTES: u64 = 128 * 1024 * 1024; +const HOLD_PER_E3_MESSAGES: usize = 512; +const HOLD_PER_E3_BYTES: u64 = 128 * 1024 * 1024; +const HOLD_TOTAL_MESSAGES: usize = 1_024; +const HOLD_TOTAL_BYTES: u64 = 256 * 1024 * 1024; + +/// How many ended E3s the node remembers, to drop late peer messages for them. +const ENDED_MEMORY: usize = 1_024; + +#[derive(Clone, Debug, Default, Eq)] +pub(crate) struct Ended { + queue: VecDeque, + set: HashSet, +} + +impl PartialEq for Ended { + fn eq(&self, other: &Self) -> bool { + self.queue == other.queue + } +} + +impl Serialize for Ended { + fn serialize(&self, serializer: S) -> Result { + self.queue.serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for Ended { + fn deserialize>(deserializer: D) -> Result { + let queue = VecDeque::::deserialize(deserializer)?; + let set = queue.iter().copied().collect(); + Ok(Self { queue, set }) + } +} + +impl Ended { + pub(crate) fn contains(&self, e3: &E3Id) -> bool { + self.set.contains(e3) + } + + pub(crate) fn record(&mut self, e3: E3Id) { + self.queue.push_back(e3); + self.set.insert(e3); + if self.queue.len() > ENDED_MEMORY { + if let Some(evicted) = self.queue.pop_front() { + if !self.queue.contains(&evicted) { + self.set.remove(&evicted); + } + } + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Held { + message: PeerMessage, + expires: UnixSecs, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Usage { + messages: usize, + bytes: u64, +} + +impl Usage { + fn fits(self, max_messages: usize, max_bytes: u64, incoming: u64) -> bool { + self.messages < max_messages && self.bytes.saturating_add(incoming) <= max_bytes + } + + fn add(&mut self, bytes: u64) { + self.messages += 1; + self.bytes = self.bytes.saturating_add(bytes); + } + + fn sub(&mut self, bytes: u64) { + self.messages = self.messages.saturating_sub(1); + self.bytes = self.bytes.saturating_sub(bytes); + } +} + +/// Persisted layout of [`Hold`], kept identical to the original struct definition so snapshots +/// remain byte-for-byte compatible. +#[derive(Serialize, Deserialize)] +struct HoldRepr { + messages: VecDeque, +} + +/// Peer messages that wait for a chain fact, in arrival order. A message that would pass its +/// sender's, its E3's, or the node's share is refused, so no sender can push out another's: the +/// sender's re-send brings it again. A message that waits too long goes, so stale ones cannot +/// hold the room. +#[derive(Clone, Debug, Default, Eq)] +pub(crate) struct Hold { + messages: VecDeque, + /// Derived O(1) metadata aligned 1:1 with `messages`: `(id, size)`. + meta: VecDeque<(B256, u64)>, + ids: HashSet, + per_sender: HashMap, + per_e3: HashMap, + total: Usage, +} + +impl PartialEq for Hold { + fn eq(&self, other: &Self) -> bool { + self.messages == other.messages + } +} + +impl Serialize for Hold { + fn serialize(&self, serializer: S) -> Result { + HoldRepr { + messages: self.messages.clone(), + } + .serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for Hold { + fn deserialize>(deserializer: D) -> Result { + let repr = HoldRepr::deserialize(deserializer)?; + let mut hold = Self::default(); + for held in repr.messages { + let id = held.message.id(); + let size = held.message.size(); + hold.index_add(&held.message, id, size); + hold.messages.push_back(held); + hold.meta.push_back((id, size)); + } + Ok(hold) + } +} + +impl Hold { + fn index_add(&mut self, message: &PeerMessage, id: B256, size: u64) { + self.ids.insert(id); + self.per_sender.entry(message.sender).or_default().add(size); + self.per_e3.entry(message.e3).or_default().add(size); + self.total.add(size); + } + + fn index_remove(&mut self, message: &PeerMessage, id: B256, size: u64) { + self.ids.remove(&id); + if let Some(usage) = self.per_sender.get_mut(&message.sender) { + usage.sub(size); + if usage.messages == 0 { + self.per_sender.remove(&message.sender); + } + } + if let Some(usage) = self.per_e3.get_mut(&message.e3) { + usage.sub(size); + if usage.messages == 0 { + self.per_e3.remove(&message.e3); + } + } + self.total.sub(size); + } + + /// Whether a copy of `message` waits here already: its re-sends cost nothing. + pub(crate) fn holds(&self, message: &PeerMessage) -> bool { + if self.messages.is_empty() { + return false; + } + self.ids.contains(&message.id()) + } + + /// Whether every share `message` would count against has room for it. + pub(crate) fn has_room(&self, message: &PeerMessage) -> bool { + let size = message.size(); + let sender = self + .per_sender + .get(&message.sender) + .copied() + .unwrap_or_default(); + let e3 = self.per_e3.get(&message.e3).copied().unwrap_or_default(); + sender.fits(HOLD_PER_SENDER_MESSAGES, HOLD_PER_SENDER_BYTES, size) + && e3.fits(HOLD_PER_E3_MESSAGES, HOLD_PER_E3_BYTES, size) + && self.total.fits(HOLD_TOTAL_MESSAGES, HOLD_TOTAL_BYTES, size) + } + + pub(crate) fn hold(&mut self, now: UnixSecs, message: PeerMessage) { + let id = message.id(); + let size = message.size(); + self.index_add(&message, id, size); + self.messages.push_back(Held { + message, + expires: now.saturating_add(HOLD_FOR), + }); + self.meta.push_back((id, size)); + } + + pub(crate) fn take(&mut self, e3: &E3Id) -> Vec { + if !self.per_e3.contains_key(e3) { + return Vec::new(); + } + let mut taken = Vec::new(); + let mut kept_messages = VecDeque::with_capacity(self.messages.len()); + let mut kept_meta = VecDeque::with_capacity(self.meta.len()); + while let (Some(held), Some((id, size))) = + (self.messages.pop_front(), self.meta.pop_front()) + { + if &held.message.e3 == e3 { + self.index_remove(&held.message, id, size); + taken.push(held.message); + } else { + kept_messages.push_back(held); + kept_meta.push_back((id, size)); + } + } + self.messages = kept_messages; + self.meta = kept_meta; + taken + } + + pub(crate) fn pass_deadlines(&mut self, now: UnixSecs) { + if self.messages.is_empty() { + return; + } + let mut kept_messages = VecDeque::with_capacity(self.messages.len()); + let mut kept_meta = VecDeque::with_capacity(self.meta.len()); + while let (Some(held), Some((id, size))) = + (self.messages.pop_front(), self.meta.pop_front()) + { + if now < held.expires { + kept_messages.push_back(held); + kept_meta.push_back((id, size)); + } else { + self.index_remove(&held.message, id, size); + } + } + self.messages = kept_messages; + self.meta = kept_meta; + } + + pub(crate) fn next_deadline(&self) -> Option { + self.messages.iter().map(|held| held.expires).min() + } +} diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 06dcdef..7800f2a 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -14,6 +14,7 @@ pub mod decryption; pub mod dkg; mod e3; mod failover; +mod hold; mod ids; mod machine; pub mod node; diff --git a/crates/protocol/src/machine.rs b/crates/protocol/src/machine.rs index b18f313..9fbd82f 100644 --- a/crates/protocol/src/machine.rs +++ b/crates/protocol/src/machine.rs @@ -23,4 +23,11 @@ pub trait Machine: Serialize + DeserializeOwned { /// When the machine next needs a [`Tick`], if ever. fn next_deadline(&self) -> Option; + + /// Whether `effect` must be written to the durable outbox and explicitly acknowledged. + /// Ephemeral effects (such as operator log notes) are returned to the caller without + /// incurring outbox persistence or acknowledgment fsyncs. + fn is_durable_effect(_effect: &Self::Effect) -> bool { + true + } } diff --git a/crates/protocol/src/node.rs b/crates/protocol/src/node.rs index d38435b..59d32c7 100644 --- a/crates/protocol/src/node.rs +++ b/crates/protocol/src/node.rs @@ -11,7 +11,8 @@ pub use crate::e3::E3; use crate::{ accusation::{ - AccusationMessage, AccusationWork, AccusationWorkResult, Ballot, SignedVote, Slashing, + AccusationMessage, AccusationWork, AccusationWorkResult, Ballot, Fault, SignedVote, + Slashing, }, decryption::{ DecryptionMessage, DecryptionSignature, DecryptionWork, DecryptionWorkResult, @@ -21,6 +22,7 @@ use crate::{ AttestationContext, DkgFailure, DkgMessage, DkgSignature, DkgTiming, DkgWork, DkgWorkResult, KeyAnchor, KeyPublication, }, + hold::{Ended, Hold}, proof::{ProofType, ZkProof}, registry::Registry, selection::{candidate_owners, candidates, Eligible}, @@ -29,15 +31,16 @@ use crate::{ use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use e3_committee::CiphernodesCommitteeSize; use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::collections::{BTreeMap, BTreeSet}; /// A failed E3 that may still see accusations keeps its work for this long after the failure, /// plus the chain's maximum vote validity: longer than the DKG and decryption windows in which /// peers can still accuse, plus five minutes for votes. const SLASHABLE_FAILURE_GRACE: UnixSecs = 24 * 60 * 60 + 5 * 60; -/// How many ended E3s the node remembers, to drop late peer messages for them. -const ENDED_MEMORY: usize = 1_024; +/// Retention window for historical registry points once a chain's histories grow large. +const REGISTRY_PRUNE_LAG: UnixSecs = 24 * 60 * 60; +const REGISTRY_PRUNE_MIN_LEN: usize = 64; /// Where a chain fact sits in its chain's confirmed log. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -286,16 +289,17 @@ pub enum Kind { impl Body { pub fn kind(&self) -> Kind { match self { - Body::Dkg(DkgMessage::EncryptionKey(_)) => Kind::EncryptionKey, - Body::Dkg(DkgMessage::Shares(_)) => Kind::Shares, - Body::Dkg(DkgMessage::Ready(_)) => Kind::Ready, - Body::Dkg(DkgMessage::Roster(_)) => Kind::Roster, - Body::Dkg(DkgMessage::DecryptionKey(_)) => Kind::DecryptionKey, - Body::Dkg(DkgMessage::Keyshare(_)) => Kind::Keyshare, - Body::Dkg(DkgMessage::NodeFold(_)) => Kind::NodeFold, - Body::Decryption(DecryptionMessage::Shares(_)) => Kind::DecryptionShares, - Body::Accusation(AccusationMessage::Accuse { .. }) => Kind::Accusation, - Body::Accusation(AccusationMessage::Vote(_)) => Kind::Vote, + Body::Dkg(message) => message.kind(), + Body::Decryption(message) => message.kind(), + Body::Accusation(message) => message.kind(), + } + } + + /// Direct recipient for pairwise messages (such as DKG shares), or `None` for broadcasts. + pub fn recipient(&self) -> Option
{ + match self { + Body::Dkg(message) => message.recipient(), + Body::Decryption(_) | Body::Accusation(_) => None, } } } @@ -305,12 +309,14 @@ impl Body { pub const MAX_MESSAGE_BLOBS: usize = 128; impl PeerMessage { + /// Direct recipient for pairwise messages, or `None` for committee broadcasts. + pub fn recipient(&self) -> Option
{ + self.body.recipient() + } + /// Whether `node` uses this message: a share message only reaches its recipient's DKG. pub fn is_for(&self, node: Address) -> bool { - match &self.body { - Body::Dkg(DkgMessage::Shares(shares)) => shares.recipient == node, - _ => true, - } + self.recipient().is_none_or(|target| target == node) } /// The blobs a node that uses this message needs in its store. @@ -322,17 +328,33 @@ impl PeerMessage { } } + /// Number of blobs named by this message without allocating a `Vec`. + pub(crate) fn blob_count(&self) -> usize { + match &self.body { + Body::Dkg(message) => message.blob_count(), + Body::Decryption(message) => message.blob_count(), + Body::Accusation(message) => message.blob_count(), + } + } + + /// Total byte length of blobs named by this message without allocating a `Vec`. + pub(crate) fn blob_bytes(&self) -> u64 { + match &self.body { + Body::Dkg(message) => message.blob_bytes(), + Body::Decryption(message) => message.blob_bytes(), + Body::Accusation(message) => message.blob_bytes(), + } + } + /// The same for every copy and re-send of the message. pub fn id(&self) -> B256 { keccak256(bincode::serialize(self).expect("a peer message encodes")) } /// Its encoded bytes and the bytes of the blobs it would bring. - fn size(&self) -> u64 { + pub(crate) fn size(&self) -> u64 { let encoded = bincode::serialized_size(self).unwrap_or(u64::MAX); - self.blobs() - .iter() - .fold(encoded, |size, blob| size.saturating_add(blob.len)) + encoded.saturating_add(self.blob_bytes()) } } @@ -356,50 +378,28 @@ impl Work { /// Whether the job makes proofs, which can hold the machine for hours. The checks that a /// deadline waits on must not queue behind them. pub fn proves(&self) -> bool { - matches!( - self, - Work::Dkg( - DkgWork::MakeEncryptionKey - | DkgWork::MakeShares { .. } - | DkgWork::MakeDecryptionKey { .. } - | DkgWork::FoldProofs { .. } - | DkgWork::FoldRoster { .. } - | DkgWork::AggregateKey { .. } - ) | Work::Decryption( - DecryptionWork::MakeShares { .. } | DecryptionWork::AggregatePlaintext { .. } - ) - ) + match self { + Work::Dkg(work) => work.proves(), + Work::Decryption(work) => work.proves(), + Work::Accusation(_) => false, + } } /// Whether the job checks a proof a member signed, which can end in an accusation. fn checks_a_member(&self) -> bool { - matches!( - self, - Work::Dkg( - DkgWork::CheckEncryptionKey { .. } - | DkgWork::CheckShares { .. } - | DkgWork::CheckDecryptionKey { .. } - | DkgWork::CheckKeyshare { .. } - ) | Work::Decryption(DecryptionWork::CheckShares { .. }) - | Work::Accusation(_) - ) + match self { + Work::Dkg(work) => work.checks_a_member(), + Work::Decryption(work) => work.checks_a_member(), + Work::Accusation(_) => true, + } } /// The kind of work, for logs. pub fn name(&self) -> &'static str { match self { - Work::Dkg(DkgWork::MakeEncryptionKey) => "dkg: make the encryption key", - Work::Dkg(DkgWork::CheckEncryptionKey { .. }) => "dkg: check an encryption key", - Work::Dkg(DkgWork::MakeShares { .. }) => "dkg: deal shares", - Work::Dkg(DkgWork::CheckShares { .. }) => "dkg: check a dealer's shares", - Work::Dkg(DkgWork::MakeDecryptionKey { .. }) => "dkg: make the decryption key", - Work::Dkg(DkgWork::CheckDecryptionKey { .. }) => "dkg: check a decryption key", - Work::Dkg(DkgWork::FoldProofs { .. }) => "dkg: fold this node's proofs", - Work::Dkg(DkgWork::CheckKeyshare { .. }) => "dkg: check a keyshare", - Work::Dkg(DkgWork::FoldRoster { .. }) => "dkg: fold a roster member's proof", - Work::Dkg(DkgWork::AggregateKey { .. }) => "dkg: aggregate the committee key", - Work::Decryption(_) => "decryption", - Work::Accusation(_) => "accusation: verify a proof", + Work::Dkg(work) => work.name(), + Work::Decryption(work) => work.name(), + Work::Accusation(work) => work.name(), } } } @@ -420,16 +420,20 @@ pub enum WorkResult { impl WorkResult { /// Whether this answers a job for which [`Work::checks_a_member`] holds. pub(crate) fn answers_a_check(&self) -> bool { - matches!( - self, - Self::Dkg( - DkgWorkResult::EncryptionKeyChecked { .. } - | DkgWorkResult::SharesChecked { .. } - | DkgWorkResult::DecryptionKeyChecked { .. } - | DkgWorkResult::KeyshareChecked { .. } - ) | Self::Decryption(DecryptionWorkResult::SharesChecked { .. }) - | Self::Accusation(_) - ) + match self { + Self::Dkg(result) => result.answers_a_check(), + Self::Decryption(result) => result.answers_a_check(), + Self::Accusation(_) => true, + } + } + + /// The member and failing proof that a check found, if any. + pub(crate) fn fault(&self) -> Option<(Address, Fault)> { + match self { + Self::Dkg(result) => result.fault(), + Self::Decryption(result) => result.fault(), + Self::Accusation(_) => None, + } } } @@ -746,14 +750,14 @@ pub struct Admission { pub committees: BTreeMap>, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Eq, Serialize, Deserialize)] pub struct Node { me: Address, e3s: BTreeMap, /// Each chain's operator registry over time. registries: BTreeMap, held: Hold, - ended: VecDeque, + ended: Ended, applied: BTreeMap, vote_validity: BTreeMap, /// Each chain's randomness providers and slashing managers, so the chain adapter reads their @@ -764,6 +768,25 @@ pub struct Node { slashing: BTreeMap, /// The node takes no new E3: it submits no ticket, and the E3s it holds go on to their end. draining: bool, + /// Monotonic counter bumped whenever [`Self::admission`] may have changed; not persisted. + #[serde(skip)] + admission_epoch: u64, +} + +impl PartialEq for Node { + fn eq(&self, other: &Self) -> bool { + self.me == other.me + && self.e3s == other.e3s + && self.registries == other.registries + && self.held == other.held + && self.ended == other.ended + && self.applied == other.applied + && self.vote_validity == other.vote_validity + && self.providers == other.providers + && self.managers == other.managers + && self.slashing == other.slashing + && self.draining == other.draining + } } impl Node { @@ -773,16 +796,27 @@ impl Node { e3s: BTreeMap::new(), registries: BTreeMap::new(), held: Hold::default(), - ended: VecDeque::new(), + ended: Ended::default(), applied: BTreeMap::new(), vote_validity: BTreeMap::new(), providers: BTreeMap::new(), managers: BTreeMap::new(), slashing: BTreeMap::new(), draining: false, + admission_epoch: 0, } } + /// Monotonic revision of [`Self::admission`]; callers can skip rebuilding and publishing + /// admission updates while this value is unchanged. + pub fn admission_epoch(&self) -> u64 { + self.admission_epoch + } + + fn touch_admission(&mut self) { + self.admission_epoch = self.admission_epoch.wrapping_add(1); + } + pub fn randomness_providers(&self, chain_id: u64) -> impl Iterator { self.providers.get(&chain_id).into_iter().flatten() } @@ -859,6 +893,11 @@ impl Node { }) } + /// Whether this node might still run `FoldProofs` for `e3`. + pub fn might_fold(&self, e3: &E3Id) -> bool { + self.e3s.get(e3).is_some_and(E3::dkg_might_fold) + } + /// The position of the last fact this node applied from chain `chain_id`. pub fn applied(&self, chain_id: u64) -> Option { self.applied.get(&chain_id).copied() @@ -927,14 +966,17 @@ impl Node { ChainFact::SeedReady { e3, seed } => self.select(now, e3, seed), ChainFact::OperatorActive { operator, active } => { registry.set_active(time, operator, active); + self.touch_admission(); self.select_again_if_me(now, operator) } ChainFact::TicketBalance { operator, balance } => { registry.set_balance(time, operator, balance); + self.touch_admission(); Vec::new() } ChainFact::BondOwner { operator, owner } => { registry.set_owner(time, operator, owner); + self.touch_admission(); Vec::new() } ChainFact::EligibilityReset => { @@ -943,6 +985,7 @@ impl Node { } ChainFact::OperatorEnabled { operator, enabled } => { registry.set_enabled(operator, enabled); + self.touch_admission(); self.select_again_if_me(now, operator) } ChainFact::CommitteeFinalized { @@ -960,6 +1003,7 @@ impl Node { return Vec::new(); }; let mut effects = state.finalize(now, members, dkg); + self.touch_admission(); effects.extend(self.release_held(now, e3)); effects } @@ -1025,7 +1069,11 @@ impl Node { Vec::new() } ChainFact::MemberExpelled { e3, member } => match self.e3s.get_mut(&e3) { - Some(state) => state.expel(now, member), + Some(state) => { + let effects = state.expel(now, member); + self.touch_admission(); + effects + } None => Vec::new(), }, ChainFact::VoteValidity { secs } => { @@ -1133,14 +1181,17 @@ impl Node { if let Some(confirmed) = confirmed { eligible.retain(|operator| confirmed.contains(&operator.operator)); } - let owner_cap = request.owner_cap && confirmed.is_some(); - let committee = state.params.committee_size.values(); - let owners = candidate_owners(committee.n, committee.threshold); - let ranked = candidates(e3, seed, &eligible, owner_cap, owners); let tickets = eligible .iter() .find(|operator| operator.operator == self.me) .map_or(0, |operator| operator.tickets); + if tickets == 0 || active_jobs >= tickets { + return Vec::new(); + } + let owner_cap = request.owner_cap && confirmed.is_some(); + let committee = state.params.committee_size.values(); + let owners = candidate_owners(committee.n, committee.threshold); + let ranked = candidates(e3, seed, &eligible, owner_cap, owners); let Some((rank, mine)) = ranked .iter() .enumerate() @@ -1148,9 +1199,6 @@ impl Node { else { return Vec::new(); }; - if active_jobs >= tickets { - return Vec::new(); - } let ticket = mine.ticket; match self.e3s.get_mut(&e3) { Some(state) => state.submit_ticket(ticket, rank, committee_deadline), @@ -1159,13 +1207,27 @@ impl Node { } fn end(&mut self, e3: E3Id) { - if self.e3s.remove(&e3).is_none() { + let Some(removed) = self.e3s.remove(&e3) else { return; + }; + if !removed.committee().is_empty() { + self.touch_admission(); } self.held.take(&e3); - self.ended.push_back(e3); - if self.ended.len() > ENDED_MEMORY { - self.ended.pop_front(); + self.ended.record(e3); + // Bound registry history growth once E3s complete, keeping all timestamps still needed by + // any open request on this chain. + if let Some(cutoff) = self + .e3s + .iter() + .filter(|(id, state)| id.chain_id == e3.chain_id && state.stage == Stage::Requested) + .map(|(_, state)| state.request.time.saturating_sub(1)) + .min() + .or_else(|| removed.request.time.checked_sub(REGISTRY_PRUNE_LAG)) + { + if let Some(registry) = self.registries.get_mut(&e3.chain_id) { + registry.prune_before(cutoff, REGISTRY_PRUNE_MIN_LEN); + } } } @@ -1177,7 +1239,7 @@ impl Node { pub fn classify(&self, now: UnixSecs, message: &PeerMessage) -> Classified { if self.ended.contains(&message.e3) || !message.is_for(self.me) - || message.blobs().len() > MAX_MESSAGE_BLOBS + || message.blob_count() > MAX_MESSAGE_BLOBS { return Classified::Drop; } @@ -1199,7 +1261,7 @@ impl Node { Classified::Deliver => self .e3s .get_mut(&message.e3) - .map_or_else(Vec::new, |state| state.receive(now, message)), + .map_or_else(Vec::new, |state| state.receive(now, message, true)), Classified::Fetch => self .e3s .get_mut(&message.e3) @@ -1212,7 +1274,7 @@ impl Node { return Vec::new(); } match self.e3s.get_mut(&message.e3) { - Some(state) if state.routes(&message.body) => state.receive(now, message), + Some(state) if state.routes(&message.body) => state.receive(now, message, false), _ => Vec::new(), } } @@ -1353,99 +1415,20 @@ impl Machine for Node { let e3s = self.e3s.values().filter_map(E3::next_deadline); e3s.chain(self.held.next_deadline()).min() } -} - -/// Peer messages that wait for a chain fact, in arrival order. A message that would pass its -/// sender's, its E3's, or the node's share is refused, so no sender can push out another's: the -/// sender's re-send brings it again. A message that waits too long goes, so stale ones cannot -/// hold the room. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -struct Hold { - messages: VecDeque, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct Held { - message: PeerMessage, - expires: UnixSecs, -} - -const HOLD_FOR: UnixSecs = 10 * 60; -const HOLD_PER_SENDER_MESSAGES: usize = 64; -const HOLD_PER_SENDER_BYTES: u64 = 128 * 1024 * 1024; -const HOLD_PER_E3_MESSAGES: usize = 512; -const HOLD_PER_E3_BYTES: u64 = 128 * 1024 * 1024; -const HOLD_TOTAL_MESSAGES: usize = 1_024; -const HOLD_TOTAL_BYTES: u64 = 256 * 1024 * 1024; - -impl Hold { - /// Whether a copy of `message` waits here already: its re-sends cost nothing. - fn holds(&self, message: &PeerMessage) -> bool { - self.messages.iter().any(|held| held.message == *message) - } - - /// Whether every share `message` would count against has room for it. - fn has_room(&self, message: &PeerMessage) -> bool { - let size = message.size(); - let sender = self.usage(|held| held.sender == message.sender); - let e3 = self.usage(|held| held.e3 == message.e3); - let total = self.usage(|_| true); - sender.fits(HOLD_PER_SENDER_MESSAGES, HOLD_PER_SENDER_BYTES, size) - && e3.fits(HOLD_PER_E3_MESSAGES, HOLD_PER_E3_BYTES, size) - && total.fits(HOLD_TOTAL_MESSAGES, HOLD_TOTAL_BYTES, size) - } - - fn hold(&mut self, now: UnixSecs, message: PeerMessage) { - self.messages.push_back(Held { - message, - expires: now.saturating_add(HOLD_FOR), - }); - } - - fn take(&mut self, e3: &E3Id) -> Vec { - let (taken, kept): (VecDeque<_>, VecDeque<_>) = self - .messages - .drain(..) - .partition(|held| &held.message.e3 == e3); - self.messages = kept; - taken.into_iter().map(|held| held.message).collect() - } - - fn pass_deadlines(&mut self, now: UnixSecs) { - self.messages.retain(|held| now < held.expires); - } - - fn next_deadline(&self) -> Option { - self.messages.iter().map(|held| held.expires).min() - } - - fn usage(&self, counts: impl Fn(&PeerMessage) -> bool) -> Usage { - self.messages - .iter() - .filter(|held| counts(&held.message)) - .fold(Usage::default(), |usage, held| Usage { - messages: usage.messages + 1, - bytes: usage.bytes + held.message.size(), - }) - } -} - -#[derive(Default)] -struct Usage { - messages: usize, - bytes: u64, -} -impl Usage { - fn fits(&self, max_messages: usize, max_bytes: u64, incoming: u64) -> bool { - self.messages < max_messages && self.bytes.saturating_add(incoming) <= max_bytes + fn is_durable_effect(effect: &Effect) -> bool { + !matches!(effect, Effect::Note(_)) } } #[cfg(test)] mod tests { use super::*; - use crate::{dkg::DkgProofs, testing::*}; + use crate::{ + dkg::DkgProofs, + hold::{HOLD_FOR, HOLD_PER_SENDER_MESSAGES}, + testing::*, + }; fn node() -> Node { Node::new(address(ME)) diff --git a/crates/protocol/src/registry.rs b/crates/protocol/src/registry.rs index 3399bda..66d3d6e 100644 --- a/crates/protocol/src/registry.rs +++ b/crates/protocol/src/registry.rs @@ -57,6 +57,18 @@ impl History { fn latest(&self) -> Option { self.points.last().map(|(_, value)| *value) } + + /// Drops history points older than `cutoff`, keeping the latest point at or before `cutoff` + /// so every lookup at `time >= cutoff` returns the exact same value. + fn prune_before(&mut self, cutoff: UnixSecs) { + let keep_from = self + .points + .partition_point(|(at, _)| *at <= cutoff) + .saturating_sub(1); + if keep_from > 0 { + self.points.drain(..keep_from); + } + } } impl Registry { @@ -126,6 +138,22 @@ impl Registry { self.operators.keys().copied() } + /// Drops historical points strictly superseded before `cutoff` across all operators once a + /// history grows past `min_len`, preserving exact `at(time)` answers for all `time >= cutoff`. + pub(crate) fn prune_before(&mut self, cutoff: UnixSecs, min_len: usize) { + for operator in self.operators.values_mut() { + if operator.active.points.len() > min_len { + operator.active.prune_before(cutoff); + } + if operator.balance.points.len() > min_len { + operator.balance.prune_before(cutoff); + } + if operator.owner.points.len() > min_len { + operator.owner.prune_before(cutoff); + } + } + } + /// Every operator active at `time` with at least one ticket at `price`, and its owner then. pub(crate) fn eligible_at(&self, time: UnixSecs, price: U256) -> Vec { if price.is_zero() { @@ -232,4 +260,23 @@ mod tests { assert!(!registry.can_submit(operator(1))); assert!(!registry.can_submit(operator(2))); } + + #[test] + fn pruning_before_cutoff_preserves_lookups_at_and_after_cutoff() { + let mut registry = Registry::default(); + for t in 1..=10 { + registry.set_active(t * 10, operator(1), t % 2 == 1); + registry.set_balance(t * 10, operator(1), U256::from(t * 100)); + registry.set_owner(t * 10, operator(1), operator(t as u8)); + } + let before: Vec<_> = (50..=120) + .map(|t| registry.eligible_at(t, U256::from(10))) + .collect(); + registry.prune_before(50, 2); + let after: Vec<_> = (50..=120) + .map(|t| registry.eligible_at(t, U256::from(10))) + .collect(); + assert_eq!(before, after); + assert!(registry.operators[&operator(1)].balance.points.len() <= 6); + } } diff --git a/crates/protocol/src/selection.rs b/crates/protocol/src/selection.rs index 4eaf900..df8b453 100644 --- a/crates/protocol/src/selection.rs +++ b/crates/protocol/src/selection.rs @@ -10,13 +10,20 @@ use crate::E3Id; use alloy_primitives::{keccak256, Address, U256}; -use alloy_sol_types::SolValue; use std::collections::BTreeMap; +/// Packed layout of `abi.encodePacked(address operator, uint256 ticketNumber, uint256 e3Id, uint256 seed)`: +/// 20 + 32 + 32 + 32 = 116 bytes. +const PACKED_TICKET_LEN: usize = 20 + 32 + 32 + 32; + /// An operator's ticket score, as the registry computes it: `keccak256(abi.encodePacked(operator, /// ticketNumber, e3Id, seed))`. Lower is better. pub fn ticket_score(operator: Address, ticket: u64, e3: E3Id, seed: U256) -> U256 { - let packed = (operator, U256::from(ticket), e3.number, seed).abi_encode_packed(); + let mut packed = [0u8; PACKED_TICKET_LEN]; + packed[0..20].copy_from_slice(operator.as_slice()); + packed[44..52].copy_from_slice(&ticket.to_be_bytes()); + packed[52..84].copy_from_slice(&e3.number.to_be_bytes::<32>()); + packed[84..116].copy_from_slice(&seed.to_be_bytes::<32>()); U256::from_be_bytes(keccak256(packed).0) } @@ -93,14 +100,29 @@ pub(crate) fn candidates( } fn best_ticket(e3: E3Id, seed: U256, operator: &Eligible) -> Candidate { - (1..=operator.tickets) - .map(|ticket| Candidate { - operator: operator.operator, - ticket, - score: ticket_score(operator.operator, ticket, e3, seed), - }) - .min_by_key(|candidate| (candidate.score, candidate.ticket)) - .expect("an operator with tickets has a best one") + // Pre-fill the invariant 108 bytes once so each ticket only overwrites its 8-byte counter. + let mut packed = [0u8; PACKED_TICKET_LEN]; + packed[0..20].copy_from_slice(operator.operator.as_slice()); + packed[52..84].copy_from_slice(&e3.number.to_be_bytes::<32>()); + packed[84..116].copy_from_slice(&seed.to_be_bytes::<32>()); + + let mut best_ticket_num = 1u64; + packed[44..52].copy_from_slice(&1u64.to_be_bytes()); + let mut best_score = U256::from_be_bytes(keccak256(packed).0); + + for ticket in 2..=operator.tickets { + packed[44..52].copy_from_slice(&ticket.to_be_bytes()); + let score = U256::from_be_bytes(keccak256(packed).0); + if score < best_score { + best_score = score; + best_ticket_num = ticket; + } + } + Candidate { + operator: operator.operator, + ticket: best_ticket_num, + score: best_score, + } } #[cfg(test)] diff --git a/crates/state/blobs/src/lib.rs b/crates/state/blobs/src/lib.rs index a410097..de86157 100644 --- a/crates/state/blobs/src/lib.rs +++ b/crates/state/blobs/src/lib.rs @@ -13,7 +13,7 @@ use alloy_primitives::{keccak256, B256, U256}; use e3_protocol::{BlobRef, E3Id, SealedRef}; use std::{ - collections::{BTreeSet, HashMap}, + collections::{BTreeSet, HashMap, HashSet, VecDeque}, fs::{self, File}, io::{self, Write}, path::{Path, PathBuf}, @@ -23,6 +23,21 @@ use std::{ }, }; +/// Maximum closed E3 IDs remembered in memory to refuse late writes without unbounded growth. +const MAX_CLOSED: usize = 16_384; +/// Default in-memory LRU cache capacity for verified public blobs served to peers. +const PUBLIC_CACHE_MAX_BYTES: usize = 64 * 1024 * 1024; +/// Largest single blob retained in the public serving cache. +const PUBLIC_CACHE_MAX_ENTRY_BYTES: usize = 16 * 1024 * 1024; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BlobCacheStats { + pub hits: u64, + pub misses: u64, + pub bytes: usize, + pub entries: usize, +} + #[derive(Debug, thiserror::Error)] pub enum BlobError { #[error("item {0} is not in the store")] @@ -38,11 +53,42 @@ pub enum BlobError { /// What a node stores, by the E3 whose work made or fetched it. pub trait BlobStore: Clone + Send + Sync + 'static { fn put(&self, e3: E3Id, bytes: &[u8]) -> Result; + /// Verifies `bytes` against `expected` in a single hash pass and stores it if absent. + /// Returns `Ok(false)` without writing when length or digest does not match `expected`. + fn put_verified(&self, e3: E3Id, expected: &BlobRef, bytes: &[u8]) -> Result { + if bytes.len() as u64 != expected.len || keccak256(bytes) != expected.hash { + return Ok(false); + } + if !self.has(e3, expected) { + self.put(e3, bytes)?; + } + Ok(true) + } + /// Verifies and stores a batch of public blobs for one E3, amortising directory syncs. + fn put_verified_batch( + &self, + e3: E3Id, + items: &[(&BlobRef, &[u8])], + ) -> Result, BlobError> { + let mut results = Vec::with_capacity(items.len()); + for (expected, bytes) in items { + results.push(self.put_verified(e3, expected, bytes)?); + } + Ok(results) + } fn get(&self, e3: E3Id, blob: &BlobRef) -> Result, BlobError>; fn has(&self, e3: E3Id, blob: &BlobRef) -> bool; /// The public blob of `e3` with this hash, for a peer that asks. This is the only way out of /// the store for the network. fn serve(&self, e3: E3Id, hash: &B256) -> Option>; + /// Zero-copy shared view of a public blob for peer serving. + fn serve_shared(&self, e3: E3Id, hash: &B256) -> Option> { + self.serve(e3, hash).map(Arc::from) + } + /// Cache telemetry for observability endpoints. + fn cache_stats(&self) -> BlobCacheStats { + BlobCacheStats::default() + } /// Stores bytes that the node's cipher already sealed. fn put_sealed(&self, e3: E3Id, bytes: &[u8]) -> Result; fn get_sealed(&self, e3: E3Id, secret: &SealedRef) -> Result, BlobError>; @@ -121,7 +167,8 @@ struct Closing { #[derive(Default)] struct Writes { running: HashMap, - closed: BTreeSet, + closed: HashSet, + closed_order: VecDeque, } impl Closing { @@ -147,7 +194,14 @@ impl Closing { fn close(&self, e3: E3Id) { let mut writes = self.lock(); - writes.closed.insert(e3); + if writes.closed.insert(e3) { + writes.closed_order.push_back(e3); + while writes.closed_order.len() > MAX_CLOSED { + if let Some(evicted) = writes.closed_order.pop_front() { + writes.closed.remove(&evicted); + } + } + } while writes.running.contains_key(&e3) { writes = self .finished @@ -281,6 +335,140 @@ impl BlobStore for MemoryBlobs { } } +/// Bounded LRU cache of hash-verified public blobs for zero-copy peer serving. +struct PublicCache { + inner: Mutex, + hits: AtomicU64, + misses: AtomicU64, + max_bytes: usize, + max_entry_bytes: usize, +} + +type CacheKey = (E3Id, B256); +type CacheValue = (Arc<[u8]>, u64); + +#[derive(Default)] +struct PublicCacheInner { + entries: HashMap, + order: VecDeque<(u64, CacheKey)>, + bytes: usize, + clock: u64, +} + +impl PublicCache { + fn new(max_bytes: usize, max_entry_bytes: usize) -> Self { + Self { + inner: Mutex::new(PublicCacheInner::default()), + hits: AtomicU64::new(0), + misses: AtomicU64::new(0), + max_bytes, + max_entry_bytes, + } + } + + fn lock(&self) -> MutexGuard<'_, PublicCacheInner> { + self.inner.lock().expect("no holder of the lock panics") + } + + fn get(&self, e3: E3Id, hash: &B256) -> Option> { + let mut inner = self.lock(); + let key = (e3, *hash); + let now = inner.clock + 1; + if let Some((bytes, tick)) = inner.entries.get_mut(&key) { + let shared = Arc::clone(bytes); + *tick = now; + inner.clock = now; + inner.order.push_back((now, key)); + compact_order(&mut inner); + drop(inner); + self.hits.fetch_add(1, Ordering::Relaxed); + return Some(shared); + } + drop(inner); + self.misses.fetch_add(1, Ordering::Relaxed); + None + } + + fn insert(&self, e3: E3Id, hash: B256, bytes: Arc<[u8]>) { + if bytes.len() > self.max_entry_bytes || bytes.len() > self.max_bytes { + return; + } + let mut inner = self.lock(); + let key = (e3, hash); + inner.clock += 1; + let now = inner.clock; + if let Some((_, tick)) = inner.entries.get_mut(&key) { + *tick = now; + inner.order.push_back((now, key)); + compact_order(&mut inner); + return; + } + inner.bytes += bytes.len(); + inner.entries.insert(key, (bytes, now)); + inner.order.push_back((now, key)); + while inner.bytes > self.max_bytes { + let Some((tick, victim)) = inner.order.pop_front() else { + break; + }; + if inner + .entries + .get(&victim) + .is_some_and(|(_, current)| *current == tick) + { + if let Some((removed, _)) = inner.entries.remove(&victim) { + inner.bytes = inner.bytes.saturating_sub(removed.len()); + } + } + } + compact_order(&mut inner); + } + + fn remove(&self, e3: E3Id, hash: &B256) { + let mut inner = self.lock(); + if let Some((removed, _)) = inner.entries.remove(&(e3, *hash)) { + inner.bytes = inner.bytes.saturating_sub(removed.len()); + } + } + + fn evict_e3(&self, e3: E3Id) { + let mut inner = self.lock(); + let mut freed = 0usize; + inner.entries.retain(|(id, _), (bytes, _)| { + if *id == e3 { + freed += bytes.len(); + false + } else { + true + } + }); + inner.bytes = inner.bytes.saturating_sub(freed); + if freed > 0 { + inner.order.retain(|(_, (id, _))| *id != e3); + } + } + + fn stats(&self) -> BlobCacheStats { + let inner = self.lock(); + BlobCacheStats { + hits: self.hits.load(Ordering::Relaxed), + misses: self.misses.load(Ordering::Relaxed), + bytes: inner.bytes, + entries: inner.entries.len(), + } + } +} + +fn compact_order(inner: &mut PublicCacheInner) { + let limit = inner.entries.len().saturating_mul(4).max(128); + if inner.order.len() <= limit { + return; + } + let entries = &inner.entries; + inner + .order + .retain(|(tick, key)| entries.get(key).is_some_and(|(_, current)| current == tick)); +} + /// Files, one directory per E3 with one folder per space, each file named by its hash or key. A /// step that names an item is journaled after the write returns, so a write returns only once the /// file is complete on disk. @@ -288,6 +476,7 @@ impl BlobStore for MemoryBlobs { pub struct FileBlobs { dir: PathBuf, closing: Arc, + public_cache: Arc, } /// Numbers each write's partial file, so two writers of one item never share one. @@ -313,6 +502,10 @@ impl FileBlobs { Ok(Self { dir, closing: Arc::default(), + public_cache: Arc::new(PublicCache::new( + PUBLIC_CACHE_MAX_BYTES, + PUBLIC_CACHE_MAX_ENTRY_BYTES, + )), }) } @@ -324,21 +517,37 @@ impl FileBlobs { self.e3_dir(e3).join(space.folder()).join(name.to_string()) } - fn write(&self, e3: E3Id, space: Space, name: &B256, bytes: &[u8]) -> Result<(), BlobError> { - let path = self.path(e3, space, name); - let folder = path.parent().expect("an item's path has a folder"); + fn ensure_folder(&self, e3: E3Id, folder: &Path) -> Result<(), BlobError> { if !folder.exists() { fs::create_dir_all(folder)?; sync_dir(&self.e3_dir(e3))?; sync_dir(&self.dir)?; } + Ok(()) + } + + fn write_without_dir_sync( + &self, + e3: E3Id, + space: Space, + name: &B256, + bytes: &[u8], + ) -> Result { + let path = self.path(e3, space, name); + let folder = path.parent().expect("an item's path has a folder"); + self.ensure_folder(e3, folder)?; let write = WRITES.fetch_add(1, Ordering::Relaxed); let partial = path.with_extension(format!("{}-{write}.partial", std::process::id())); let mut file = File::create(&partial)?; file.write_all(bytes)?; - file.sync_all()?; + file.sync_data()?; fs::rename(&partial, &path)?; - sync_dir(folder)?; + Ok(folder.to_path_buf()) + } + + fn write(&self, e3: E3Id, space: Space, name: &B256, bytes: &[u8]) -> Result<(), BlobError> { + let folder = self.write_without_dir_sync(e3, space, name, bytes)?; + sync_dir(&folder)?; Ok(()) } @@ -349,6 +558,9 @@ impl FileBlobs { match fs::read(&path) { Ok(bytes) if keccak256(&bytes) == *hash => Ok(bytes), Ok(_) => { + if space == Space::Public { + self.public_cache.remove(e3, hash); + } fs::remove_file(&path)?; Err(BlobError::Corrupt(*hash)) } @@ -386,9 +598,65 @@ impl BlobStore for FileBlobs { self.closing .write(e3, || self.write(e3, Space::Public, &blob.hash, bytes))?; } + self.public_cache.insert(e3, blob.hash, Arc::from(bytes)); Ok(blob) } + fn put_verified(&self, e3: E3Id, expected: &BlobRef, bytes: &[u8]) -> Result { + if bytes.len() as u64 != expected.len || keccak256(bytes) != expected.hash { + return Ok(false); + } + if !self.has(e3, expected) { + self.closing + .write(e3, || self.write(e3, Space::Public, &expected.hash, bytes))?; + } + self.public_cache + .insert(e3, expected.hash, Arc::from(bytes)); + Ok(true) + } + + fn put_verified_batch( + &self, + e3: E3Id, + items: &[(&BlobRef, &[u8])], + ) -> Result, BlobError> { + let mut results = vec![false; items.len()]; + let mut to_write: Vec<(&BlobRef, &[u8])> = Vec::new(); + let mut seen = HashSet::new(); + for (idx, (expected, bytes)) in items.iter().enumerate() { + if bytes.len() as u64 == expected.len && keccak256(bytes) == expected.hash { + results[idx] = true; + if seen.insert(expected.hash) && !self.has(e3, expected) { + to_write.push((*expected, *bytes)); + } + } + } + if !to_write.is_empty() { + self.closing.write(e3, || { + let mut folder = None; + for (expected, bytes) in &to_write { + folder = Some(self.write_without_dir_sync( + e3, + Space::Public, + &expected.hash, + bytes, + )?); + } + if let Some(folder) = folder { + sync_dir(&folder)?; + } + Ok(()) + })?; + } + for (idx, (expected, bytes)) in items.iter().enumerate() { + if results[idx] { + self.public_cache + .insert(e3, expected.hash, Arc::from(*bytes)); + } + } + Ok(results) + } + fn get(&self, e3: E3Id, blob: &BlobRef) -> Result, BlobError> { self.read_named(e3, Space::Public, &blob.hash) } @@ -400,13 +668,31 @@ impl BlobStore for FileBlobs { } fn serve(&self, e3: E3Id, hash: &B256) -> Option> { - self.read_named(e3, Space::Public, hash).ok() + self.serve_shared(e3, hash).map(|bytes| bytes.to_vec()) + } + + fn serve_shared(&self, e3: E3Id, hash: &B256) -> Option> { + if let Some(cached) = self.public_cache.get(e3, hash) { + return Some(cached); + } + let bytes = self.read_named(e3, Space::Public, hash).ok()?; + let shared: Arc<[u8]> = Arc::from(bytes); + self.public_cache.insert(e3, *hash, Arc::clone(&shared)); + Some(shared) + } + + fn cache_stats(&self) -> BlobCacheStats { + self.public_cache.stats() } fn put_sealed(&self, e3: E3Id, bytes: &[u8]) -> Result { let secret = SealedRef::of(bytes); - self.closing - .write(e3, || self.write(e3, Space::Sealed, &secret.hash, bytes))?; + let exists = fs::metadata(self.path(e3, Space::Sealed, &secret.hash)) + .is_ok_and(|file| file.len() == bytes.len() as u64); + if !exists { + self.closing + .write(e3, || self.write(e3, Space::Sealed, &secret.hash, bytes))?; + } Ok(secret) } @@ -442,6 +728,7 @@ impl BlobStore for FileBlobs { fn close(&self, e3: E3Id) -> Result<(), BlobError> { self.closing.close(e3); + self.public_cache.evict_e3(e3); match fs::remove_dir_all(self.e3_dir(e3)) { Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error.into()), _ => Ok(()), @@ -659,4 +946,30 @@ mod tests { assert!(!blobs.has(e3(1), &blob)); assert_eq!(blobs.get(e3(2), &blob).unwrap(), b"proof"); } + + #[test] + fn put_verified_batch_and_shared_serve_cache_work_and_evict_on_close() { + let dir = tempfile::tempdir().unwrap(); + let blobs = FileBlobs::open(dir.path()).unwrap(); + let a = BlobRef::of(b"alpha"); + let b = BlobRef::of(b"beta"); + let bad = BlobRef::of(b"expected"); + + let ok = blobs + .put_verified_batch(e3(1), &[(&a, b"alpha"), (&bad, b"wrong"), (&b, b"beta")]) + .unwrap(); + assert_eq!(ok, vec![true, false, true]); + assert!(blobs.has(e3(1), &a)); + assert!(!blobs.has(e3(1), &bad)); + assert!(blobs.has(e3(1), &b)); + + let s1 = blobs.serve_shared(e3(1), &a.hash).unwrap(); + let s2 = blobs.serve_shared(e3(1), &a.hash).unwrap(); + assert!(Arc::ptr_eq(&s1, &s2)); + assert!(blobs.cache_stats().hits >= 2); + + blobs.close(e3(1)).unwrap(); + assert!(blobs.serve_shared(e3(1), &a.hash).is_none()); + assert_eq!(blobs.cache_stats().entries, 0); + } } diff --git a/crates/state/journal/src/lib.rs b/crates/state/journal/src/lib.rs index 23c1748..d3485c6 100644 --- a/crates/state/journal/src/lib.rs +++ b/crates/state/journal/src/lib.rs @@ -7,7 +7,7 @@ //! The v2 node's durable store: the journal, the latest snapshot, and the outbox in one redb file. //! Every commit is one fsynced redb transaction. -use e3_engine::{EffectKey, Step, Store, StoreError, Stored}; +use e3_engine::{BatchCommit, EffectKey, Step, Store, StoreError, Stored}; use redb::{ Database, ReadOnlyDatabase, ReadableDatabase, ReadableTable, TableDefinition, WriteTransaction, }; @@ -82,6 +82,38 @@ impl Journal { txn.commit()?; Ok(()) } + + fn commit_batch_tx(&self, batch: BatchCommit) -> Result<(), redb::Error> { + if batch.steps.is_empty() && batch.acks.is_empty() && batch.snapshot.is_none() { + return Ok(()); + } + let snapshot_seq = batch.snapshot.as_ref().map(|(seq, _)| *seq); + let txn = self.db.begin_write()?; + { + let mut journal = txn.open_table(JOURNAL)?; + let mut outbox = txn.open_table(OUTBOX)?; + for step in &batch.steps { + // Skip writing journal entries already subsumed by this batch's snapshot. + if snapshot_seq.is_none_or(|snap| step.seq > snap) { + journal.insert(step.seq, step.entry.as_slice())?; + } + for (key, bytes) in &step.effects { + outbox.insert((key.seq, key.index), bytes.as_slice())?; + } + if let Some(key) = step.answers { + outbox.remove((key.seq, key.index))?; + } + } + for key in &batch.acks { + outbox.remove((key.seq, key.index))?; + } + } + if let Some((seq, snapshot)) = &batch.snapshot { + keep_snapshot(&txn, *seq, snapshot)?; + } + txn.commit()?; + Ok(()) + } } /// Keeps `snapshot`, the state after step `seq`, as the only one. It holds every step up to it, so @@ -141,6 +173,10 @@ impl Store for Journal { fn checkpoint(&mut self, seq: u64, snapshot: Vec) -> Result<(), StoreError> { self.checkpoint_at(seq, &snapshot).map_err(store_error) } + + fn commit_batch(&mut self, batch: BatchCommit) -> Result<(), StoreError> { + self.commit_batch_tx(batch).map_err(store_error) + } } fn store_error(error: redb::Error) -> StoreError { @@ -256,4 +292,39 @@ mod tests { .collect(); assert_eq!(kept, [4, 5]); } + + #[test] + fn commit_batch_persists_steps_acks_and_prunes_covered_journal_entries() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("node.redb"); + let mut journal = Journal::open(&path).unwrap(); + journal + .commit_batch(BatchCommit { + steps: vec![ + Step { + seq: 1, + entry: b"a".to_vec(), + effects: vec![(key(1, 0), b"e1".to_vec())], + snapshot: None, + answers: None, + }, + Step { + seq: 2, + entry: b"b".to_vec(), + effects: vec![(key(2, 0), b"e2".to_vec())], + snapshot: None, + answers: None, + }, + ], + acks: vec![key(1, 0)], + snapshot: Some((2, b"snap2".to_vec())), + }) + .unwrap(); + drop(journal); + + let stored = Journal::open(&path).unwrap().read().unwrap(); + assert_eq!(stored.snapshot, Some((2, b"snap2".to_vec()))); + assert!(stored.journal.is_empty()); + assert_eq!(stored.outbox, vec![(key(2, 0), b"e2".to_vec())]); + } }