fix(wormhole): one paced zk-tree scan for every open wallet, under the node's rate limit
ci / gate (push) Failing after 1m33s

With three phrase wallets open, the Accounts page showed "RPC rate limit
exceeded (-32999)" on every wormhole panel and on the pending reversible
transfers.

The Quantus node limits each connection to 300 calls a minute
(--rpc-rate-limit 300 in lair/quantus). The wallet keeps one WebSocket
per chain, so everything it asks shares those five calls a second. Each
wallet's first wormhole scan reads mainnet's zk-tree 500 leaves a call,
about 950 calls, and the three scans ran at once at full speed.

- The tree is public and the same for every wallet, so one scan now
  matches the wormhole accounts of every open phrase wallet in a single
  pass. It starts from the lowest cursor among them and records each
  wallet's leaves and frontier.
- Scans run one at a time behind a lock; a wallet whose turn comes after
  another's scan finds itself caught up.
- Bulk pages are paced at three a second, leaving room for balance and
  transfer reads on the same connection.
- under_rate_limit retries a call refused with -32999, backing off 1 to
  16 seconds, rather than putting the node's refusal on screen. The scan
  pages, the nullifier bucket reads, the leaf count and the pending
  reversible transfers all go through it.

Checked from an empty cache: the first scan of 481,540 leaves took 396 s,
with no error shown and no backoff needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUx7SPonBnB3ofU4mH41WT
This commit is contained in:
2026-10-09 20:38:20 +03:00
co-authored by Claude Opus 5.5
parent 52ac684661
commit 5d5baf1c21
3 changed files with 137 additions and 46 deletions
+57 -22
View File
@@ -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<ShieldedLeaf> = 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<ShieldedLeaf> = 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
+4
View File
@@ -56,6 +56,9 @@ pub struct AppState {
pub history_cache: Arc<dyn HistoryCache>,
/// The same SQLite file, for the zk-tree scan of the wormhole address.
pub shielded_cache: Arc<dyn ShieldedCache>,
/// 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<dyn OrderStore>,
/// 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,
+76 -24
View File
@@ -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<T, F, Fut>(mut call: F) -> Result<T, ChainError>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T, ChainError>>,
{
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<u64, ChainError> {
let addr = dynamic::storage("ZkTree", "LeafCount", Vec::<Value>::new());
@@ -60,16 +94,22 @@ pub async fn leaf_count(conn: &ChainConnection) -> Result<u64, ChainError> {
.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<Vec<Leaf>, ChainError> {
) -> Result<Vec<(usize, Leaf)>, 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<Vec<u8>> = (start..end)
.map(|i| {
@@ -80,11 +120,13 @@ pub async fn leaves_paying(
.map_err(|e| ChainError::Other(e.to_string()))
})
.collect::<Result<_, _>>()?;
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<Vec<u8>> = 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<Leaf> = 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(),