diff --git a/Cargo.lock b/Cargo.lock index a4e15ff..82a4866 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -719,7 +719,7 @@ checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" [[package]] name = "equihash" version = "0.3.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "blake2b_simd", "corez", @@ -771,7 +771,7 @@ dependencies = [ [[package]] name = "f4jumble" version = "0.1.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "blake2b_simd", ] @@ -1785,7 +1785,7 @@ dependencies = [ [[package]] name = "pczt" version = "0.8.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "blake2b_simd", "bls12_381", @@ -3629,7 +3629,7 @@ dependencies = [ [[package]] name = "zcash_address" version = "0.13.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "bech32", "bs58", @@ -3642,7 +3642,7 @@ dependencies = [ [[package]] name = "zcash_client_backend" version = "0.24.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "async-trait", "base64", @@ -3696,7 +3696,7 @@ dependencies = [ [[package]] name = "zcash_client_memory" version = "0.0.0" -source = "git+https://github.com/red-dev-inc/zcash_client_memory?branch=feat%2Fsnap-nu63#1feb38d92d214ec65d410a01c0f9da42b787f76b" +source = "git+https://github.com/sqhell/zcash_client_memory?rev=e15c962dd84f59b27c06f41a52d89366846dc7be#e15c962dd84f59b27c06f41a52d89366846dc7be" dependencies = [ "async-trait", "bip32", @@ -3738,7 +3738,7 @@ dependencies = [ [[package]] name = "zcash_client_sqlite" version = "0.22.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "bitflags", "bs58", @@ -3781,7 +3781,7 @@ dependencies = [ [[package]] name = "zcash_encoding" version = "0.4.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "corez", "hex", @@ -3791,7 +3791,7 @@ dependencies = [ [[package]] name = "zcash_keys" version = "0.15.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "bech32", "bip32", @@ -3833,7 +3833,7 @@ dependencies = [ [[package]] name = "zcash_primitives" version = "0.29.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "blake2b_simd", "block-buffer 0.11.0-rc.3", @@ -3863,7 +3863,7 @@ dependencies = [ [[package]] name = "zcash_proofs" version = "0.29.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "bellman", "blake2b_simd", @@ -3882,7 +3882,7 @@ dependencies = [ [[package]] name = "zcash_protocol" version = "0.10.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "corez", "document-features", @@ -3920,7 +3920,7 @@ dependencies = [ [[package]] name = "zcash_transparent" version = "0.9.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "bip32", "bs58", @@ -3997,7 +3997,7 @@ dependencies = [ [[package]] name = "zip321" version = "0.9.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "git+https://github.com/sqhell/librustzcash?rev=b7b65fe3310eb4c8420469c48303c07ded6a74d5#b7b65fe3310eb4c8420469c48303c07ded6a74d5" dependencies = [ "base64", "nom", diff --git a/Cargo.toml b/Cargo.toml index d661552..f4c5033 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,9 @@ tokio_with_wasm = { version = "0.7.1", features = ["rt", "rt-multi-thread", "syn ## rc crates (pczt, client_backend, zip321, sqlite) keep the explicit -rc.1 so the pre-release matches. zcash_keys = { version = "0.15.0", features = ["transparent-inputs", "orchard", "sapling", "unstable"] } zcash_client_backend = { version = "0.24.0-rc.1", default-features = false, features = ["sync", "lightwalletd-tonic", "orchard"] } -zcash_client_memory = { git = "https://github.com/red-dev-inc/zcash_client_memory", branch = "feat/snap-nu63", features = ["orchard", "transparent-inputs"] } +# sqhell fork of red-dev-inc "feat/snap-nu63" with the eager block-cache delete, nullifier-map pruning +# and Ironwood (NU6.3) pool support. Switch back to red-dev-inc once those land there. +zcash_client_memory = { git = "https://github.com/sqhell/zcash_client_memory", rev = "e15c962dd84f59b27c06f41a52d89366846dc7be", features = ["orchard", "transparent-inputs"] } zcash_primitives = { version = "0.29.0" } zcash_transparent = { version = "0.9.0", default-features = false } zcash_address = { version = "0.13.0" } @@ -95,18 +97,18 @@ byte-unit = { version = "5.1.4", features = ["byte"] } # while librustzcash pulls the git rev -> two `orchard` versions -> trait mismatch. Drop once it lands # in an orchard release. orchard = { git = "https://github.com/zcash/orchard.git", rev = "3bd2b736d1273226595773265313fc3f3428af16" } -equihash = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_address = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_client_backend = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_client_sqlite = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_encoding = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_keys = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_protocol = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zip321 = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_primitives = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_proofs = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -pczt = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } -zcash_transparent = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" } +equihash = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_address = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_client_backend = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_client_sqlite = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_encoding = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_keys = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_protocol = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zip321 = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_primitives = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_proofs = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +pczt = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } +zcash_transparent = { git = "https://github.com/sqhell/librustzcash", rev = "b7b65fe3310eb4c8420469c48303c07ded6a74d5" } [workspace.lints.rust] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(wasm_bindgen)', 'cfg(wasm_bindgen_unstable_test_coverage)'] } \ No newline at end of file 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/Cargo.toml b/crates/webzjs-wallet/Cargo.toml index 81dffa8..b6685ec 100644 --- a/crates/webzjs-wallet/Cargo.toml +++ b/crates/webzjs-wallet/Cargo.toml @@ -71,8 +71,8 @@ bip32.workspace = true prost = { version = "0.14", default-features = false } tonic = { version = "0.14", default-features = false, features = ["codegen"] } -# Used in Native tests -tokio.workspace = true +# "sync" for the mpsc/oneshot channels of the shared sync worker; the rest is used in native tests +tokio = { workspace = true, features = ["sync"] } zcash_client_sqlite = { workspace = true, optional = true } getrandom = { workspace = true, features = ["js"] } diff --git a/crates/webzjs-wallet/src/bindgen/wallet.rs b/crates/webzjs-wallet/src/bindgen/wallet.rs index 7b29651..18d4de2 100644 --- a/crates/webzjs-wallet/src/bindgen/wallet.rs +++ b/crates/webzjs-wallet/src/bindgen/wallet.rs @@ -1,7 +1,11 @@ use std::str::FromStr; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; +use futures_util::future::{select, Either}; use nonempty::NonEmpty; use serde::{Deserialize, Serialize}; +use tokio::sync::{mpsc, oneshot, Notify}; use wasm_bindgen::prelude::*; use tonic_web_wasm_client::Client; @@ -29,6 +33,121 @@ pub type MemoryWallet = Wallet, T>; pub type AccountId = as WalletRead>::AccountId; pub type NoteRef = as InputSource>::NoteRef; +/// What a [`SyncRequest`] asks the sync worker to do. +enum SyncKind { + /// Sync until no scan work remains (`Wallet::sync`). + Full, + /// One bounded step (`Wallet::sync_step`); `first` refreshes the subtree roots. + Step { first: bool }, +} + +/// Why a request failed inside the sync worker. +/// +/// `Error` holds a `JsValue` and is not `Send`, so the worker cannot reply with it directly. The +/// closed case is kept apart so the caller can surface it as `Error::InstanceClosed` again. +enum SyncFailure { + InstanceClosed, + Other(String), +} + +impl From for SyncFailure { + fn from(e: Error) -> Self { + match e { + Error::InstanceClosed => SyncFailure::InstanceClosed, + other => SyncFailure::Other(other.to_string()), + } + } +} + +/// One `WebWallet::sync` or `WebWallet::sync_step` call, handed to the sync worker. +struct SyncRequest { + wallet: MemoryWallet, + kind: SyncKind, + /// `Ok(true)` if more sync work remains (only ever for `SyncKind::Step`), `Ok(false)` otherwise. + reply: oneshot::Sender>, +} + +/// Set once JS has reported that the sync worker trapped; see [`report_sync_worker_trap`]. +static SYNC_WORKER_POISONED: AtomicBool = AtomicBool::new(false); + +/// Wakes callers waiting on a reply from the sync worker when it is reported as trapped. +fn sync_worker_poison_signal() -> &'static Notify { + static SIGNAL: OnceLock = OnceLock::new(); + SIGNAL.get_or_init(Notify::new) +} + +/// Tell the library that the shared sync worker has trapped and will never reply again. +/// +/// A Rust panic inside the sync worker compiles to a wasm trap. The library cannot observe it: the +/// worker's event loop simply stops, the request it was running never resolves, and anything queued +/// behind it would wait forever. The browser does report it, as an uncaught +/// `RuntimeError: unreachable` delivered to the window's `error` event (the message comes from the +/// worker thread, so it is not thrown by the `sync` promise). Call this function from that handler. +/// +/// After this call every in-flight and future `sync` / `sync_step` call rejects with +/// "the sync worker stopped after an internal error; reload the page" instead of hanging. The +/// worker is not restarted; the wallet state may be mid-update, so the page should persist nothing +/// further from this instance and reload. Calling it more than once is harmless. +/// +/// # Examples +/// +/// ```javascript +/// window.addEventListener("error", (event) => { +/// if (event.message && event.message.includes("unreachable")) { +/// report_sync_worker_trap(); +/// } +/// }); +/// ``` +#[wasm_bindgen] +pub fn report_sync_worker_trap() { + if !SYNC_WORKER_POISONED.swap(true, Ordering::SeqCst) { + tracing::error!("sync worker reported as trapped; refusing further sync requests"); + } + sync_worker_poison_signal().notify_waiters(); +} + +/// Whether [`report_sync_worker_trap`] has been called. +fn sync_worker_poisoned() -> bool { + SYNC_WORKER_POISONED.load(Ordering::SeqCst) +} + +/// The single web worker that runs every `WebWallet::sync` and `WebWallet::sync_step` call, +/// spawned on first use. +/// +/// Each call used to spawn its own worker. Those workers are never torn down: `wasm_thread` is built +/// with `keep_worker_alive`, and a worker's thread-locals are not dropped even when it is closed. +/// The tracing registry gives each thread that creates a span one of only 128 slots on wasm32 and +/// relies on the thread-local drop to hand it back, so the periodic rescan exhausted the slots after +/// about 128 syncs (around 75 minutes at the default interval) and the next sync panicked with +/// "Thread count overflowed the configured max count". Reusing one worker keeps the thread count, +/// and the memory held by idle workers, constant. Requests run one at a time, in order. +fn sync_worker() -> &'static mpsc::UnboundedSender { + static WORKER: OnceLock> = OnceLock::new(); + WORKER.get_or_init(|| { + let (tx, mut rx) = mpsc::unbounded_channel::(); + thread::Builder::new() + .name("sync".to_string()) + .spawn_async(move || async move { + assert!(thread::is_web_worker_thread()); + while let Some(SyncRequest { + wallet, + kind, + reply, + }) = rx.recv().await + { + let result = match kind { + SyncKind::Full => wallet.sync().await.map(|()| false), + SyncKind::Step { first } => wallet.sync_step(first).await, + }; + // The caller only goes away if its future was dropped; nothing to do then. + let _ = reply.send(result.map_err(SyncFailure::from)); + } + }) + .unwrap_throw(); + tx + }) +} + /// # A Zcash wallet /// /// This is the main entry point for interacting with this library. @@ -71,6 +190,17 @@ pub type NoteRef = as InputSource>::NoteRef; /// await wallet.sync(); /// ``` /// +/// A sync can also be driven one bounded step at a time with `sync_step`, which releases the wallet lock between +/// steps so the wallet can be persisted with `db_to_bytes` as it goes and stopped with `close`: +/// +/// ```javascript +/// let first = true; +/// while (await wallet.sync_step(first)) { +/// first = false; +/// await persist(await wallet.db_to_bytes()); +/// } +/// ``` +/// /// ## Transacting /// /// Sending a transaction is a three step process: proposing, authorizing, and sending. @@ -268,43 +398,155 @@ impl WebWallet { /// /// Start a background sync task which will fetch and scan blocks from the connected lighwalletd server /// - /// IMPORTANT: This will spawn a new webworker which will handle the sync task. The sync task will continue to run in the background until the sync process is complete. + /// IMPORTANT: The sync runs on a dedicated webworker that is shared by every wallet and reused for every call, + /// so concurrent calls run one after another. The sync task will continue to run in the background until the sync process is complete. /// During this time the main thread will not block but certain wallet methods may temporarily block while the wallet is being written to during the sync. + /// The sync is performed in bounded steps (see `sync_step`): the wallet lock is released between batches, and + /// closing the instance with `close` stops the sync at the next batch boundary. + /// + /// A trap inside the worker (a Rust panic compiled to wasm) cannot be observed from Rust: the worker stops + /// taking requests and the trapped call never resolves. The browser surfaces it as an uncaught + /// `RuntimeError: unreachable` on the window's `error` event, not as a rejection of this promise. JS should + /// call `report_sync_worker_trap()` from that handler; from then on this call and every later `sync` / + /// `sync_step` reject with "the sync worker stopped after an internal error; reload the page" instead of + /// hanging or queueing behind the dead worker. + /// + /// # Errors + /// + /// Rejects with "the sync worker stopped after an internal error; reload the page" once the worker has been + /// reported as trapped, with "this wallet instance was closed; reload the wallet" if `close` has been called, + /// and with a "Syncing Error" for server, cache, scanning and wallet errors. /// + /// # Examples + /// + /// ```javascript + /// await wallet.sync(); + /// ``` pub async fn sync(&self) -> Result<(), Error> { - assert!(!thread::is_web_worker_thread()); + self.run_on_sync_worker(SyncKind::Full).await.map(|_| ()) + } - let db = self.inner.clone(); + /// Perform one bounded step of the sync on the shared sync webworker. + /// + /// A step refreshes the wallet's view of the chain tip, then fetches and scans at most one batch of blocks + /// before releasing the wallet lock, so `db_to_bytes` and other wallet methods can run between steps and the + /// wallet state at every step boundary can be resumed from later, including from a new page load restored + /// from `db_to_bytes`. A sync is complete when a step resolves to `false`. + /// + /// # Arguments + /// + /// * `first` - `true` for the first step of a sync (and after a long pause); the subtree roots are then + /// refreshed from the server before scanning. Pass `false` on later steps to skip that round trip. + /// + /// # Returns + /// + /// `true` if more sync work remains and `sync_step` should be called again, `false` once the wallet reports + /// nothing left to scan. + /// + /// # Errors + /// + /// Rejects with "the sync worker stopped after an internal error; reload the page" once the worker has been + /// reported as trapped (see `report_sync_worker_trap`), with "this wallet instance was closed; reload the + /// wallet" if `close` has been called, and with a "Syncing Error" for server, cache, scanning and wallet + /// errors. + /// + /// # Examples + /// + /// ```javascript + /// let first = true; + /// while (await wallet.sync_step(first)) { + /// first = false; + /// await persist(await wallet.db_to_bytes()); + /// } + /// ``` + pub async fn sync_step(&self, first: bool) -> Result { + self.run_on_sync_worker(SyncKind::Step { first }).await + } - let sync_handler = thread::Builder::new() - .name("sync".to_string()) - .spawn_async(|| async { - assert!(thread::is_web_worker_thread()); - tracing::debug!( - "Current num threads (wasm_thread) {}", - rayon::current_num_threads() - ); + /// The id of this wallet instance. + /// + /// Every `new WebWallet(...)` gets a fresh id; clones share it. Use it to tell whether a sync step's result + /// still belongs to the wallet currently in use after the page has swapped in a new instance. + /// + /// # Examples + /// + /// ```javascript + /// const id = wallet.instance_id; + /// ``` + #[wasm_bindgen(getter)] + pub fn instance_id(&self) -> String { + self.inner.instance_id().to_string() + } - let db = db; - // Convert error to String since Error isn't Send (contains JsValue) - db.sync().await.map_err(|e| e.to_string()) - }) - .unwrap_throw() - .join_async(); + /// Close this wallet instance. + /// + /// After this, `sync`, `sync_step`, `db_to_bytes`, account creation and every transaction building or + /// sending method reject with "this wallet instance was closed; reload the wallet". A sync step that is + /// already running finishes its current batch, and the next step is refused, so a sync loop over this + /// instance stops at the next batch boundary. Call it before replacing the instance with a new one (for + /// example on a full resync) so that a step still queued for the old instance cannot write into it. + /// Closing is idempotent and cannot be undone. + /// + /// # Examples + /// + /// ```javascript + /// oldWallet.close(); + /// const wallet = new WebWallet("main", url, 10, 10, bytes); + /// ``` + pub fn close(&self) { + self.inner.close(); + } - // sync_handler.await returns Result, Box> - // The outer Result is for the join (thread panics), inner is sync result - match sync_handler.await { - Ok(Ok(())) => Ok(()), - Ok(Err(err_string)) => { + /// Whether `close` has been called on this instance. + /// + /// # Examples + /// + /// ```javascript + /// if (wallet.is_closed()) { reloadWallet(); } + /// ``` + pub fn is_closed(&self) -> bool { + self.inner.is_closed() + } + + /// Hand a request to the shared sync worker and wait for its reply. + /// + /// Refuses immediately, without queueing, when the worker has been reported as trapped or the instance is + /// closed. While waiting it also watches the poison signal, so a request that is in flight when the worker + /// traps is released as soon as JS reports the trap. + async fn run_on_sync_worker(&self, kind: SyncKind) -> Result { + assert!(!thread::is_web_worker_thread()); + + if sync_worker_poisoned() { + return Err(Error::SyncWorkerUnavailable); + } + if self.inner.is_closed() { + return Err(Error::InstanceClosed); + } + + let (reply, result) = oneshot::channel(); + sync_worker() + .send(SyncRequest { + wallet: self.inner.clone(), + kind, + reply, + }) + .map_err(|_| Error::SyncWorkerUnavailable)?; + + let poisoned = sync_worker_poison_signal().notified(); + futures_util::pin_mut!(poisoned); + match select(result, poisoned).await { + Either::Left((Ok(Ok(more)), _)) => Ok(more), + Either::Left((Ok(Err(SyncFailure::InstanceClosed)), _)) => Err(Error::InstanceClosed), + Either::Left((Ok(Err(SyncFailure::Other(err_string))), _)) => { tracing::warn!("Sync error (will be retried by caller): {}", err_string); Err(Error::Sync(err_string)) } - Err(panic_error) => { - let msg = format!("Sync thread panicked: {:?}", panic_error); + Either::Left((Err(_), _)) => { + let msg = "Sync worker dropped the request without replying".to_string(); tracing::error!("{}", msg); Err(Error::Sync(msg)) } + Either::Right(((), _)) => Err(Error::SyncWorkerUnavailable), } } @@ -686,6 +928,8 @@ impl WalletSummary { pub struct AccountBalance { pub sapling_balance: u64, pub orchard_balance: u64, + /// Ironwood pool (NU6.3). Payments to shielded addresses arrive here after the upgrade. + pub ironwood_balance: u64, pub unshielded_balance: u64, /// Change from sent transactions waiting for mining confirmation pub pending_change: u64, @@ -698,6 +942,7 @@ impl From for AccountBalance { AccountBalance { sapling_balance: balance.sapling_balance().spendable_value().into(), orchard_balance: balance.orchard_balance().spendable_value().into(), + ironwood_balance: balance.ironwood_balance().spendable_value().into(), unshielded_balance: balance.unshielded_balance().spendable_value().into(), pending_change: balance.change_pending_confirmation().into(), pending_spendable: balance.value_pending_spendability().into(), diff --git a/crates/webzjs-wallet/src/error.rs b/crates/webzjs-wallet/src/error.rs index a360053..0fd49da 100644 --- a/crates/webzjs-wallet/src/error.rs +++ b/crates/webzjs-wallet/src/error.rs @@ -55,6 +55,10 @@ pub enum Error { // See: zcash_client_backend::sync::Error #[error("Syncing Error: {0}")] Sync(String), + #[error("this wallet instance was closed; reload the wallet")] + InstanceClosed, + #[error("the sync worker stopped after an internal error; reload the page")] + SyncWorkerUnavailable, #[error("Attempted to create a transaction with a memo to an unsupported recipient. Only shielded addresses are supported.")] UnsupportedMemoRecipient, diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index fa5e779..3ad426e 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -22,16 +22,17 @@ use serde::de::DeserializeOwned; use serde::Serialize; use std::fmt::Debug; use std::hash::Hash; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; 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, @@ -52,7 +53,7 @@ use zcash_primitives::transaction::TxId; use zcash_proofs::prover::LocalTxProver; use zcash_protocol::ShieldedProtocol; -use zcash_client_backend::sync::run; +use zcash_client_backend::sync::{run_step, StepOptions}; use zcash_protocol::consensus::BranchId; use zcash_protocol::consensus::Parameters; @@ -60,7 +61,26 @@ use zcash_protocol::value::Zatoshis; use zip32; use zip32::fingerprint::SeedFingerprint; -const BATCH_SIZE: u32 = 10000; // Smaller batches = shorter CPU bursts with I/O pauses between them +/// Blocks fetched and scanned per batch. One `sync_step` scans exactly one batch (after verifying +/// the few lookahead blocks above the max scanned height), so this also bounds how long a step holds +/// the wallet write lock and how much block data is cached at once. Each step also costs a chain tip +/// refresh, a UTXO refresh and a tree state fetch, so batches much smaller than this spend more time +/// on that overhead than on scanning. +const BATCH_SIZE: u32 = 10000; + +/// Source of the per-process part of [`Wallet::instance_id`]. +static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1); + +/// Builds a fresh instance id: a process-local counter plus a random suffix, so ids from +/// different page loads (where the counter restarts) still differ. +fn next_instance_id() -> String { + let n = NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed); + let mut suffix = [0u8; 4]; + match getrandom::getrandom(&mut suffix) { + Ok(()) => format!("{}-{}", n, hex::encode(suffix)), + Err(_) => n.to_string(), + } +} /// constant that signals what's the minimum transparent balance for proposing a /// shielding transaction @@ -96,6 +116,10 @@ pub struct Wallet { pub(crate) target_note_count: usize, /// Note management: the minimum allowed value for split change amounts pub(crate) min_split_output_value: u64, + /// Identifies this wallet instance (and its clones) for the lifetime of the process + instance_id: String, + /// Set by [`Wallet::close`]; shared by every clone of this instance + closed: Arc, } impl Clone for Wallet { @@ -107,13 +131,57 @@ impl Clone for Wallet { min_confirmations: self.min_confirmations, target_note_count: self.target_note_count, min_split_output_value: self.min_split_output_value, + instance_id: self.instance_id.clone(), + closed: self.closed.clone(), + } + } +} + +impl Wallet { + /// The id of this wallet instance. + /// + /// Every call to [`Wallet::new`] produces a new id; clones share the id of the instance they + /// were cloned from. Use it to tell whether a result (for example from a sync step) belongs to + /// the wallet currently in use after the wallet has been reloaded. + pub fn instance_id(&self) -> &str { + &self.instance_id + } + + /// Close this instance and all of its clones. + /// + /// After this, every method that reads or writes wallet state (`sync`, `sync_step`, + /// `db_to_bytes`, account creation, transaction building and sending) fails with + /// [`Error::InstanceClosed`]. A sync step that is already running finishes its current batch + /// and then the next step is refused, so a caller driving `sync_step` in a loop stops promptly. + /// Closing is idempotent and cannot be undone; construct a new wallet instead. + pub fn close(&self) { + self.closed.store(true, Ordering::SeqCst); + } + + /// Whether [`Wallet::close`] has been called on this instance or one of its clones. + pub fn is_closed(&self) -> bool { + self.closed.load(Ordering::SeqCst) + } + + /// Returns [`Error::InstanceClosed`] if the instance has been closed. + fn ensure_open(&self) -> Result<(), Error> { + if self.is_closed() { + Err(Error::InstanceClosed) + } else { + Ok(()) } } } impl Wallet, T> { - // Encodes the MemoryWallet into protobuf bytes + /// Encodes the memory wallet database to bytes. + /// + /// # Errors + /// + /// Returns [`Error::InstanceClosed`] if the instance has been closed, or a serialization + /// error from the database. pub async fn db_to_bytes(&self) -> Result, Error> { + self.ensure_open()?; let mut memory_wallet_bytes = Vec::new(); self.db.read().await.encode(&mut memory_wallet_bytes)?; Ok(memory_wallet_bytes) @@ -167,6 +235,8 @@ where min_confirmations, target_note_count: 4, min_split_output_value: 10000000, + instance_id: next_instance_id(), + closed: Arc::new(AtomicBool::new(false)), }) } @@ -185,6 +255,7 @@ where birthday_height: Option, key_source: Option<&str>, ) -> Result { + self.ensure_open()?; // decode the mnemonic and derive the first account let (usk, seed_fp) = usk_from_seed_str(seed_phrase, account_hd_index, &self.network)?; let ufvk = usk.to_unified_full_viewing_key(); @@ -214,6 +285,7 @@ where birthday_height: Option, key_source: Option<&str>, ) -> Result { + self.ensure_open()?; self.import_account_ufvk(account_name, ufvk, birthday_height, purpose, key_source) .await } @@ -276,21 +348,71 @@ where })?) } + /// Synchronize the wallet with the chain until no scan work remains. + /// + /// This is [`Wallet::sync_step`] in a loop: the wallet write lock is released between + /// batches, so other wallet methods can run between them, and closing the instance stops the + /// loop at the next batch boundary. + /// + /// # Errors + /// + /// Returns [`Error::InstanceClosed`] if the instance is (or becomes) closed, or any error of + /// [`Wallet::sync_step`]. pub async fn sync(&self) -> Result<(), Error> { + let mut first = true; + while self.sync_step(first).await? { + first = false; + } + Ok(()) + } + + /// Perform one bounded step of the sync: refresh the chain tip, then fetch and scan at most + /// one batch of [`BATCH_SIZE`] blocks. + /// + /// The wallet write lock is held only for the duration of the step and released on return, + /// so the caller can persist the wallet (`db_to_bytes`), serve reads, or stop between steps. + /// Each return point leaves the wallet in a state a later step, or a later page load restored + /// from `db_to_bytes`, can resume from. + /// + /// # Arguments + /// + /// * `first` - `true` for the first step of a sync (and after a long pause): the subtree roots + /// are refreshed from the server before scanning. Pass `false` on later steps to save the + /// round trip. + /// + /// # Returns + /// + /// `true` if more work remains and the caller should call `sync_step` again, `false` once the + /// wallet reports nothing left to scan. + /// + /// # Errors + /// + /// Returns [`Error::InstanceClosed`] if the instance has been closed (checked before and + /// after waiting for the write lock), or [`Error::Sync`] for server, cache, scanning and + /// wallet errors. + pub async fn sync_step(&self, first: bool) -> Result { + self.ensure_open()?; let mut client = self.client.clone(); - // TODO: This should be held in the Wallet struct so we can download in parallel + // Scanned blocks are deleted from the cache before a step returns, so a cache per step + // carries nothing over and holds at most one batch of blocks. let db_cache = MemBlockCache::new(); let mut db = self.db.write().await; - run( + // The instance may have been closed while we waited for the lock. + self.ensure_open()?; + let more = run_step( &mut client, - &self.network.clone(), + &self.network, &db_cache, &mut *db, BATCH_SIZE, + StepOptions { + refresh_subtree_roots: first, + max_batches: 1, + }, ) - .await - .map_err(Into::into) + .await?; + Ok(more) } pub async fn get_wallet_summary(&self) -> Result>, Error> { @@ -310,6 +432,7 @@ where to_address: ZcashAddress, value: u64, ) -> Result, Error> { + self.ensure_open()?; let input_selector = GreedyInputSelector::new(); let change_strategy = MultiOutputChangeStrategy::new( @@ -368,6 +491,7 @@ where proposal: Proposal, usk: &UnifiedSpendingKey, ) -> Result, Error> { + self.ensure_open()?; let prover = LocalTxProver::bundled(); let mut db = self.db.write().await; let transactions = create_proposed_transactions::< @@ -394,6 +518,7 @@ where } pub async fn send_authorized_transactions(&self, txids: &NonEmpty) -> Result<(), Error> { + self.ensure_open()?; let mut client = self.client.clone(); for txid in txids.iter() { let (txid, raw_tx) = self @@ -450,6 +575,7 @@ where to_address: ZcashAddress, value: u64, ) -> Result<(), Error> { + self.ensure_open()?; let (usk, _) = usk_from_seed_str(seed_phrase, account_hd_index, &self.network)?; let proposal = self .propose_transfer(from_account_id, to_address, value) @@ -463,6 +589,7 @@ where } pub async fn pczt_shield(&self, account_id: AccountId) -> Result { + self.ensure_open()?; tracing::info!("pczt_shield: Starting for account {:?}", account_id); // Ensure wallet is synced to latest block before creating transaction @@ -559,7 +686,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 +711,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"); @@ -599,6 +726,7 @@ where to_address: ZcashAddress, value: u64, ) -> Result { + self.ensure_open()?; // Ensure wallet is synced before creating transaction to prevent expiry errors let mut client = self.client.clone(); let chain_tip: u32 = client @@ -658,7 +786,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 +808,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) } @@ -693,6 +821,7 @@ where pczt: Pczt, sapling_proof_gen_key: Option, ) -> Result { + self.ensure_open()?; // Add Sapling proof generation key. // TODO: Check to see if there is any sapling in here in the first place let pczt = if let Some(sapling_proof_gen_key) = sapling_proof_gen_key { @@ -726,10 +855,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,23 +867,30 @@ 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(); + // The Ironwood bundle (NU6.3) is a second Orchard-protocol bundle and is proven with the + // same circuit; without its proof, extraction fails on any payment to a shielded + // address, since those are delivered through Ironwood after NU6.3. + let orchard_pk = orchard::circuit::ProvingKey::build(orchard_circuit_version); 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_pk) + .map_err(|e| Error::PcztProve(format!("Failed to create Orchard proof: {e:?}")))? + .create_ironwood_proof(&orchard_pk) + .map_err(|e| Error::PcztProve(format!("Failed to create Ironwood 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) } pub async fn pczt_send(&self, pczt: Pczt) -> Result<(), Error> { + self.ensure_open()?; // Verify the wallet is sufficiently synced before sending // The network only accepts anchors within the last 100 blocks let mut client = self.client.clone(); @@ -784,8 +917,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 +933,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 +945,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); @@ -827,9 +960,10 @@ where } pub fn pczt_combine(&self, pczts: Vec) -> Result { + self.ensure_open()?; 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:?}"))) } } 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 new file mode 100644 index 0000000..80761e0 --- /dev/null +++ b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.test.tsx @@ -0,0 +1,181 @@ +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, + storedWalletUnreadable: null, + isWriter: true, + resumableResync: null, +}; + +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()); + }); +}); + +describe('BlockHeightCard interrupted resync', () => { + const resumableState: WebZjsState = { + ...baseState, + resumableResync: { birthday: 2_600_000, fullyScanned: 2_900_000, chainTip: 3_500_000 }, + }; + + it('offers nothing when no resync was interrupted', () => { + render(); + expect(screen.queryByText('Resume')).not.toBeInTheDocument(); + expect(screen.queryByText('Discard')).not.toBeInTheDocument(); + }); + + it('describes the interrupted resync and resumes it from its checkpoint', async () => { + let finish!: () => void; + const onFullResync = vi.fn( + (_birthday?: number, options?: FullResyncOptions) => + new Promise((resolve) => { + finish = resolve; + options?.onStart?.(); + }), + ); + render(); + + expect(screen.getByText('A resync from block 2600000 stopped at 2900000 of 3500000.')).toBeInTheDocument(); + await act(async () => { fireEvent.click(screen.getByText('Resume')); }); + + expect(onFullResync).toHaveBeenCalledWith( + undefined, + expect.objectContaining({ resume: true, signal: expect.any(AbortSignal) }), + ); + expect(screen.getByText('Resuming…')).toBeDisabled(); + expect(screen.getByText('Discard')).toBeDisabled(); + + await act(async () => { finish(); }); + await waitFor(() => expect(screen.getByText('Resume')).toBeEnabled()); + }); + + it('discards the checkpoint without starting a resync', async () => { + const onFullResync = vi.fn().mockResolvedValue(undefined); + let finish!: () => void; + const onDiscardResync = vi.fn(() => new Promise((resolve) => { finish = resolve; })); + render(); + + await act(async () => { fireEvent.click(screen.getByText('Discard')); }); + + expect(onDiscardResync).toHaveBeenCalledTimes(1); + expect(onFullResync).not.toHaveBeenCalled(); + expect(screen.getByText('Discarding…')).toBeDisabled(); + expect(screen.getByText('Resume')).toBeDisabled(); + + await act(async () => { finish(); }); + await waitFor(() => expect(screen.getByText('Discard')).toBeEnabled()); + }); + + it('keeps the regular Full Resync available alongside the offer to resume', () => { + render(); + expect(screen.getByText('Full Resync')).toBeEnabled(); + }); +}); diff --git a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx index 31cb630..5c4318d 100644 --- a/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx +++ b/packages/web-wallet/src/components/BlockHeightCard/BlockHeightCard.tsx @@ -1,26 +1,101 @@ -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; -}> = ({ state, syncedFrom, onFullResync }) => { + onFullResync?: (customBirthday?: number, options?: FullResyncOptions) => Promise; + /** Drops the checkpoint of an interrupted resync. */ + onDiscardResync?: () => Promise; +}> = ({ state, syncedFrom, onFullResync, onDiscardResync }) => { const [showConfirm, setShowConfirm] = useState(false); const [customBirthday, setCustomBirthday] = useState(''); + const [phase, setPhase] = useState(() => (pendingFullResync() ? 'running' : 'idle')); + const [birthdayError, setBirthdayError] = useState(null); + const [discarding, setDiscarding] = useState(false); + 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 resumable = state.resumableResync; + + const startResync = async (birthday: number | undefined, resume: boolean) => { + 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'), + resume, + }); + } finally { + abortRef.current = null; + setPhase('idle'); + setShowConfirm(false); + setCustomBirthday(''); + } + }; + + 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; } - onFullResync?.(birthday); + 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; + } + setBirthdayError(null); + await startResync(birthday, false); + }; + + const handleResume = () => startResync(undefined, true); + + const handleDiscard = async () => { + setDiscarding(true); + try { + await onDiscardResync?.(); + } finally { + setDiscarding(false); + } + }; + + const cancelResync = () => { + abortRef.current?.abort(); + abortRef.current = null; + setPhase('idle'); + setShowConfirm(false); setCustomBirthday(''); + setBirthdayError(null); }; return ( @@ -82,14 +157,43 @@ export const BlockHeightCard: FC<{ )} - {onFullResync && !state.syncInProgress && ( + {resumable && onFullResync && ( +
+

+ A resync from block {resumable.birthday ?? '?'} stopped at{' '} + {resumable.fullyScanned ?? resumable.birthday ?? '?'} of {resumable.chainTip ?? '?'}. +

+
+ + +
+
+ )} + {onFullResync && (
{!showConfirm ? ( ) : (
@@ -98,30 +202,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/context/WebzjsContext.tsx b/packages/web-wallet/src/context/WebzjsContext.tsx index a3914d0..7e61b43 100644 --- a/packages/web-wallet/src/context/WebzjsContext.tsx +++ b/packages/web-wallet/src/context/WebzjsContext.tsx @@ -6,10 +6,10 @@ import React, { useCallback, useRef, } from 'react'; -import { get } from 'idb-keyval'; import initWebzJSWallet, { initThreadPool, + report_sync_worker_trap, WalletSummary, WebWallet, } from '@zcashcommunitygrants/webzjs-wallet'; @@ -17,6 +17,26 @@ 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, + readStaging, + registerWallet, + stagingIsResumable, + walletOrigin, + writesSettled, +} from '../storage/walletStore'; +import { isWasmTrapEvent } from '../utils/wasmTrap'; + +/** An interrupted full resync whose checkpoint is in storage and can be continued. */ +export interface ResumableResync { + birthday: number | null; + fullyScanned: number | null; + chainTip: number | null; +} export interface WebZjsState { webWallet: WebWallet | null; @@ -28,6 +48,12 @@ 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; + /** Set when a full resync was interrupted (reload, failure) and left a checkpoint behind. */ + resumableResync: ResumableResync | null; } type Action = @@ -38,7 +64,10 @@ 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 } + | { type: 'set-resumable-resync'; payload: ResumableResync | null }; const initialState: WebZjsState = { webWallet: null, @@ -50,6 +79,9 @@ const initialState: WebZjsState = { syncInProgress: false, loading: false, initialized: false, + storedWalletUnreadable: null, + isWriter: false, + resumableResync: null, }; function reducer(state: WebZjsState, action: Action): WebZjsState { @@ -70,6 +102,12 @@ 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 }; + case 'set-resumable-resync': + return { ...state, resumableResync: action.payload }; default: return state; } @@ -79,21 +117,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 +185,59 @@ 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 }); + await applyLoadedWallet(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) { + // A resync that was interrupted by a reload left its checkpoint behind; offer to continue it. + try { + const staged = await readStaging(); + if (staged && stagingIsResumable(staged.meta)) { + console.info( + `Found an interrupted resync checkpoint at ${staged.meta.fullyScanned} of ${staged.meta.chainTip}`, + ); dispatch({ - type: 'set-active-account', - payload: summary.account_balances[0][0], + type: 'set-resumable-resync', + payload: { + birthday: staged.meta.birthday, + fullyScanned: staged.meta.fullyScanned, + chainTip: staged.meta.chainTip, + }, }); } + } catch (err) { + console.warn('Could not check for an interrupted resync:', err); } - 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 +247,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 +263,108 @@ 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); + if (current) { + // The replacement is in state; once any save of the old instance has settled, close + // it so that a sync step still queued for it is refused instead of run. + await writesSettled(); + current.close(); + } + } 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]); + + // A trap in the wasm sync worker (a Rust panic) never rejects the call that caused it; the + // browser reports it on the window instead. Tell the module so that every pending and later + // sync call rejects promptly, and tell the user that a reload is needed. + const trapReportedRef = useRef(false); + useEffect(() => { + const onTrap = () => { + if (trapReportedRef.current) return; + trapReportedRef.current = true; + try { + report_sync_worker_trap(); + } catch (err) { + console.warn('Could not report the sync worker trap to the wallet module:', err); + } + dispatch({ + type: 'set-error', + payload: + 'The wallet engine hit an internal error. Reload the page to continue; your last saved state is intact.', + }); + }; + const onError = (event: ErrorEvent) => { + if (isWasmTrapEvent(event.message, event.error)) onTrap(); + }; + const onRejection = (event: PromiseRejectionEvent) => { + const reason: unknown = event.reason; + const message = reason instanceof Error ? reason.message : reason; + if (isWasmTrapEvent(message, reason)) onTrap(); + }; + window.addEventListener('error', onError); + window.addEventListener('unhandledrejection', onRejection); + return () => { + window.removeEventListener('error', onError); + window.removeEventListener('unhandledrejection', onRejection); + }; + }, []); + useEffect(() => { if (state.error) { toast.error(state.error.toString()); } }, [state.error, dispatch]); - return ( - + {children} diff --git a/packages/web-wallet/src/hooks/fullResyncQueue.ts b/packages/web-wallet/src/hooks/fullResyncQueue.ts new file mode 100644 index 0000000..2357a98 --- /dev/null +++ b/packages/web-wallet/src/hooks/fullResyncQueue.ts @@ -0,0 +1,30 @@ +/** Options for a full resync requested from the UI. */ +export interface FullResyncOptions { + /** + * Aborting before the resync starts drops it from the sync queue. Once started, the resync + * stops at the next step boundary, drops its checkpoint and leaves the current wallet in place. + */ + signal?: AbortSignal; + /** Called when the resync starts, once any sync queued ahead of it has finished. */ + onStart?: () => void; + /** Continue from the checkpoint of an earlier resync instead of starting from the birthday. */ + resume?: boolean; +} + +// 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/useBalance.ts b/packages/web-wallet/src/hooks/useBalance.ts index cb0d60b..a97e24e 100644 --- a/packages/web-wallet/src/hooks/useBalance.ts +++ b/packages/web-wallet/src/hooks/useBalance.ts @@ -3,7 +3,7 @@ import { useWebZjsContext } from '../context/WebzjsContext'; import { useMetaMaskContext } from '../context/MetamaskContext'; type BalanceType = { - /** Confirmed shielded balance (sapling + orchard) */ + /** Confirmed shielded balance (sapling + orchard + ironwood) */ shieldedBalance: number; /** Confirmed unshielded (transparent) balance */ unshieldedBalance: number; @@ -13,6 +13,8 @@ type BalanceType = { spendableBalance: number; saplingBalance: number; orchardBalance: number; + /** Ironwood pool (NU6.3): where payments to shielded addresses land after the upgrade */ + ironwoodBalance: number; /** Change from sent transactions waiting for mining confirmation */ pendingChange: number; /** Received notes waiting for required confirmations to become spendable */ @@ -52,11 +54,13 @@ const useBalance = () => { let livePendingSpendable = 0; let liveSapling = 0; let liveOrchard = 0; + let liveIronwood = 0; if (activeBalanceReport) { liveSapling = activeBalanceReport[1].sapling_balance || 0; liveOrchard = activeBalanceReport[1].orchard_balance || 0; - confirmedShielded = liveSapling + liveOrchard; + liveIronwood = activeBalanceReport[1].ironwood_balance || 0; + confirmedShielded = liveSapling + liveOrchard + liveIronwood; confirmedUnshielded = activeBalanceReport[1].unshielded_balance || 0; livePendingChange = activeBalanceReport[1].pending_change || 0; livePendingSpendable = activeBalanceReport[1].pending_spendable || 0; @@ -80,6 +84,7 @@ const useBalance = () => { spendableBalance: confirmedTotal, saplingBalance: liveSapling, orchardBalance: liveOrchard, + ironwoodBalance: liveIronwood, pendingChange: livePendingChange, pendingSpendable: livePendingSpendable, totalPending: pendingTotal, @@ -101,6 +106,7 @@ const useBalance = () => { spendableBalance: cachedTotal, // cache is from last known state saplingBalance: 0, orchardBalance: 0, + ironwoodBalance: 0, pendingChange: livePendingChange, pendingSpendable: livePendingSpendable, totalPending: pendingTotal, @@ -121,6 +127,7 @@ const useBalance = () => { spendableBalance: confirmedTotal, saplingBalance: liveSapling, orchardBalance: liveOrchard, + ironwoodBalance: liveIronwood, pendingChange: livePendingChange, pendingSpendable: livePendingSpendable, totalPending: pendingTotal, @@ -140,6 +147,7 @@ const useBalance = () => { spendableBalance: 0, saplingBalance: 0, orchardBalance: 0, + ironwoodBalance: 0, pendingChange: 0, pendingSpendable: 0, totalPending: 0, 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..777a9a9 --- /dev/null +++ b/packages/web-wallet/src/hooks/useWebzjsActions.test.ts @@ -0,0 +1,452 @@ +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); + interface Staged { + v: 2; + bytes: Uint8Array; + meta: { epoch: number; birthday: number | null; fullyScanned: number | null; chainTip: number | null }; + } + const stageWallet = vi.fn(async (_w: object, _b: Uint8Array, opts: { fullyScanned: number | null }) => { + calls.push(`stage:${opts.fullyScanned}`); + }); + const promoteStaging = vi.fn(async () => { + calls.push('promote'); + return { epoch: 8, birthday: 2_400_000, fullyScanned: null, savedAt: 0, writerId: 't', reason: 'resync' }; + }); + const readStaging = vi.fn(async (): Promise => null); + const clearStaging = vi.fn(async () => { + calls.push('clear-staging'); + }); + let instances = 0; + const live = { + snapState: null as { webWalletSyncStartBlock: string } | null, + contextState: {} as Record, + /** Results handed out by sync_step, in order; exhausted means "no more work". */ + stepResults: [] as boolean[], + /** Called at the start of each step, with the number of steps attempted before it. */ + onStep: null as ((steps: number) => void | Promise) | null, + stepsTaken: 0, + }; + class FakeWallet { + summary = { fully_scanned_height: 3_522_000, account_balances: [[0, { orchard_balance: 10 }]] }; + name: string; + bytes: Uint8Array | null; + instance_id: string; + closed = false; + constructor(_net?: string, _url?: string, _a?: number, _b?: number, bytes: Uint8Array | null = null, name = 'fresh') { + this.name = name; + this.bytes = bytes; + this.instance_id = `${name}-${++instances}`; + calls.push(`new:${name}:${bytes ? 'from-bytes' : 'empty'}`); + } + 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_step(first: boolean) { + // Counts attempts, including ones onStep fails; onStep sees the number before this one. + const attempted = live.stepsTaken++; + await live.onStep?.(attempted); + calls.push(`step:${this.name}:${first ? 'first' : 'next'}`); + return live.stepResults.length > 0 ? live.stepResults.shift()! : false; + } + async db_to_bytes() { + return new Uint8Array([1, 2, 3]); + } + close() { + this.closed = true; + calls.push(`close:${this.name}`); + } + is_closed() { + return this.closed; + } + } + const dispatch = vi.fn((action: { type: string }) => calls.push(`dispatch:${action.type}`)); + const reloadWallet = vi.fn(async () => calls.push('reload')); + return { + calls, origins, saveWallet, markSuperseded, registerWallet, readWalletBackup, stageWallet, promoteStaging, + readStaging, clearStaging, 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(), + stageWallet: (...args: Parameters) => h.stageWallet(...args), + promoteStaging: (...args: Parameters) => h.promoteStaging(...args), + readStaging: () => h.readStaging(), + clearStaging: () => h.clearStaging(), + }; +}); + +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.stageWallet.mockClear(); + h.promoteStaging.mockClear(); + h.readStaging.mockReset().mockResolvedValue(null); + h.clearStaging.mockClear(); + h.live.snapState = { webWalletSyncStartBlock: '2600000' }; + h.live.stepResults = []; + h.live.onStep = null; + h.live.stepsTaken = 0; + h.live.contextState = { + webWallet: new h.FakeWallet('main', 'url', 1, 1, null, 'old'), + loading: false, + initialized: true, + activeAccount: 0, + summary: undefined, + chainHeight: undefined, + syncInProgress: false, + storedWalletUnreadable: null, + isWriter: true, + resumableResync: null, + }; + }); + + it('full resync steps until the wallet has no more work, checkpointing every 4 steps and at the end', async () => { + const oldWallet = h.live.contextState.webWallet as object; + h.origins.map.set(oldWallet, { epoch: 3, birthday: 2_400_000 }); + h.live.stepResults = [true, true, true, true, true, true, true, true, true, false]; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(3_000_000); + }); + + const steps = h.calls.filter((c) => c.startsWith('step:fresh:')); + expect(steps).toHaveLength(10); + expect(steps[0]).toBe('step:fresh:first'); + expect(steps.slice(1).every((c) => c === 'step:fresh:next')).toBe(true); + expect(h.stageWallet).toHaveBeenCalledTimes(3); + const stageIndexes = h.calls.map((c, i) => (c.startsWith('stage:') ? i : -1)).filter((i) => i >= 0); + const stepIndexes = h.calls.map((c, i) => (c.startsWith('step:fresh') ? i : -1)).filter((i) => i >= 0); + expect(stageIndexes[0]).toBeGreaterThan(stepIndexes[3]); + expect(stageIndexes[0]).toBeLessThan(stepIndexes[4]); + expect(stageIndexes[1]).toBeGreaterThan(stepIndexes[7]); + expect(stageIndexes[1]).toBeLessThan(stepIndexes[8]); + expect(stageIndexes[2]).toBeGreaterThan(stepIndexes[9]); + expect(h.stageWallet).toHaveBeenLastCalledWith( + expect.anything(), + expect.any(Uint8Array), + { birthday: 3_000_000, fullyScanned: 3_522_000, chainTip: 3_522_001 }, + ); + expect(h.calls).toContain('create_account:3000000'); + expect(h.saveWallet).not.toHaveBeenCalled(); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('full resync promotes the checkpoint before making the wallet visible and closes the old instance after', async () => { + const oldWallet = h.live.contextState.webWallet as object; + h.origins.map.set(oldWallet, { epoch: 3, birthday: 2_400_000 }); + h.live.stepResults = [true, false]; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(); + }); + + const promote = h.calls.indexOf('promote'); + const closeOld = h.calls.indexOf('close:old'); + const supersede = h.calls.indexOf('supersede:1'); + const swap = h.calls.indexOf('dispatch:set-web-wallet'); + const lastStage = h.calls.lastIndexOf('stage:3522000'); + expect(promote).toBeGreaterThan(lastStage); + expect(closeOld).toBeGreaterThan(promote); + expect(supersede).toBeGreaterThan(promote); + expect(swap).toBeGreaterThan(closeOld); + expect(swap).toBeGreaterThan(supersede); + expect(h.promoteStaging).toHaveBeenCalledTimes(1); + expect(h.markSuperseded).toHaveBeenCalledWith(oldWallet); + expect(h.calls).not.toContain('close:fresh'); + expect(h.calls).not.toContain('clear-staging'); + expect(h.dispatch).toHaveBeenCalledWith({ type: 'set-resumable-resync', payload: null }); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('full resync aborted between steps drops the checkpoint and keeps the old wallet', async () => { + const oldWallet = h.live.contextState.webWallet as object; + h.origins.map.set(oldWallet, { epoch: 3, birthday: 2_400_000 }); + h.live.stepResults = [true, true, true, true, true, true, true, true, true, false]; + const controller = new AbortController(); + h.live.onStep = (steps) => { + if (steps === 5) controller.abort(); + }; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(undefined, { signal: controller.signal }); + }); + + // Step 6 was already running when the abort came; the loop stops before step 7. + expect(h.calls.filter((c) => c.startsWith('step:fresh:'))).toHaveLength(6); + expect(h.stageWallet).toHaveBeenCalledTimes(1); + expect(h.clearStaging).toHaveBeenCalledTimes(1); + expect(h.promoteStaging).not.toHaveBeenCalled(); + expect(h.calls).toContain('close:fresh'); + expect(h.calls).not.toContain('close:old'); + expect(h.markSuperseded).not.toHaveBeenCalled(); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-web-wallet' })); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('full resync that fails keeps the old wallet and offers the checkpoint for resume', async () => { + const oldWallet = h.live.contextState.webWallet as object; + h.origins.map.set(oldWallet, { epoch: 3, birthday: 2_400_000 }); + h.live.stepResults = [true, true, true, true, true]; + h.live.onStep = (steps) => { + if (steps === 5) throw new Error('this wallet instance was closed; reload the wallet'); + }; + h.readStaging.mockResolvedValue({ + v: 2, + bytes: new Uint8Array([9]), + meta: { epoch: 4, birthday: 2_400_000, fullyScanned: 2_410_000, chainTip: 3_522_001 }, + }); + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(); + }); + + expect(h.calls.filter((c) => c.startsWith('step:fresh:'))).toHaveLength(5); + expect(h.promoteStaging).not.toHaveBeenCalled(); + expect(h.clearStaging).not.toHaveBeenCalled(); + expect(h.calls).toContain('close:fresh'); + expect(h.calls).not.toContain('close:old'); + expect(h.dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + expect(h.dispatch).toHaveBeenCalledWith({ + type: 'set-resumable-resync', + payload: { birthday: 2_400_000, fullyScanned: 2_410_000, chainTip: 3_522_001 }, + }); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-web-wallet' })); + }); + + it('resuming builds the wallet from the checkpoint bytes and does not import the account', async () => { + const oldWallet = h.live.contextState.webWallet as object; + h.origins.map.set(oldWallet, { epoch: 3, birthday: 2_400_000 }); + h.readStaging.mockResolvedValue({ + v: 2, + bytes: new Uint8Array([9, 9]), + meta: { epoch: 4, birthday: 2_600_000, fullyScanned: 2_900_000, chainTip: 3_522_001 }, + }); + h.live.stepResults = [true, false]; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(undefined, { resume: true }); + }); + + expect(h.calls).toContain('new:fresh:from-bytes'); + expect(h.calls).not.toContain('new:fresh:empty'); + expect(h.calls.some((c) => c.startsWith('create_account:'))).toBe(false); + expect(h.calls.filter((c) => c.startsWith('step:fresh:'))).toEqual(['step:fresh:first', 'step:fresh:next']); + expect(h.stageWallet).toHaveBeenCalledWith( + expect.anything(), + expect.any(Uint8Array), + expect.objectContaining({ birthday: 2_600_000 }), + ); + expect(h.calls.indexOf('promote')).toBeLessThan(h.calls.indexOf('dispatch:set-web-wallet')); + expect(h.calls).toContain('close:old'); + expect(h.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('resuming without a checkpoint fails without touching the old wallet', async () => { + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.fullResync(undefined, { resume: true }); + }); + + expect(h.calls.some((c) => c.startsWith('new:fresh:'))).toBe(false); + expect(h.calls).not.toContain('close:old'); + expect(h.dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: 'set-error' })); + }); + + it('discardResync clears the checkpoint and the offer to resume', async () => { + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.discardResync(); + }); + + expect(h.clearStaging).toHaveBeenCalledTimes(1); + expect(h.dispatch).toHaveBeenCalledWith({ type: 'set-resumable-resync', payload: null }); + }); + + 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('periodic rescan steps until the wallet has no more work and then saves', async () => { + h.live.stepResults = [true, true, false]; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.triggerRescan(); + }); + + expect(h.calls.filter((c) => c.startsWith('step:old:'))).toEqual(['step:old:first', 'step:old:next', 'step:old:next']); + expect(h.calls.lastIndexOf('step:old:next')).toBeLessThan(h.calls.indexOf('save:sync:checked')); + expect(h.saveWallet).toHaveBeenCalledTimes(1); + }); + + it('periodic rescan stops without saving once its instance is closed', async () => { + const wallet = h.live.contextState.webWallet as InstanceType; + h.live.stepResults = [true, true, true]; + h.live.onStep = (steps) => { + // Closed while the second step runs: the loop notices before starting a third. + if (steps === 1) wallet.close(); + }; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + await result.current.triggerRescan(); + }); + + expect(h.calls.filter((c) => c.startsWith('step:old:'))).toHaveLength(2); + expect(h.saveWallet).not.toHaveBeenCalled(); + }); + + it('does not retry a sync step once the instance was closed or the worker trapped', async () => { + const { result } = renderHook(() => useWebZjsActions()); + + h.live.onStep = () => { + throw new Error('this wallet instance was closed; reload the wallet'); + }; + await act(async () => { + await result.current.triggerRescan(); + }); + expect(h.live.stepsTaken).toBe(1); + + h.live.onStep = () => { + throw new Error('the sync worker stopped after an internal error; reload the page'); + }; + await act(async () => { + await result.current.triggerRescan(); + }); + expect(h.live.stepsTaken).toBe(2); + expect(h.saveWallet).not.toHaveBeenCalled(); + }); + + it('retries a sync step after an ordinary failure', async () => { + vi.useFakeTimers(); + try { + let failures = 0; + h.live.onStep = () => { + if (failures++ === 0) throw new Error('grpc: connection reset'); + }; + const { result } = renderHook(() => useWebZjsActions()); + + await act(async () => { + const run = result.current.triggerRescan(); + await vi.advanceTimersByTimeAsync(3000); + await run; + }); + + expect(h.live.stepsTaken).toBe(2); + expect(h.saveWallet).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + 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 04aa31d..9eb251a 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -8,25 +8,106 @@ 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'; +import { + SaveReason, + StaleWalletError, + clearStaging, + markSuperseded, + promoteStaging, + readStaging, + readWalletBackup, + registerWallet, + saveWallet, + stageWallet, + stagingIsResumable, + 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 +// 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; } +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) => Promise; - recoverWallet: () => Promise; + fullResync: (customBirthday?: number, options?: FullResyncOptions) => Promise; + /** Drops the checkpoint of an interrupted resync. The current wallet is not touched. */ + discardResync: () => Promise; + recoverWallet: (options?: RecoverOptions) => Promise; +} + +// A full resync checkpoints its progress to storage every this many sync steps (a step is one +// batch of about 2500 blocks), so a reload loses at most that much work. +const STAGE_EVERY_STEPS = 4; +// Backoff after a failed step: this doubles per consecutive failure, and the resync gives up +// after MAX_CONSECUTIVE_FAILURES in a row. There is no limit on the number of steps. +const SYNC_STEP_RETRY_DELAY = 2000; +const MAX_CONSECUTIVE_FAILURES = 4; + +/** + * Errors after which no retry can succeed: the instance was closed (it has been replaced) or + * the sync worker trapped (only a page reload brings it back). + */ +function isUnrecoverableWalletError(err: unknown): boolean { + const message = err instanceof Error ? err.message : String(err); + return message.includes('instance was closed') || message.includes('sync worker stopped'); +} + +/** 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( @@ -37,7 +118,7 @@ async function withRetry( try { return await fn(); } catch (err) { - if (attempt === retries) throw err; + if (attempt === retries || isUnrecoverableWalletError(err)) throw err; const delay = baseDelay * Math.pow(2, attempt - 1); console.warn(`${label} failed (attempt ${attempt}/${retries}), retrying in ${delay}ms:`, err); await new Promise(r => setTimeout(r, delay)); @@ -47,17 +128,42 @@ 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(); // Refs for values read inside triggerRescan but that shouldn't cause it to be recreated const fullySyncedRef = useRef(state.summary?.fully_scanned_height); const chainHeightRef = useRef(state.chainHeight); + const currentWalletRef = useRef(state.webWallet); fullySyncedRef.current = state.summary?.fully_scanned_height; chainHeightRef.current = state.chainHeight; + currentWalletRef.current = state.webWallet; + + /** + * Drives `sync_step` until the wallet reports no more work. The loop is tagged with the + * instance it started on and stops, returning false, as soon as that instance is closed or + * no longer the one in state, so a step queued for a replaced wallet never runs on it. + */ + const syncToTip = useCallback(async (webWallet: WebWallet): Promise => { + const id = webWallet.instance_id; + let first = true; + for (;;) { + if (webWallet.is_closed() || currentWalletRef.current !== webWallet) { + console.info(`Sync loop for wallet ${id} stopped: the instance was replaced`); + return false; + } + const more = await withRetry(() => webWallet.sync_step(first), { + label: `sync_step (${id})`, + retries: 2, + baseDelay: 3000, + }); + first = false; + if (!more) return true; + } + }, []); /** * Read-merge-write helper for snap state. Always reads existing state first, @@ -138,13 +244,17 @@ export function useWebZjsActions(): WebzjsActions { const cacheBalanceInSnap = useCallback(async (balanceReport: { sapling_balance?: number; orchard_balance?: number; + ironwood_balance?: number; unshielded_balance?: number; pending_change?: number; pending_spendable?: number; } | null, force = false) => { if (!balanceReport) return; - const confirmed = (balanceReport.sapling_balance ?? 0) + (balanceReport.orchard_balance ?? 0); + const confirmed = + (balanceReport.sapling_balance ?? 0) + + (balanceReport.orchard_balance ?? 0) + + (balanceReport.ironwood_balance ?? 0); const unshielded = balanceReport.unshielded_balance ?? 0; const pending = (balanceReport.pending_change ?? 0) + (balanceReport.pending_spendable ?? 0); const total = confirmed + unshielded + pending; @@ -206,24 +316,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 { @@ -243,40 +379,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', @@ -288,9 +416,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}`; @@ -302,14 +437,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; @@ -330,212 +470,280 @@ 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 () => { + 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; + 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)) { + if (!(await syncToTip(webWallet))) return; 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 { + if (!(await syncToTip(webWallet))) return; + 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, + repairSnapBirthday, + syncToTip, ]); /** * Performs a full wallet resync by: - * 1. Creating a fresh wallet in a local variable (old wallet stays in state) - * 2. Re-importing the account with the original birthday - * 3. Syncing from birthday with retry - * 4. Only on success: swapping the new wallet into state + IndexedDB + * 1. Creating a fresh wallet in a local variable (old wallet stays in state), or, when + * resuming, rebuilding it from the checkpoint of an earlier resync + * 2. Re-importing the account with the original birthday (not when resuming) + * 3. Syncing from there one step at a time, checkpointing to `wallet.staging` every few + * steps so that a reload can resume instead of starting over + * 4. Only on success: promoting the checkpoint to the stored wallet in one transaction, + * closing the old instance, and swapping the new one into state * - * 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. + * A failure before promotion leaves the old wallet untouched in state and storage and the + * checkpoint in place for Resume. Aborting between steps drops the checkpoint. */ - 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, and between steps once it runs. + const run = runExclusiveSync(dispatch, async () => { + if (options?.signal?.aborted) { + console.info('Full resync: cancelled before it started'); + return; } - - // 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; + options?.onStart?.(); + const oldWallet = state.webWallet; + let freshWallet: WebWallet | null = null; + try { + let birthdayBlock: number | undefined; + let accountId: number; + + if (options?.resume) { + // 1b. Rebuild the wallet from the checkpoint. The account is already in it. + const staged = await readStaging(); + if (!staged) { + throw new Error('There is no interrupted resync to resume'); } - - // Not done yet — pause before next round - if (round < MAX_SYNC_ROUNDS) { - await new Promise(r => setTimeout(r, SYNC_ROUND_DELAY)); + birthdayBlock = staged.meta.birthday ?? undefined; + console.info( + `Full resync: resuming from the checkpoint at ${staged.meta.fullyScanned} (birthday ${birthdayBlock})`, + ); + try { + freshWallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, staged.bytes); + } catch (decodeErr) { + await clearStaging(); + dispatch({ type: 'set-resumable-resync', payload: null }); + throw new Error(`The resync checkpoint could not be read and was discarded: ${String(decodeErr)}`); } - } 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 + const stagedSummary = await freshWallet.get_wallet_summary(); + if (!stagedSummary?.account_balances?.length) { + throw new Error('The resync checkpoint holds no account'); } - - // 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)); + accountId = stagedSummary.account_balances[0][0]; + } else { + // 1. Get the stored birthday from snap state + const snapState = (await invokeSnap({ + method: 'getSnapStete', + })) as SnapState | null; + + // 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 7), so a failed resync leaves the old + // wallet and its stored birthday consistent. + 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 seedFingerprint = seedFingerprintFromSnap(await invokeSnap({ + method: 'getSeedFingerprint', + })); + + // 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)'); + freshWallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); + const created = freshWallet; + + // 4. Re-import the account with retry (makes GetTreeState gRPC call) + console.info(`Full resync: Re-importing account with birthday ${birthdayBlock}`); + accountId = await withRetry( + () => created.create_account_ufvk('account-0', viewingKey, seedFingerprint, 0, birthdayBlock), + { label: 'create_account_ufvk', retries: 3, baseDelay: 2000 }, + ); + } + const wallet = freshWallet; + // Never persisted as `wallet` yet; the birthday is the fallback for the checkpoint metadata. + registerWallet(wallet, { epoch: null, birthday: birthdayBlock ?? null }); + + // 5. Sync one bounded step at a time. Every STAGE_EVERY_STEPS steps, and once the + // wallet reports no more work, the progress so far is checkpointed to storage. + // `first` refreshes the subtree roots: on the first step, and again after a pause. + console.info('Full resync: Starting sync'); + let first = true; + let steps = 0; + let consecutiveFailures = 0; + for (;;) { + if (options?.signal?.aborted) { + console.info(`Full resync: cancelled after ${steps} steps; dropping the checkpoint`); + await clearStaging(); + dispatch({ type: 'set-resumable-resync', payload: null }); + wallet.close(); + return; + } + let more: boolean; + try { + more = await wallet.sync_step(first); + first = false; + consecutiveFailures = 0; + } catch (syncErr) { + consecutiveFailures++; + console.debug(`Full resync: step ${steps + 1} failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}):`, syncErr); + if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES || isUnrecoverableWalletError(syncErr)) { + throw syncErr; + } + const backoff = SYNC_STEP_RETRY_DELAY * Math.pow(2, consecutiveFailures - 1); + console.debug(`Full resync: backing off ${backoff}ms before retrying`); + await new Promise(r => setTimeout(r, backoff)); + first = true; + continue; + } + steps++; + + if (steps % STAGE_EVERY_STEPS === 0 || !more) { + const bytes = await wallet.db_to_bytes(); + const summary = await wallet.get_wallet_summary(); + const chainTip = Number(await wallet.get_latest_block()); + const scannedHeight = summary?.fully_scanned_height ?? null; + await stageWallet(wallet, bytes, { + birthday: birthdayBlock ?? null, + fullyScanned: scannedHeight, + chainTip: Number.isFinite(chainTip) ? chainTip : null, + }); + console.info( + `Full resync: checkpointed after ${steps} steps at ${scannedHeight} / ${chainTip} (${bytes.length} bytes)`, + ); + } + if (!more) break; } - } - - // 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 }); + // 6. SUCCESS: promote the checkpoint to the stored wallet in one transaction, with its + // birthday, superseding whatever is stored. Only then make it visible. A failure + // before this point leaves storage untouched (the checkpoint can be resumed); after + // it, storage already holds the resynced wallet, so nothing that follows can lose it. + const summary = await wallet.get_wallet_summary(); + const chainHeight = await wallet.get_latest_block(); + const promoted = await promoteStaging(wallet); + console.info(`Full resync: promoted as epoch ${promoted.epoch}, swapping wallet into state`); + + // 7. Retire the old instance (no step queued for it can write into it any more) and + // swap the fresh one in. + if (oldWallet) { + oldWallet.close(); + markSuperseded(oldWallet); + } + dispatch({ type: 'set-resumable-resync', payload: null }); + dispatch({ type: 'set-web-wallet', payload: wallet }); + dispatch({ type: 'set-active-account', payload: accountId }); + if (summary) { + dispatch({ type: 'set-summary', payload: summary }); + } + if (chainHeight) { + dispatch({ type: 'set-chain-height', payload: chainHeight }); + } - // 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); + // 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); } - } - const chainHeight = await freshWallet.get_latest_block(); - if (chainHeight) { - dispatch({ type: 'set-chain-height', payload: chainHeight }); + console.info('Full resync: Complete'); + } catch (err: unknown) { + // FAILURE: old wallet remains in state + IndexedDB, user sees last known balances. + // The checkpoint, if one was taken, is offered for Resume. + console.error('Full resync failed (old wallet preserved):', err); + dispatch({ type: 'set-error', payload: String(err) }); + try { + freshWallet?.close(); + } catch (closeErr) { + console.warn('Full resync: could not close the abandoned instance:', closeErr); + } + try { + const staged = await readStaging(); + dispatch({ + type: 'set-resumable-resync', + payload: staged && stagingIsResumable(staged.meta) + ? { birthday: staged.meta.birthday, fullyScanned: staged.meta.fullyScanned, chainTip: staged.meta.chainTip } + : null, + }); + } catch (readErr) { + console.warn('Full resync: could not read the checkpoint:', readErr); + } } + }); + await trackFullResync(run); + }, [installedSnap, state.webWallet, invokeSnap, dispatch, updateSnapState, cacheBalanceInSnap]); - // 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]); + const discardResync = useCallback(async () => { + await clearStaging(); + dispatch({ type: 'set-resumable-resync', payload: null }); + }, [dispatch]); /** * Recovers the wallet from snap credentials when IndexedDB data is empty or incompatible. @@ -544,34 +752,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(); @@ -591,13 +806,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, @@ -606,6 +837,7 @@ export function useWebZjsActions(): WebzjsActions { syncStateWithWallet, connectWebZjsSnap, fullResync, + discardResync, recoverWallet, }; } diff --git a/packages/web-wallet/src/pages/AccountSummary.tsx b/packages/web-wallet/src/pages/AccountSummary.tsx index e83b49c..1f798b7 100644 --- a/packages/web-wallet/src/pages/AccountSummary.tsx +++ b/packages/web-wallet/src/pages/AccountSummary.tsx @@ -19,7 +19,7 @@ function AccountSummary() { const { pendingTxs } = usePendingTransactions(); const { state } = useWebZjsContext(); const { snapState } = useMetaMaskContext(); - const { fullResync } = useWebZjsActions(); + const { fullResync, discardResync } = useWebZjsActions(); const BalanceCards: BalanceCard[] = [ { @@ -95,6 +95,7 @@ function AccountSummary() { state={state} syncedFrom={snapState?.webWalletSyncStartBlock} onFullResync={fullResync} + onDiscardResync={discardResync} /> ); 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..0f072a5 --- /dev/null +++ b/packages/web-wallet/src/storage/walletStore.test.ts @@ -0,0 +1,392 @@ +// @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); + }); +}); + +describe('a record that cannot be stored', () => { + // Structured cloning rejects functions with a DataCloneError, the same error class the browser + // raises when the renderer is out of memory. `put` throws it synchronously inside the request + // callback, where an uncaught exception would leave the write promise pending forever. + const uncloneable = { toJSON() {} } as unknown as Uint8Array; + + it('saveWallet rejects and leaves the stored wallet as it was', async () => { + const store = await freshStore(); + const wallet = {}; + store.registerWallet(wallet, { epoch: null, birthday: null }); + await store.saveWallet(wallet, bytesOf('v1'), { reason: 'sync' }); + + await expect(store.saveWallet(wallet, uncloneable, { reason: 'sync' })).rejects.toMatchObject({ + name: 'DataCloneError', + }); + + const record = (await stored('wallet')) as { bytes: Uint8Array; meta: { epoch: number } }; + expect(new TextDecoder().decode(record.bytes)).toBe('v1'); + expect(record.meta.epoch).toBe(1); + expect(store.walletOrigin(wallet)).toMatchObject({ epoch: 1 }); + // The instance can still save afterwards. + await store.saveWallet(wallet, bytesOf('v2'), { reason: 'sync' }); + expect(await store.peekStoredEpoch()).toBe(2); + }); + + it('stageWallet rejects and leaves the previous checkpoint in place', async () => { + const store = await freshStore(); + const fresh = {}; + await store.stageWallet(fresh, bytesOf('partial'), { birthday: 1, fullyScanned: 2, chainTip: 3 }); + + await expect( + store.stageWallet(fresh, uncloneable, { birthday: 1, fullyScanned: 4, chainTip: 5 }), + ).rejects.toMatchObject({ name: 'DataCloneError' }); + + const staged = (await store.readStaging())!; + expect(new TextDecoder().decode(staged.bytes)).toBe('partial'); + expect(staged.meta.fullyScanned).toBe(2); + }); +}); + +describe('resync checkpoints', () => { + const stagedMeta = { birthday: 2_600_000, fullyScanned: 2_700_000, chainTip: 3_500_000 }; + + it('readStaging returns null when nothing is staged', async () => { + const store = await freshStore(); + expect(await store.readStaging()).toBeNull(); + }); + + it('stages a checkpoint without touching the stored wallet', async () => { + const store = await freshStore(); + const current = {}; + store.registerWallet(current, { epoch: null, birthday: null }); + await store.saveWallet(current, bytesOf('v1'), { reason: 'sync' }); + const fresh = {}; + store.registerWallet(fresh, { epoch: null, birthday: 2_600_000 }); + + const meta = await store.stageWallet(fresh, bytesOf('partial'), stagedMeta); + + expect(meta).toMatchObject({ epoch: 2, reason: 'resync', ...stagedMeta }); + const staged = (await store.readStaging())!; + expect(new TextDecoder().decode(staged.bytes)).toBe('partial'); + expect(staged.meta).toEqual(meta); + expect(store.stagingIsResumable(staged.meta)).toBe(true); + expect(await store.peekStoredEpoch()).toBe(1); + const record = (await stored('wallet')) as { bytes: Uint8Array }; + expect(new TextDecoder().decode(record.bytes)).toBe('v1'); + expect(store.walletOrigin(fresh)).toEqual({ epoch: null, birthday: 2_600_000 }); + }); + + it('a checkpoint at the chain tip is not resumable', async () => { + const store = await freshStore(); + const fresh = {}; + await store.stageWallet(fresh, bytesOf('done'), { ...stagedMeta, fullyScanned: 3_499_998 }); + expect(store.stagingIsResumable((await store.readStaging())!.meta)).toBe(false); + }); + + it('promotes the checkpoint at the next epoch, keeps the previous wallet and clears staging', async () => { + const store = await freshStore(); + const current = {}; + store.registerWallet(current, { epoch: null, birthday: 2_400_000 }); + await store.saveWallet(current, bytesOf('v1'), { reason: 'sync' }); + await store.saveWallet(current, bytesOf('v2'), { reason: 'sync' }); + const fresh = {}; + store.registerWallet(fresh, { epoch: null, birthday: 2_600_000 }); + await store.stageWallet(fresh, bytesOf('resynced'), { ...stagedMeta, fullyScanned: 3_500_000 }); + + const meta = await store.promoteStaging(fresh); + + expect(meta).toMatchObject({ epoch: 3, birthday: 2_600_000, fullyScanned: 3_500_000, reason: 'resync' }); + const record = (await stored('wallet')) as { bytes: Uint8Array; meta: unknown }; + expect(new TextDecoder().decode(record.bytes)).toBe('resynced'); + expect(record.meta).toEqual(meta); + expect(await stored('wallet.meta')).toEqual(meta); + expect(await stored('birthdayBlock')).toBe('2600000'); + const previous = (await stored('wallet.backup.previous')) as { bytes: Uint8Array; meta: { epoch: number } }; + expect(new TextDecoder().decode(previous.bytes)).toBe('v2'); + expect(previous.meta.epoch).toBe(2); + expect(await store.readStaging()).toBeNull(); + expect(store.walletOrigin(fresh)).toEqual({ epoch: 3, birthday: 2_600_000 }); + await expect(store.saveWallet(current, bytesOf('late'), { reason: 'sync' })).rejects.toBeInstanceOf( + store.StaleWalletError, + ); + await store.saveWallet(fresh, bytesOf('v4'), { reason: 'sync' }); + expect(await store.peekStoredEpoch()).toBe(4); + }); + + it('promotes over an empty store at epoch 1', async () => { + const store = await freshStore(); + const fresh = {}; + await store.stageWallet(fresh, bytesOf('first'), stagedMeta); + const meta = await store.promoteStaging(fresh); + expect(meta.epoch).toBe(1); + expect(await stored('wallet.backup.previous')).toBeUndefined(); + }); + + it('rejects promotion when nothing is staged and changes nothing', async () => { + const store = await freshStore(); + const current = {}; + store.registerWallet(current, { epoch: null, birthday: null }); + await store.saveWallet(current, bytesOf('v1'), { reason: 'sync' }); + + await expect(store.promoteStaging({})).rejects.toThrow(/no checkpointed resync/); + expect(await store.peekStoredEpoch()).toBe(1); + }); + + it('leaves the wallet untouched and the checkpoint in place when the promotion fails midway', async () => { + const store = await freshStore(); + const current = {}; + store.registerWallet(current, { epoch: null, birthday: null }); + await store.saveWallet(current, bytesOf('v1'), { reason: 'sync' }); + const fresh = {}; + await store.stageWallet(fresh, bytesOf('partial'), stagedMeta); + + // The wallet record is already written inside the transaction when the metadata write + // throws; the whole transaction must roll back. + const put = IDBObjectStore.prototype.put; + const spy = vi.spyOn(IDBObjectStore.prototype, 'put').mockImplementation(function ( + this: IDBObjectStore, + value: unknown, + key?: IDBValidKey, + ) { + if (key === 'wallet.meta') throw new Error('disk full'); + return put.call(this, value, key); + }); + try { + await expect(store.promoteStaging(fresh)).rejects.toThrow('disk full'); + } finally { + spy.mockRestore(); + } + + const record = (await stored('wallet')) as { bytes: Uint8Array; meta: { epoch: number } }; + expect(new TextDecoder().decode(record.bytes)).toBe('v1'); + expect(record.meta.epoch).toBe(1); + expect(await stored('wallet.backup.previous')).toBeUndefined(); + const staged = (await store.readStaging())!; + expect(new TextDecoder().decode(staged.bytes)).toBe('partial'); + expect(store.walletOrigin(fresh)).toBeUndefined(); + }); + + it('clearStaging removes the checkpoint only', async () => { + const store = await freshStore(); + const current = {}; + store.registerWallet(current, { epoch: null, birthday: null }); + await store.saveWallet(current, bytesOf('v1'), { reason: 'sync' }); + await store.stageWallet({}, bytesOf('partial'), stagedMeta); + + await store.clearStaging(); + + expect(await store.readStaging()).toBeNull(); + expect(await store.peekStoredEpoch()).toBe(1); + await expect(store.clearStaging()).resolves.toBeUndefined(); + }); +}); diff --git a/packages/web-wallet/src/storage/walletStore.ts b/packages/web-wallet/src/storage/walletStore.ts new file mode 100644 index 0000000..e9b9ba7 --- /dev/null +++ b/packages/web-wallet/src/storage/walletStore.ts @@ -0,0 +1,490 @@ +/** + * 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 + * - `wallet.staging` StagedWalletRecord: the checkpoint of a full resync in progress. It never + * replaces `wallet` on its own; `promoteStaging` moves it there atomically + * - `wallet.backup.previous` the `wallet` value a promotion replaced (one is kept) + */ +import { createStore, del, 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; +} + +/** Metadata of a resync checkpoint; `epoch` is provisional until the checkpoint is promoted. */ +export interface StagedWalletMeta extends WalletMeta { + /** Chain tip the resync was heading for when the checkpoint was taken. */ + chainTip: number | null; +} + +export interface StagedWalletRecord { + v: 2; + bytes: Uint8Array; + meta: StagedWalletMeta; +} + +export interface StageOptions { + birthday: number | null; + fullyScanned: number | null; + chainTip: number | null; +} + +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'; +export const STAGING_KEY = 'wallet.staging'; +export const PREVIOUS_BACKUP_KEY = 'wallet.backup.previous'; +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' + ); +} + +function isStagedRecord(value: unknown): value is StagedWalletRecord { + return isRecord(value) && 'chainTip' in value.meta; +} + +/** 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; +} + +/** Rejects with `error` after aborting `transaction`, so nothing queued on it is committed. */ +function failWith(transaction: IDBTransaction, reject: (error: unknown) => void): (error: unknown) => void { + return (error: unknown) => { + try { + transaction.abort(); + } catch { + // Already aborted or finished. + } + reject(error); + }; +} + +// 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; +} + +/** Resolves once every save or promotion queued so far has finished, whether or not it succeeded. */ +export function writesSettled(): Promise { + return writes.then( + () => undefined, + () => undefined, + ); +} + +/** + * 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 fail = failWith(objectStore.transaction, reject); + const request = objectStore.get(WALLET_KEY); + request.onerror = () => fail(request.error); + request.onsuccess = () => { + try { + const storedEpoch = epochOf(request.result); + if (!opts.force && storedEpoch !== expected) { + fail(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)); + } catch (error) { + // `put` throws synchronously when the record cannot be cloned (for example + // `DataCloneError` when the renderer is out of memory). Reject instead of letting + // the exception escape the event handler, which would leave this promise pending. + fail(error); + } + }; + }), + ); + + 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; +} + +/** + * Writes a checkpoint of a resync in progress under `wallet.staging`. The checkpoint never + * replaces the stored wallet by itself, so there is no epoch check; its epoch is the value + * the wallet would get if it were promoted right now. Staging again overwrites the previous + * checkpoint. + */ +export function stageWallet(wallet: object, bytes: Uint8Array, opts: StageOptions): Promise { + return serialize(async () => { + const origin = origins.get(wallet); + const birthday = readBlobBirthday(bytes) ?? opts.birthday ?? origin?.birthday ?? null; + return store( + 'readwrite', + (objectStore) => + new Promise((resolve, reject) => { + const fail = failWith(objectStore.transaction, reject); + const request = objectStore.get(WALLET_KEY); + request.onerror = () => fail(request.error); + request.onsuccess = () => { + try { + const meta: StagedWalletMeta = { + epoch: (epochOf(request.result) ?? 0) + 1, + birthday, + fullyScanned: opts.fullyScanned, + chainTip: opts.chainTip, + savedAt: Date.now(), + writerId: TAB_ID, + reason: 'resync', + }; + const record: StagedWalletRecord = { v: 2, bytes, meta }; + objectStore.put(record, STAGING_KEY); + resolve(promisifyRequest(objectStore.transaction).then(() => meta)); + } catch (error) { + // See saveWallet: a throwing `put` must reject, not hang the checkpoint. + fail(error); + } + }; + }), + ); + }); +} + +/** The checkpoint of a resync in progress, or null when there is none. */ +export async function readStaging(): Promise { + const staged = await get(STAGING_KEY, store); + return isStagedRecord(staged) ? staged : null; +} + +/** Drops the checkpoint. The stored wallet is not touched. */ +export function clearStaging(): Promise { + return serialize(() => del(STAGING_KEY, store)); +} + +/** True while the checkpoint has not reached the chain tip it was heading for. */ +export function stagingIsResumable(meta: StagedWalletMeta): boolean { + if (meta.chainTip === null) return true; + return (meta.fullyScanned ?? 0) < meta.chainTip - 2; +} + +/** + * Makes the checkpoint the stored wallet, in one transaction: the previous `wallet` value is + * kept under `wallet.backup.previous`, the checkpoint becomes `wallet` at the next epoch, the + * metadata and birthday mirror follow, and the checkpoint is deleted. Nothing is changed if + * any part fails, or if there is no checkpoint (the returned promise rejects). On success the + * instance is registered at the new epoch and other tabs are told. + */ +export function promoteStaging(wallet: object): Promise { + return serialize(async () => { + const meta = await store( + 'readwrite', + (objectStore) => + new Promise((resolve, reject) => { + const transaction = objectStore.transaction; + const fail = failWith(transaction, reject); + const stagedRequest = objectStore.get(STAGING_KEY); + stagedRequest.onerror = () => fail(stagedRequest.error); + stagedRequest.onsuccess = () => { + const staged = stagedRequest.result; + if (!isStagedRecord(staged)) { + fail(new Error('There is no checkpointed resync to promote')); + return; + } + const currentRequest = objectStore.get(WALLET_KEY); + currentRequest.onerror = () => fail(currentRequest.error); + currentRequest.onsuccess = () => { + try { + const current = currentRequest.result; + const next: WalletMeta = { + epoch: (epochOf(current) ?? 0) + 1, + birthday: staged.meta.birthday, + fullyScanned: staged.meta.fullyScanned, + savedAt: Date.now(), + writerId: TAB_ID, + reason: 'resync', + }; + if (current !== undefined && current !== null) { + objectStore.put(current, PREVIOUS_BACKUP_KEY); + } + const record: WalletRecord = { v: 2, bytes: staged.bytes, meta: next }; + objectStore.put(record, WALLET_KEY); + objectStore.put(next, META_KEY); + if (next.birthday !== null) { + objectStore.put(String(next.birthday), BIRTHDAY_KEY); + } + objectStore.delete(STAGING_KEY); + resolve(promisifyRequest(transaction).then(() => next)); + } catch (error) { + fail(error); + } + }; + }; + }), + ); + + origins.set(wallet, { epoch: meta.epoch, birthday: meta.birthday }); + broadcast({ type: 'saved', epoch: meta.epoch, writerId: TAB_ID }); + return meta; + }); +} + +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/packages/web-wallet/src/utils/wasmTrap.test.ts b/packages/web-wallet/src/utils/wasmTrap.test.ts new file mode 100644 index 0000000..441f8de --- /dev/null +++ b/packages/web-wallet/src/utils/wasmTrap.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest'; +import { isWasmTrapEvent } from './wasmTrap'; + +describe('isWasmTrapEvent', () => { + it('matches the message of an uncaught unreachable trap', () => { + expect(isWasmTrapEvent('Uncaught RuntimeError: unreachable', undefined)).toBe(true); + expect(isWasmTrapEvent('unreachable executed', null)).toBe(true); + }); + + it('matches a RuntimeError carried in the error object', () => { + class RuntimeError extends Error { + name = 'RuntimeError'; + } + expect(isWasmTrapEvent('Script error.', new RuntimeError('unreachable'))).toBe(true); + expect(isWasmTrapEvent(undefined, new RuntimeError('memory access out of bounds'))).toBe(true); + }); + + it('ignores ordinary errors and empty events', () => { + expect(isWasmTrapEvent('Network request failed', new TypeError('Failed to fetch'))).toBe(false); + expect(isWasmTrapEvent(undefined, undefined)).toBe(false); + expect(isWasmTrapEvent('', null)).toBe(false); + expect(isWasmTrapEvent(undefined, 'the sync worker stopped after an internal error')).toBe(false); + }); +}); diff --git a/packages/web-wallet/src/utils/wasmTrap.ts b/packages/web-wallet/src/utils/wasmTrap.ts new file mode 100644 index 0000000..98160a3 --- /dev/null +++ b/packages/web-wallet/src/utils/wasmTrap.ts @@ -0,0 +1,14 @@ +/** + * Recognizes the browser's report of a trap inside the wasm sync worker. + * + * A Rust panic compiled to wasm becomes `RuntimeError: unreachable`. It happens on the worker + * thread, so it never rejects the promise of the call that caused it; the browser delivers it + * to the window's `error` event (or, through a promise inside the worker shim, to + * `unhandledrejection`). The page has to notice it there and tell the wasm module, or every + * later sync call would hang forever waiting for a worker that stopped taking requests. + */ +export function isWasmTrapEvent(message: unknown, error: unknown): boolean { + if (/unreachable/.test(String(message ?? ''))) return true; + if (error === undefined || error === null) return false; + return /RuntimeError/.test(String(error)); +} 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"