From 7b4a1947cca0fc4b3688024ee6cc069fa1e69233 Mon Sep 17 00:00:00 2001 From: sqhell Date: Mon, 19 Oct 2026 10:36:55 -0600 Subject: [PATCH 1/2] chore: make rustfmt and clippy pass on main Rust-Checks has failed on main since the NU6.3 toolchain bump: rustfmt differs in nine files, and clippy on nightly-2025-06-15 rejects ten uninlined format arguments in webzjs-keys and one map iteration in webzjs-requests under -D warnings. Apply rustfmt and clippy's own suggestions; no behaviour changes. --- crates/webzjs-keys/src/demo_pczt.rs | 34 +++- crates/webzjs-keys/src/lib.rs | 8 +- crates/webzjs-keys/src/pczt_describe.rs | 21 ++- crates/webzjs-keys/src/pczt_sign.rs | 152 ++++++++---------- crates/webzjs-keys/tests/gen_fixtures.rs | 50 ++++-- crates/webzjs-keys/tests/security_finding1.rs | 10 +- crates/webzjs-keys/tests/spoof_pczt.rs | 63 ++++++-- crates/webzjs-requests/src/requests.rs | 4 +- crates/webzjs-wallet/src/wallet.rs | 55 ++++--- 9 files changed, 242 insertions(+), 155 deletions(-) diff --git a/crates/webzjs-keys/src/demo_pczt.rs b/crates/webzjs-keys/src/demo_pczt.rs index d5446d1..3dc3ce4 100644 --- a/crates/webzjs-keys/src/demo_pczt.rs +++ b/crates/webzjs-keys/src/demo_pczt.rs @@ -34,6 +34,7 @@ use orchard::value::NoteValue as OrchardNoteValue; use orchard::Address as OrchardAddress; use pczt::roles::creator::Creator; +use webzjs_common::Network; use zcash_keys::address::UnifiedAddress; use zcash_keys::encoding::AddressCodec; use zcash_keys::keys::{UnifiedFullViewingKey as InnerUfvk, UnifiedSpendingKey}; @@ -41,11 +42,10 @@ use zcash_primitives::transaction::builder::PcztParts; use zcash_primitives::transaction::TxVersion; use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkConstants, Parameters}; use zcash_protocol::value::Zatoshis; -use webzjs_common::Network; use zcash_transparent::address::TransparentAddress; -use zcash_transparent::bundle::{OutPoint, TxOut}; use zcash_transparent::builder::TransparentBuilder; +use zcash_transparent::bundle::{OutPoint, TxOut}; use zcash_transparent::keys::{NonHardenedChildIndex, TransparentKeyScope}; use zcash_transparent::pczt::Bip32Derivation; @@ -155,7 +155,10 @@ fn build_transparent( .map_err(|e| Error::PcztDescribe(format!("derive t-pubkey: {e:?}")))?; let taddr = TransparentAddress::from_pubkey(&pk); - let coin = TxOut::new(Zatoshis::from_u64(SPEND_VALUE).unwrap(), taddr.script().into()); + let coin = TxOut::new( + Zatoshis::from_u64(SPEND_VALUE).unwrap(), + taddr.script().into(), + ); let mut builder = TransparentBuilder::empty(); builder .add_p2pkh_input(pk, OutPoint::new([0u8; 32], 0), coin) @@ -310,7 +313,11 @@ fn build_orchard( .clone(); let mut rng = StdRng::seed_from_u64(0x0_C_5A_u64); - let note = make_orchard_note(&mut rng, fvk.address_at(0u32, OrchardScope::External), SPEND_VALUE); + let note = make_orchard_note( + &mut rng, + fvk.address_at(0u32, OrchardScope::External), + SPEND_VALUE, + ); let cmx: ExtractedNoteCommitment = note.commitment().into(); let sibling = MerkleHashOrchard::from_cmx(&cmx); let path = OrchardMerklePath::from_parts(0, [sibling; 32]); @@ -347,7 +354,9 @@ fn build_orchard( fn make_orchard_note(rng: &mut StdRng, recipient: OrchardAddress, value: u64) -> OrchardNote { let mut rho_bytes = [0u8; 32]; rho_bytes[0] = 7; - let rho = Rho::from_bytes(&rho_bytes).into_option().expect("valid rho"); + let rho = Rho::from_bytes(&rho_bytes) + .into_option() + .expect("valid rho"); loop { let mut rseed_bytes = [0u8; 32]; rng.fill_bytes(&mut rseed_bytes); @@ -388,9 +397,18 @@ mod tests { let attacker = ufvk_from_seed(&net, ATTACKER_SEED).unwrap(); for (pool, demo) in [ - ("transparent", transparent_demo(&net, &me, &bridge, &attacker).unwrap()), - ("sapling", sapling_demo(&net, &me, &bridge, &attacker).unwrap()), - ("orchard", orchard_demo(&net, &me, &bridge, &attacker).unwrap()), + ( + "transparent", + transparent_demo(&net, &me, &bridge, &attacker).unwrap(), + ), + ( + "sapling", + sapling_demo(&net, &me, &bridge, &attacker).unwrap(), + ), + ( + "orchard", + orchard_demo(&net, &me, &bridge, &attacker).unwrap(), + ), ] { let honest = hex_to_pczt(&demo.honest); let spoof = hex_to_pczt(&demo.spoof); diff --git a/crates/webzjs-keys/src/lib.rs b/crates/webzjs-keys/src/lib.rs index 3a75cfb..320dba8 100644 --- a/crates/webzjs-keys/src/lib.rs +++ b/crates/webzjs-keys/src/lib.rs @@ -1,16 +1,16 @@ // Copyright 2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT +#[cfg(feature = "demo-builder")] +mod demo_pczt; mod error; mod keys; mod pczt_describe; mod pczt_sign; -#[cfg(feature = "demo-builder")] -mod demo_pczt; +#[cfg(feature = "demo-builder")] +pub use demo_pczt::*; pub use error::*; pub use keys::*; pub use pczt_describe::*; pub use pczt_sign::*; -#[cfg(feature = "demo-builder")] -pub use demo_pczt::*; diff --git a/crates/webzjs-keys/src/pczt_describe.rs b/crates/webzjs-keys/src/pczt_describe.rs index b92030e..02a5485 100644 --- a/crates/webzjs-keys/src/pczt_describe.rs +++ b/crates/webzjs-keys/src/pczt_describe.rs @@ -360,7 +360,9 @@ fn transparent_addr_is_ours( }; bip32_derivation.iter().any(|(claimed_pk, deriv)| { match tfvk.derive_pubkey_at_bip32_path(network, account, deriv.derivation_path()) { - Ok(pk) => &pk.serialize() == claimed_pk && TransparentAddress::from_pubkey(&pk) == *addr, + Ok(pk) => { + &pk.serialize() == claimed_pk && TransparentAddress::from_pubkey(&pk) == *addr + } Err(_) => false, } }) @@ -378,8 +380,10 @@ fn transparent_addr_is_ours( /// invariants (spends are ours, value balances / turnstile identity holds, every /// output is commitment-bound, fee is sane) for migrations as for any PCZT. fn detect_migration(outputs: &[PcztOutputSummary]) -> Option { - let ironwood: Vec<&PcztOutputSummary> = - outputs.iter().filter(|o| o.pool == pool::IRONWOOD).collect(); + let ironwood: Vec<&PcztOutputSummary> = outputs + .iter() + .filter(|o| o.pool == pool::IRONWOOD) + .collect(); if ironwood.is_empty() { return None; } @@ -499,7 +503,8 @@ fn analyze( } for output in bundle.outputs() { - if let Err(sapling::pczt::VerifyError::InvalidValueCommitment) = output.verify_cv() { + if let Err(sapling::pczt::VerifyError::InvalidValueCommitment) = output.verify_cv() + { cv_mismatch = true; } match output.value().map(|v| v.inner()) { @@ -562,7 +567,9 @@ fn analyze( let value = u64::from(*input.value()); total_in += value; let ours = TransparentAddress::from_script_from_chain(input.script_pubkey()) - .map(|addr| transparent_addr_is_ours(&network, tfvk, &addr, input.bip32_derivation())) + .map(|addr| { + transparent_addr_is_ours(&network, tfvk, &addr, input.bip32_derivation()) + }) .unwrap_or(false); if !ours { foreign_input = true; @@ -577,7 +584,9 @@ fn analyze( let recipient = addr.map(|addr| addr.encode(&network)); // Change = the coin pays back to one of our own transparent keys. let is_change = addr - .map(|addr| transparent_addr_is_ours(&network, tfvk, &addr, output.bip32_derivation())) + .map(|addr| { + transparent_addr_is_ours(&network, tfvk, &addr, output.bip32_derivation()) + }) .unwrap_or(false); total_out += value; outputs.push(PcztOutputSummary { diff --git a/crates/webzjs-keys/src/pczt_sign.rs b/crates/webzjs-keys/src/pczt_sign.rs index 84290cf..ffe9253 100644 --- a/crates/webzjs-keys/src/pczt_sign.rs +++ b/crates/webzjs-keys/src/pczt_sign.rs @@ -64,11 +64,11 @@ pub async fn pczt_sign_inner( }, } let mut keys = BTreeMap::>::new(); - let pczt = Verifier::new(pczt) - .with_orchard::(|bundle| { - for (index, action) in bundle.actions().iter().enumerate() { - if let Some(account_index) = - action + let pczt = + Verifier::new(pczt) + .with_orchard::(|bundle| { + for (index, action) in bundle.actions().iter().enumerate() { + if let Some(account_index) = action .spend() .zip32_derivation() .as_ref() @@ -78,21 +78,20 @@ pub async fn pczt_sign_inner( zip32::ChildIndex::hardened(network.network_type().coin_type()), ) }) - { - keys.entry(account_index) - .or_default() - .push(KeyRef::Orchard { index }); + { + keys.entry(account_index) + .or_default() + .push(KeyRef::Orchard { index }); + } } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .with_ironwood::(|bundle| { - // Ironwood reuses the Orchard action/key shape, so collect spendable - // Ironwood actions exactly as for Orchard (same zip32 derivation). - for (index, action) in bundle.actions().iter().enumerate() { - if let Some(account_index) = - action + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .with_ironwood::(|bundle| { + // Ironwood reuses the Orchard action/key shape, so collect spendable + // Ironwood actions exactly as for Orchard (same zip32 derivation). + for (index, action) in bundle.actions().iter().enumerate() { + if let Some(account_index) = action .spend() .zip32_derivation() .as_ref() @@ -102,59 +101,59 @@ pub async fn pczt_sign_inner( zip32::ChildIndex::hardened(network.network_type().coin_type()), ) }) - { - keys.entry(account_index) - .or_default() - .push(KeyRef::Ironwood { index }); - } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .with_sapling::(|bundle| { - for (index, spend) in bundle.spends().iter().enumerate() { - if let Some(account_index) = - spend.zip32_derivation().as_ref().and_then(|derivation| { - derivation.extract_account_index( - &seed_fp, - zip32::ChildIndex::hardened(network.network_type().coin_type()), - ) - }) - { - keys.entry(account_index) - .or_default() - .push(KeyRef::Sapling { index }); + { + keys.entry(account_index) + .or_default() + .push(KeyRef::Ironwood { index }); + } } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .with_transparent::(|bundle| { - for (index, input) in bundle.inputs().iter().enumerate() { - for derivation in input.bip32_derivation().values() { - if let Some((account_index, scope, address_index)) = derivation - .extract_bip_44_fields( - &seed_fp, - bip32::ChildNumber( - network.network_type().coin_type() - | bip32::ChildNumber::HARDENED_FLAG, - ), - ) + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .with_sapling::(|bundle| { + for (index, spend) in bundle.spends().iter().enumerate() { + if let Some(account_index) = + spend.zip32_derivation().as_ref().and_then(|derivation| { + derivation.extract_account_index( + &seed_fp, + zip32::ChildIndex::hardened(network.network_type().coin_type()), + ) + }) { keys.entry(account_index) .or_default() - .push(KeyRef::Transparent { - index, - scope, - address_index, - }); + .push(KeyRef::Sapling { index }); } } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .finish(); + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .with_transparent::(|bundle| { + for (index, input) in bundle.inputs().iter().enumerate() { + for derivation in input.bip32_derivation().values() { + if let Some((account_index, scope, address_index)) = derivation + .extract_bip_44_fields( + &seed_fp, + bip32::ChildNumber( + network.network_type().coin_type() + | bip32::ChildNumber::HARDENED_FLAG, + ), + ) + { + keys.entry(account_index) + .or_default() + .push(KeyRef::Transparent { + index, + scope, + address_index, + }); + } + } + } + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .finish(); let mut signer = Signer::new(pczt).unwrap(); //.map_err(|e| anyhow!("Failed to initialize Signer: {:?}", e))?; for (_, spends) in keys { @@ -168,10 +167,7 @@ pub async fn pczt_sign_inner( &orchard::keys::SpendAuthorizingKey::from(usk.orchard()), ) .map_err(|e| { - Error::PcztSign(format!( - "Failed to sign Orchard spend {index}: {:?}", - e - )) + Error::PcztSign(format!("Failed to sign Orchard spend {index}: {e:?}")) })?; } KeyRef::Ironwood { index } => { @@ -182,20 +178,14 @@ pub async fn pczt_sign_inner( &orchard::keys::SpendAuthorizingKey::from(usk.orchard()), ) .map_err(|e| { - Error::PcztSign(format!( - "Failed to sign Ironwood spend {index}: {:?}", - e - )) + Error::PcztSign(format!("Failed to sign Ironwood spend {index}: {e:?}")) })?; } KeyRef::Sapling { index } => { signer .sign_sapling(index, &usk.sapling().expsk.ask) .map_err(|e| { - Error::PcztSign(format!( - "Failed to sign Sapling spend {index}: {:?}", - e - )) + Error::PcztSign(format!("Failed to sign Sapling spend {index}: {e:?}")) })?; } KeyRef::Transparent { @@ -210,15 +200,13 @@ pub async fn pczt_sign_inner( .derive_secret_key(scope, address_index) .map_err(|e| { Error::PcztSign(format!( - "Failed to derive transparent key at .../{:?}/{:?}: {:?}", - scope, address_index, e, + "Failed to derive transparent key at .../{scope:?}/{address_index:?}: {e:?}" )) })?, ) .map_err(|e| { Error::PcztSign(format!( - "Failed to sign transparent input {index}: {:?}", - e + "Failed to sign transparent input {index}: {e:?}" )) })?; } diff --git a/crates/webzjs-keys/tests/gen_fixtures.rs b/crates/webzjs-keys/tests/gen_fixtures.rs index 5ce78ab..c297b66 100644 --- a/crates/webzjs-keys/tests/gen_fixtures.rs +++ b/crates/webzjs-keys/tests/gen_fixtures.rs @@ -85,7 +85,9 @@ fn make_note_versioned( // A small canonical field element is a fine `rho` for an off-chain note. let mut rho_bytes = [0u8; 32]; rho_bytes[0] = 7; - let rho = Rho::from_bytes(&rho_bytes).into_option().expect("valid rho"); + let rho = Rho::from_bytes(&rho_bytes) + .into_option() + .expect("valid rho"); loop { let mut rseed_bytes = [0u8; 32]; rng.fill_bytes(&mut rseed_bytes); @@ -138,7 +140,12 @@ fn make_orchard_pczt( .expect("add_spend"); for (ovk, recipient, value) in outputs { builder - .add_output(ovk.clone(), *recipient, NoteValue::from_raw(*value), [0u8; 512]) + .add_output( + ovk.clone(), + *recipient, + NoteValue::from_raw(*value), + [0u8; 512], + ) .expect("add_output"); } @@ -188,7 +195,12 @@ fn make_ironwood_pczt( .expect("add_spend"); for (ovk, recipient, value) in outputs { builder - .add_output(ovk.clone(), *recipient, NoteValue::from_raw(*value), [0u8; 512]) + .add_output( + ovk.clone(), + *recipient, + NoteValue::from_raw(*value), + [0u8; 512], + ) .expect("add_output"); } @@ -252,7 +264,12 @@ fn make_turnstile_migration_pczt( ) .expect("ironwood Builder::new"); iw_builder - .add_output(out_ovk, out_addr, NoteValue::from_raw(out_value), [0u8; 512]) + .add_output( + out_ovk, + out_addr, + NoteValue::from_raw(out_value), + [0u8; 512], + ) .expect("add_output"); let (iw_bundle, _) = iw_builder .build_for_pczt(&mut *rng) @@ -314,11 +331,16 @@ fn make_transparent_pczt( let (pk, taddr) = transparent_addr0(spend_seed); // The coin being spent: a P2PKH output paying our own address. - let coin = TxOut::new(Zatoshis::from_u64(spend_value).unwrap(), taddr.script().into()); + let coin = TxOut::new( + Zatoshis::from_u64(spend_value).unwrap(), + taddr.script().into(), + ); let utxo = OutPoint::new([0u8; 32], 0); let mut builder = TransparentBuilder::empty(); - builder.add_p2pkh_input(pk, utxo, coin).expect("add p2pkh input"); + builder + .add_p2pkh_input(pk, utxo, coin) + .expect("add p2pkh input"); builder .add_output(recipient, Zatoshis::from_u64(out_value).unwrap()) .expect("add transparent output"); @@ -391,12 +413,16 @@ fn make_sapling_pczt( rng: &mut StdRng, spend_dfvk: &sapling::zip32::DiversifiableFullViewingKey, spend_value: u64, - outputs: &[(sapling::keys::OutgoingViewingKey, sapling::PaymentAddress, u64)], + outputs: &[( + sapling::keys::OutgoingViewingKey, + sapling::PaymentAddress, + u64, + )], ) -> pczt::Pczt { let note = make_sapling_note(rng, spend_dfvk, spend_value); let node = sapling::Node::from_cmu(¬e.cmu()); - let path = - sapling::MerklePath::from_parts(vec![node; 32], 0u64.into()).expect("32-element merkle path"); + let path = sapling::MerklePath::from_parts(vec![node; 32], 0u64.into()) + .expect("32-element merkle path"); let anchor = sapling::Anchor::from(path.root(node)); let mut builder = sapling::builder::Builder::new( @@ -435,7 +461,11 @@ fn make_sapling_pczt( } fn write_fixture(name: &str, pczt: &pczt::Pczt) { - let path = format!("{}/tests/fixtures/{}.pczt", env!("CARGO_MANIFEST_DIR"), name); + let path = format!( + "{}/tests/fixtures/{}.pczt", + env!("CARGO_MANIFEST_DIR"), + name + ); let bytes = pczt.clone().serialize().expect("serialize pczt"); std::fs::write(&path, bytes).unwrap_or_else(|e| panic!("write {path}: {e}")); eprintln!("wrote {path}"); diff --git a/crates/webzjs-keys/tests/security_finding1.rs b/crates/webzjs-keys/tests/security_finding1.rs index 08daa60..05c33e4 100644 --- a/crates/webzjs-keys/tests/security_finding1.rs +++ b/crates/webzjs-keys/tests/security_finding1.rs @@ -43,7 +43,11 @@ fn ufvk_for_seed(seed: &[u8; 32]) -> zcash_keys::keys::UnifiedFullViewingKey { } fn load_pczt(name: &str) -> pczt::Pczt { - let path = format!("{}/tests/fixtures/{}.pczt", env!("CARGO_MANIFEST_DIR"), name); + let path = format!( + "{}/tests/fixtures/{}.pczt", + env!("CARGO_MANIFEST_DIR"), + name + ); let bytes = std::fs::read(&path).unwrap_or_else(|e| { panic!( "missing fixture {path}: {e}\n\ @@ -109,7 +113,9 @@ fn fvk_plant_does_not_bypass_foreign_input_detection() { // Fixed behaviour: the planted foreign spend is rejected as a foreign input. let err = pczt_validate_inner(Network::TestNetwork, poisoned.clone(), &our_ufvk) .expect_err("FVK-planted foreign input must be rejected"); - println!("│ validate → REJECTED (attribution is nullifier-only, ignores the fvk label): {err}"); + println!( + "│ validate → REJECTED (attribution is nullifier-only, ignores the fvk label): {err}" + ); assert!( err.to_string().contains("not under this key"), "must be rejected specifically as a foreign input, got: {err}" diff --git a/crates/webzjs-keys/tests/spoof_pczt.rs b/crates/webzjs-keys/tests/spoof_pczt.rs index 8d74d9e..ced536f 100644 --- a/crates/webzjs-keys/tests/spoof_pczt.rs +++ b/crates/webzjs-keys/tests/spoof_pczt.rs @@ -160,7 +160,11 @@ fn narrate_describe(summary: &PcztSummary) { short(o.recipient.as_deref()), if o.verified { "verified" } else { "UNVERIFIED" }, if o.is_change { ", change" } else { "" }, - if o.is_ours && !o.is_change { ", self" } else { "" }, + if o.is_ours && !o.is_change { + ", self" + } else { + "" + }, )); } if let Some(m) = &summary.migration { @@ -177,7 +181,9 @@ fn narrate_describe(summary: &PcztSummary) { fn narrate_validate(result: &Result<(), E>) { match result { Ok(()) => line("validate → Ok (Layer B would allow signing)"), - Err(e) => line(&format!("validate → REJECTED (Layer B refuses to sign): {e}")), + Err(e) => line(&format!( + "validate → REJECTED (Layer B refuses to sign): {e}" + )), } } @@ -190,7 +196,9 @@ fn honest_pczt_is_accepted() { ); let ufvk = our_ufvk(); let pczt = load_pczt("honest_bridge_deposit"); - line("fixture: honest_bridge_deposit.pczt (spend 100k ours → bridge 50k + change 40k, fee 10k)"); + line( + "fixture: honest_bridge_deposit.pczt (spend 100k ours → bridge 50k + change 40k, fee 10k)", + ); let result = pczt_validate_inner(Network::from_str("test").unwrap(), pczt, &ufvk); narrate_validate(&result); @@ -221,7 +229,10 @@ fn spoofed_recipient_is_surfaced() { let summary = pczt_describe_inner(Network::from_str("test").unwrap(), pczt.clone(), &ufvk) .expect("describe must succeed and surface the real outputs"); narrate_describe(&summary); - line(&format!("expected true payee (attacker) = {}", short(Some(&attacker_addr())))); + line(&format!( + "expected true payee (attacker) = {}", + short(Some(&attacker_addr())) + )); assert!( summary @@ -318,7 +329,11 @@ fn ironwood_payment_is_described_and_accepted() { .expect("describe must succeed on an Ironwood PCZT"); narrate_describe(&summary); - let ironwood_outs: Vec<_> = summary.outputs.iter().filter(|o| o.pool == "ironwood").collect(); + let ironwood_outs: Vec<_> = summary + .outputs + .iter() + .filter(|o| o.pool == "ironwood") + .collect(); assert_eq!( ironwood_outs.len(), 1, @@ -383,7 +398,10 @@ fn self_migration_is_recognized() { .migration .as_ref() .expect("an Ironwood-output PCZT must be recognised as a migration"); - assert_eq!(migration.amount, 90_000, "migrated amount = Ironwood output value"); + assert_eq!( + migration.amount, 90_000, + "migrated amount = Ironwood output value" + ); assert!( migration.to_self, "migrating to our own address must be flagged as a self-migration" @@ -424,11 +442,18 @@ fn turnstile_migration_end_to_end() { // Value crosses the turnstile: 100_000 spent from Orchard, 90_000 into Ironwood, // 10_000 fee. This IS the turnstile value identity the validator checks. assert_eq!(summary.total_in, 100_000, "the Orchard spend is our input"); - assert_eq!(summary.total_out, 90_000, "the Ironwood output is the migrated value"); + assert_eq!( + summary.total_out, 90_000, + "the Ironwood output is the migrated value" + ); assert_eq!(summary.fee, 10_000, "fee = Orchard out − Ironwood in"); // Exactly one displayed output: the Ironwood note, to us, commitment-bound. - assert_eq!(summary.outputs.len(), 1, "only the Ironwood output is displayed"); + assert_eq!( + summary.outputs.len(), + 1, + "only the Ironwood output is displayed" + ); let out = &summary.outputs[0]; assert_eq!(out.pool, "ironwood"); assert!(out.is_ours, "the migration output pays our own address"); @@ -440,8 +465,14 @@ fn turnstile_migration_end_to_end() { .as_ref() .expect("a cross-pool Orchard→Ironwood tx must be recognised as a migration"); assert_eq!(m.amount, 90_000); - assert!(m.to_self, "migrating to our own address is a self-migration"); - assert!(m.is_clean_path_a, "one Ironwood output, no third-party outputs"); + assert!( + m.to_self, + "migrating to our own address is a self-migration" + ); + assert!( + m.is_clean_path_a, + "one Ironwood output, no third-party outputs" + ); // Layer B accepts the turnstile: spends ours, balances, verified, fee in band. let result = pczt_validate_inner(Network::from_str("test").unwrap(), pczt, &ufvk); @@ -484,7 +515,10 @@ fn transparent_input_under_our_key_is_accepted() { let summary = pczt_describe_inner(Network::from_str("test").unwrap(), pczt.clone(), &ufvk) .expect("describe must succeed on a transparent PCZT"); narrate_describe(&summary); - line(&format!("expected bridge t-address = {}", short(Some(&bridge_taddr())))); + line(&format!( + "expected bridge t-address = {}", + short(Some(&bridge_taddr())) + )); assert!( summary .outputs @@ -538,7 +572,11 @@ fn sapling_change_is_detected() { let summary = pczt_describe_inner(Network::from_str("test").unwrap(), pczt.clone(), &ufvk) .expect("describe must succeed on a Sapling PCZT"); narrate_describe(&summary); - let sapling_outs: Vec<_> = summary.outputs.iter().filter(|o| o.pool == "sapling").collect(); + let sapling_outs: Vec<_> = summary + .outputs + .iter() + .filter(|o| o.pool == "sapling") + .collect(); assert_eq!( sapling_outs.len(), 2, @@ -560,4 +598,3 @@ fn sapling_change_is_detected() { ); verdict("change (internal scope) is told apart from the external payment; ACCEPTED"); } - diff --git a/crates/webzjs-requests/src/requests.rs b/crates/webzjs-requests/src/requests.rs index b6f4b21..c9e1c67 100644 --- a/crates/webzjs-requests/src/requests.rs +++ b/crates/webzjs-requests/src/requests.rs @@ -33,8 +33,8 @@ impl TransactionRequest { // BTreeMap automatically stores keys in sorted order so we can do this self.0 .payments() - .iter() - .map(|(_index, p)| PaymentRequest(p.clone())) + .values() + .map(|p| PaymentRequest(p.clone())) .collect() } diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index fa5e779..97b362e 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -26,12 +26,12 @@ use std::sync::Arc; use subtle::ConditionallySelectable; use tokio::sync::RwLock; use zcash_address::ZcashAddress; +use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; use zcash_client_backend::data_api::wallet::{ create_pczt_from_proposal, create_proposed_transactions, extract_and_store_transaction_from_pczt, input_selection::GreedyInputSelector, propose_shielding, propose_transfer, ConfirmationsPolicy, SpendingKeys, }; -use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; use zcash_client_backend::data_api::CoinbaseFilter; use zcash_client_backend::data_api::{ Account, AccountBirthday, AccountPurpose, InputSource, WalletRead, WalletSummary, WalletWrite, @@ -559,7 +559,7 @@ where ) .map_err(|e| { tracing::error!("pczt_shield: propose_shielding failed: {:?}", e); - Error::Generic(format!("Error when shielding: {:?}", e)) + Error::Generic(format!("Error when shielding: {e:?}")) })?; tracing::info!("pczt_shield: proposal created successfully"); @@ -584,7 +584,7 @@ where ) .map_err(|e| { tracing::error!("pczt_shield: create_pczt_from_proposal failed: {:?}", e); - Error::PcztCreate(format!("{:?}", e)) + Error::PcztCreate(format!("{e:?}")) })?; tracing::info!("pczt_shield: PCZT created from proposal successfully"); @@ -658,7 +658,7 @@ where &SpendPolicy::default(), None, ) - .map_err(|e| Error::Generic(format!("something bad happened when calling propose transfer. Possibly insufficient balance... {:?}", e)))?; + .map_err(|e| Error::Generic(format!("something bad happened when calling propose transfer. Possibly insufficient balance... {e:?}")))?; tracing::info!("PCZT proposal created"); let pczt = create_pczt_from_proposal::< _, @@ -680,7 +680,7 @@ where ) .map_err(|e| { tracing::error!("pczt_create: create_pczt_from_proposal failed: {:?}", e); - Error::PcztCreate(format!("{:?}", e)) + Error::PcztCreate(format!("{e:?}")) })?; Ok(pczt) } @@ -726,10 +726,7 @@ where Ok(()) }) .map_err(|e| { - Error::PcztProve(format!( - "Failed to add Sapling proof generation key: {:?}", - e - )) + Error::PcztProve(format!("Failed to add Sapling proof generation key: {e:?}")) })? .finish() } else { @@ -741,18 +738,20 @@ where // Nu6_3 -> PostNu6_3 (the Ironwood-era circuit that enforces the disableCrossAddress // constraint sealing the Orchard pool); everything current (Nu6_2) -> FixedPostNu6_2. // The same version must build the verifying key when extracting the transaction below. - let orchard_circuit_version = - match BranchId::try_from(*pczt.global().consensus_branch_id()) { - Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, - _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, - }; + let orchard_circuit_version = match BranchId::try_from(*pczt.global().consensus_branch_id()) + { + Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, + _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, + }; let prover = LocalTxProver::bundled(); let pczt = Prover::new(pczt) - .create_orchard_proof(&orchard::circuit::ProvingKey::build(orchard_circuit_version)) - .map_err(|e| Error::PcztProve(format!("Failed to create Orchard proof: {:?}", e)))? + .create_orchard_proof(&orchard::circuit::ProvingKey::build( + orchard_circuit_version, + )) + .map_err(|e| Error::PcztProve(format!("Failed to create Orchard proof: {e:?}")))? .create_sapling_proofs(&prover, &prover) - .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {:?}", e)))? + .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {e:?}")))? .finish(); Ok(pczt) } @@ -784,8 +783,7 @@ where blocks_behind ); return Err(Error::Generic(format!( - "Wallet is {} blocks behind the chain tip. Please sync before sending (max allowed: 100 blocks).", - blocks_behind + "Wallet is {blocks_behind} blocks behind the chain tip. Please sync before sending (max allowed: 100 blocks)." ))); } tracing::info!( @@ -801,11 +799,11 @@ where // Build the Orchard verifying key with the circuit version for this PCZT's target // branch (Nu6_3 -> PostNu6_3, else FixedPostNu6_2), matching how the proof was // created. See the proving-key derivation in the pczt_prove path. - let orchard_circuit_version = - match BranchId::try_from(*pczt.global().consensus_branch_id()) { - Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, - _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, - }; + let orchard_circuit_version = match BranchId::try_from(*pczt.global().consensus_branch_id()) + { + Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, + _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, + }; let prover = LocalTxProver::bundled(); let (spend_vk, output_vk) = prover.verifying_keys(); let mut db = self.db.write().await; @@ -813,12 +811,13 @@ where &mut *db, pczt, Some((&spend_vk, &output_vk)), - Some(&orchard::circuit::VerifyingKey::build(orchard_circuit_version)), + Some(&orchard::circuit::VerifyingKey::build( + orchard_circuit_version, + )), ) .map_err(|e| { Error::PcztSend(format!( - "Failed to extract and store transaction from PCZT: {:?}", - e + "Failed to extract and store transaction from PCZT: {e:?}" )) })?; drop(db); @@ -829,7 +828,7 @@ where pub fn pczt_combine(&self, pczts: Vec) -> Result { Combiner::new(pczts) .combine() - .map_err(|e| Error::PcztCombine(format!("Failed to combine PCZT: {:?}", e))) + .map_err(|e| Error::PcztCombine(format!("Failed to combine PCZT: {e:?}"))) } } From 44375cf19a3ab3420ef58c0ffc0333aa4f90f56b Mon Sep 17 00:00:00 2001 From: sqhell Date: Sat, 17 Oct 2026 16:29:47 -0600 Subject: [PATCH 2/2] fix(web-wallet): keep the Full Resync form usable during background syncs The resync form was rendered only while no sync was running, and fullResync refused with "Sync already in progress" if a periodic rescan happened to be in flight. With a 35 s rescan interval that made the dialog vanish mid-typing and reject Confirm at random. Syncs are now serialised on the JS side instead of refused: a small module-level scheduler owns `syncInProgress`, periodic rescans skip their turn while a sync runs, and a full resync waits behind an in-flight rescan. This also closes the race where a rescan that had passed its guard could clear `syncInProgress` while a full resync was still running. (The wasm wallet runs syncs on one serial worker in a separate change; this one stands alone.) The form stays mounted during background syncs. While the resync waits for a running sync it can still be cancelled, which drops it from the queue; once it starts, Confirm and Cancel are disabled until it settles, and a card mounted while a resync is in flight shows that instead of offering another. The birthday is validated against the chain height inline instead of an alert. A custom birthday is written to the snap only once the resync succeeds, and before the fresh wallet is swapped into state, so a failed resync never leaves a birthday the old wallet never used (a birthday above the tip previously broke auto-recovery with "block is not in the main chain"), and a failed snap write leaves state, the snap and IndexedDB describing the same wallet. --- .../BlockHeightCard/BlockHeightCard.test.tsx | 118 ++++++ .../BlockHeightCard/BlockHeightCard.tsx | 110 +++++- .../web-wallet/src/hooks/fullResyncQueue.ts | 25 ++ .../web-wallet/src/hooks/useWebzjsActions.ts | 350 ++++++++++-------- 4 files changed, 420 insertions(+), 183 deletions(-) create mode 100644 packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx create mode 100644 packages/web-wallet/src/hooks/fullResyncQueue.ts diff --git a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx new file mode 100644 index 0000000..3ed5944 --- /dev/null +++ b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx @@ -0,0 +1,118 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'; +import { BlockHeightCard } from './BlockHeightCard'; +import { WebZjsState } from 'src/context/WebzjsContext'; +import { FullResyncOptions } from 'src/hooks/fullResyncQueue'; + +const baseState: WebZjsState = { + webWallet: null, + installedSnap: null, + error: null, + summary: undefined, + chainHeight: 3_500_000n, + activeAccount: 0, + syncInProgress: false, + loading: false, + initialized: true, +}; + +function openForm() { + fireEvent.click(screen.getByText('Full Resync')); + return screen.getByPlaceholderText('e.g. 2674500') as HTMLInputElement; +} + +describe('BlockHeightCard full resync form', () => { + it('keeps the form open while a background sync is in progress', () => { + const onFullResync = vi.fn().mockResolvedValue(undefined); + const { rerender } = render( + , + ); + const input = openForm(); + fireEvent.change(input, { target: { value: '2600000' } }); + + rerender( + , + ); + + expect(screen.getByText('Sync in progress...')).toBeInTheDocument(); + expect(screen.getByPlaceholderText('e.g. 2674500')).toHaveValue(2600000); + expect(screen.getByText('Confirm Resync')).toBeEnabled(); + }); + + it('disables Confirm and Cancel once the resync runs, then closes the form when it settles', async () => { + let finish!: () => void; + const onFullResync = vi.fn( + (_birthday?: number, options?: FullResyncOptions) => + new Promise((resolve) => { + finish = resolve; + options?.onStart?.(); + }), + ); + render(); + const input = openForm(); + fireEvent.change(input, { target: { value: '2600000' } }); + await act(async () => { fireEvent.click(screen.getByText('Confirm Resync')); }); + + expect(onFullResync).toHaveBeenCalledWith( + 2600000, + expect.objectContaining({ signal: expect.any(AbortSignal) }), + ); + expect(screen.getByText('Resyncing…')).toBeDisabled(); + expect(screen.getByText('Cancel')).toBeDisabled(); + + await act(async () => { finish(); }); + await waitFor(() => expect(screen.getByText('Full Resync')).toBeInTheDocument()); + }); + + it('can be cancelled while the resync is still waiting for another sync to finish', async () => { + let signal: AbortSignal | undefined; + const onFullResync = vi.fn( + (_birthday?: number, options?: FullResyncOptions) => + new Promise(() => { + signal = options?.signal; + }), + ); + render(); + openForm(); + await act(async () => { fireEvent.click(screen.getByText('Confirm Resync')); }); + + expect(screen.getByText('Waiting for the current sync…')).toBeDisabled(); + expect(screen.getByText('Cancel')).toBeEnabled(); + + await act(async () => { fireEvent.click(screen.getByText('Cancel')); }); + expect(signal?.aborted).toBe(true); + expect(screen.getByText('Full Resync')).toBeInTheDocument(); + }); + + it('rejects a birthday above the chain height without starting a resync', () => { + const onFullResync = vi.fn().mockResolvedValue(undefined); + render(); + const input = openForm(); + fireEvent.change(input, { target: { value: '30000000' } }); + fireEvent.click(screen.getByText('Confirm Resync')); + + expect(onFullResync).not.toHaveBeenCalled(); + expect(screen.getByRole('alert')).toHaveTextContent('above the chain height (3500000)'); + expect(screen.getByPlaceholderText('e.g. 2674500')).toBeInTheDocument(); + }); + + it('rejects a birthday below Sapling activation', () => { + const onFullResync = vi.fn().mockResolvedValue(undefined); + render(); + const input = openForm(); + fireEvent.change(input, { target: { value: '100' } }); + fireEvent.click(screen.getByText('Confirm Resync')); + + expect(onFullResync).not.toHaveBeenCalled(); + expect(screen.getByRole('alert')).toHaveTextContent('at least 419200'); + }); + + it('passes undefined when the birthday field is left empty', async () => { + const onFullResync = vi.fn().mockResolvedValue(undefined); + render(); + openForm(); + await act(async () => { fireEvent.click(screen.getByText('Confirm Resync')); }); + + expect(onFullResync).toHaveBeenCalledWith(undefined, expect.anything()); + }); +}); diff --git a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx index 31cb630..fda11ae 100644 --- a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx +++ b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx @@ -1,26 +1,81 @@ -import { FC, useState } from 'react'; +import { FC, useEffect, useRef, useState } from 'react'; import { WebZjsState } from 'src/context/WebzjsContext'; +import { FullResyncOptions, pendingFullResync } from 'src/hooks/fullResyncQueue'; // Zcash mainnet activation block (Sapling activation) const ZCASH_SAPLING_ACTIVATION = 419200; +/** Idle, waiting for a sync that is already running to finish, or resyncing. */ +type ResyncPhase = 'idle' | 'queued' | 'running'; + export const BlockHeightCard: FC<{ state: WebZjsState; syncedFrom?: string; - onFullResync?: (customBirthday?: number) => Promise; + onFullResync?: (customBirthday?: number, options?: FullResyncOptions) => Promise; }> = ({ state, syncedFrom, onFullResync }) => { const [showConfirm, setShowConfirm] = useState(false); const [customBirthday, setCustomBirthday] = useState(''); + const [phase, setPhase] = useState(() => (pendingFullResync() ? 'running' : 'idle')); + const [birthdayError, setBirthdayError] = useState(null); + const abortRef = useRef(null); + const resyncing = phase !== 'idle'; - const handleResync = () => { - setShowConfirm(false); + // A resync started from an earlier mount of this card is shown until it settles, so a + // second one cannot be queued behind it. + useEffect(() => { + const pending = pendingFullResync(); + if (!pending) return; + let active = true; + pending.finally(() => { + if (active) setPhase('idle'); + }); + return () => { + active = false; + }; + }, []); + + const chainHeight = state.chainHeight ? Number(state.chainHeight) : undefined; + + const handleResync = async () => { const birthday = customBirthday ? parseInt(customBirthday, 10) : undefined; - if (birthday && birthday < ZCASH_SAPLING_ACTIVATION) { - alert(`Birthday must be at least ${ZCASH_SAPLING_ACTIVATION} (Sapling activation)`); + if (birthday !== undefined && Number.isNaN(birthday)) { + setBirthdayError('Birthday must be a block height'); + return; + } + if (birthday !== undefined && birthday < ZCASH_SAPLING_ACTIVATION) { + setBirthdayError(`Birthday must be at least ${ZCASH_SAPLING_ACTIVATION} (Sapling activation)`); + return; + } + if (birthday !== undefined && chainHeight !== undefined && birthday > chainHeight) { + setBirthdayError(`Birthday cannot be above the chain height (${chainHeight})`); return; } - onFullResync?.(birthday); + setBirthdayError(null); + const controller = new AbortController(); + abortRef.current = controller; + setPhase('queued'); + try { + // Queued behind any background sync that is running; the form stays open and can + // still be cancelled until the resync itself starts. + await onFullResync?.(birthday, { + signal: controller.signal, + onStart: () => setPhase('running'), + }); + } finally { + abortRef.current = null; + setPhase('idle'); + setShowConfirm(false); + setCustomBirthday(''); + } + }; + + const cancelResync = () => { + abortRef.current?.abort(); + abortRef.current = null; + setPhase('idle'); + setShowConfirm(false); setCustomBirthday(''); + setBirthdayError(null); }; return ( @@ -82,14 +137,15 @@ export const BlockHeightCard: FC<{ )} - {onFullResync && !state.syncInProgress && ( + {onFullResync && (
{!showConfirm ? ( ) : (
@@ -98,30 +154,44 @@ export const BlockHeightCard: FC<{

setCustomBirthday(e.target.value)} + onChange={(e) => { + setCustomBirthday(e.target.value); + setBirthdayError(null); + }} placeholder="e.g. 2674500" min={ZCASH_SAPLING_ACTIVATION} - className="px-2 py-1 border border-[#afafaf] rounded text-sm w-full bg-white text-black" + max={chainHeight} + disabled={resyncing} + className="px-2 py-1 border border-[#afafaf] rounded text-sm w-full bg-white text-black disabled:opacity-60" /> + {birthdayError && ( +

+ {birthdayError} +

+ )}
diff --git a/packages/web-wallet/src/hooks/fullResyncQueue.ts b/packages/web-wallet/src/hooks/fullResyncQueue.ts new file mode 100644 index 0000000..8ea2cd5 --- /dev/null +++ b/packages/web-wallet/src/hooks/fullResyncQueue.ts @@ -0,0 +1,25 @@ +/** Options for a full resync requested from the UI. */ +export interface FullResyncOptions { + /** Aborting before the resync starts drops it from the sync queue; it has no effect once started. */ + signal?: AbortSignal; + /** Called when the resync starts, once any sync queued ahead of it has finished. */ + onStart?: () => void; +} + +// The full resync in flight, if any, so a remounted card shows it instead of offering another. +let pending: Promise | null = null; + +export function pendingFullResync(): Promise | null { + return pending; +} + +/** Records `run` as the full resync in flight until it settles. */ +export function trackFullResync(run: Promise): Promise { + const tracked: Promise = run + .catch(() => undefined) + .finally(() => { + if (pending === tracked) pending = null; + }); + pending = tracked; + return tracked; +} diff --git a/packages/web-wallet/src/hooks/useWebzjsActions.ts b/packages/web-wallet/src/hooks/useWebzjsActions.ts index 04aa31d..7ae7f5a 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -8,10 +8,35 @@ import { useRequestSnap } from './snaps/useRequestSnap'; import { SeedFingerprint, WebWallet } from '@zcashcommunitygrants/webzjs-wallet'; import { MAINNET_LIGHTWALLETD_PROXY } from '../config/constants'; import { SnapState } from '../types/snap'; - -// Synchronous guard: prevents triggerRescan from overlapping with fullResync. -// Module-level so it's shared across all hook instances and immune to stale closures. -let _fullResyncActive = false; +import { FullResyncOptions, trackFullResync } from './fullResyncQueue'; + +// Sync scheduler. The WASM wallet runs every sync on one serial worker, so JS queues +// syncs rather than refusing them: a periodic rescan skips its turn while another sync +// runs, and a full resync waits for an in-flight rescan instead of failing. +// Module-level so it's shared across all hook instances and immune to stale closures, +// and the sole owner of `syncInProgress`, so one sync's completion can't clear the flag +// while another is still running. +let _syncChain: Promise = Promise.resolve(); +let _syncBusy = false; + +function runExclusiveSync( + dispatch: (action: { type: 'set-sync-in-progress'; payload: boolean }) => void, + job: () => Promise, +): Promise { + const run = async () => { + _syncBusy = true; + dispatch({ type: 'set-sync-in-progress', payload: true }); + try { + return await job(); + } finally { + _syncBusy = false; + dispatch({ type: 'set-sync-in-progress', payload: false }); + } + }; + const result = _syncChain.then(run); + _syncChain = result.catch(() => undefined); + return result; +} interface SyncOptions { skipBalanceCache?: boolean; @@ -25,7 +50,7 @@ interface WebzjsActions { flushDbToStore: () => Promise; syncStateWithWallet: (options?: SyncOptions) => Promise; connectWebZjsSnap: () => Promise; - fullResync: (customBirthday?: number) => Promise; + fullResync: (customBirthday?: number, options?: FullResyncOptions) => Promise; recoverWallet: () => Promise; } @@ -330,55 +355,49 @@ export function useWebZjsActions(): WebzjsActions { // No account yet - user needs to connect first. Not an error. return; } - if (state.syncInProgress || _fullResyncActive) { + if (_syncBusy) { + // Another sync (periodic or full resync) is running; the next tick will try again. return; } - // Check if we're already at chain tip - skip redundant syncs - // Allow a small buffer (2 blocks) for network propagation - const fullySyncedHeight = fullySyncedRef.current; - const chainHeight = chainHeightRef.current ? Number(chainHeightRef.current) : 0; - if (fullySyncedHeight && chainHeight && fullySyncedHeight >= chainHeight - 2) { - // Already synced to chain tip, just refresh the chain height - try { - const latestBlock = await state.webWallet.get_latest_block(); - if (latestBlock && latestBlock !== chainHeightRef.current) { - dispatch({ type: 'set-chain-height', payload: latestBlock }); - // Only sync if chain has advanced - if (fullySyncedHeight < Number(latestBlock)) { - dispatch({ type: 'set-sync-in-progress', payload: true }); - try { - await withRetry(() => state.webWallet!.sync(), { label: 'sync', retries: 2, baseDelay: 3000 }); + const webWallet = state.webWallet; + await runExclusiveSync(dispatch, async () => { + // Check if we're already at chain tip - skip redundant syncs + // Allow a small buffer (2 blocks) for network propagation + const fullySyncedHeight = fullySyncedRef.current; + const chainHeight = chainHeightRef.current ? Number(chainHeightRef.current) : 0; + if (fullySyncedHeight && chainHeight && fullySyncedHeight >= chainHeight - 2) { + // Already synced to chain tip, just refresh the chain height + try { + const latestBlock = await webWallet.get_latest_block(); + if (latestBlock && latestBlock !== chainHeightRef.current) { + dispatch({ type: 'set-chain-height', payload: latestBlock }); + // Only sync if chain has advanced + if (fullySyncedHeight < Number(latestBlock)) { + await withRetry(() => webWallet.sync(), { label: 'sync', retries: 2, baseDelay: 3000 }); await syncStateWithWallet(); await flushDbToStore(); - } finally { - dispatch({ type: 'set-sync-in-progress', payload: false }); } } + } catch (err) { + console.error('Error checking chain height:', err); } - } catch (err) { - console.error('Error checking chain height:', err); + return; } - return; - } - dispatch({ type: 'set-sync-in-progress', payload: true }); - - try { - await withRetry(() => state.webWallet!.sync(), { label: 'sync', retries: 2, baseDelay: 3000 }); - await syncStateWithWallet(); - await flushDbToStore(); - } catch (err: unknown) { - console.warn('Sync failed (will retry next interval):', err); - } finally { - dispatch({ type: 'set-sync-in-progress', payload: false }); - } + try { + await withRetry(() => webWallet.sync(), { label: 'sync', retries: 2, baseDelay: 3000 }); + await syncStateWithWallet(); + await flushDbToStore(); + } catch (err: unknown) { + console.warn('Sync failed (will retry next interval):', err); + } + }); }, [ installedSnap, state.loading, state.webWallet, state.activeAccount, - state.syncInProgress, dispatch, syncStateWithWallet, flushDbToStore, @@ -394,148 +413,153 @@ export function useWebZjsActions(): WebzjsActions { * If any gRPC call fails, the old wallet remains untouched in state and IndexedDB. * This is a user-initiated action for recovering from sync issues. */ - const fullResync = useCallback(async (customBirthday?: number) => { + const fullResync = useCallback(async (customBirthday?: number, options?: FullResyncOptions) => { if (!installedSnap) { dispatch({ type: 'set-error', payload: new Error('Snap not installed') }); return; } - if (state.syncInProgress) { - dispatch({ type: 'set-error', payload: new Error('Sync already in progress') }); - return; - } - - _fullResyncActive = true; - dispatch({ type: 'set-sync-in-progress', payload: true }); - - try { - // 1. Get the stored birthday from snap state - const snapState = (await invokeSnap({ - method: 'getSnapStete', - })) as SnapState | null; - - // Use custom birthday if provided, otherwise fall back to stored value - const birthdayBlock = customBirthday ?? (snapState?.webWalletSyncStartBlock - ? Number(snapState.webWalletSyncStartBlock) - : undefined); - - // Save the new birthday to snap state if custom one was provided - if (customBirthday) { - await updateSnapState({ webWalletSyncStartBlock: String(customBirthday) }); + // Queued behind any periodic rescan that is already running. The caller may cancel + // while it waits; once the job starts it runs to completion. + const run = runExclusiveSync(dispatch, async () => { + if (options?.signal?.aborted) { + console.info('Full resync: cancelled before it started'); + return; } + options?.onStart?.(); + try { + // 1. Get the stored birthday from snap state + const snapState = (await invokeSnap({ + method: 'getSnapStete', + })) as SnapState | null; + + // Use custom birthday if provided, otherwise fall back to stored value. + // A custom birthday is only persisted once the resync succeeds (step 6), so a + // failed resync leaves the old wallet and its stored birthday consistent. + const birthdayBlock = customBirthday ?? (snapState?.webWalletSyncStartBlock + ? Number(snapState.webWalletSyncStartBlock) + : undefined); + + // 2. Get credentials from snap + const viewingKey = (await invokeSnap({ + method: 'getViewingKey', + })) as string; + + const seedFingerprintResult = await invokeSnap({ + method: 'getSeedFingerprint', + }); + + const hexString = typeof seedFingerprintResult === 'string' + ? seedFingerprintResult + : typeof seedFingerprintResult === 'object' && seedFingerprintResult !== null && 'data' in seedFingerprintResult + ? Array.from(seedFingerprintResult.data as number[]).map((b: number) => b.toString(16).padStart(2, '0')).join('') + : String(seedFingerprintResult); + + const seedFingerprintUint8Array = new Uint8Array( + (hexString.match(/.{1,2}/g) || []).map((byte: string) => parseInt(byte, 16)), + ); + const seedFingerprint = SeedFingerprint.from_bytes(seedFingerprintUint8Array); + + // 3. Create fresh wallet in LOCAL variable: old wallet stays in React state + IndexedDB + console.info('Full resync: Creating fresh wallet (old wallet preserved as fallback)'); + const freshWallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); + + // 4. Re-import the account with retry (makes GetTreeState gRPC call) + console.info(`Full resync: Re-importing account with birthday ${birthdayBlock}`); + const accountId = await withRetry( + () => freshWallet.create_account_ufvk('account-0', viewingKey, seedFingerprint, 0, birthdayBlock), + { label: 'create_account_ufvk', retries: 3, baseDelay: 2000 }, + ); + + // 5. Sync from birthday in a loop: each sync() makes incremental progress + // The Rust WASM wallet resumes from where it left off on each call. + // With many blocks to scan, one sync() call can't finish before the + // lightwalletd proxy drops the connection, so we keep calling it. + console.info('Full resync: Starting sync from birthday'); + const MAX_SYNC_ROUNDS = 20; + const SYNC_ROUND_DELAY = 2000; // ms between rounds to let proxy recover + let consecutiveFailures = 0; + const MAX_CONSECUTIVE_FAILURES = 4; + + for (let round = 1; round <= MAX_SYNC_ROUNDS; round++) { + try { + console.info(`Full resync: sync round ${round}/${MAX_SYNC_ROUNDS}`); + await freshWallet.sync(); + consecutiveFailures = 0; + + // Check if fully synced + const summary = await freshWallet.get_wallet_summary(); + const chainTip = Number(await freshWallet.get_latest_block()); + const scannedHeight = summary?.fully_scanned_height ?? 0; + + console.info(`Full resync: scanned to ${scannedHeight} / ${chainTip}`); + + if (scannedHeight >= chainTip - 2) { + console.info('Full resync: Fully synced'); + break; + } - // 2. Get credentials from snap - const viewingKey = (await invokeSnap({ - method: 'getViewingKey', - })) as string; - - const seedFingerprintResult = await invokeSnap({ - method: 'getSeedFingerprint', - }); - - const hexString = typeof seedFingerprintResult === 'string' - ? seedFingerprintResult - : typeof seedFingerprintResult === 'object' && seedFingerprintResult !== null && 'data' in seedFingerprintResult - ? Array.from(seedFingerprintResult.data as number[]).map((b: number) => b.toString(16).padStart(2, '0')).join('') - : String(seedFingerprintResult); - - const seedFingerprintUint8Array = new Uint8Array( - (hexString.match(/.{1,2}/g) || []).map((byte: string) => parseInt(byte, 16)), - ); - const seedFingerprint = SeedFingerprint.from_bytes(seedFingerprintUint8Array); - - // 3. Create fresh wallet in LOCAL variable — old wallet stays in React state + IndexedDB - console.info('Full resync: Creating fresh wallet (old wallet preserved as fallback)'); - const freshWallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); - - // 4. Re-import the account with retry (makes GetTreeState gRPC call) - console.info(`Full resync: Re-importing account with birthday ${birthdayBlock}`); - const accountId = await withRetry( - () => freshWallet.create_account_ufvk('account-0', viewingKey, seedFingerprint, 0, birthdayBlock), - { label: 'create_account_ufvk', retries: 3, baseDelay: 2000 }, - ); - - // 5. Sync from birthday in a loop — each sync() makes incremental progress - // The Rust WASM wallet resumes from where it left off on each call. - // With many blocks to scan, one sync() call can't finish before the - // lightwalletd proxy drops the connection, so we keep calling it. - console.info('Full resync: Starting sync from birthday'); - const MAX_SYNC_ROUNDS = 20; - const SYNC_ROUND_DELAY = 2000; // ms between rounds to let proxy recover - let consecutiveFailures = 0; - const MAX_CONSECUTIVE_FAILURES = 4; - - for (let round = 1; round <= MAX_SYNC_ROUNDS; round++) { - try { - console.info(`Full resync: sync round ${round}/${MAX_SYNC_ROUNDS}`); - await freshWallet.sync(); - consecutiveFailures = 0; - - // Check if fully synced - const summary = await freshWallet.get_wallet_summary(); - const chainTip = Number(await freshWallet.get_latest_block()); - const scannedHeight = summary?.fully_scanned_height ?? 0; + // Not done yet: pause before next round + if (round < MAX_SYNC_ROUNDS) { + await new Promise(r => setTimeout(r, SYNC_ROUND_DELAY)); + } + } catch (syncErr) { + consecutiveFailures++; + console.debug(`Full resync: sync round ${round} failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}):`, syncErr); - console.info(`Full resync: scanned to ${scannedHeight} / ${chainTip}`); + if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) { + throw syncErr; // give up after too many consecutive failures + } - if (scannedHeight >= chainTip - 2) { - console.info('Full resync: Fully synced'); - break; + // Back off longer after failures + const backoff = SYNC_ROUND_DELAY * Math.pow(2, consecutiveFailures - 1); + console.debug(`Full resync: backing off ${backoff}ms before retry`); + await new Promise(r => setTimeout(r, backoff)); } - // Not done yet — pause before next round - if (round < MAX_SYNC_ROUNDS) { - await new Promise(r => setTimeout(r, SYNC_ROUND_DELAY)); + if (round === MAX_SYNC_ROUNDS) { + console.info('Full resync: not at chain tip after the last round; the periodic rescan will finish catching up'); } - } catch (syncErr) { - consecutiveFailures++; - console.debug(`Full resync: sync round ${round} failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}):`, syncErr); + } - if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) { - throw syncErr; // give up after too many consecutive failures + // 6. SUCCESS: record the birthday the fresh wallet was built with, then swap the + // wallet into state and IndexedDB. The snap write comes first so that a failure + // there leaves the old wallet, its stored birthday and IndexedDB all consistent. + if (customBirthday) { + await updateSnapState({ webWalletSyncStartBlock: String(customBirthday) }); + } + console.info('Full resync: Sync succeeded, swapping wallet into state'); + dispatch({ type: 'set-web-wallet', payload: freshWallet }); + dispatch({ type: 'set-active-account', payload: accountId }); + + const summary = await freshWallet.get_wallet_summary(); + if (summary) { + dispatch({ type: 'set-summary', payload: summary }); + + // Cache balance in snap state: force update after full resync + if (summary.account_balances?.length > 0) { + const [, balanceReport] = summary.account_balances[0]; + await cacheBalanceInSnap(balanceReport, true); } - - // Back off longer after failures - const backoff = SYNC_ROUND_DELAY * Math.pow(2, consecutiveFailures - 1); - console.debug(`Full resync: backing off ${backoff}ms before retry`); - await new Promise(r => setTimeout(r, backoff)); } - } - - // 6. SUCCESS — now swap the fresh wallet into state and IndexedDB - console.info('Full resync: Sync succeeded, swapping wallet into state'); - dispatch({ type: 'set-web-wallet', payload: freshWallet }); - dispatch({ type: 'set-active-account', payload: accountId }); - - const summary = await freshWallet.get_wallet_summary(); - if (summary) { - dispatch({ type: 'set-summary', payload: summary }); - // Cache balance in snap state — force update after full resync - if (summary.account_balances?.length > 0) { - const [, balanceReport] = summary.account_balances[0]; - await cacheBalanceInSnap(balanceReport, true); + const chainHeight = await freshWallet.get_latest_block(); + if (chainHeight) { + dispatch({ type: 'set-chain-height', payload: chainHeight }); } - } - const chainHeight = await freshWallet.get_latest_block(); - if (chainHeight) { - dispatch({ type: 'set-chain-height', payload: chainHeight }); - } - - // 7. Persist — overwrites old data (no need to del() first) - const bytes = await freshWallet.db_to_bytes(); - await set('wallet', bytes); + // 7. Persist: overwrites old data (no need to del() first) + const bytes = await freshWallet.db_to_bytes(); + await set('wallet', bytes); - console.info('Full resync: Complete'); - } catch (err: unknown) { - // FAILURE — old wallet remains in state + IndexedDB, user sees last known balances - console.error('Full resync failed (old wallet preserved):', err); - dispatch({ type: 'set-error', payload: String(err) }); - } finally { - _fullResyncActive = false; - dispatch({ type: 'set-sync-in-progress', payload: false }); - } - }, [installedSnap, state.syncInProgress, invokeSnap, dispatch, updateSnapState, cacheBalanceInSnap]); + console.info('Full resync: Complete'); + } catch (err: unknown) { + // FAILURE: old wallet remains in state + IndexedDB, user sees last known balances + console.error('Full resync failed (old wallet preserved):', err); + dispatch({ type: 'set-error', payload: String(err) }); + } + }); + await trackFullResync(run); + }, [installedSnap, invokeSnap, dispatch, updateSnapState, cacheBalanceInSnap]); /** * Recovers the wallet from snap credentials when IndexedDB data is empty or incompatible.