zcash_client_backend/data_api/defaults.rs
1//! Reference implementations of [`WalletRead`] and [`WalletWrite`] trait methods.
2//!
3//! This module provides standalone free functions that implement the canonical semantics of
4//! selected trait methods in terms of other, more primitive operations. Wallet backend authors
5//! who do not have a more efficient implementation available can delegate the corresponding
6//! trait method to the function provided here; backends that can do better (e.g. via an
7//! indexed database lookup) should implement the trait method directly.
8//!
9//! [`WalletRead`]: super::WalletRead
10//! [`WalletWrite`]: super::WalletWrite
11
12use ::transparent::address::TransparentAddress;
13use zcash_keys::address::{Address, UnifiedAddress};
14use zcash_protocol::consensus;
15
16use super::{Account, WalletRead, error::FindAccountForAddressError};
17
18/// Returns `true` if `address` contains any receiver that matches one of the receivers of the
19/// given [`UnifiedAddress`].
20pub fn address_receiver_matches_ua<P: consensus::Parameters>(
21 address: &Address,
22 ua: &UnifiedAddress,
23 params: &P,
24) -> bool {
25 let zcash_address = address.to_zcash_address(params);
26 ua.as_understood_receivers()
27 .iter()
28 .any(|r| r.corresponds(&zcash_address))
29}
30
31/// Reference implementation of [`WalletRead::find_account_for_address`].
32///
33/// A TEX address is looked up as the P2PKH address that has the same public key hash.
34///
35/// Any address whose shielded component can be represented as a [`UnifiedAddress`] — either
36/// directly, or by synthesizing a single-receiver UA around a bare Sapling address — is
37/// first resolved via UIVK algebra: each account's
38/// [`UnifiedIncomingViewingKey::decrypt_diversifiers`] is asked whether it could have derived
39/// any shielded receiver of the (possibly synthesized) UA. An account matches if at least
40/// one shielded receiver is attributable to it, which finds addresses the account could
41/// produce even if they have never been exposed. If more than one account matches,
42/// [`FindAccountForAddressError::UnifiedAddressConflict`] is returned.
43///
44/// If the algebraic step does not resolve a match (or the address has no shielded receiver,
45/// as is the case for transparent and TEX addresses), this falls back to a linear scan over
46/// each account's tracked addresses via [`WalletRead::list_addresses`], returning the first
47/// account that holds a matching address (as an exact match, or as a receiver embedded in a
48/// stored UA).
49///
50/// Backends that can answer this query more efficiently (e.g. via an indexed database
51/// lookup) should implement [`WalletRead::find_account_for_address`] directly rather than
52/// delegating to this function.
53///
54/// See [`WalletRead::find_account_for_address`] for the semantics of the return value.
55///
56/// [`UnifiedIncomingViewingKey`]: zcash_keys::keys::UnifiedIncomingViewingKey
57/// [`UnifiedIncomingViewingKey::decrypt_diversifiers`]: zcash_keys::keys::UnifiedIncomingViewingKey::decrypt_diversifiers
58pub fn find_account_for_address<W: WalletRead, P: consensus::Parameters>(
59 wallet: &W,
60 params: &P,
61 address: &Address,
62) -> Result<Option<W::AccountId>, FindAccountForAddressError<W::Error>> {
63 // A TEX address holds the public key hash of a P2PKH address. Wallets track the P2PKH
64 // address, so that is the address to look up.
65 let p2pkh_address;
66 let address = match address {
67 Address::Tex(pubkey_hash) => {
68 p2pkh_address = Address::Transparent(TransparentAddress::PublicKeyHash(*pubkey_hash));
69 &p2pkh_address
70 }
71 _ => address,
72 };
73
74 // Promote bare shielded addresses to a synthesized single-receiver UA so that every
75 // address with a shielded component is resolved through the same UIVK algebra. The
76 // synthesized UA is owned by this local binding; `shielded_ua` borrows from either the
77 // original address or this binding.
78 let synthesized_ua;
79 let shielded_ua: Option<&UnifiedAddress> = match address {
80 Address::Unified(ua) => Some(ua),
81 Address::Sapling(pa) => {
82 synthesized_ua = UnifiedAddress::from_receivers(
83 #[cfg(feature = "orchard")]
84 None,
85 Some(**pa),
86 None,
87 None,
88 None,
89 );
90 synthesized_ua.as_ref()
91 }
92 Address::Transparent(_) | Address::Tex(_) => None,
93 };
94
95 if let Some(ua) = shielded_ua {
96 let mut found_acc_id: Option<W::AccountId> = None;
97 for acc_id in wallet.get_account_ids()? {
98 let Some(account) = wallet.get_account(acc_id)? else {
99 continue;
100 };
101 if !account.uivk().decrypt_diversifiers(ua).is_empty() {
102 match found_acc_id {
103 None => found_acc_id = Some(acc_id),
104 Some(prev) if prev == acc_id => {}
105 Some(_) => return Err(FindAccountForAddressError::UnifiedAddressConflict),
106 }
107 }
108 }
109 if found_acc_id.is_some() {
110 return Ok(found_acc_id);
111 }
112 }
113
114 // Fall back to a linear scan over each account's tracked addresses. This handles
115 // addresses with no shielded component (transparent and TEX) as well as UAs whose
116 // shielded receivers are not derivable from any account's UIVK but whose transparent
117 // receiver matches a stored address.
118 let zcash_address = address.to_zcash_address(params);
119 for acc_id in wallet.get_account_ids()? {
120 for addr_info in wallet.list_addresses(acc_id)? {
121 let stored = addr_info.address();
122 if stored == address {
123 return Ok(Some(acc_id));
124 }
125 if let Address::Unified(stored_ua) = stored
126 && stored_ua
127 .as_understood_receivers()
128 .iter()
129 .any(|r| r.corresponds(&zcash_address))
130 {
131 return Ok(Some(acc_id));
132 }
133 }
134 }
135 Ok(None)
136}