From 7b4a1947cca0fc4b3688024ee6cc069fa1e69233 Mon Sep 17 00:00:00 2001 From: sqhell Date: Mon, 19 Oct 2026 10:36:55 -0600 Subject: [PATCH 1/3] 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/3] 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. From 16fdfde8269ee16080e32f1605b9b946518703b2 Mon Sep 17 00:00:00 2001 From: sqhell Date: Sun, 18 Oct 2026 16:38:17 -0600 Subject: [PATCH 3/3] fix(web-wallet): make wallet persistence refuse stale and silent overwrites Twice in one day a correct wallet was replaced in IndexedDB by a worse one. A second tab kept saving its old copy over a completed Full Resync, because every tab wrote the single `wallet` key unconditionally and the last writer won. Earlier, stored bytes that failed to load were replaced by auto-recovery with an account-only wallet built from the chain tip. All wallet storage now goes through one module, src/storage/walletStore.ts, which enforces one rule: a save lands only if the instance saving descends from what is stored right now, or it is an explicit resync or recovery that is allowed to win. - The stored value is a versioned record with metadata; `epoch` increments on every write and is checked and written in one IndexedDB transaction. A legacy byte array counts as epoch 0 and is converted on its first save. - The epoch is bound to the WebWallet instance through a registry, not to React state, so a stale closure, an old hook or another tab is rejected by construction. A superseded instance can never write again. - Full Resync persists the fresh wallet as a forced write, with its birthday, before it becomes visible, then retires the old instance. Snap state is updated afterwards and repaired later if that fails. - Stored bytes that fail to decode are backed up and left in place. The empty wallet built instead is never registered, so no save, including auto-recovery, can replace them. The home page offers an explicit "Discard unreadable wallet data and recover from MetaMask" action. - A rejected writer reloads the wallet from storage instead of fighting; tabs learn of saves through a BroadcastChannel and reload when visible. One tab per origin holds a Web Locks writer lock and runs the periodic rescan; the others follow. Both are for freshness and efficiency only, the epoch check keeps every configuration safe. - The blob's own account birthday, read straight from the stored bytes, is authoritative. The snap value is repaired downward when it is later, never raised. Tests: the store module under fake-indexeddb (stale write rejected with storage untouched, forced resync wins, superseded instance blocked, legacy migration, unreadable bytes quarantined, concurrent saves serialized, and a two-tab simulation), the hook ordering (persist before swap, birthday precedence, reload on stale write, recovery guard) and the home page guard. --- packages/web-wallet/package.json | 1 + packages/web-wallet/src/App.tsx | 4 +- .../BlockHeightCard/BlockHeightCard.test.tsx | 2 + .../web-wallet/src/context/WebzjsContext.tsx | 179 +++++++--- packages/web-wallet/src/hooks/usePCZT.ts | 2 +- .../src/hooks/useWebzjsActions.test.ts | 173 ++++++++++ .../web-wallet/src/hooks/useWebzjsActions.ts | 288 ++++++++++------ packages/web-wallet/src/pages/Home.test.tsx | 34 +- packages/web-wallet/src/pages/Home.tsx | 45 ++- .../web-wallet/src/storage/walletBlobMeta.ts | 98 ++++++ .../src/storage/walletStore.test.ts | 218 ++++++++++++ .../web-wallet/src/storage/walletStore.ts | 317 ++++++++++++++++++ yarn.lock | 8 + 13 files changed, 1227 insertions(+), 142 deletions(-) create mode 100644 packages/web-wallet/src/hooks/useWebzjsActions.test.ts create mode 100644 packages/web-wallet/src/storage/walletBlobMeta.ts create mode 100644 packages/web-wallet/src/storage/walletStore.test.ts create mode 100644 packages/web-wallet/src/storage/walletStore.ts diff --git a/packages/web-wallet/package.json b/packages/web-wallet/package.json index cdffbb4..e033743 100644 --- a/packages/web-wallet/package.json +++ b/packages/web-wallet/package.json @@ -45,6 +45,7 @@ "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.14", "express": "^4.21.2", + "fake-indexeddb": "^6.2.6", "globals": "^15.11.0", "jsdom": "^24.0.0", "parcel": "^2.13.3", diff --git a/packages/web-wallet/src/App.tsx b/packages/web-wallet/src/App.tsx index 3b09c22..ceba5df 100644 --- a/packages/web-wallet/src/App.tsx +++ b/packages/web-wallet/src/App.tsx @@ -11,7 +11,9 @@ function App() { const { installedSnap } = useMetaMaskContext(); const { state } = useWebZjsContext(); - const interval = installedSnap && state.initialized && !state.syncInProgress ? RESCAN_INTERVAL : null; + // Only the tab holding the writer lock runs periodic syncs; others follow storage. + const interval = + installedSnap && state.initialized && state.isWriter && !state.syncInProgress ? RESCAN_INTERVAL : null; useInterval(() => { triggerRescan(); diff --git a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx index 3ed5944..0019f33 100644 --- a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx +++ b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx @@ -14,6 +14,8 @@ const baseState: WebZjsState = { syncInProgress: false, loading: false, initialized: true, + storedWalletUnreadable: null, + isWriter: true, }; function openForm() { diff --git a/packages/web-wallet/src/context/WebzjsContext.tsx b/packages/web-wallet/src/context/WebzjsContext.tsx index a3914d0..c40fcd3 100644 --- a/packages/web-wallet/src/context/WebzjsContext.tsx +++ b/packages/web-wallet/src/context/WebzjsContext.tsx @@ -6,7 +6,6 @@ import React, { useCallback, useRef, } from 'react'; -import { get } from 'idb-keyval'; import initWebzJSWallet, { initThreadPool, @@ -17,6 +16,15 @@ import initWebzJSKeys from '@zcashcommunitygrants/webzjs-keys'; import { MAINNET_LIGHTWALLETD_PROXY } from '../config/constants'; import { Snap } from '../types'; import toast, { Toaster } from 'react-hot-toast'; +import { + claimWriterRole, + loadWallet, + markSuperseded, + onWalletChanged, + peekStoredEpoch, + registerWallet, + walletOrigin, +} from '../storage/walletStore'; export interface WebZjsState { webWallet: WebWallet | null; @@ -28,6 +36,10 @@ export interface WebZjsState { syncInProgress: boolean; loading: boolean; initialized: boolean; + /** Set when stored wallet bytes could not be read; they are kept and backed up, never replaced silently. */ + storedWalletUnreadable: { error: string } | null; + /** True once this tab holds the single-writer lock and may run periodic syncs. */ + isWriter: boolean; } type Action = @@ -38,7 +50,9 @@ type Action = | { type: 'set-active-account'; payload: number } | { type: 'set-sync-in-progress'; payload: boolean } | { type: 'set-loading'; payload: boolean } - | { type: 'set-initialized'; payload: boolean }; + | { type: 'set-initialized'; payload: boolean } + | { type: 'set-stored-wallet-unreadable'; payload: { error: string } | null } + | { type: 'set-writer'; payload: boolean }; const initialState: WebZjsState = { webWallet: null, @@ -50,6 +64,8 @@ const initialState: WebZjsState = { syncInProgress: false, loading: false, initialized: false, + storedWalletUnreadable: null, + isWriter: false, }; function reducer(state: WebZjsState, action: Action): WebZjsState { @@ -70,6 +86,10 @@ function reducer(state: WebZjsState, action: Action): WebZjsState { return { ...state, loading: action.payload }; case 'set-initialized': return { ...state, initialized: action.payload }; + case 'set-stored-wallet-unreadable': + return { ...state, storedWalletUnreadable: action.payload }; + case 'set-writer': + return { ...state, isWriter: action.payload }; default: return state; } @@ -79,21 +99,56 @@ interface WebZjsContextType { state: WebZjsState; dispatch: React.Dispatch; initWallet: () => Promise; + /** Replaces the in-memory wallet with what is stored, when storage has moved past it. */ + reloadWallet: () => Promise; } const WebZjsContext = createContext({ state: initialState, dispatch: () => {}, initWallet: async () => {}, + reloadWallet: async () => {}, }); export function useWebZjsContext(): WebZjsContextType { return useContext(WebZjsContext); } +const decodeWallet = (bytes: Uint8Array | null) => + new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, bytes); + export const WebZjsProvider = ({ children }: { children: React.ReactNode }) => { const [state, dispatch] = useReducer(reducer, initialState); const initializingRef = useRef(false); + const reloadingRef = useRef(false); + const writerClaimedRef = useRef(false); + const walletRef = useRef(null); + walletRef.current = state.webWallet; + + // Puts a wallet into state with its summary, account and chain height. + const applyLoadedWallet = useCallback(async (wallet: WebWallet) => { + dispatch({ type: 'set-web-wallet', payload: wallet }); + + const summary = await wallet.get_wallet_summary(); + if (summary) { + dispatch({ type: 'set-summary', payload: summary }); + if (summary.account_balances.length > 0) { + dispatch({ + type: 'set-active-account', + payload: summary.account_balances[0][0], + }); + } + } + + try { + const chainHeight = await wallet.get_latest_block(); + if (chainHeight) { + dispatch({ type: 'set-chain-height', payload: chainHeight }); + } + } catch (err) { + console.warn('Could not fetch chain height on startup (will retry on first sync):', err); + } + }, []); const initAll = useCallback(async () => { try { @@ -112,47 +167,39 @@ export const WebZjsProvider = ({ children }: { children: React.ReactNode }) => { return; } - const bytes = await get('wallet'); + const loaded = await loadWallet(decodeWallet); let wallet: WebWallet; - - if (bytes) { - console.info('Saved wallet detected. Restoring wallet from storage'); - try { - wallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, bytes); - } catch (deserializeError) { - console.warn( - 'Failed to restore wallet from storage (possibly incompatible format after upgrade). Creating fresh wallet.', - deserializeError + switch (loaded.status) { + case 'ok': + console.info( + `Saved wallet restored from storage (epoch ${loaded.meta.epoch}${loaded.legacy ? ', legacy format' : ''})`, + ); + wallet = loaded.wallet; + break; + case 'none': + console.info('No saved wallet detected. Creating new wallet'); + wallet = decodeWallet(null); + registerWallet(wallet, { epoch: null, birthday: null }); + break; + case 'unreadable': { + const error = + loaded.error instanceof Error ? loaded.error.message : String(loaded.error); + console.warn('Stored wallet could not be read. It was kept and backed up:', loaded.error); + toast.error( + 'The saved wallet could not be read. It was kept and backed up; open the home page to recover.', ); - toast.error('Wallet data incompatible after upgrade. Please re-sync your wallet.'); - wallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); + // Deliberately not registered: an unregistered instance can never overwrite storage. + wallet = decodeWallet(null); + dispatch({ type: 'set-stored-wallet-unreadable', payload: { error } }); + break; } - } else { - console.info('No saved wallet detected. Creating new wallet'); - wallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); } - dispatch({ type: 'set-web-wallet', payload: wallet }); - - // Retrieve summary (accounts, balances, etc.) - const summary = await wallet.get_wallet_summary(); - if (summary) { - dispatch({ type: 'set-summary', payload: summary }); - if (summary.account_balances.length > 0) { - dispatch({ - type: 'set-active-account', - payload: summary.account_balances[0][0], - }); - } - } + await applyLoadedWallet(wallet); - try { - const chainHeight = await wallet.get_latest_block(); - if (chainHeight) { - dispatch({ type: 'set-chain-height', payload: chainHeight }); - } - } catch (err) { - console.warn('Could not fetch chain height on startup (will retry on first sync):', err); + if (!writerClaimedRef.current) { + writerClaimedRef.current = true; + claimWriterRole(() => dispatch({ type: 'set-writer', payload: true })); } dispatch({ type: 'set-loading', payload: false }); @@ -162,7 +209,7 @@ export const WebZjsProvider = ({ children }: { children: React.ReactNode }) => { dispatch({ type: 'set-error', payload: Error(String(err)) }); dispatch({ type: 'set-loading', payload: false }); } - }, []); + }, [applyLoadedWallet]); // Lazy-load WASM: call this when user wants to use wallet features const initWallet = useCallback(async () => { @@ -178,15 +225,67 @@ export const WebZjsProvider = ({ children }: { children: React.ReactNode }) => { } }, [state.initialized, initAll]); + const reloadWallet = useCallback(async () => { + if (reloadingRef.current) return; + reloadingRef.current = true; + try { + const current = walletRef.current; + const storedEpoch = await peekStoredEpoch(); + if (current && walletOrigin(current)?.epoch === storedEpoch) { + return; // Already current. + } + const loaded = await loadWallet(decodeWallet); + if (loaded.status !== 'ok') { + if (loaded.status === 'unreadable') { + const error = + loaded.error instanceof Error ? loaded.error.message : String(loaded.error); + dispatch({ type: 'set-stored-wallet-unreadable', payload: { error } }); + } + return; + } + console.info(`Storage moved to epoch ${loaded.meta.epoch}; reloading the wallet from it`); + if (current) markSuperseded(current); + dispatch({ type: 'set-stored-wallet-unreadable', payload: null }); + await applyLoadedWallet(loaded.wallet); + } catch (err) { + console.error('Could not reload the wallet from storage:', err); + } finally { + reloadingRef.current = false; + } + }, [applyLoadedWallet]); + + // Follow saves made by other tabs. Background tabs wait until they are visible so they do + // not decode the wallet on every save the writer makes. + useEffect(() => { + let pending = false; + const onVisible = () => { + if (pending && document.visibilityState === 'visible') { + pending = false; + void reloadWallet(); + } + }; + document.addEventListener('visibilitychange', onVisible); + const unsubscribe = onWalletChanged(() => { + if (document.visibilityState === 'visible') { + void reloadWallet(); + } else { + pending = true; + } + }); + return () => { + unsubscribe(); + document.removeEventListener('visibilitychange', onVisible); + }; + }, [reloadWallet]); + useEffect(() => { if (state.error) { toast.error(state.error.toString()); } }, [state.error, dispatch]); - return ( - + {children} diff --git a/packages/web-wallet/src/hooks/usePCZT.ts b/packages/web-wallet/src/hooks/usePCZT.ts index 53321ce..541564e 100644 --- a/packages/web-wallet/src/hooks/usePCZT.ts +++ b/packages/web-wallet/src/hooks/usePCZT.ts @@ -156,7 +156,7 @@ export const usePczt = (): IUsePczt => { console.info('Shield: Transaction broadcast complete'); // Persist wallet state immediately after broadcast to prevent data loss on crash - await flushDbToStore(); + await flushDbToStore('send'); console.info('Shield: Wallet state persisted'); // Log transaction history for debugging pending transaction detection diff --git a/packages/web-wallet/src/hooks/useWebzjsActions.test.ts b/packages/web-wallet/src/hooks/useWebzjsActions.test.ts new file mode 100644 index 0000000..394b295 --- /dev/null +++ b/packages/web-wallet/src/hooks/useWebzjsActions.test.ts @@ -0,0 +1,173 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook } from '@testing-library/react'; + +// Everything the vi.mock factories reference must be hoisted along with them. +const h = vi.hoisted(() => { + // Order of persistence and state changes, recorded by the mocks. + const calls: string[] = []; + const origins = { map: new Map() }; + const saveWallet = vi.fn( + async (...args: [object, Uint8Array, { force?: boolean; reason: string }]) => { + const opts = args[2]; + calls.push(`save:${opts.reason}:${opts.force ? 'forced' : 'checked'}`); + return { epoch: 7, birthday: 2_400_000, fullyScanned: null, savedAt: 0, writerId: 't', reason: opts.reason }; + }, + ); + const markSuperseded = vi.fn((...args: [object]) => calls.push(`supersede:${args.length}`)); + const registerWallet = vi.fn(); + const readWalletBackup = vi.fn(async () => null); + class FakeWallet { + summary = { fully_scanned_height: 3_522_000, account_balances: [[0, { orchard_balance: 10 }]] }; + async get_wallet_summary() { + return this.summary; + } + async get_latest_block() { + return 3_522_001n; + } + async create_account_ufvk(_n: string, _k: string, _f: unknown, _i: number, birthday?: number) { + calls.push(`create_account:${birthday}`); + return 0; + } + async sync() { + calls.push('sync'); + } + async db_to_bytes() { + return new Uint8Array([1, 2, 3]); + } + } + const dispatch = vi.fn((action: { type: string }) => calls.push(`dispatch:${action.type}`)); + const reloadWallet = vi.fn(async () => calls.push('reload')); + const live = { + snapState: null as { webWalletSyncStartBlock: string } | null, + contextState: {} as Record, + }; + return { calls, origins, saveWallet, markSuperseded, registerWallet, readWalletBackup, FakeWallet, dispatch, reloadWallet, live }; +}); + +vi.mock('../storage/walletStore', async () => { + const actual = await vi.importActual('../storage/walletStore'); + return { + ...actual, + saveWallet: (...args: Parameters) => h.saveWallet(...args), + markSuperseded: (w: object) => h.markSuperseded(w), + registerWallet: (w: object, origin: { epoch: number | null; birthday: number | null }) => { + h.origins.map.set(w, origin); + h.registerWallet(w, origin); + }, + walletOrigin: (w: object) => h.origins.map.get(w), + readWalletBackup: () => h.readWalletBackup(), + }; +}); + +vi.mock('@zcashcommunitygrants/webzjs-wallet', () => ({ + WebWallet: h.FakeWallet, + SeedFingerprint: { from_bytes: (b: Uint8Array) => b }, +})); + +vi.mock('../context/WebzjsContext', () => ({ + useWebZjsContext: () => ({ state: h.live.contextState, dispatch: h.dispatch, reloadWallet: h.reloadWallet }), +})); +vi.mock('../context/MetamaskContext', () => ({ + useMetaMaskContext: () => ({ refreshSnapState: vi.fn(), snapState: h.live.snapState }), +})); +vi.mock('./snaps/useMetaMask', () => ({ useMetaMask: () => ({ installedSnap: { id: 'snap' } }) })); +vi.mock('./snaps/useRequestSnap', () => ({ useRequestSnap: () => vi.fn() })); +vi.mock('./snaps/useInvokeSnap', () => ({ + useInvokeSnap: () => async ({ method }: { method: string }) => { + if (method === 'getSnapStete') return h.live.snapState; + if (method === 'getViewingKey') return 'ufvk'; + if (method === 'getSeedFingerprint') return 'aa'.repeat(32); + return null; + }, +})); +vi.mock('idb-keyval', () => ({ get: vi.fn(async () => undefined), set: vi.fn(async () => undefined) })); + +import { useWebZjsActions } from './useWebzjsActions'; +import { StaleWalletError } from '../storage/walletStore'; + +describe('useWebZjsActions persistence rules', () => { + beforeEach(() => { + h.calls.length = 0; + h.origins.map = new Map(); + h.saveWallet.mockClear(); + h.markSuperseded.mockClear(); + h.registerWallet.mockClear(); + h.dispatch.mockClear(); + h.reloadWallet.mockClear(); + h.live.snapState = { webWalletSyncStartBlock: '2600000' }; + h.live.contextState = { + webWallet: new h.FakeWallet(), + loading: false, + initialized: true, + activeAccount: 0, + summary: undefined, + chainHeight: undefined, + syncInProgress: false, + storedWalletUnreadable: null, + isWriter: true, + }; + }); + + it('full resync persists the fresh wallet as a forced write before making it visible', async () => { + const oldWallet = h.live.contextState.webWallet as object; + h.origins.map.set(oldWallet, { epoch: 3, birthday: 2_400_000 }); + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(3_000_000); + }); + + const save = h.calls.indexOf('save:resync:forced'); + const swap = h.calls.indexOf('dispatch:set-web-wallet'); + const supersede = h.calls.indexOf('supersede:1'); + expect(save).toBeGreaterThan(-1); + expect(swap).toBeGreaterThan(save); + expect(supersede).toBeGreaterThan(save); + expect(supersede).toBeLessThan(swap); + expect(h.markSuperseded).toHaveBeenCalledWith(oldWallet); + expect(h.calls).toContain('create_account:3000000'); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('full resync prefers the stored wallet birthday over a later snap value', async () => { + h.origins.map.set(h.live.contextState.webWallet as object, { epoch: 3, birthday: 2_400_000 }); + h.live.snapState = { webWalletSyncStartBlock: '2600000' }; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(); + }); + + expect(h.calls).toContain('create_account:2400000'); + }); + + it('flushDbToStore reloads instead of erroring when storage has moved on', async () => { + h.saveWallet.mockRejectedValueOnce(new StaleWalletError(2, 5)); + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.flushDbToStore('sync'); + }); + + expect(h.reloadWallet).toHaveBeenCalledTimes(1); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('recoverWallet refuses to run over unreadable stored data unless told to replace it', async () => { + h.live.contextState.storedWalletUnreadable = { error: 'bad' }; + const { result } = renderHook(() => useWebZjsActions()); + + await expect(result.current.recoverWallet()).rejects.toThrow(/could not be read/); + expect(h.saveWallet).not.toHaveBeenCalled(); + + await act(async () => { + await result.current.recoverWallet({ replaceUnreadable: true }); + }); + expect(h.saveWallet).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + expect.objectContaining({ reason: 'recover', force: true }), + ); + expect(h.dispatch).toHaveBeenCalledWith({ type: 'set-stored-wallet-unreadable', payload: null }); + }); +}); diff --git a/packages/web-wallet/src/hooks/useWebzjsActions.ts b/packages/web-wallet/src/hooks/useWebzjsActions.ts index 7ae7f5a..0573ec5 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -9,6 +9,16 @@ import { SeedFingerprint, WebWallet } from '@zcashcommunitygrants/webzjs-wallet' import { MAINNET_LIGHTWALLETD_PROXY } from '../config/constants'; import { SnapState } from '../types/snap'; import { FullResyncOptions, trackFullResync } from './fullResyncQueue'; +import { + SaveReason, + StaleWalletError, + markSuperseded, + readWalletBackup, + registerWallet, + saveWallet, + walletOrigin, +} from '../storage/walletStore'; +import { readBlobBirthday } from '../storage/walletBlobMeta'; // 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 @@ -42,16 +52,38 @@ interface SyncOptions { skipBalanceCache?: boolean; } +interface FlushOptions { + /** Skip the stored-epoch check. Only for an explicit recovery over unreadable data. */ + force?: boolean; +} + +interface RecoverOptions { + /** Replace stored wallet bytes that could not be read. Requires an explicit user action. */ + replaceUnreadable?: boolean; +} + interface WebzjsActions { getAccountData: () => Promise< { unifiedAddress: string; transparentAddress: string } | undefined >; triggerRescan: () => Promise; - flushDbToStore: () => Promise; + flushDbToStore: (reason?: SaveReason, options?: FlushOptions) => Promise; syncStateWithWallet: (options?: SyncOptions) => Promise; connectWebZjsSnap: () => Promise; fullResync: (customBirthday?: number, options?: FullResyncOptions) => Promise; - recoverWallet: () => Promise; + recoverWallet: (options?: RecoverOptions) => Promise; +} + +/** Parses the seed fingerprint the snap returns, as hex or as a byte object. */ +function seedFingerprintFromSnap(result: unknown): SeedFingerprint { + const hexString = typeof result === 'string' + ? result + : typeof result === 'object' && result !== null && 'data' in result + ? Array.from((result as { data: number[] }).data).map((b: number) => b.toString(16).padStart(2, '0')).join('') + : String(result); + return SeedFingerprint.from_bytes(new Uint8Array( + (hexString.match(/.{1,2}/g) || []).map((byte: string) => parseInt(byte, 16)), + )); } async function withRetry( @@ -72,9 +104,9 @@ async function withRetry( } export function useWebZjsActions(): WebzjsActions { - const { state, dispatch } = useWebZjsContext(); + const { state, dispatch, reloadWallet } = useWebZjsContext(); const { installedSnap } = useMetaMask(); - const { refreshSnapState } = useMetaMaskContext(); + const { refreshSnapState, snapState } = useMetaMaskContext(); const invokeSnap = useInvokeSnap(); const requestSnap = useRequestSnap(); @@ -231,24 +263,50 @@ export function useWebZjsActions(): WebzjsActions { } }, [state.webWallet, dispatch, cacheBalanceInSnap]); - const flushDbToStore = useCallback(async () => { - if (!state.webWallet) { - // dispatch({ - // type: 'set-error', - // payload: new Error('Wallet not initialized'), - // }); + /** + * Persists the current wallet instance. The store refuses the write if storage has moved on + * (another tab or a resync saved a newer wallet); then this tab reloads from storage instead + * of overwriting it. + */ + const flushDbToStore = useCallback(async (reason: SaveReason = 'sync', options?: FlushOptions) => { + const wallet = state.webWallet; + if (!wallet) { return; } try { console.info('Serializing wallet and dumping to IndexedDB store'); - const bytes = await state.webWallet.db_to_bytes(); - await set('wallet', bytes); - console.info('Wallet saved to storage'); + const bytes = await wallet.db_to_bytes(); + const meta = await saveWallet(wallet, bytes, { + reason, + force: options?.force, + fullyScanned: fullySyncedRef.current ?? null, + }); + console.info(`Wallet saved to storage (epoch ${meta.epoch})`); } catch (error) { + if (error instanceof StaleWalletError) { + console.warn('Storage holds a newer wallet than this tab; reloading instead of overwriting:', error.message); + void reloadWallet(); + return; + } console.error('Error flushing DB to store:', error); dispatch({ type: 'set-error', payload: String(error) }); } - }, [state.webWallet, dispatch]); + }, [state.webWallet, dispatch, reloadWallet]); + + /** + * The blob's own birthday is authoritative. If the snap carries a later value (a stale or + * clobbered mirror), lower it; never raise it. + */ + const repairSnapBirthday = useCallback(async () => { + const wallet = state.webWallet; + if (!wallet) return; + const blobBirthday = walletOrigin(wallet)?.birthday; + const snapBirthday = Number(snapState?.webWalletSyncStartBlock); + if (blobBirthday && snapBirthday && snapBirthday > blobBirthday) { + console.info(`Repairing snap birthday ${snapBirthday} to the wallet's own ${blobBirthday}`); + await updateSnapState({ webWalletSyncStartBlock: String(blobBirthday) }); + } + }, [state.webWallet, snapState, updateSnapState]); const connectWebZjsSnap = useCallback(async () => { try { @@ -268,40 +326,32 @@ export function useWebZjsActions(): WebzjsActions { // Account already exists - just set it as active and sync const existingAccountId = existingSummary.account_balances[0][0]; dispatch({ type: 'set-active-account', payload: existingAccountId }); + await repairSnapBirthday(); await syncStateWithWallet(); return; } + if (state.storedWalletUnreadable) { + throw new Error( + 'The saved wallet could not be read. Recover it from the home page before connecting.', + ); + } + // No existing account - create one using latest block as birthday // Users can do a full resync from the app if they need an earlier birthday const latestBlockBigInt = await state.webWallet.get_latest_block(); const latestBlock = Number(latestBlockBigInt); const birthdayBlock = latestBlock; - await set('birthdayBlock', String(birthdayBlock)); await updateSnapState({ webWalletSyncStartBlock: String(latestBlock) }); const viewingKey = (await invokeSnap({ method: 'getViewingKey', })) as string; - const seedFingerprintResult = await invokeSnap({ + const seedFingerprint = seedFingerprintFromSnap(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, - ); + })); const account_id = await state.webWallet.create_account_ufvk( 'account-0', @@ -313,9 +363,16 @@ export function useWebZjsActions(): WebzjsActions { dispatch({ type: 'set-active-account', payload: account_id }); + // The instance keeps the epoch it was loaded at (none for a fresh install), so the + // save below is rejected if another tab created the account first. + registerWallet(state.webWallet, { + epoch: walletOrigin(state.webWallet)?.epoch ?? null, + birthday: birthdayBlock, + }); + await syncStateWithWallet(); - await flushDbToStore(); + await flushDbToStore('connect'); } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error); const fullMessage = `Failed to connect to MetaMask Snap and create account: ${errorMsg}`; @@ -327,14 +384,19 @@ export function useWebZjsActions(): WebzjsActions { } }, [ state.webWallet, + state.storedWalletUnreadable, invokeSnap, dispatch, syncStateWithWallet, flushDbToStore, updateSnapState, + repairSnapBirthday, requestSnap, ]); + // Instances whose snap birthday has been checked against the blob's, once each. + const birthdayRepairedRef = useRef(new WeakSet()); + const triggerRescan = useCallback(async () => { if (!installedSnap) { return; @@ -362,6 +424,15 @@ export function useWebZjsActions(): WebzjsActions { const webWallet = state.webWallet; await runExclusiveSync(dispatch, async () => { + if (!birthdayRepairedRef.current.has(webWallet)) { + birthdayRepairedRef.current.add(webWallet); + try { + await repairSnapBirthday(); + } catch (err) { + console.warn('Could not repair the snap birthday (will retry next interval):', err); + birthdayRepairedRef.current.delete(webWallet); + } + } // Check if we're already at chain tip - skip redundant syncs // Allow a small buffer (2 blocks) for network propagation const fullySyncedHeight = fullySyncedRef.current; @@ -401,6 +472,7 @@ export function useWebZjsActions(): WebzjsActions { dispatch, syncStateWithWallet, flushDbToStore, + repairSnapBirthday, ]); /** @@ -432,32 +504,25 @@ export function useWebZjsActions(): WebzjsActions { 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); + // Birthday precedence: the value typed in, then the current wallet's own birthday + // (read from its stored bytes), then the snap's mirror. 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 oldWallet = state.webWallet; + const birthdayBlock = customBirthday + ?? (oldWallet ? walletOrigin(oldWallet)?.birthday ?? undefined : undefined) + ?? (snapState?.webWalletSyncStartBlock + ? Number(snapState.webWalletSyncStartBlock) + : undefined); // 2. Get credentials from snap const viewingKey = (await invokeSnap({ method: 'getViewingKey', })) as string; - const seedFingerprintResult = await invokeSnap({ + const seedFingerprint = seedFingerprintFromSnap(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)'); @@ -521,35 +586,45 @@ export function useWebZjsActions(): WebzjsActions { } } - // 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'); + // 6. SUCCESS: persist the fresh wallet FIRST, together with its birthday, as a forced + // write that supersedes whatever is stored. Only then make it visible. A failure + // before this point leaves storage untouched; after it, storage already holds the + // resynced wallet, so nothing that follows can lose it. + const summary = await freshWallet.get_wallet_summary(); + const chainHeight = await freshWallet.get_latest_block(); + registerWallet(freshWallet, { epoch: null, birthday: birthdayBlock ?? null }); + const bytes = await freshWallet.db_to_bytes(); + const saved = await saveWallet(freshWallet, bytes, { + reason: 'resync', + force: true, + birthday: birthdayBlock ?? null, + fullyScanned: summary?.fully_scanned_height ?? null, + }); + console.info(`Full resync: persisted as epoch ${saved.epoch}, swapping wallet into state`); + + // 7. Retire the old instance and swap the fresh one in. + if (oldWallet) markSuperseded(oldWallet); 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 }); } - // 7. Persist: overwrites old data (no need to del() first) - const bytes = await freshWallet.db_to_bytes(); - await set('wallet', bytes); + // 8. Snap state is a backup; a failure here is repaired on the next sync. + try { + if (customBirthday) { + await updateSnapState({ webWalletSyncStartBlock: String(customBirthday) }); + } + if (summary?.account_balances?.length) { + const [, balanceReport] = summary.account_balances[0]; + await cacheBalanceInSnap(balanceReport, true); + } + } catch (snapErr) { + console.warn('Full resync: could not update snap state (will be repaired later):', snapErr); + } console.info('Full resync: Complete'); } catch (err: unknown) { @@ -559,7 +634,7 @@ export function useWebZjsActions(): WebzjsActions { } }); await trackFullResync(run); - }, [installedSnap, invokeSnap, dispatch, updateSnapState, cacheBalanceInSnap]); + }, [installedSnap, state.webWallet, invokeSnap, dispatch, updateSnapState, cacheBalanceInSnap]); /** * Recovers the wallet from snap credentials when IndexedDB data is empty or incompatible. @@ -568,34 +643,41 @@ export function useWebZjsActions(): WebzjsActions { * Key insight: Snap credentials (viewing key, seed fingerprint) are derived from * MetaMask's BIP44 seed - they survive reinstallation. */ - const recoverWallet = useCallback(async () => { + const recoverWallet = useCallback(async (options?: RecoverOptions) => { if (!state.webWallet) { throw new Error('Wallet not initialized'); } + if (state.storedWalletUnreadable && !options?.replaceUnreadable) { + throw new Error( + 'The saved wallet data could not be read and was kept. Use "Discard and recover" to replace it.', + ); + } console.info('Auto-recovery: Attempting to recover wallet from snap credentials'); // 1. Get credentials from snap (derived from MetaMask seed) const viewingKey = (await invokeSnap({ method: 'getViewingKey' })) as string; - const seedFingerprintResult = await invokeSnap({ method: 'getSeedFingerprint' }); - - const seedFingerprintHex = 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 seedFingerprint = SeedFingerprint.from_bytes(new Uint8Array( - (seedFingerprintHex.match(/.{1,2}/g) || []).map((byte: string) => parseInt(byte, 16)), - )); - - // 2. Get birthday from snap state, or use latest block as fallback - const snapState = (await invokeSnap({ method: 'getSnapStete' })) as SnapState | null; - - let birthdayBlock = snapState?.webWalletSyncStartBlock - ? Number(snapState.webWalletSyncStartBlock) - : undefined; - + const seedFingerprint = seedFingerprintFromSnap(await invokeSnap({ method: 'getSeedFingerprint' })); + + // 2. Birthday: the unreadable wallet's own birthday when replacing it, then the snap, + // then the IndexedDB mirror, then the chain tip (a genuinely new wallet). + let birthdayBlock: number | undefined; + if (options?.replaceUnreadable) { + const backup = await readWalletBackup(); + birthdayBlock = backup + ? readBlobBirthday(backup.bytes) ?? backup.meta?.birthday ?? undefined + : undefined; + } + if (!birthdayBlock) { + const snapState = (await invokeSnap({ method: 'getSnapStete' })) as SnapState | null; + birthdayBlock = snapState?.webWalletSyncStartBlock + ? Number(snapState.webWalletSyncStartBlock) + : undefined; + } + if (!birthdayBlock) { + const mirrored = Number(await get('birthdayBlock')); + birthdayBlock = Number.isFinite(mirrored) && mirrored > 0 ? mirrored : undefined; + } if (!birthdayBlock) { console.info('Auto-recovery: No stored birthday, using latest block'); const latestBlock = await state.webWallet.get_latest_block(); @@ -615,13 +697,29 @@ export function useWebZjsActions(): WebzjsActions { ); dispatch({ type: 'set-active-account', payload: accountId }); + registerWallet(state.webWallet, { + epoch: walletOrigin(state.webWallet)?.epoch ?? null, + birthday: birthdayBlock, + }); - // 4. Sync state and persist (skip balance cache — wallet hasn't synced, balance is 0) + // 4. Sync state and persist (skip balance cache: wallet hasn't synced, balance is 0). + // Replacing unreadable data is the one recovery allowed to overwrite storage. await syncStateWithWallet({ skipBalanceCache: true }); - await flushDbToStore(); + await flushDbToStore('recover', { force: !!options?.replaceUnreadable }); + if (options?.replaceUnreadable) { + dispatch({ type: 'set-stored-wallet-unreadable', payload: null }); + } console.info('Auto-recovery: Wallet recovered successfully'); - }, [state.webWallet, invokeSnap, dispatch, syncStateWithWallet, flushDbToStore, updateSnapState]); + }, [ + state.webWallet, + state.storedWalletUnreadable, + invokeSnap, + dispatch, + syncStateWithWallet, + flushDbToStore, + updateSnapState, + ]); return { getAccountData, diff --git a/packages/web-wallet/src/pages/Home.test.tsx b/packages/web-wallet/src/pages/Home.test.tsx index 238d7ff..b02f212 100644 --- a/packages/web-wallet/src/pages/Home.test.tsx +++ b/packages/web-wallet/src/pages/Home.test.tsx @@ -10,22 +10,26 @@ vi.mock('react-router-dom', () => ({ })); // Mock contexts -const mockWebZjsState = { +const mockWebZjsState: Record = { loading: false, activeAccount: null, error: null, + initialized: false, + storedWalletUnreadable: null, }; const mockWebZjsDispatch = vi.fn(); const mockGetAccountData = vi.fn(); const mockConnectWebZjsSnap = vi.fn(); -const mockInstalledSnap = null; +const mockRecoverWallet = vi.fn(); +let mockInstalledSnap: { id: string } | null = null; let mockIsPendingRequest = false; vi.mock('../context/WebzjsContext', () => ({ useWebZjsContext: () => ({ state: mockWebZjsState, dispatch: mockWebZjsDispatch, + initWallet: vi.fn(), }), })); @@ -42,6 +46,7 @@ vi.mock('../hooks', () => ({ useWebZjsActions: () => ({ getAccountData: mockGetAccountData, connectWebZjsSnap: mockConnectWebZjsSnap, + recoverWallet: mockRecoverWallet, }), })); @@ -63,9 +68,31 @@ describe('Home', () => { mockWebZjsState.loading = false; mockWebZjsState.activeAccount = null; mockWebZjsState.error = null; + mockWebZjsState.initialized = false; + mockWebZjsState.storedWalletUnreadable = null; + mockInstalledSnap = null; mockIsPendingRequest = false; }); + it('does not auto-recover over unreadable stored wallet data and offers an explicit discard', async () => { + mockInstalledSnap = { id: 'snap' }; + mockWebZjsState.initialized = true; + mockWebZjsState.storedWalletUnreadable = { error: 'bad format' }; + mockRecoverWallet.mockResolvedValueOnce(undefined); + + render(); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(mockRecoverWallet).not.toHaveBeenCalled(); + expect(screen.getByText('The saved wallet could not be read')).toBeInTheDocument(); + + fireEvent.click(screen.getByText('Discard unreadable wallet data and recover from MetaMask')); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(mockRecoverWallet).toHaveBeenCalledWith({ replaceUnreadable: true }); + expect(mockNavigate).toHaveBeenCalledWith('/dashboard/account-summary'); + }); + it('renders the home page with connect button', () => { render(); @@ -93,7 +120,7 @@ describe('Home', () => { })); // Direct manipulation for this test - const { rerender } = render(); + render(); // Since we're using module-level mock variables, we need to test by updating mockIsPendingRequest // The component should show the warning banner @@ -131,6 +158,7 @@ describe('Home', () => { const button = screen.getByRole('button'); fireEvent.click(button); + await new Promise(resolve => setTimeout(resolve, 0)); expect(mockConnectWebZjsSnap).toHaveBeenCalledTimes(1); }); diff --git a/packages/web-wallet/src/pages/Home.tsx b/packages/web-wallet/src/pages/Home.tsx index a6b9357..f6657a3 100644 --- a/packages/web-wallet/src/pages/Home.tsx +++ b/packages/web-wallet/src/pages/Home.tsx @@ -14,6 +14,7 @@ const Home: React.FC = () => { const { isPendingRequest } = useMetaMaskContext(); const [showResetInstructions, setShowResetInstructions] = useState(false); const [recovering, setRecovering] = useState(false); + const [discarding, setDiscarding] = useState(false); const recoveryAttemptedRef = useRef(false); const connectingRef = useRef(false); @@ -79,7 +80,12 @@ const Home: React.FC = () => { return; } - // Case 3: Wallet initialized but no account - attempt recovery (once only) + // Case 3: Wallet initialized but no account - attempt recovery (once only). + // Never automatically when the stored wallet could not be read: that data is kept + // until the user decides what to do with it. + if (state.storedWalletUnreadable) { + return; + } if (state.initialized && !recoveryAttemptedRef.current && !connectingRef.current) { recoveryAttemptedRef.current = true; try { @@ -97,7 +103,22 @@ const Home: React.FC = () => { }; homeReload(); - }, [state.loading, state.activeAccount, state.initialized, installedSnap, navigate, dispatch, getAccountData, recoverWallet, initWallet]); + }, [state.loading, state.activeAccount, state.initialized, state.storedWalletUnreadable, installedSnap, navigate, dispatch, getAccountData, recoverWallet, initWallet]); + + const handleDiscardUnreadable: React.MouseEventHandler = async (e) => { + e.preventDefault(); + setDiscarding(true); + try { + await recoverWallet({ replaceUnreadable: true }); + navigate('/dashboard/account-summary'); + } catch (err) { + console.error('Recovery over unreadable wallet data failed:', err); + dispatch({ type: 'set-error', payload: err instanceof Error ? err : new Error(String(err)) }); + setShowResetInstructions(true); + } finally { + setDiscarding(false); + } + }; return (
@@ -115,6 +136,26 @@ const Home: React.FC = () => { Access the Zcash network from your web browser with the Zcash MetaMask Snap

+ {state.storedWalletUnreadable && ( +
+
The saved wallet could not be read
+
+ It was kept and backed up in this browser; nothing has been replaced. Discarding + it rebuilds the wallet from MetaMask and rescans from the saved birthday. +
+
+ Show error details +
{state.storedWalletUnreadable.error}
+
+ +
+ )} {showResetInstructions && (
Error occurred while loading the wallet data, please reset the wallet
diff --git a/packages/web-wallet/src/storage/walletBlobMeta.ts b/packages/web-wallet/src/storage/walletBlobMeta.ts new file mode 100644 index 0000000..f1b867d --- /dev/null +++ b/packages/web-wallet/src/storage/walletBlobMeta.ts @@ -0,0 +1,98 @@ +/** + * Reads the account birthday straight out of a serialized wallet blob, without the wasm + * module. The blob is the protobuf `memwallet.MemoryWallet`; only its top level and the + * account birthday are walked, everything else is skipped by length. + * + * Used to make the blob's own birthday the source of truth for stored metadata, instead of + * the separately stored `birthdayBlock` mirror, which can lag or be clobbered. + */ + +interface Field { + num: number; + wire: number; + /** Varint value for wire type 0, or the raw bytes for wire type 2. */ + value: number | Uint8Array; +} + +function parseMessage(bytes: Uint8Array): Field[] { + const fields: Field[] = []; + let i = 0; + const varint = (): number => { + let result = 0; + let shift = 0; + for (;;) { + if (i >= bytes.length) throw new Error('truncated varint'); + const b = bytes[i++]; + result += (b & 0x7f) * 2 ** shift; + if (!(b & 0x80)) return result; + shift += 7; + if (shift > 63) throw new Error('varint too long'); + } + }; + while (i < bytes.length) { + const key = varint(); + const num = Math.floor(key / 8); + const wire = key % 8; + switch (wire) { + case 0: + fields.push({ num, wire, value: varint() }); + break; + case 1: + i += 8; + break; + case 2: { + const len = varint(); + if (i + len > bytes.length) throw new Error('truncated field'); + fields.push({ num, wire, value: bytes.subarray(i, i + len) }); + i += len; + break; + } + case 5: + i += 4; + break; + default: + throw new Error(`unsupported wire type ${wire}`); + } + } + return fields; +} + +const bytesOf = (fields: Field[], num: number): Uint8Array | undefined => { + const f = fields.find((x) => x.num === num && x.wire === 2); + return f ? (f.value as Uint8Array) : undefined; +}; + +const numberOf = (fields: Field[], num: number): number | undefined => { + const f = fields.find((x) => x.num === num && x.wire === 0); + return f ? (f.value as number) : undefined; +}; + +/** + * The lowest account birthday height in the blob, or null if the blob has no account or + * cannot be walked. `MemoryWallet.accounts (2) -> Accounts.accounts (1, repeated) -> + * Account.birthday (7) -> AccountBirthday.prior_chain_state (1) -> ChainState.block_height (1)`; + * the birthday is the height after the prior chain state. + */ +export function readBlobBirthday(bytes: Uint8Array): number | null { + try { + const top = parseMessage(bytes); + const accounts = bytesOf(top, 2); + if (!accounts) return null; + let birthday: number | null = null; + for (const field of parseMessage(accounts)) { + if (field.num !== 1 || field.wire !== 2) continue; + const account = parseMessage(field.value as Uint8Array); + const accountBirthday = bytesOf(account, 7); + if (!accountBirthday) continue; + const chainState = bytesOf(parseMessage(accountBirthday), 1); + if (!chainState) continue; + const priorHeight = numberOf(parseMessage(chainState), 1); + if (priorHeight === undefined) continue; + const height = priorHeight + 1; + birthday = birthday === null ? height : Math.min(birthday, height); + } + return birthday; + } catch { + return null; + } +} diff --git a/packages/web-wallet/src/storage/walletStore.test.ts b/packages/web-wallet/src/storage/walletStore.test.ts new file mode 100644 index 0000000..e8435eb --- /dev/null +++ b/packages/web-wallet/src/storage/walletStore.test.ts @@ -0,0 +1,218 @@ +// @vitest-environment node +import 'fake-indexeddb/auto'; +import { IDBFactory } from 'fake-indexeddb'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +type Store = typeof import('./walletStore'); + +const bytesOf = (text: string) => new TextEncoder().encode(text); + +// idb-keyval caches its database connection per module instance, so every test gets a fresh +// IndexedDB and a freshly imported module. A second import in one test stands in for a second +// browser tab sharing the same storage. +async function freshStore(): Promise { + vi.resetModules(); + return import('./walletStore'); +} + +// Raw IndexedDB helpers against the current global factory. idb-keyval itself lives in +// node_modules, which vitest does not reset, so its default connection would stick to the +// first test's database. +function withStore(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest): Promise { + return new Promise((resolve, reject) => { + const open = indexedDB.open('keyval-store'); + open.onupgradeneeded = () => open.result.createObjectStore('keyval'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const db = open.result; + const request = run(db.transaction('keyval', mode).objectStore('keyval')); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + db.close(); + resolve(request.result); + }; + }; + }); +} + +const stored = (key: string) => withStore('readonly', (store) => store.get(key)); +const seed = (key: string, value: unknown) => withStore('readwrite', (store) => store.put(value, key)); + +beforeEach(() => { + // A fresh database per test; the module under test opens it lazily. + Object.assign(globalThis, { indexedDB: new IDBFactory() }); +}); + +describe('saveWallet', () => { + it('writes a versioned record, its metadata and the birthday mirror on first save', async () => { + const store = await freshStore(); + const wallet = {}; + store.registerWallet(wallet, { epoch: null, birthday: 2_500_000 }); + + const meta = await store.saveWallet(wallet, bytesOf('w1'), { reason: 'connect' }); + + expect(meta.epoch).toBe(1); + expect(meta.birthday).toBe(2_500_000); + expect(meta.writerId).toBe(store.TAB_ID); + const record = (await stored('wallet')) as { v: number; meta: { epoch: number } }; + expect(record.v).toBe(2); + expect(record.meta.epoch).toBe(1); + expect(await stored('wallet.meta')).toEqual(meta); + expect(await stored('birthdayBlock')).toBe('2500000'); + expect(store.walletOrigin(wallet)).toEqual({ epoch: 1, birthday: 2_500_000 }); + }); + + it('rejects a write from an instance behind storage and leaves storage untouched', async () => { + const store = await freshStore(); + const current = {}; + const stale = {}; + store.registerWallet(current, { epoch: null, birthday: null }); + await store.saveWallet(current, bytesOf('v1'), { reason: 'sync' }); + store.registerWallet(stale, { epoch: 1, birthday: null }); + await store.saveWallet(current, bytesOf('v2'), { reason: 'sync' }); // storage -> epoch 2 + + await expect(store.saveWallet(stale, bytesOf('stale'), { reason: 'sync' })).rejects.toBeInstanceOf( + store.StaleWalletError, + ); + + const record = (await stored('wallet')) as { bytes: Uint8Array; meta: { epoch: number } }; + expect(new TextDecoder().decode(record.bytes)).toBe('v2'); + expect(record.meta.epoch).toBe(2); + expect((await stored('wallet.meta')) as { epoch: number }).toMatchObject({ epoch: 2 }); + }); + + it('lets a forced resync write win and strictly raises the epoch', async () => { + const store = await freshStore(); + const current = {}; + store.registerWallet(current, { epoch: null, birthday: null }); + for (let i = 0; i < 5; i++) await store.saveWallet(current, bytesOf(`v${i}`), { reason: 'sync' }); + + const fresh = {}; + store.registerWallet(fresh, { epoch: null, birthday: 3_200_000 }); + const meta = await store.saveWallet(fresh, bytesOf('resynced'), { reason: 'resync', force: true }); + + expect(meta.epoch).toBe(6); + expect(meta.birthday).toBe(3_200_000); + expect(await stored('birthdayBlock')).toBe('3200000'); + await expect(store.saveWallet(current, bytesOf('late'), { reason: 'sync' })).rejects.toBeInstanceOf( + store.StaleWalletError, + ); + }); + + it('never writes from a superseded instance', async () => { + const store = await freshStore(); + const wallet = {}; + store.registerWallet(wallet, { epoch: null, birthday: null }); + await store.saveWallet(wallet, bytesOf('v1'), { reason: 'sync' }); + + store.markSuperseded(wallet); + + await expect(store.saveWallet(wallet, bytesOf('v2'), { reason: 'sync' })).rejects.toBeInstanceOf( + store.StaleWalletError, + ); + expect(await store.peekStoredEpoch()).toBe(1); + }); + + it('serializes concurrent saves of one instance', async () => { + const store = await freshStore(); + const wallet = {}; + store.registerWallet(wallet, { epoch: null, birthday: null }); + + const [a, b] = await Promise.all([ + store.saveWallet(wallet, bytesOf('a'), { reason: 'sync' }), + store.saveWallet(wallet, bytesOf('b'), { reason: 'send' }), + ]); + + expect([a.epoch, b.epoch]).toEqual([1, 2]); + expect(await store.peekStoredEpoch()).toBe(2); + }); +}); + +describe('loadWallet', () => { + it('migrates legacy bytes in memory at epoch 0 and converts them on the first save', async () => { + await seed('wallet', bytesOf('legacy')); + await seed('birthdayBlock', '2500000'); + const store = await freshStore(); + + const loaded = await store.loadWallet((bytes) => ({ text: new TextDecoder().decode(bytes) })); + expect(loaded.status).toBe('ok'); + if (loaded.status !== 'ok') return; + expect(loaded.legacy).toBe(true); + expect(loaded.meta).toMatchObject({ epoch: 0, birthday: 2_500_000, reason: 'legacy' }); + expect(await store.peekStoredEpoch()).toBe(0); + + await store.saveWallet(loaded.wallet, bytesOf('converted'), { reason: 'sync' }); + const record = (await stored('wallet')) as { v: number; meta: { epoch: number; birthday: number } }; + expect(record.v).toBe(2); + expect(record.meta).toMatchObject({ epoch: 1, birthday: 2_500_000 }); + }); + + it('keeps and backs up bytes that fail to decode, and the empty wallet cannot save', async () => { + const original = bytesOf('corrupt'); + await seed('wallet', original); + const store = await freshStore(); + + const loaded = await store.loadWallet(() => { + throw new Error('bad format'); + }); + + expect(loaded.status).toBe('unreadable'); + expect(await stored('wallet')).toEqual(original); + const backup = (await store.readWalletBackup())!; + expect(new TextDecoder().decode(backup.bytes)).toBe('corrupt'); + expect(backup.error).toContain('bad format'); + + const empty = {}; // not registered, like the context's fallback wallet + await expect(store.saveWallet(empty, bytesOf('fresh'), { reason: 'recover' })).rejects.toBeInstanceOf( + store.StaleWalletError, + ); + expect(await stored('wallet')).toEqual(original); + + const forced = await store.saveWallet(empty, bytesOf('fresh'), { reason: 'recover', force: true }); + expect(forced.epoch).toBe(1); + }); + + it('returns none when nothing is stored', async () => { + const store = await freshStore(); + expect(await store.loadWallet(() => ({}))).toEqual({ status: 'none' }); + expect(await store.peekStoredEpoch()).toBeNull(); + }); +}); + +describe('two tabs sharing one storage', () => { + it('lets each tab write only while it is current, and a resync beats both', async () => { + const decode = (bytes: Uint8Array) => ({ text: new TextDecoder().decode(bytes) }); + await seed('wallet', bytesOf('shared')); + + const tabA = await freshStore(); + const loadedA = await tabA.loadWallet(decode); + const tabB = await freshStore(); + const loadedB = await tabB.loadWallet(decode); + if (loadedA.status !== 'ok' || loadedB.status !== 'ok') throw new Error('both tabs load'); + expect(tabA.TAB_ID).not.toBe(tabB.TAB_ID); + + await tabA.saveWallet(loadedA.wallet, bytesOf('a1'), { reason: 'sync' }); // epoch 1 + await expect(tabB.saveWallet(loadedB.wallet, bytesOf('b-stale'), { reason: 'sync' })).rejects.toBeInstanceOf( + tabB.StaleWalletError, + ); + + const reloadedB = await tabB.loadWallet(decode); + if (reloadedB.status !== 'ok') throw new Error('tab B reloads'); + expect(reloadedB.meta.epoch).toBe(1); + await tabB.saveWallet(reloadedB.wallet, bytesOf('b2'), { reason: 'sync' }); // epoch 2 + await expect(tabA.saveWallet(loadedA.wallet, bytesOf('a-stale'), { reason: 'sync' })).rejects.toBeInstanceOf( + tabA.StaleWalletError, + ); + + const resynced = {}; + tabA.registerWallet(resynced, { epoch: null, birthday: 3_200_000 }); + const meta = await tabA.saveWallet(resynced, bytesOf('resynced'), { reason: 'resync', force: true }); + expect(meta.epoch).toBe(3); + await expect(tabB.saveWallet(reloadedB.wallet, bytesOf('b3'), { reason: 'sync' })).rejects.toBeInstanceOf( + tabB.StaleWalletError, + ); + const record = (await stored('wallet')) as { bytes: Uint8Array; meta: { writerId: string } }; + expect(new TextDecoder().decode(record.bytes)).toBe('resynced'); + expect(record.meta.writerId).toBe(tabA.TAB_ID); + }); +}); diff --git a/packages/web-wallet/src/storage/walletStore.ts b/packages/web-wallet/src/storage/walletStore.ts new file mode 100644 index 0000000..789af07 --- /dev/null +++ b/packages/web-wallet/src/storage/walletStore.ts @@ -0,0 +1,317 @@ +/** + * The only module that reads or writes the wallet in IndexedDB. + * + * Invariant: a wallet is written only if the instance writing it descends from what is + * stored right now (same epoch), or the write is an explicit resync or recovery that is + * allowed to win. The check and the write happen in one IndexedDB transaction, so a stale + * instance in any tab, hook or closure can never overwrite newer data. + * + * Keys (all in idb-keyval's default database and store, so older builds' data is visible): + * - `wallet` WalletRecord, or a bare Uint8Array written by older builds (epoch 0) + * - `wallet.meta` WalletMeta of the stored record, cheap to read on its own + * - `wallet.backup` bytes that failed to load, kept until the user decides + * - `birthdayBlock` mirror of the stored birthday, kept for the snap-state fallback + */ +import { createStore, get, promisifyRequest, set, type UseStore } from 'idb-keyval'; + +import { readBlobBirthday } from './walletBlobMeta'; + +export type SaveReason = 'connect' | 'sync' | 'send' | 'resync' | 'recover'; + +export interface WalletMeta { + /** Bumped on every successful write; the ordering authority. */ + epoch: number; + /** Birthday read out of the blob itself, or null when the blob has no account. */ + birthday: number | null; + fullyScanned: number | null; + savedAt: number; + writerId: string; + reason: SaveReason | 'legacy'; +} + +export interface WalletRecord { + v: 2; + bytes: Uint8Array; + meta: WalletMeta; +} + +export interface WalletBackup { + bytes: Uint8Array; + meta: WalletMeta | null; + error: string; + failedAt: number; +} + +/** What an in-memory instance believes is stored: the epoch it was loaded from or last saved at. */ +export interface WalletOrigin { + /** null: never persisted and expects no stored wallet. SUPERSEDED: may never write again. */ + epoch: number | null; + birthday: number | null; +} + +export type LoadResult = + | { status: 'none' } + | { status: 'ok'; wallet: W; meta: WalletMeta; legacy: boolean } + | { status: 'unreadable'; error: unknown; meta: WalletMeta | null }; + +export interface SaveOptions { + reason: SaveReason; + /** Used only when the blob itself carries no birthday. */ + birthday?: number | null; + fullyScanned?: number | null; + /** Skip the epoch check. Only for a completed resync or an explicit recovery. */ + force?: boolean; +} + +export class StaleWalletError extends Error { + constructor( + readonly expected: number | null, + readonly stored: number | null, + ) { + super( + `Refusing to save the wallet: this instance was loaded at epoch ${expected}, storage is at epoch ${stored}`, + ); + this.name = 'StaleWalletError'; + } +} + +export const WALLET_KEY = 'wallet'; +export const META_KEY = 'wallet.meta'; +export const BACKUP_KEY = 'wallet.backup'; +export const BIRTHDAY_KEY = 'birthdayBlock'; +const CHANNEL_NAME = 'webzjs-wallet'; +const WRITER_LOCK = 'webzjs-wallet-writer'; +export const SUPERSEDED = -1; + +export const TAB_ID: string = + typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' + ? crypto.randomUUID() + : Math.random().toString(36).slice(2); + +// Same database and store idb-keyval uses by default, opened on first use so that importing +// this module needs no IndexedDB (component tests run without one). +let storeRef: UseStore | undefined; +function store(mode: IDBTransactionMode, callback: (objectStore: IDBObjectStore) => T | PromiseLike): Promise { + storeRef ??= createStore('keyval-store', 'keyval'); + return storeRef(mode, callback); +} + +const origins = new WeakMap(); + +export function registerWallet(wallet: object, origin: WalletOrigin): void { + origins.set(wallet, origin); +} + +export function walletOrigin(wallet: object): WalletOrigin | undefined { + return origins.get(wallet); +} + +/** After this the instance can never write; used when another instance replaces it. */ +export function markSuperseded(wallet: object): void { + origins.set(wallet, { epoch: SUPERSEDED, birthday: origins.get(wallet)?.birthday ?? null }); +} + +function isBytes(value: unknown): value is Uint8Array { + return value instanceof Uint8Array || ArrayBuffer.isView(value); +} + +function isRecord(value: unknown): value is WalletRecord { + return ( + typeof value === 'object' && + value !== null && + (value as WalletRecord).v === 2 && + isBytes((value as WalletRecord).bytes) && + typeof (value as WalletRecord).meta?.epoch === 'number' + ); +} + +/** The epoch a stored value represents: nothing → null, legacy bytes → 0, record → its epoch. */ +function epochOf(stored: unknown): number | null { + if (stored === undefined || stored === null) return null; + if (isBytes(stored)) return 0; + if (isRecord(stored)) return stored.meta.epoch; + return 0; +} + +function toHeight(value: unknown): number | null { + const n = Number(value); + return Number.isFinite(n) && n > 0 ? n : null; +} + +// Saves from one tab run one at a time so two saves of the same instance cannot race each +// other's registry update. +let writes: Promise = Promise.resolve(); +function serialize(job: () => Promise): Promise { + const result = writes.then(job); + writes = result.catch(() => undefined); + return result; +} + +/** + * Loads the stored wallet. A bare byte array from an older build is migrated in memory (epoch 0) + * and converted on its first save. Bytes that fail to decode are copied to `wallet.backup` and + * left in place; the caller must not register the empty wallet it builds instead, so that every + * unforced save is rejected until the user explicitly replaces the stored data. + */ +export async function loadWallet( + decode: (bytes: Uint8Array) => W, +): Promise> { + const stored = await get(WALLET_KEY, store); + if (stored === undefined || stored === null) return { status: 'none' }; + + let bytes: Uint8Array; + let meta: WalletMeta | null; + let legacy = false; + if (isBytes(stored)) { + bytes = stored; + legacy = true; + const mirrored = toHeight(await get(BIRTHDAY_KEY, store)); + meta = { + epoch: 0, + birthday: readBlobBirthday(bytes) ?? mirrored, + fullyScanned: null, + savedAt: 0, + writerId: '', + reason: 'legacy', + }; + } else if (isRecord(stored)) { + bytes = stored.bytes; + meta = stored.meta; + } else { + return { status: 'unreadable', error: new Error('Stored wallet has an unknown shape'), meta: null }; + } + + try { + const wallet = decode(bytes); + registerWallet(wallet, { epoch: meta.epoch, birthday: meta.birthday }); + return { status: 'ok', wallet, meta, legacy }; + } catch (error) { + const backup: WalletBackup = { + bytes, + meta: legacy ? null : meta, + error: error instanceof Error ? `${error.name}: ${error.message}` : String(error), + failedAt: Date.now(), + }; + try { + await set(BACKUP_KEY, backup, store); + } catch (backupError) { + console.error('Could not back up the unreadable wallet bytes:', backupError); + } + return { status: 'unreadable', error, meta: legacy ? null : meta }; + } +} + +/** + * Compare-and-swap write of the wallet, its metadata and the birthday mirror in one + * transaction. Throws StaleWalletError, and writes nothing, when storage is not at the epoch + * this instance expects, unless `force` is set. On success the instance's origin moves to the + * new epoch and other tabs are told. + */ +export function saveWallet(wallet: object, bytes: Uint8Array, opts: SaveOptions): Promise { + return serialize(async () => { + const origin = origins.get(wallet); + const expected = origin ? origin.epoch : null; + if (expected === SUPERSEDED) { + throw new StaleWalletError(expected, null); + } + const birthday = readBlobBirthday(bytes) ?? opts.birthday ?? origin?.birthday ?? null; + + const meta = await store( + 'readwrite', + (objectStore) => + new Promise((resolve, reject) => { + const request = objectStore.get(WALLET_KEY); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + const storedEpoch = epochOf(request.result); + if (!opts.force && storedEpoch !== expected) { + objectStore.transaction.abort(); + reject(new StaleWalletError(expected, storedEpoch)); + return; + } + const next: WalletMeta = { + epoch: (storedEpoch ?? 0) + 1, + birthday, + fullyScanned: opts.fullyScanned ?? null, + savedAt: Date.now(), + writerId: TAB_ID, + reason: opts.reason, + }; + const record: WalletRecord = { v: 2, bytes, meta: next }; + objectStore.put(record, WALLET_KEY); + objectStore.put(next, META_KEY); + if (birthday !== null) { + objectStore.put(String(birthday), BIRTHDAY_KEY); + } + resolve(promisifyRequest(objectStore.transaction).then(() => next)); + }; + }), + ); + + origins.set(wallet, { epoch: meta.epoch, birthday: meta.birthday }); + broadcast({ type: 'saved', epoch: meta.epoch, writerId: TAB_ID }); + return meta; + }); +} + +/** Epoch of what is stored: record epoch, 0 for legacy bytes, null when nothing is stored. */ +export async function peekStoredEpoch(): Promise { + const meta = (await get(META_KEY, store)) as WalletMeta | undefined; + if (meta && typeof meta.epoch === 'number') return meta.epoch; + return epochOf(await get(WALLET_KEY, store)); +} + +export async function readWalletBackup(): Promise { + return ((await get(BACKUP_KEY, store)) as WalletBackup | undefined) ?? null; +} + +export interface WalletChangedMessage { + type: 'saved'; + epoch: number; + writerId: string; +} + +const channel: BroadcastChannel | null = + typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel(CHANNEL_NAME) : null; + +function broadcast(message: WalletChangedMessage): void { + try { + channel?.postMessage(message); + } catch (error) { + console.warn('Could not notify other tabs of the wallet save:', error); + } +} + +/** Calls `cb` when another tab saves the wallet. Returns the unsubscribe function. */ +export function onWalletChanged(cb: (message: WalletChangedMessage) => void): () => void { + if (!channel) return () => undefined; + const listener = (event: MessageEvent) => { + const message = event.data; + if (message?.type === 'saved' && message.writerId !== TAB_ID) cb(message); + }; + channel.addEventListener('message', listener); + return () => channel.removeEventListener('message', listener); +} + +/** + * Holds the single-writer lock for the life of this tab and calls `onClaimed` once it is + * held. Tabs that do not hold it should not run periodic syncs. Where Web Locks are not + * available every tab is a writer; the epoch check keeps that safe, only less efficient. + */ +export function claimWriterRole(onClaimed: () => void): void { + const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined; + if (!locks) { + onClaimed(); + return; + } + void locks + .request(WRITER_LOCK, () => { + onClaimed(); + // Never resolves: the lock is released when the tab goes away. + return new Promise(() => undefined); + }) + .catch((error) => { + console.warn('Writer lock unavailable, continuing as a writer:', error); + onClaimed(); + }); +} diff --git a/yarn.lock b/yarn.lock index b32d861..99b0fc3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6304,6 +6304,7 @@ __metadata: eslint-plugin-react-hooks: "npm:^5.0.0" eslint-plugin-react-refresh: "npm:^0.4.14" express: "npm:^4.21.2" + fake-indexeddb: "npm:^6.2.6" globals: "npm:^15.11.0" idb-keyval: "npm:^6.2.1" jsdom: "npm:^24.0.0" @@ -10054,6 +10055,13 @@ __metadata: languageName: node linkType: hard +"fake-indexeddb@npm:^6.2.6": + version: 6.2.6 + resolution: "fake-indexeddb@npm:6.2.6" + checksum: 10c0/d55b3155548f08da1c9d7552314eed30fd1880c1f7643654c8b0c1fdf80591682d9f88e7a5c481113f48b994cb09820d61eee0dd8b966ca4f4497fce0eb748de + languageName: node + linkType: hard + "fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": version: 3.1.3 resolution: "fast-deep-equal@npm:3.1.3"