From 7b4a1947cca0fc4b3688024ee6cc069fa1e69233 Mon Sep 17 00:00:00 2001 From: sqhell Date: Mon, 19 Oct 2026 10:36:55 -0600 Subject: [PATCH 1/3] chore: make rustfmt and clippy pass on main Rust-Checks has failed on main since the NU6.3 toolchain bump: rustfmt differs in nine files, and clippy on nightly-2025-06-15 rejects ten uninlined format arguments in webzjs-keys and one map iteration in webzjs-requests under -D warnings. Apply rustfmt and clippy's own suggestions; no behaviour changes. --- crates/webzjs-keys/src/demo_pczt.rs | 34 +++- crates/webzjs-keys/src/lib.rs | 8 +- crates/webzjs-keys/src/pczt_describe.rs | 21 ++- crates/webzjs-keys/src/pczt_sign.rs | 152 ++++++++---------- crates/webzjs-keys/tests/gen_fixtures.rs | 50 ++++-- crates/webzjs-keys/tests/security_finding1.rs | 10 +- crates/webzjs-keys/tests/spoof_pczt.rs | 63 ++++++-- crates/webzjs-requests/src/requests.rs | 4 +- crates/webzjs-wallet/src/wallet.rs | 55 ++++--- 9 files changed, 242 insertions(+), 155 deletions(-) diff --git a/crates/webzjs-keys/src/demo_pczt.rs b/crates/webzjs-keys/src/demo_pczt.rs index d5446d1..3dc3ce4 100644 --- a/crates/webzjs-keys/src/demo_pczt.rs +++ b/crates/webzjs-keys/src/demo_pczt.rs @@ -34,6 +34,7 @@ use orchard::value::NoteValue as OrchardNoteValue; use orchard::Address as OrchardAddress; use pczt::roles::creator::Creator; +use webzjs_common::Network; use zcash_keys::address::UnifiedAddress; use zcash_keys::encoding::AddressCodec; use zcash_keys::keys::{UnifiedFullViewingKey as InnerUfvk, UnifiedSpendingKey}; @@ -41,11 +42,10 @@ use zcash_primitives::transaction::builder::PcztParts; use zcash_primitives::transaction::TxVersion; use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkConstants, Parameters}; use zcash_protocol::value::Zatoshis; -use webzjs_common::Network; use zcash_transparent::address::TransparentAddress; -use zcash_transparent::bundle::{OutPoint, TxOut}; use zcash_transparent::builder::TransparentBuilder; +use zcash_transparent::bundle::{OutPoint, TxOut}; use zcash_transparent::keys::{NonHardenedChildIndex, TransparentKeyScope}; use zcash_transparent::pczt::Bip32Derivation; @@ -155,7 +155,10 @@ fn build_transparent( .map_err(|e| Error::PcztDescribe(format!("derive t-pubkey: {e:?}")))?; let taddr = TransparentAddress::from_pubkey(&pk); - let coin = TxOut::new(Zatoshis::from_u64(SPEND_VALUE).unwrap(), taddr.script().into()); + let coin = TxOut::new( + Zatoshis::from_u64(SPEND_VALUE).unwrap(), + taddr.script().into(), + ); let mut builder = TransparentBuilder::empty(); builder .add_p2pkh_input(pk, OutPoint::new([0u8; 32], 0), coin) @@ -310,7 +313,11 @@ fn build_orchard( .clone(); let mut rng = StdRng::seed_from_u64(0x0_C_5A_u64); - let note = make_orchard_note(&mut rng, fvk.address_at(0u32, OrchardScope::External), SPEND_VALUE); + let note = make_orchard_note( + &mut rng, + fvk.address_at(0u32, OrchardScope::External), + SPEND_VALUE, + ); let cmx: ExtractedNoteCommitment = note.commitment().into(); let sibling = MerkleHashOrchard::from_cmx(&cmx); let path = OrchardMerklePath::from_parts(0, [sibling; 32]); @@ -347,7 +354,9 @@ fn build_orchard( fn make_orchard_note(rng: &mut StdRng, recipient: OrchardAddress, value: u64) -> OrchardNote { let mut rho_bytes = [0u8; 32]; rho_bytes[0] = 7; - let rho = Rho::from_bytes(&rho_bytes).into_option().expect("valid rho"); + let rho = Rho::from_bytes(&rho_bytes) + .into_option() + .expect("valid rho"); loop { let mut rseed_bytes = [0u8; 32]; rng.fill_bytes(&mut rseed_bytes); @@ -388,9 +397,18 @@ mod tests { let attacker = ufvk_from_seed(&net, ATTACKER_SEED).unwrap(); for (pool, demo) in [ - ("transparent", transparent_demo(&net, &me, &bridge, &attacker).unwrap()), - ("sapling", sapling_demo(&net, &me, &bridge, &attacker).unwrap()), - ("orchard", orchard_demo(&net, &me, &bridge, &attacker).unwrap()), + ( + "transparent", + transparent_demo(&net, &me, &bridge, &attacker).unwrap(), + ), + ( + "sapling", + sapling_demo(&net, &me, &bridge, &attacker).unwrap(), + ), + ( + "orchard", + orchard_demo(&net, &me, &bridge, &attacker).unwrap(), + ), ] { let honest = hex_to_pczt(&demo.honest); let spoof = hex_to_pczt(&demo.spoof); diff --git a/crates/webzjs-keys/src/lib.rs b/crates/webzjs-keys/src/lib.rs index 3a75cfb..320dba8 100644 --- a/crates/webzjs-keys/src/lib.rs +++ b/crates/webzjs-keys/src/lib.rs @@ -1,16 +1,16 @@ // Copyright 2024 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT +#[cfg(feature = "demo-builder")] +mod demo_pczt; mod error; mod keys; mod pczt_describe; mod pczt_sign; -#[cfg(feature = "demo-builder")] -mod demo_pczt; +#[cfg(feature = "demo-builder")] +pub use demo_pczt::*; pub use error::*; pub use keys::*; pub use pczt_describe::*; pub use pczt_sign::*; -#[cfg(feature = "demo-builder")] -pub use demo_pczt::*; diff --git a/crates/webzjs-keys/src/pczt_describe.rs b/crates/webzjs-keys/src/pczt_describe.rs index b92030e..02a5485 100644 --- a/crates/webzjs-keys/src/pczt_describe.rs +++ b/crates/webzjs-keys/src/pczt_describe.rs @@ -360,7 +360,9 @@ fn transparent_addr_is_ours( }; bip32_derivation.iter().any(|(claimed_pk, deriv)| { match tfvk.derive_pubkey_at_bip32_path(network, account, deriv.derivation_path()) { - Ok(pk) => &pk.serialize() == claimed_pk && TransparentAddress::from_pubkey(&pk) == *addr, + Ok(pk) => { + &pk.serialize() == claimed_pk && TransparentAddress::from_pubkey(&pk) == *addr + } Err(_) => false, } }) @@ -378,8 +380,10 @@ fn transparent_addr_is_ours( /// invariants (spends are ours, value balances / turnstile identity holds, every /// output is commitment-bound, fee is sane) for migrations as for any PCZT. fn detect_migration(outputs: &[PcztOutputSummary]) -> Option { - let ironwood: Vec<&PcztOutputSummary> = - outputs.iter().filter(|o| o.pool == pool::IRONWOOD).collect(); + let ironwood: Vec<&PcztOutputSummary> = outputs + .iter() + .filter(|o| o.pool == pool::IRONWOOD) + .collect(); if ironwood.is_empty() { return None; } @@ -499,7 +503,8 @@ fn analyze( } for output in bundle.outputs() { - if let Err(sapling::pczt::VerifyError::InvalidValueCommitment) = output.verify_cv() { + if let Err(sapling::pczt::VerifyError::InvalidValueCommitment) = output.verify_cv() + { cv_mismatch = true; } match output.value().map(|v| v.inner()) { @@ -562,7 +567,9 @@ fn analyze( let value = u64::from(*input.value()); total_in += value; let ours = TransparentAddress::from_script_from_chain(input.script_pubkey()) - .map(|addr| transparent_addr_is_ours(&network, tfvk, &addr, input.bip32_derivation())) + .map(|addr| { + transparent_addr_is_ours(&network, tfvk, &addr, input.bip32_derivation()) + }) .unwrap_or(false); if !ours { foreign_input = true; @@ -577,7 +584,9 @@ fn analyze( let recipient = addr.map(|addr| addr.encode(&network)); // Change = the coin pays back to one of our own transparent keys. let is_change = addr - .map(|addr| transparent_addr_is_ours(&network, tfvk, &addr, output.bip32_derivation())) + .map(|addr| { + transparent_addr_is_ours(&network, tfvk, &addr, output.bip32_derivation()) + }) .unwrap_or(false); total_out += value; outputs.push(PcztOutputSummary { diff --git a/crates/webzjs-keys/src/pczt_sign.rs b/crates/webzjs-keys/src/pczt_sign.rs index 84290cf..ffe9253 100644 --- a/crates/webzjs-keys/src/pczt_sign.rs +++ b/crates/webzjs-keys/src/pczt_sign.rs @@ -64,11 +64,11 @@ pub async fn pczt_sign_inner( }, } let mut keys = BTreeMap::>::new(); - let pczt = Verifier::new(pczt) - .with_orchard::(|bundle| { - for (index, action) in bundle.actions().iter().enumerate() { - if let Some(account_index) = - action + let pczt = + Verifier::new(pczt) + .with_orchard::(|bundle| { + for (index, action) in bundle.actions().iter().enumerate() { + if let Some(account_index) = action .spend() .zip32_derivation() .as_ref() @@ -78,21 +78,20 @@ pub async fn pczt_sign_inner( zip32::ChildIndex::hardened(network.network_type().coin_type()), ) }) - { - keys.entry(account_index) - .or_default() - .push(KeyRef::Orchard { index }); + { + keys.entry(account_index) + .or_default() + .push(KeyRef::Orchard { index }); + } } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .with_ironwood::(|bundle| { - // Ironwood reuses the Orchard action/key shape, so collect spendable - // Ironwood actions exactly as for Orchard (same zip32 derivation). - for (index, action) in bundle.actions().iter().enumerate() { - if let Some(account_index) = - action + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .with_ironwood::(|bundle| { + // Ironwood reuses the Orchard action/key shape, so collect spendable + // Ironwood actions exactly as for Orchard (same zip32 derivation). + for (index, action) in bundle.actions().iter().enumerate() { + if let Some(account_index) = action .spend() .zip32_derivation() .as_ref() @@ -102,59 +101,59 @@ pub async fn pczt_sign_inner( zip32::ChildIndex::hardened(network.network_type().coin_type()), ) }) - { - keys.entry(account_index) - .or_default() - .push(KeyRef::Ironwood { index }); - } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .with_sapling::(|bundle| { - for (index, spend) in bundle.spends().iter().enumerate() { - if let Some(account_index) = - spend.zip32_derivation().as_ref().and_then(|derivation| { - derivation.extract_account_index( - &seed_fp, - zip32::ChildIndex::hardened(network.network_type().coin_type()), - ) - }) - { - keys.entry(account_index) - .or_default() - .push(KeyRef::Sapling { index }); + { + keys.entry(account_index) + .or_default() + .push(KeyRef::Ironwood { index }); + } } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .with_transparent::(|bundle| { - for (index, input) in bundle.inputs().iter().enumerate() { - for derivation in input.bip32_derivation().values() { - if let Some((account_index, scope, address_index)) = derivation - .extract_bip_44_fields( - &seed_fp, - bip32::ChildNumber( - network.network_type().coin_type() - | bip32::ChildNumber::HARDENED_FLAG, - ), - ) + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .with_sapling::(|bundle| { + for (index, spend) in bundle.spends().iter().enumerate() { + if let Some(account_index) = + spend.zip32_derivation().as_ref().and_then(|derivation| { + derivation.extract_account_index( + &seed_fp, + zip32::ChildIndex::hardened(network.network_type().coin_type()), + ) + }) { keys.entry(account_index) .or_default() - .push(KeyRef::Transparent { - index, - scope, - address_index, - }); + .push(KeyRef::Sapling { index }); } } - } - Ok(()) - }) - .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {:?}", e)))? - .finish(); + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .with_transparent::(|bundle| { + for (index, input) in bundle.inputs().iter().enumerate() { + for derivation in input.bip32_derivation().values() { + if let Some((account_index, scope, address_index)) = derivation + .extract_bip_44_fields( + &seed_fp, + bip32::ChildNumber( + network.network_type().coin_type() + | bip32::ChildNumber::HARDENED_FLAG, + ), + ) + { + keys.entry(account_index) + .or_default() + .push(KeyRef::Transparent { + index, + scope, + address_index, + }); + } + } + } + Ok(()) + }) + .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? + .finish(); let mut signer = Signer::new(pczt).unwrap(); //.map_err(|e| anyhow!("Failed to initialize Signer: {:?}", e))?; for (_, spends) in keys { @@ -168,10 +167,7 @@ pub async fn pczt_sign_inner( &orchard::keys::SpendAuthorizingKey::from(usk.orchard()), ) .map_err(|e| { - Error::PcztSign(format!( - "Failed to sign Orchard spend {index}: {:?}", - e - )) + Error::PcztSign(format!("Failed to sign Orchard spend {index}: {e:?}")) })?; } KeyRef::Ironwood { index } => { @@ -182,20 +178,14 @@ pub async fn pczt_sign_inner( &orchard::keys::SpendAuthorizingKey::from(usk.orchard()), ) .map_err(|e| { - Error::PcztSign(format!( - "Failed to sign Ironwood spend {index}: {:?}", - e - )) + Error::PcztSign(format!("Failed to sign Ironwood spend {index}: {e:?}")) })?; } KeyRef::Sapling { index } => { signer .sign_sapling(index, &usk.sapling().expsk.ask) .map_err(|e| { - Error::PcztSign(format!( - "Failed to sign Sapling spend {index}: {:?}", - e - )) + Error::PcztSign(format!("Failed to sign Sapling spend {index}: {e:?}")) })?; } KeyRef::Transparent { @@ -210,15 +200,13 @@ pub async fn pczt_sign_inner( .derive_secret_key(scope, address_index) .map_err(|e| { Error::PcztSign(format!( - "Failed to derive transparent key at .../{:?}/{:?}: {:?}", - scope, address_index, e, + "Failed to derive transparent key at .../{scope:?}/{address_index:?}: {e:?}" )) })?, ) .map_err(|e| { Error::PcztSign(format!( - "Failed to sign transparent input {index}: {:?}", - e + "Failed to sign transparent input {index}: {e:?}" )) })?; } diff --git a/crates/webzjs-keys/tests/gen_fixtures.rs b/crates/webzjs-keys/tests/gen_fixtures.rs index 5ce78ab..c297b66 100644 --- a/crates/webzjs-keys/tests/gen_fixtures.rs +++ b/crates/webzjs-keys/tests/gen_fixtures.rs @@ -85,7 +85,9 @@ fn make_note_versioned( // A small canonical field element is a fine `rho` for an off-chain note. let mut rho_bytes = [0u8; 32]; rho_bytes[0] = 7; - let rho = Rho::from_bytes(&rho_bytes).into_option().expect("valid rho"); + let rho = Rho::from_bytes(&rho_bytes) + .into_option() + .expect("valid rho"); loop { let mut rseed_bytes = [0u8; 32]; rng.fill_bytes(&mut rseed_bytes); @@ -138,7 +140,12 @@ fn make_orchard_pczt( .expect("add_spend"); for (ovk, recipient, value) in outputs { builder - .add_output(ovk.clone(), *recipient, NoteValue::from_raw(*value), [0u8; 512]) + .add_output( + ovk.clone(), + *recipient, + NoteValue::from_raw(*value), + [0u8; 512], + ) .expect("add_output"); } @@ -188,7 +195,12 @@ fn make_ironwood_pczt( .expect("add_spend"); for (ovk, recipient, value) in outputs { builder - .add_output(ovk.clone(), *recipient, NoteValue::from_raw(*value), [0u8; 512]) + .add_output( + ovk.clone(), + *recipient, + NoteValue::from_raw(*value), + [0u8; 512], + ) .expect("add_output"); } @@ -252,7 +264,12 @@ fn make_turnstile_migration_pczt( ) .expect("ironwood Builder::new"); iw_builder - .add_output(out_ovk, out_addr, NoteValue::from_raw(out_value), [0u8; 512]) + .add_output( + out_ovk, + out_addr, + NoteValue::from_raw(out_value), + [0u8; 512], + ) .expect("add_output"); let (iw_bundle, _) = iw_builder .build_for_pczt(&mut *rng) @@ -314,11 +331,16 @@ fn make_transparent_pczt( let (pk, taddr) = transparent_addr0(spend_seed); // The coin being spent: a P2PKH output paying our own address. - let coin = TxOut::new(Zatoshis::from_u64(spend_value).unwrap(), taddr.script().into()); + let coin = TxOut::new( + Zatoshis::from_u64(spend_value).unwrap(), + taddr.script().into(), + ); let utxo = OutPoint::new([0u8; 32], 0); let mut builder = TransparentBuilder::empty(); - builder.add_p2pkh_input(pk, utxo, coin).expect("add p2pkh input"); + builder + .add_p2pkh_input(pk, utxo, coin) + .expect("add p2pkh input"); builder .add_output(recipient, Zatoshis::from_u64(out_value).unwrap()) .expect("add transparent output"); @@ -391,12 +413,16 @@ fn make_sapling_pczt( rng: &mut StdRng, spend_dfvk: &sapling::zip32::DiversifiableFullViewingKey, spend_value: u64, - outputs: &[(sapling::keys::OutgoingViewingKey, sapling::PaymentAddress, u64)], + outputs: &[( + sapling::keys::OutgoingViewingKey, + sapling::PaymentAddress, + u64, + )], ) -> pczt::Pczt { let note = make_sapling_note(rng, spend_dfvk, spend_value); let node = sapling::Node::from_cmu(¬e.cmu()); - let path = - sapling::MerklePath::from_parts(vec![node; 32], 0u64.into()).expect("32-element merkle path"); + let path = sapling::MerklePath::from_parts(vec![node; 32], 0u64.into()) + .expect("32-element merkle path"); let anchor = sapling::Anchor::from(path.root(node)); let mut builder = sapling::builder::Builder::new( @@ -435,7 +461,11 @@ fn make_sapling_pczt( } fn write_fixture(name: &str, pczt: &pczt::Pczt) { - let path = format!("{}/tests/fixtures/{}.pczt", env!("CARGO_MANIFEST_DIR"), name); + let path = format!( + "{}/tests/fixtures/{}.pczt", + env!("CARGO_MANIFEST_DIR"), + name + ); let bytes = pczt.clone().serialize().expect("serialize pczt"); std::fs::write(&path, bytes).unwrap_or_else(|e| panic!("write {path}: {e}")); eprintln!("wrote {path}"); diff --git a/crates/webzjs-keys/tests/security_finding1.rs b/crates/webzjs-keys/tests/security_finding1.rs index 08daa60..05c33e4 100644 --- a/crates/webzjs-keys/tests/security_finding1.rs +++ b/crates/webzjs-keys/tests/security_finding1.rs @@ -43,7 +43,11 @@ fn ufvk_for_seed(seed: &[u8; 32]) -> zcash_keys::keys::UnifiedFullViewingKey { } fn load_pczt(name: &str) -> pczt::Pczt { - let path = format!("{}/tests/fixtures/{}.pczt", env!("CARGO_MANIFEST_DIR"), name); + let path = format!( + "{}/tests/fixtures/{}.pczt", + env!("CARGO_MANIFEST_DIR"), + name + ); let bytes = std::fs::read(&path).unwrap_or_else(|e| { panic!( "missing fixture {path}: {e}\n\ @@ -109,7 +113,9 @@ fn fvk_plant_does_not_bypass_foreign_input_detection() { // Fixed behaviour: the planted foreign spend is rejected as a foreign input. let err = pczt_validate_inner(Network::TestNetwork, poisoned.clone(), &our_ufvk) .expect_err("FVK-planted foreign input must be rejected"); - println!("│ validate → REJECTED (attribution is nullifier-only, ignores the fvk label): {err}"); + println!( + "│ validate → REJECTED (attribution is nullifier-only, ignores the fvk label): {err}" + ); assert!( err.to_string().contains("not under this key"), "must be rejected specifically as a foreign input, got: {err}" diff --git a/crates/webzjs-keys/tests/spoof_pczt.rs b/crates/webzjs-keys/tests/spoof_pczt.rs index 8d74d9e..ced536f 100644 --- a/crates/webzjs-keys/tests/spoof_pczt.rs +++ b/crates/webzjs-keys/tests/spoof_pczt.rs @@ -160,7 +160,11 @@ fn narrate_describe(summary: &PcztSummary) { short(o.recipient.as_deref()), if o.verified { "verified" } else { "UNVERIFIED" }, if o.is_change { ", change" } else { "" }, - if o.is_ours && !o.is_change { ", self" } else { "" }, + if o.is_ours && !o.is_change { + ", self" + } else { + "" + }, )); } if let Some(m) = &summary.migration { @@ -177,7 +181,9 @@ fn narrate_describe(summary: &PcztSummary) { fn narrate_validate(result: &Result<(), E>) { match result { Ok(()) => line("validate → Ok (Layer B would allow signing)"), - Err(e) => line(&format!("validate → REJECTED (Layer B refuses to sign): {e}")), + Err(e) => line(&format!( + "validate → REJECTED (Layer B refuses to sign): {e}" + )), } } @@ -190,7 +196,9 @@ fn honest_pczt_is_accepted() { ); let ufvk = our_ufvk(); let pczt = load_pczt("honest_bridge_deposit"); - line("fixture: honest_bridge_deposit.pczt (spend 100k ours → bridge 50k + change 40k, fee 10k)"); + line( + "fixture: honest_bridge_deposit.pczt (spend 100k ours → bridge 50k + change 40k, fee 10k)", + ); let result = pczt_validate_inner(Network::from_str("test").unwrap(), pczt, &ufvk); narrate_validate(&result); @@ -221,7 +229,10 @@ fn spoofed_recipient_is_surfaced() { let summary = pczt_describe_inner(Network::from_str("test").unwrap(), pczt.clone(), &ufvk) .expect("describe must succeed and surface the real outputs"); narrate_describe(&summary); - line(&format!("expected true payee (attacker) = {}", short(Some(&attacker_addr())))); + line(&format!( + "expected true payee (attacker) = {}", + short(Some(&attacker_addr())) + )); assert!( summary @@ -318,7 +329,11 @@ fn ironwood_payment_is_described_and_accepted() { .expect("describe must succeed on an Ironwood PCZT"); narrate_describe(&summary); - let ironwood_outs: Vec<_> = summary.outputs.iter().filter(|o| o.pool == "ironwood").collect(); + let ironwood_outs: Vec<_> = summary + .outputs + .iter() + .filter(|o| o.pool == "ironwood") + .collect(); assert_eq!( ironwood_outs.len(), 1, @@ -383,7 +398,10 @@ fn self_migration_is_recognized() { .migration .as_ref() .expect("an Ironwood-output PCZT must be recognised as a migration"); - assert_eq!(migration.amount, 90_000, "migrated amount = Ironwood output value"); + assert_eq!( + migration.amount, 90_000, + "migrated amount = Ironwood output value" + ); assert!( migration.to_self, "migrating to our own address must be flagged as a self-migration" @@ -424,11 +442,18 @@ fn turnstile_migration_end_to_end() { // Value crosses the turnstile: 100_000 spent from Orchard, 90_000 into Ironwood, // 10_000 fee. This IS the turnstile value identity the validator checks. assert_eq!(summary.total_in, 100_000, "the Orchard spend is our input"); - assert_eq!(summary.total_out, 90_000, "the Ironwood output is the migrated value"); + assert_eq!( + summary.total_out, 90_000, + "the Ironwood output is the migrated value" + ); assert_eq!(summary.fee, 10_000, "fee = Orchard out − Ironwood in"); // Exactly one displayed output: the Ironwood note, to us, commitment-bound. - assert_eq!(summary.outputs.len(), 1, "only the Ironwood output is displayed"); + assert_eq!( + summary.outputs.len(), + 1, + "only the Ironwood output is displayed" + ); let out = &summary.outputs[0]; assert_eq!(out.pool, "ironwood"); assert!(out.is_ours, "the migration output pays our own address"); @@ -440,8 +465,14 @@ fn turnstile_migration_end_to_end() { .as_ref() .expect("a cross-pool Orchard→Ironwood tx must be recognised as a migration"); assert_eq!(m.amount, 90_000); - assert!(m.to_self, "migrating to our own address is a self-migration"); - assert!(m.is_clean_path_a, "one Ironwood output, no third-party outputs"); + assert!( + m.to_self, + "migrating to our own address is a self-migration" + ); + assert!( + m.is_clean_path_a, + "one Ironwood output, no third-party outputs" + ); // Layer B accepts the turnstile: spends ours, balances, verified, fee in band. let result = pczt_validate_inner(Network::from_str("test").unwrap(), pczt, &ufvk); @@ -484,7 +515,10 @@ fn transparent_input_under_our_key_is_accepted() { let summary = pczt_describe_inner(Network::from_str("test").unwrap(), pczt.clone(), &ufvk) .expect("describe must succeed on a transparent PCZT"); narrate_describe(&summary); - line(&format!("expected bridge t-address = {}", short(Some(&bridge_taddr())))); + line(&format!( + "expected bridge t-address = {}", + short(Some(&bridge_taddr())) + )); assert!( summary .outputs @@ -538,7 +572,11 @@ fn sapling_change_is_detected() { let summary = pczt_describe_inner(Network::from_str("test").unwrap(), pczt.clone(), &ufvk) .expect("describe must succeed on a Sapling PCZT"); narrate_describe(&summary); - let sapling_outs: Vec<_> = summary.outputs.iter().filter(|o| o.pool == "sapling").collect(); + let sapling_outs: Vec<_> = summary + .outputs + .iter() + .filter(|o| o.pool == "sapling") + .collect(); assert_eq!( sapling_outs.len(), 2, @@ -560,4 +598,3 @@ fn sapling_change_is_detected() { ); verdict("change (internal scope) is told apart from the external payment; ACCEPTED"); } - diff --git a/crates/webzjs-requests/src/requests.rs b/crates/webzjs-requests/src/requests.rs index b6f4b21..c9e1c67 100644 --- a/crates/webzjs-requests/src/requests.rs +++ b/crates/webzjs-requests/src/requests.rs @@ -33,8 +33,8 @@ impl TransactionRequest { // BTreeMap automatically stores keys in sorted order so we can do this self.0 .payments() - .iter() - .map(|(_index, p)| PaymentRequest(p.clone())) + .values() + .map(|p| PaymentRequest(p.clone())) .collect() } diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index fa5e779..97b362e 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -26,12 +26,12 @@ use std::sync::Arc; use subtle::ConditionallySelectable; use tokio::sync::RwLock; use zcash_address::ZcashAddress; +use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; use zcash_client_backend::data_api::wallet::{ create_pczt_from_proposal, create_proposed_transactions, extract_and_store_transaction_from_pczt, input_selection::GreedyInputSelector, propose_shielding, propose_transfer, ConfirmationsPolicy, SpendingKeys, }; -use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; use zcash_client_backend::data_api::CoinbaseFilter; use zcash_client_backend::data_api::{ Account, AccountBirthday, AccountPurpose, InputSource, WalletRead, WalletSummary, WalletWrite, @@ -559,7 +559,7 @@ where ) .map_err(|e| { tracing::error!("pczt_shield: propose_shielding failed: {:?}", e); - Error::Generic(format!("Error when shielding: {:?}", e)) + Error::Generic(format!("Error when shielding: {e:?}")) })?; tracing::info!("pczt_shield: proposal created successfully"); @@ -584,7 +584,7 @@ where ) .map_err(|e| { tracing::error!("pczt_shield: create_pczt_from_proposal failed: {:?}", e); - Error::PcztCreate(format!("{:?}", e)) + Error::PcztCreate(format!("{e:?}")) })?; tracing::info!("pczt_shield: PCZT created from proposal successfully"); @@ -658,7 +658,7 @@ where &SpendPolicy::default(), None, ) - .map_err(|e| Error::Generic(format!("something bad happened when calling propose transfer. Possibly insufficient balance... {:?}", e)))?; + .map_err(|e| Error::Generic(format!("something bad happened when calling propose transfer. Possibly insufficient balance... {e:?}")))?; tracing::info!("PCZT proposal created"); let pczt = create_pczt_from_proposal::< _, @@ -680,7 +680,7 @@ where ) .map_err(|e| { tracing::error!("pczt_create: create_pczt_from_proposal failed: {:?}", e); - Error::PcztCreate(format!("{:?}", e)) + Error::PcztCreate(format!("{e:?}")) })?; Ok(pczt) } @@ -726,10 +726,7 @@ where Ok(()) }) .map_err(|e| { - Error::PcztProve(format!( - "Failed to add Sapling proof generation key: {:?}", - e - )) + Error::PcztProve(format!("Failed to add Sapling proof generation key: {e:?}")) })? .finish() } else { @@ -741,18 +738,20 @@ where // Nu6_3 -> PostNu6_3 (the Ironwood-era circuit that enforces the disableCrossAddress // constraint sealing the Orchard pool); everything current (Nu6_2) -> FixedPostNu6_2. // The same version must build the verifying key when extracting the transaction below. - let orchard_circuit_version = - match BranchId::try_from(*pczt.global().consensus_branch_id()) { - Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, - _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, - }; + let orchard_circuit_version = match BranchId::try_from(*pczt.global().consensus_branch_id()) + { + Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, + _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, + }; let prover = LocalTxProver::bundled(); let pczt = Prover::new(pczt) - .create_orchard_proof(&orchard::circuit::ProvingKey::build(orchard_circuit_version)) - .map_err(|e| Error::PcztProve(format!("Failed to create Orchard proof: {:?}", e)))? + .create_orchard_proof(&orchard::circuit::ProvingKey::build( + orchard_circuit_version, + )) + .map_err(|e| Error::PcztProve(format!("Failed to create Orchard proof: {e:?}")))? .create_sapling_proofs(&prover, &prover) - .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {:?}", e)))? + .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {e:?}")))? .finish(); Ok(pczt) } @@ -784,8 +783,7 @@ where blocks_behind ); return Err(Error::Generic(format!( - "Wallet is {} blocks behind the chain tip. Please sync before sending (max allowed: 100 blocks).", - blocks_behind + "Wallet is {blocks_behind} blocks behind the chain tip. Please sync before sending (max allowed: 100 blocks)." ))); } tracing::info!( @@ -801,11 +799,11 @@ where // Build the Orchard verifying key with the circuit version for this PCZT's target // branch (Nu6_3 -> PostNu6_3, else FixedPostNu6_2), matching how the proof was // created. See the proving-key derivation in the pczt_prove path. - let orchard_circuit_version = - match BranchId::try_from(*pczt.global().consensus_branch_id()) { - Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, - _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, - }; + let orchard_circuit_version = match BranchId::try_from(*pczt.global().consensus_branch_id()) + { + Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, + _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, + }; let prover = LocalTxProver::bundled(); let (spend_vk, output_vk) = prover.verifying_keys(); let mut db = self.db.write().await; @@ -813,12 +811,13 @@ where &mut *db, pczt, Some((&spend_vk, &output_vk)), - Some(&orchard::circuit::VerifyingKey::build(orchard_circuit_version)), + Some(&orchard::circuit::VerifyingKey::build( + orchard_circuit_version, + )), ) .map_err(|e| { Error::PcztSend(format!( - "Failed to extract and store transaction from PCZT: {:?}", - e + "Failed to extract and store transaction from PCZT: {e:?}" )) })?; drop(db); @@ -829,7 +828,7 @@ where pub fn pczt_combine(&self, pczts: Vec) -> Result { Combiner::new(pczts) .combine() - .map_err(|e| Error::PcztCombine(format!("Failed to combine PCZT: {:?}", e))) + .map_err(|e| Error::PcztCombine(format!("Failed to combine PCZT: {e:?}"))) } } From aedcb989f5997ee3c3591867c284b5a2dcaffa1b Mon Sep 17 00:00:00 2001 From: sqhell Date: Sat, 17 Oct 2026 17:13:47 -0600 Subject: [PATCH 2/3] feat: send again from the transaction history, with a caution for new recipients Transaction history entries now carry the encoded addresses of their external recipients (the wallet already stored them in its sent notes, the history serializer just dropped them). Sent rows show the recipient and a "Send again" link that opens Transfer Balance with the address filled in; shielding rows link to Shield Balance. The recipient field checks the typed address against the wallet's own send history through a new `has_sent_to` wasm method. A known address gets a green border and "You have sent to this address before"; an address this wallet has never paid gets an amber border and a caution to check it carefully. Matching is by the whole encoded address: a Unified Address only counts as known when that exact address was paid before, so an address that shares one receiver with a known recipient but pays another cannot pass as known. The same call rejects malformed addresses, which gives the form real address validation; it previously only checked that the field was not empty. A wallet failure that is not about the address leaves the field usable and only withholds the hint. --- .../src/bindgen/transaction_history.rs | 18 +++- crates/webzjs-wallet/src/bindgen/wallet.rs | 28 +++++ .../web-wallet/src/components/Input/Input.tsx | 31 +++++- .../TransactionHistory.test.tsx | 60 +++++++++++ .../TransactionHistory/TransactionHistory.tsx | 44 ++++++++ .../TransferInput.recipient.test.tsx | 91 ++++++++++++++++ .../TransferCards/TransferInput.tsx | 101 ++++++++++++++++-- .../pages/TransferBalance/TransferBalance.tsx | 2 + .../TransferBalance/useTransferBalanceForm.ts | 25 ++++- packages/web-wallet/src/types/transaction.ts | 2 + 10 files changed, 386 insertions(+), 16 deletions(-) create mode 100644 packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx create mode 100644 packages/web-wallet/src/components/TransferCards/TransferInput.recipient.test.tsx diff --git a/crates/webzjs-wallet/src/bindgen/transaction_history.rs b/crates/webzjs-wallet/src/bindgen/transaction_history.rs index 85efabb..fc08ccc 100644 --- a/crates/webzjs-wallet/src/bindgen/transaction_history.rs +++ b/crates/webzjs-wallet/src/bindgen/transaction_history.rs @@ -61,6 +61,8 @@ pub struct TransactionHistoryEntry { timestamp: Option, /// Pool type: "sapling", "orchard", "transparent", or "mixed" pool: String, + /// Encoded addresses of the external recipients (empty unless funds left the wallet) + recipients: Vec, } #[wasm_bindgen] @@ -114,6 +116,11 @@ impl TransactionHistoryEntry { pub fn pool(&self) -> String { self.pool.clone() } + + #[wasm_bindgen(getter)] + pub fn recipients(&self) -> Vec { + self.recipients.clone() + } } /// Response containing paginated transaction history @@ -151,6 +158,7 @@ struct TxAccumulator { fee: Option, memos: Vec, pools: std::collections::HashSet, + recipients: Vec, block_height: Option, status: Option, expiry_height: Option, @@ -223,7 +231,14 @@ pub fn extract_transaction_history( // Determine pool from recipient let pool = match sent_note.to() { - zcash_client_backend::wallet::Recipient::External { output_pool, .. } => { + zcash_client_backend::wallet::Recipient::External { + recipient_address, + output_pool, + } => { + let encoded = recipient_address.encode(); + if !entry.recipients.contains(&encoded) { + entry.recipients.push(encoded); + } match output_pool { zcash_protocol::PoolType::Transparent => "transparent", zcash_protocol::PoolType::Shielded( @@ -353,6 +368,7 @@ pub fn extract_transaction_history( memo, timestamp, pool, + recipients: acc.recipients, } }) .collect(); diff --git a/crates/webzjs-wallet/src/bindgen/wallet.rs b/crates/webzjs-wallet/src/bindgen/wallet.rs index 7b29651..df404f2 100644 --- a/crates/webzjs-wallet/src/bindgen/wallet.rs +++ b/crates/webzjs-wallet/src/bindgen/wallet.rs @@ -594,6 +594,34 @@ impl WebWallet { ) } + /// Returns whether `account_id` has previously sent funds to `address`. + /// + /// Matching is by the whole encoded address: the typed address is parsed and re-encoded, so + /// a Unified Address only counts as known when this exact Unified Address was paid before. + /// Matching on individual receivers would let an address that shares one receiver with a + /// known recipient, but pays a different one, pass as known. + /// + /// Fails if `address` is not a valid Zcash address for the wallet's network. + pub async fn has_sent_to(&self, account_id: u32, address: &str) -> Result { + let network = &self.inner.network; + let parsed = ZcashAddress::try_from_encoded(address)?; + // Only the network check is needed from the conversion. + zcash_keys::address::Address::try_from_zcash_address(network, parsed.clone()) + .map_err(|e| Error::Generic(format!("Address is not valid for this network: {e}")))?; + let target = parsed.encode(); + let account = AccountId::from(account_id); + + let db = self.inner.db.read().await; + Ok(db.sent_notes().iter().any(|(_, sent_note)| { + sent_note.from_account_id() == account + && matches!( + sent_note.to(), + zcash_client_backend::wallet::Recipient::External { recipient_address, .. } + if recipient_address.encode() == target + ) + })) + } + /////////////////////////////////////////////////////////////////////////////////////// // lightwalletd gRPC methods /////////////////////////////////////////////////////////////////////////////////////// diff --git a/packages/web-wallet/src/components/Input/Input.tsx b/packages/web-wallet/src/components/Input/Input.tsx index 77ec42d..accf51d 100644 --- a/packages/web-wallet/src/components/Input/Input.tsx +++ b/packages/web-wallet/src/components/Input/Input.tsx @@ -1,9 +1,15 @@ import React from 'react'; import ErrorMessage from '../ErrorMessage/ErrorMessage'; +export type InputTone = 'default' | 'success' | 'warning'; + interface InputProps extends React.InputHTMLAttributes { label?: string; error?: string; + /** Colors the field border: green for a confirmed value, amber for one to double-check */ + tone?: InputTone; + /** A short note under the field, shown in the tone's color (an error replaces it) */ + hint?: string; containerClassName?: string; labelClassName?: string; inputClassName?: string; @@ -11,9 +17,23 @@ interface InputProps extends React.InputHTMLAttributes { id: string; } +const toneBorder: Record = { + default: 'border-[#afafaf]', + success: 'border-green-600', + warning: 'border-amber-500', +}; + +const toneText: Record = { + default: 'text-[#595959]', + success: 'text-green-700', + warning: 'text-amber-700', +}; + const Input: React.FC = ({ label, error, + tone = 'default', + hint, containerClassName = '', labelClassName = '', inputClassName = '', @@ -31,12 +51,14 @@ const Input: React.FC = ({ {label} )} -
+
= ({
+ {!error && hint && ( + + {hint} + + )}
); }; diff --git a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx new file mode 100644 index 0000000..978808b --- /dev/null +++ b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx @@ -0,0 +1,60 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import TransactionHistory from './TransactionHistory'; +import type { TransactionHistoryEntry } from '../../types/transaction'; + +const base: TransactionHistoryEntry = { + txid: 'ab'.repeat(32), + tx_type: 'Sent', + value: -1_000_000, + fee: null, + block_height: 3_500_000, + confirmations: 3, + status: 'Confirmed', + memo: null, + timestamp: 1_760_000_000, + pool: 'orchard', + recipients: ['u1recipientaddressthatislongenoughtobeshortened'], +}; + +const transactions: TransactionHistoryEntry[] = [ + base, + { ...base, txid: 'cd'.repeat(32), tx_type: 'Received', value: 500_000, recipients: [] }, + { ...base, txid: 'ef'.repeat(32), tx_type: 'Shielded', value: 200_000, pool: 'mixed', recipients: [] }, +]; + +vi.mock('../../hooks/useTransactionHistory', () => ({ + useTransactionHistory: () => ({ + transactions, + loading: false, + error: null, + totalCount: transactions.length, + hasMore: false, + loadMore: vi.fn(), + refresh: vi.fn(), + }), +})); + +describe('TransactionHistory repeat links', () => { + it('offers Send again for a sent transaction, with the recipient in the link state', () => { + render( + + + , + ); + const sendAgain = screen.getByText('Send again'); + expect(sendAgain).toHaveAttribute('href', '/dashboard/transfer-balance'); + expect(screen.getByText(/^To: u1recipient/)).toBeInTheDocument(); + }); + + it('offers Shield again for a shielding transaction and nothing for a received one', () => { + render( + + + , + ); + expect(screen.getByText('Shield again')).toHaveAttribute('href', '/dashboard/shield-balance'); + expect(screen.getAllByText(/again$/)).toHaveLength(2); + }); +}); diff --git a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx index 56581ba..21979ec 100644 --- a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx +++ b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx @@ -1,4 +1,5 @@ import React from 'react'; +import { Link } from 'react-router-dom'; import { useTransactionHistory } from '../../hooks/useTransactionHistory'; import { zatsToZec } from '../../utils'; import type { TransactionHistoryEntry, TransactionType, TransactionStatus } from '../../types/transaction'; @@ -45,11 +46,43 @@ function getStatusBadge(status: TransactionStatus): { text: string; className: s } } +function shortAddress(address: string): string { + return address.length > 24 ? `${address.slice(0, 12)}…${address.slice(-8)}` : address; +} + +/** The repeat action for a row: send to the same recipient again, or shield again. */ +function RepeatLink({ transaction }: TransactionRowProps) { + const linkClass = + 'text-sm font-medium text-orange-600 hover:text-orange-700 underline whitespace-nowrap'; + const recipient = transaction.recipients?.[0]; + if (transaction.tx_type === 'Sent' && recipient) { + return ( + + Send again + + ); + } + if (transaction.tx_type === 'Shielded') { + return ( + + Shield again + + ); + } + return null; +} + function TransactionRow({ transaction }: TransactionRowProps) { const isPositive = transaction.value > 0; const valueColor = isPositive ? 'text-green-600' : 'text-red-600'; const valuePrefix = isPositive ? '+' : ''; const statusBadge = getStatusBadge(transaction.status); + const recipient = transaction.recipients?.[0]; return (
@@ -69,6 +102,14 @@ function TransactionRow({ transaction }: TransactionRowProps) {
{formatTimestamp(transaction.timestamp)}
+ {transaction.tx_type === 'Sent' && recipient && ( +
+ To: {shortAddress(recipient)} + {(transaction.recipients?.length ?? 0) > 1 && ( + +{transaction.recipients.length - 1} more + )} +
+ )} {transaction.memo && (
{transaction.memo} @@ -84,6 +125,9 @@ function TransactionRow({ transaction }: TransactionRowProps) { {transaction.confirmations} confirmation{transaction.confirmations !== 1 ? 's' : ''}
)} +
+ +
diff --git a/packages/web-wallet/src/components/TransferCards/TransferInput.recipient.test.tsx b/packages/web-wallet/src/components/TransferCards/TransferInput.recipient.test.tsx new file mode 100644 index 0000000..b2d9a2a --- /dev/null +++ b/packages/web-wallet/src/components/TransferCards/TransferInput.recipient.test.tsx @@ -0,0 +1,91 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'; +import { + TransferInput, + KNOWN_RECIPIENT_HINT, + NEW_RECIPIENT_HINT, +} from './TransferInput'; + +const hasSentTo = vi.fn(); +const mockState = { webWallet: { has_sent_to: hasSentTo }, activeAccount: 0 }; + +vi.mock('../../context/WebzjsContext', () => ({ + useWebZjsContext: () => ({ state: mockState, dispatch: vi.fn() }), +})); + +vi.mock('../../hooks/useBalance', () => ({ + default: () => ({ spendableBalance: 100_000_000 }), +})); + +const KNOWN = 'u1knownaddress'; +const NEW = 'u1newaddress'; + +function renderInput(recipient: string, prefilledRecipient = '') { + const nextStep = vi.fn(); + render( + () => undefined} + nextStep={nextStep} + />, + ); + return nextStep; +} + +describe('TransferInput recipient check', () => { + beforeEach(() => { + vi.useFakeTimers(); + hasSentTo.mockReset(); + }); + + it('shows a prefilled recipient as known without asking the wallet', () => { + renderInput(KNOWN, KNOWN); + expect(screen.getByText(KNOWN_RECIPIENT_HINT)).toBeInTheDocument(); + expect(hasSentTo).not.toHaveBeenCalled(); + }); + + it('cautions about an address the wallet has never sent to', async () => { + hasSentTo.mockResolvedValue(false); + renderInput(NEW); + await act(async () => { await vi.advanceTimersByTimeAsync(500); }); + expect(hasSentTo).toHaveBeenCalledWith(0, NEW); + expect(screen.getByText(NEW_RECIPIENT_HINT)).toBeInTheDocument(); + }); + + it('marks an address the wallet has sent to before as known', async () => { + hasSentTo.mockResolvedValue(true); + renderInput(KNOWN); + await act(async () => { await vi.advanceTimersByTimeAsync(500); }); + expect(screen.getByText(KNOWN_RECIPIENT_HINT)).toBeInTheDocument(); + }); + + it('blocks Continue when the wallet rejects the address', async () => { + hasSentTo.mockRejectedValue(new Error('Error attempting to decode address')); + const nextStep = renderInput('not an address'); + await act(async () => { await vi.advanceTimersByTimeAsync(500); }); + await act(async () => { fireEvent.click(screen.getByText('Continue')); }); + vi.useRealTimers(); + await waitFor(() => expect(screen.getByText('Please enter a valid Zcash address')).toBeInTheDocument()); + expect(nextStep).not.toHaveBeenCalled(); + }); + + it('treats a wallet failure that is not about the address as a new recipient', async () => { + hasSentTo.mockRejectedValue(new Error('wallet is busy')); + const nextStep = renderInput(NEW); + await act(async () => { await vi.advanceTimersByTimeAsync(500); }); + expect(screen.getByText(NEW_RECIPIENT_HINT)).toBeInTheDocument(); + await act(async () => { fireEvent.click(screen.getByText('Continue')); }); + vi.useRealTimers(); + await waitFor(() => expect(nextStep).toHaveBeenCalled()); + }); + + it('still lets a never-sent-to address continue', async () => { + hasSentTo.mockResolvedValue(false); + const nextStep = renderInput(NEW); + await act(async () => { await vi.advanceTimersByTimeAsync(500); }); + await act(async () => { fireEvent.click(screen.getByText('Continue')); }); + vi.useRealTimers(); + await waitFor(() => expect(nextStep).toHaveBeenCalled()); + }); +}); diff --git a/packages/web-wallet/src/components/TransferCards/TransferInput.tsx b/packages/web-wallet/src/components/TransferCards/TransferInput.tsx index 9a280c7..25fe6d5 100644 --- a/packages/web-wallet/src/components/TransferCards/TransferInput.tsx +++ b/packages/web-wallet/src/components/TransferCards/TransferInput.tsx @@ -1,41 +1,120 @@ -import React, { useState } from 'react'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; import { TransferBalanceFormData, TransferBalanceFormHandleChange, } from '../../pages/TransferBalance/useTransferBalanceForm'; -import Input from '../Input/Input'; +import Input, { InputTone } from '../Input/Input'; import Button from '../Button/Button'; import useBalance from '../../hooks/useBalance'; +import { useWebZjsContext } from '../../context/WebzjsContext'; import { zecToZats, zatsToZec } from '../../utils/balance'; interface TransferInputProps { formData: TransferBalanceFormData; + /** Recipient the page was opened with (from "Send again"); shown as a known address */ + prefilledRecipient?: string; handleChange: TransferBalanceFormHandleChange; nextStep: () => void; } +/** What the wallet knows about the typed recipient. */ +type RecipientStatus = 'empty' | 'checking' | 'known' | 'new' | 'invalid'; + +const RECIPIENT_CHECK_DELAY_MS = 400; + +export const KNOWN_RECIPIENT_HINT = 'You have sent to this address before.'; +export const NEW_RECIPIENT_HINT = + 'You have never sent to this address from this wallet. Check it carefully before continuing.'; + +const recipientTone: Record = { + empty: 'default', + checking: 'default', + known: 'success', + new: 'warning', + invalid: 'default', +}; + +const recipientHint: Record = { + empty: undefined, + checking: undefined, + known: KNOWN_RECIPIENT_HINT, + new: NEW_RECIPIENT_HINT, + invalid: undefined, +}; + export function TransferInput({ - formData: { recipient, amount}, + formData: { recipient, amount }, + prefilledRecipient = '', nextStep, handleChange, }: TransferInputProps): React.JSX.Element { const { spendableBalance } = useBalance(); + const { state } = useWebZjsContext(); const [errors, setErrors] = useState({ recipient: '', - transactionType: '', amount: '', }); - const validateFields = () => { + // A prefilled recipient came from the wallet's own history, so it is known by construction. + const [recipientStatus, setRecipientStatus] = useState( + recipient && recipient === prefilledRecipient ? 'known' : 'empty', + ); + const latestCheck = useRef(0); + // Read through a ref so the check always sees the current wallet without the effect + // below restarting whenever the context re-renders. + const stateRef = useRef(state); + stateRef.current = state; + + const checkRecipient = useCallback(async (address: string): Promise => { + const { webWallet, activeAccount } = stateRef.current; + if (!address) return 'empty'; + if (!webWallet || activeAccount === null || activeAccount === undefined) return 'empty'; + try { + return (await webWallet.has_sent_to(activeAccount, address)) ? 'known' : 'new'; + } catch (error) { + // The wallet rejects a malformed address. Any other failure (worker busy, storage + // error) must not block a valid address, so it only loses the "known" hint. + const message = error instanceof Error ? error.message : String(error); + return /address/i.test(message) ? 'invalid' : 'new'; + } + }, []); + + // Re-check a little after the user stops typing. The prefilled address skips the check. + useEffect(() => { + if (recipient && recipient === prefilledRecipient) { + setRecipientStatus('known'); + return; + } + if (!recipient) { + setRecipientStatus('empty'); + return; + } + const check = ++latestCheck.current; + setRecipientStatus('checking'); + const timer = setTimeout(async () => { + const status = await checkRecipient(recipient); + if (check === latestCheck.current) setRecipientStatus(status); + }, RECIPIENT_CHECK_DELAY_MS); + return () => clearTimeout(timer); + }, [recipient, prefilledRecipient, checkRecipient]); + + const validateFields = async () => { const newErrors = { recipient: '', - transactionType: '', amount: '', }; if (!recipient) { newErrors.recipient = 'Please enter a valid address'; + } else { + // Settle a pending check now, rather than letting the user continue with a bad address. + const status = + recipientStatus === 'checking' ? await checkRecipient(recipient) : recipientStatus; + setRecipientStatus(status); + if (status === 'invalid') { + newErrors.recipient = 'Please enter a valid Zcash address'; + } } // Amount validation @@ -67,15 +146,14 @@ export function TransferInput({ return !Object.values(newErrors).some((error) => error !== ''); }; - const handleContinue = () => { - - if (validateFields()) nextStep(); + const handleContinue = async () => { + if (await validateFields()) nextStep(); }; return (
-
+
handleChange('recipient')(event)} /> @@ -109,4 +189,3 @@ export function TransferInput({
); } - diff --git a/packages/web-wallet/src/pages/TransferBalance/TransferBalance.tsx b/packages/web-wallet/src/pages/TransferBalance/TransferBalance.tsx index def4ac4..0232384 100644 --- a/packages/web-wallet/src/pages/TransferBalance/TransferBalance.tsx +++ b/packages/web-wallet/src/pages/TransferBalance/TransferBalance.tsx @@ -11,6 +11,7 @@ function TransferBalance(): React.JSX.Element { const { currentStep, formData, + prefilledRecipient, pcztTransferStatus, lastError, nextStep, @@ -44,6 +45,7 @@ function TransferBalance(): React.JSX.Element { {currentStep === TransferStep.INPUT && ( diff --git a/packages/web-wallet/src/pages/TransferBalance/useTransferBalanceForm.ts b/packages/web-wallet/src/pages/TransferBalance/useTransferBalanceForm.ts index 46c91b6..a81c71b 100644 --- a/packages/web-wallet/src/pages/TransferBalance/useTransferBalanceForm.ts +++ b/packages/web-wallet/src/pages/TransferBalance/useTransferBalanceForm.ts @@ -1,7 +1,13 @@ -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; +import { useLocation } from 'react-router-dom'; import { PcztTransferStatus, usePczt } from '../../hooks/usePCZT'; import { useWebZjsContext } from '../../context/WebzjsContext'; +/** Route state accepted by the Transfer Balance page, e.g. from "Send again" in the history. */ +export interface TransferBalanceRouteState { + recipient?: string; +} + export interface TransferBalanceFormData { amount: string; recipient: string; @@ -20,6 +26,8 @@ export type TransferBalanceFormHandleChange = ( export interface TransferBalanceFormType { currentStep: number; formData: TransferBalanceFormData; + /** The recipient the page was opened with, if it came from a previous transaction */ + prefilledRecipient: string; pcztTransferStatus: PcztTransferStatus; lastError: string | null; nextStep: () => void; @@ -37,12 +45,24 @@ export enum TransferStep { const useTransferBalanceForm = (): TransferBalanceFormType => { const { state } = useWebZjsContext(); const { handlePcztTransaction, pcztTransferStatus, lastError } = usePczt(); + const location = useLocation(); + const prefilledRecipient = + (location.state as TransferBalanceRouteState | null)?.recipient ?? ''; const [currentStep, setCurrentStep] = useState(0); const [formData, setFormData] = useState({ amount: '', - recipient: '', + recipient: prefilledRecipient, }); + // A later "Send again" while this page is already mounted replaces the recipient + // and starts the form over. + useEffect(() => { + if (prefilledRecipient) { + setFormData({ amount: '', recipient: prefilledRecipient }); + setCurrentStep(TransferStep.INPUT); + } + }, [prefilledRecipient, location.key]); + const nextStep = () => setCurrentStep((prev) => prev + 1); const handleChange: TransferBalanceFormHandleChange = (input) => (e) => { @@ -71,6 +91,7 @@ const useTransferBalanceForm = (): TransferBalanceFormType => { return { currentStep, formData, + prefilledRecipient, pcztTransferStatus, lastError, nextStep, diff --git a/packages/web-wallet/src/types/transaction.ts b/packages/web-wallet/src/types/transaction.ts index 0143e5f..ace383b 100644 --- a/packages/web-wallet/src/types/transaction.ts +++ b/packages/web-wallet/src/types/transaction.ts @@ -12,6 +12,8 @@ export interface TransactionHistoryEntry { memo: string | null; timestamp: number | null; pool: string; + /** Encoded addresses of the external recipients; empty unless funds left the wallet */ + recipients: string[]; } export interface TransactionHistoryResponse { From cd8b3d56656b63a8b8bacae6d5eaddb79b552863 Mon Sep 17 00:00:00 2001 From: sqhell Date: Sun, 18 Oct 2026 16:05:29 -0600 Subject: [PATCH 3/3] feat(web-wallet): point to Full Resync from the end of the transaction history The history lists only what the wallet has scanned since its sync start block, and nothing on the page said so. Someone whose wallet was synced from a recent block saw a short list and no way to get the rest. Add a note under the list, also in the empty state, saying that older transactions need a Full Resync from an earlier block, with a link to the Account Summary tab where that control lives. --- .../TransactionHistory.test.tsx | 36 +++++++++++++++++-- .../TransactionHistory/TransactionHistory.tsx | 17 +++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx index 978808b..bac5307 100644 --- a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx +++ b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.test.tsx @@ -1,7 +1,7 @@ -import { describe, it, expect, vi } from 'vitest'; +import { beforeEach, describe, it, expect, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; -import TransactionHistory from './TransactionHistory'; +import TransactionHistory, { OLDER_HISTORY_HINT } from './TransactionHistory'; import type { TransactionHistoryEntry } from '../../types/transaction'; const base: TransactionHistoryEntry = { @@ -18,12 +18,15 @@ const base: TransactionHistoryEntry = { recipients: ['u1recipientaddressthatislongenoughtobeshortened'], }; -const transactions: TransactionHistoryEntry[] = [ +const sample: TransactionHistoryEntry[] = [ base, { ...base, txid: 'cd'.repeat(32), tx_type: 'Received', value: 500_000, recipients: [] }, { ...base, txid: 'ef'.repeat(32), tx_type: 'Shielded', value: 200_000, pool: 'mixed', recipients: [] }, ]; +// Reassigned per test so the empty state can be exercised with the same mock. +let transactions: TransactionHistoryEntry[] = sample; + vi.mock('../../hooks/useTransactionHistory', () => ({ useTransactionHistory: () => ({ transactions, @@ -36,6 +39,10 @@ vi.mock('../../hooks/useTransactionHistory', () => ({ }), })); +beforeEach(() => { + transactions = sample; +}); + describe('TransactionHistory repeat links', () => { it('offers Send again for a sent transaction, with the recipient in the link state', () => { render( @@ -58,3 +65,26 @@ describe('TransactionHistory repeat links', () => { expect(screen.getAllByText(/again$/)).toHaveLength(2); }); }); + +describe('TransactionHistory older-history hint', () => { + it('points to Full Resync on the Account Summary tab under the list', () => { + render( + + + , + ); + expect(screen.getByText(new RegExp(OLDER_HISTORY_HINT))).toBeInTheDocument(); + expect(screen.getByText('Account Summary')).toHaveAttribute('href', '/dashboard/account-summary'); + }); + + it('shows the hint in the empty state as well', () => { + transactions = []; + render( + + + , + ); + expect(screen.getByText(/No transactions found/)).toBeInTheDocument(); + expect(screen.getByText('Account Summary')).toHaveAttribute('href', '/dashboard/account-summary'); + }); +}); diff --git a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx index 21979ec..c3c9fcc 100644 --- a/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx +++ b/packages/web-wallet/src/components/TransactionHistory/TransactionHistory.tsx @@ -50,6 +50,10 @@ function shortAddress(address: string): string { return address.length > 24 ? `${address.slice(0, 12)}…${address.slice(-8)}` : address; } +/** Shown under the list: the wallet only knows transactions since its sync start block. */ +export const OLDER_HISTORY_HINT = + 'Only transactions since the sync start block are shown. To see older ones, run Full Resync from an earlier block on the'; + /** The repeat action for a row: send to the same recipient again, or shield again. */ function RepeatLink({ transaction }: TransactionRowProps) { const linkClass = @@ -204,6 +208,19 @@ function TransactionHistory() {
)} + + {!loading && ( +

+ {OLDER_HISTORY_HINT}{' '} + + Account Summary + {' '} + tab. +

+ )}
); }