diff --git a/crates/wallet-app/src/commands.rs b/crates/wallet-app/src/commands.rs index e59540b..8281a0e 100644 --- a/crates/wallet-app/src/commands.rs +++ b/crates/wallet-app/src/commands.rs @@ -930,7 +930,9 @@ pub async fn reversible_pending( ))); } let adapter = adapter_for(&state, &chain)?; - adapter.pending_reversible(me).await.map_err(chain_error) + wallet_data::substrate::wormhole::under_rate_limit(|| adapter.pending_reversible(me)) + .await + .map_err(chain_error) } #[tauri::command] @@ -1302,27 +1304,60 @@ pub async fn wormhole_summary( let conn = manager.connection().map_err(chain_error)?; let cache = state.shielded_cache.clone(); - // Scan what was appended since the last look. - let leaf_count = zk::leaf_count(&conn).await.map_err(chain_error)?; - let scanned_to = cache - .scanned_to(&chain, &address) - .map_err(|e| WalletError::Internal(e.to_string()))?; - if leaf_count > scanned_to { - let found = zk::leaves_paying(&conn, &account, scanned_to, leaf_count) - .await - .map_err(chain_error)?; - let rows: Vec = found - .iter() - .map(|l| ShieldedLeaf { - index: l.index, - transfer_count: l.transfer_count, - amount: l.amount, - spent: false, - }) - .collect(); - cache - .record(&chain, &address, &rows, leaf_count) - .map_err(|e| WalletError::Internal(e.to_string()))?; + // Scan what was appended since the last look, for every open wallet + // with a phrase at once: the tree is the same for all of them, and the + // node's per-connection rate limit is shared by everything this wallet + // asks. One scan at a time; a wallet whose turn comes after another's + // scan finds itself caught up. + let leaf_count = zk::under_rate_limit(|| zk::leaf_count(&conn)) + .await + .map_err(chain_error)?; + { + let _scan = state.zk_scan.lock().await; + let mut targets = vec![(address.clone(), account)]; + if let Ok(status) = state.session.status(std::time::Instant::now()) { + for w in status.wallets.iter().filter(|w| w.has_seed) { + if w.summary.name == wallet { + continue; + } + if let Ok(Some(Ok(k))) = state + .session + .with_seed(&w.summary.name, |seed| WormholeKeys::derive(seed, 0)) + { + targets.push((k.address(profile.ss58_prefix), k.account_id())); + } + } + } + let mut cursors = Vec::with_capacity(targets.len()); + for (addr, _) in &targets { + cursors.push( + cache + .scanned_to(&chain, addr) + .map_err(|e| WalletError::Internal(e.to_string()))?, + ); + } + let from = cursors.iter().copied().min().unwrap_or(leaf_count); + if leaf_count > from { + let accounts: Vec<[u8; 32]> = targets.iter().map(|(_, a)| *a).collect(); + let found = zk::leaves_paying(&conn, &accounts, from, leaf_count) + .await + .map_err(chain_error)?; + for (i, (addr, _)) in targets.iter().enumerate() { + let rows: Vec = found + .iter() + .filter(|(w, _)| *w == i) + .map(|(_, l)| ShieldedLeaf { + index: l.index, + transfer_count: l.transfer_count, + amount: l.amount, + spent: false, + }) + .collect(); + cache + .record(&chain, addr, &rows, leaf_count) + .map_err(|e| WalletError::Internal(e.to_string()))?; + } + } } // Which of the unspent ones have been spent since. Decided here from diff --git a/crates/wallet-app/src/state.rs b/crates/wallet-app/src/state.rs index 11b532c..1a62cdb 100644 --- a/crates/wallet-app/src/state.rs +++ b/crates/wallet-app/src/state.rs @@ -56,6 +56,9 @@ pub struct AppState { pub history_cache: Arc, /// The same SQLite file, for the zk-tree scan of the wormhole address. pub shielded_cache: Arc, + /// One zk-tree scan at a time: a scan covers every open wallet, so a + /// second one waiting here finds its wallet already caught up. + pub zk_scan: tokio::sync::Mutex<()>, /// Swap orders, in the same file, polled while open. pub orders: Arc, /// The swap provider: NEAR Intents' 1Click, through the asset registry. @@ -135,6 +138,7 @@ impl AppState { history_source: Arc::new(ObserverHistory::new()), history_cache: cache.clone(), shielded_cache: cache.clone(), + zk_scan: tokio::sync::Mutex::new(()), orders: cache, swap: Arc::new(OneClick::new(assets.clone())), assets, diff --git a/crates/wallet-data/src/substrate/wormhole.rs b/crates/wallet-data/src/substrate/wormhole.rs index 19701cb..5c9f622 100644 --- a/crates/wallet-data/src/substrate/wormhole.rs +++ b/crates/wallet-data/src/substrate/wormhole.rs @@ -41,6 +41,40 @@ pub struct Leaf { /// (Identity hasher over a u64), so a page is one `state_queryStorageAt`. pub const LEAF_PAGE: u64 = 500; +/// The pause between bulk pages. A Quantus node limits each connection +/// (ours: `--rpc-rate-limit 300`, five calls a second), and the wallet +/// keeps one connection per chain, so a scan at full speed starves the +/// balance and transfer reads sharing it. Three pages a second leaves them +/// room. A first scan of mainnet's tree is about 950 pages. +pub const PAGE_PACE: std::time::Duration = std::time::Duration::from_millis(330); + +/// Retry `call` while the node says it is over its rate limit (JSON-RPC +/// error -32999), backing off 1, 2, 4, 8 and 16 seconds; any other error, +/// or a sixth refusal, is returned. +pub async fn under_rate_limit(mut call: F) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let mut wait = std::time::Duration::from_secs(1); + for _ in 0..5 { + match call().await { + Err(e) if is_rate_limited(&e) => { + tracing::debug!(?wait, "node rate limit; backing off"); + tokio::time::sleep(wait).await; + wait *= 2; + } + other => return other, + } + } + call().await +} + +fn is_rate_limited(e: &ChainError) -> bool { + let t = e.to_string(); + t.contains("-32999") || t.to_ascii_lowercase().contains("rate limit") +} + /// `ZkTree::LeafCount` at the best block. pub async fn leaf_count(conn: &ChainConnection) -> Result { let addr = dynamic::storage("ZkTree", "LeafCount", Vec::::new()); @@ -60,16 +94,22 @@ pub async fn leaf_count(conn: &ChainConnection) -> Result { .ok_or_else(|| ChainError::Other("LeafCount is not a number".into())) } -/// The leaves in `[from, to)` that pay `account`, read in pages. +/// The leaves in `[from, to)` that pay any of `accounts`, read in pages, +/// each tagged with the index of the account it pays. One pass serves every +/// open wallet: the tree is public and the same for all of them, so reading +/// it once per wallet only multiplies the calls. pub async fn leaves_paying( conn: &ChainConnection, - account: &[u8; 32], + accounts: &[[u8; 32]], from: u64, to: u64, -) -> Result, ChainError> { +) -> Result, ChainError> { let mut out = Vec::new(); let mut start = from; while start < to { + if start > from { + tokio::time::sleep(PAGE_PACE).await; + } let end = (start + LEAF_PAGE).min(to); let keys: Vec> = (start..end) .map(|i| { @@ -80,11 +120,13 @@ pub async fn leaves_paying( .map_err(|e| ChainError::Other(e.to_string())) }) .collect::>()?; - let sets = conn - .rpc - .state_query_storage_at(keys.iter().map(Vec::as_slice), None) - .await - .map_err(|e| ChainError::Rpc(e.to_string()))?; + let sets = under_rate_limit(|| async { + conn.rpc + .state_query_storage_at(keys.iter().map(Vec::as_slice), None) + .await + .map_err(|e| ChainError::Rpc(e.to_string())) + }) + .await?; let leaf_ty = leaf_type_id(conn)?; for set in sets { for (key, data) in set.changes { @@ -101,9 +143,9 @@ pub async fn leaves_paying( .at("to") .and_then(as_account_bytes) .ok_or_else(|| ChainError::Other(format!("leaf {index}: no recipient")))?; - if &to != account { + let Some(which) = accounts.iter().position(|a| *a == to) else { continue; - } + }; let transfer_count = value .at("transfer_count") .and_then(|v| v.as_u128()) @@ -113,16 +155,19 @@ pub async fn leaves_paying( .at("amount") .and_then(|v| v.as_u128()) .ok_or_else(|| ChainError::Other(format!("leaf {index}: no amount")))?; - out.push(Leaf { - index, - transfer_count, - amount, - }); + out.push(( + which, + Leaf { + index, + transfer_count, + amount, + }, + )); } } start = end; } - out.sort_by_key(|l| l.index); + out.sort_by_key(|(_, l)| l.index); Ok(out) } @@ -220,11 +265,13 @@ pub async fn spent_among( let prefix = bucket_prefix(&root, bucket); let mut start: Option> = None; loop { - let keys = conn - .rpc - .state_get_keys_paged(&prefix, KEYS_PAGE, start.as_deref(), None) - .await - .map_err(|e| ChainError::Rpc(e.to_string()))?; + let keys = under_rate_limit(|| async { + conn.rpc + .state_get_keys_paged(&prefix, KEYS_PAGE, start.as_deref(), None) + .await + .map_err(|e| ChainError::Rpc(e.to_string())) + }) + .await?; for key in &keys { if let Some(n) = nullifier_from_key(root.len(), key) { used.insert(n); @@ -366,7 +413,12 @@ mod tests { assert!(count > 91928, "leaf count {count}"); let (_, bob) = wallet_core::ss58::decode("qzp2AxZw8szXc5qDe1aU8P5kt1dkf1JFYktvV7N6cVbFZrs8L").unwrap(); - let leaves = leaves_paying(&conn, &bob, 91900, 91930).await.unwrap(); + let leaves: Vec = leaves_paying(&conn, &[bob], 91900, 91930) + .await + .unwrap() + .into_iter() + .map(|(_, l)| l) + .collect(); let l = leaves .iter() .find(|l| l.index == 91928) @@ -408,8 +460,8 @@ mod tests { // 2026-09-16 was 9330000000000 over 30 rewards) plus anything sent // to the address since. Timed, since it is what the first open pays. let t0 = std::time::Instant::now(); - let all = leaves_paying(&conn, &bob, 0, count).await.unwrap(); - let total: u128 = all.iter().map(|l| l.amount).sum(); + let all = leaves_paying(&conn, &[bob], 0, count).await.unwrap(); + let total: u128 = all.iter().map(|(_, l)| l.amount).sum(); eprintln!( "full scan of {count} leaves in {:?}: {} leaves pay bob, {} base units", t0.elapsed(),