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..60a2b54 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()) { /* reload */ } + /// ``` + 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/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/useWebzjsActions.ts b/packages/web-wallet/src/hooks/useWebzjsActions.ts index 04aa31d..f6ed40d 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -138,13 +138,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;