zcash_client_backend/data_api.rs
1//! # Utilities for Zcash wallet construction
2//!
3//! This module defines a set of APIs for wallet data persistence, and provides a suite of methods
4//! based upon these APIs that can be used to implement a fully functional Zcash wallet. At
5//! present, the interfaces provided here are built primarily around the use of a source of
6//! [`CompactBlock`] data such as the Zcash Light Client Protocol as defined in
7//! [ZIP 307](https://zips.z.cash/zip-0307) but they may be generalized to full-block use cases in
8//! the future.
9//!
10//! ## Important Concepts
11//!
12//! There are several important operations that a Zcash wallet must perform that distinguish Zcash
13//! wallet design from wallets for other cryptocurrencies.
14//!
15//! * Viewing Keys: Wallets based upon this module are built around the capabilities of Zcash
16//! [`UnifiedFullViewingKey`]s; the wallet backend provides no facilities for the storage
17//! of spending keys, and spending keys must be provided by the caller (or delegated to external
18//! devices via the provided [`pczt`] functionality) in order to perform transaction creation
19//! operations.
20//! * Blockchain Scanning: A Zcash wallet must download and trial-decrypt each transaction on the
21//! Zcash blockchain using one or more Viewing Keys in order to find new shielded transaction
22//! outputs (generally termed "notes") belonging to the wallet. The primary entrypoint for this
23//! functionality is the [`scan_cached_blocks`] method. See the [`chain`] module for additional
24//! details.
25//! * Witness Updates: In order to spend a shielded note, the wallet must be able to compute the
26//! Merkle path to that note in the global note commitment tree. When [`scan_cached_blocks`] is
27//! used to process a range of blocks, the note commitment tree is updated with the note
28//! commitments for the blocks in that range.
29//! * Transaction Construction: The [`wallet`] module provides functions for creating Zcash
30//! transactions that spend funds belonging to the wallet. Input selection for transaction
31//! construction is performed automatically. When spending funds received at transparent
32//! addresses, the caller is required to explicitly specify the set of addresses from which to
33//! spend funds, in order to prevent inadvertent commingling of funds received at different
34//! addresses; allowing such commingling would enable chain observers to identify those
35//! addresses as belonging to the same user.
36//!
37//! ## Core Traits
38//!
39//! The utility functions described above depend upon four important traits defined in this
40//! module, which between them encompass the data storage requirements of a light wallet.
41//! The relevant traits are [`InputSource`], [`WalletRead`], [`WalletWrite`], and
42//! [`WalletCommitmentTrees`]. A complete implementation of the data storage layer for a wallet
43//! will include an implementation of all four of these traits. See the [`zcash_client_sqlite`]
44//! crate for a complete example of the implementation of these traits.
45//!
46//! ## Accounts
47//!
48//! The operation of the [`InputSource`], [`WalletRead`] and [`WalletWrite`] traits is built around
49//! the concept of a wallet having one or more accounts, with a unique `AccountId` for each
50//! account.
51//!
52//! An account identifier corresponds to at most a single [`UnifiedSpendingKey`]'s worth of spend
53//! authority, with the received and spent notes of that account tracked via the corresponding
54//! [`UnifiedFullViewingKey`]. Both received notes and change spendable by that spending authority
55//! (both the external and internal parts of that key, as defined by
56//! [ZIP 316](https://zips.z.cash/zip-0316)) will be interpreted as belonging to that account.
57//!
58//! [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
59//! [`scan_cached_blocks`]: crate::data_api::chain::scan_cached_blocks
60//! [`zcash_client_sqlite`]: https://docs.rs/zcash_client_sqlite
61//! [`TransactionRequest`]: crate::zip321::TransactionRequest
62//! [`propose_shielding`]: crate::data_api::wallet::propose_shielding
63//! [`pczt`]: https://docs.rs/pczt
64
65use nonempty::NonEmpty;
66use secrecy::SecretVec;
67use std::{
68 collections::{HashMap, HashSet},
69 fmt::{self, Debug},
70 hash::Hash,
71 io,
72 num::{NonZeroU32, TryFromIntError},
73};
74
75use incrementalmerkletree::{Retention, frontier::Frontier};
76use shardtree::{ShardTree, error::ShardTreeError, store::ShardStore};
77
78use zcash_keys::{
79 address::{Address, UnifiedAddress},
80 keys::{
81 UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedIncomingViewingKey, UnifiedSpendingKey,
82 },
83};
84use zcash_primitives::{block::BlockHash, transaction::Transaction};
85use zcash_protocol::{
86 PoolType, ShieldedPool, TxId,
87 consensus::{self, BlockHeight, TxIndex},
88 memo::{Memo, MemoBytes},
89 value::{BalanceError, Zatoshis},
90};
91use zip32::{DiversifierIndex, fingerprint::SeedFingerprint};
92
93use self::{
94 chain::{ChainState, CommitmentTreeRoot},
95 scanning::{ScanPriority, ScanRange},
96};
97use crate::{
98 data_api::{
99 error::RewindError,
100 wallet::{ConfirmationsPolicy, TargetHeight, input_selection::LockFilter},
101 },
102 decrypt::DecryptedOutput,
103 proto::service::TreeState,
104 wallet::{Note, NoteId, ReceivedNote, Recipient, WalletTransparentOutput, WalletTx},
105};
106
107#[cfg(feature = "transparent-inputs")]
108use {
109 crate::{fees::StandardFeeRule, wallet::TransparentAddressMetadata},
110 getset::{CopyGetters, Getters},
111 std::time::SystemTime,
112 transparent::{address::TransparentAddress, bundle::OutPoint, keys::TransparentKeyScope},
113};
114
115#[cfg(all(
116 feature = "transparent-inputs",
117 any(test, feature = "test-dependencies")
118))]
119use {std::ops::Range, transparent::keys::NonHardenedChildIndex};
120
121#[cfg(feature = "zcashd-compat")]
122use zcash_keys::keys::zcashd;
123
124#[cfg(feature = "test-dependencies")]
125use ambassador::delegatable_trait;
126
127#[cfg(any(test, feature = "test-dependencies"))]
128use zcash_protocol::consensus::NetworkUpgrade;
129
130pub mod anchor_retention;
131pub mod chain;
132pub mod defaults;
133pub mod error;
134pub mod ll;
135pub mod locking;
136pub use locking::OutputLockStore;
137#[cfg(feature = "test-dependencies")]
138pub use locking::ambassador_impl_OutputLockStore;
139pub mod scanning;
140pub mod wallet;
141#[cfg(feature = "orchard")]
142pub mod zip318;
143
144#[cfg(any(test, feature = "test-dependencies"))]
145pub mod testing;
146
147/// The origin of a transparent address within a wallet.
148#[cfg(feature = "transparent-inputs")]
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum TransparentKeyOrigin {
151 /// The address was imported standalone (no HD derivation scope).
152 Imported,
153 /// The address was derived from the account's HD key tree.
154 Derived { scope: TransparentKeyScope },
155}
156
157/// A mapping from transparent addresses to their key origin and balance.
158#[cfg(feature = "transparent-inputs")]
159pub type TransparentBalances = HashMap<TransparentAddress, (TransparentKeyOrigin, Balance)>;
160
161/// The height of subtree roots in the Sapling note commitment tree.
162///
163/// This conforms to the structure of subtree data returned by
164/// `lightwalletd` when using the `GetSubtreeRoots` GRPC call.
165pub const SAPLING_SHARD_HEIGHT: u8 = sapling::NOTE_COMMITMENT_TREE_DEPTH / 2;
166
167/// The height of subtree roots in the Orchard note commitment tree.
168///
169/// This conforms to the structure of subtree data returned by
170/// `lightwalletd` when using the `GetSubtreeRoots` GRPC call.
171#[cfg(feature = "orchard")]
172pub const ORCHARD_SHARD_HEIGHT: u8 = { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 } / 2;
173
174/// The height of subtree roots in the Ironwood note commitment tree.
175///
176/// This conforms to the structure of subtree data returned by
177/// `lightwalletd` when using the `GetSubtreeRoots` GRPC call.
178#[cfg(feature = "orchard")]
179pub const IRONWOOD_SHARD_HEIGHT: u8 = { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 } / 2;
180
181/// An enumeration of constraints that can be applied when querying for nullifiers for notes
182/// belonging to the wallet.
183pub enum NullifierQuery {
184 Unspent,
185 All,
186}
187
188/// An intent of representing spendable value to reach a certain targeted
189/// amount.
190///
191/// `AtLeast(Zatoshis)` refers to the amount of `Zatoshis` that can cover
192/// at minimum the given zatoshis that is conformed by the sum of spendable notes.
193///
194///
195/// Discussion: why not just use ``Zatoshis``?
196///
197/// the `Zatoshis` value isn't enough to explain intent when seeking to match a
198/// given a given amount. Is the value expressed in `Zatoshis` the ceiling value
199/// or the minimum value of a given spend intent? How would you express that the
200/// value spend intent is "as much as possible" without knowing the value upfront?
201#[derive(Debug, Clone, Copy)]
202pub enum TargetValue {
203 AtLeast(Zatoshis),
204 AllFunds(MaxSpendMode),
205}
206
207/// Specifies how an TargetValue::AllFunds should be evaluated
208#[derive(Debug, Clone, Copy)]
209pub enum MaxSpendMode {
210 /// `MaxSpendable` will target to spend all _currently_ spendable funds where it
211 /// could be the case that the wallet has received other funds that are not
212 /// confirmed and therefore not spendable yet and the caller evaluates that as
213 /// an acceptable scenario.
214 MaxSpendable,
215 /// `Everything` will target to spend **all funds** and will fail if there are
216 /// unspendable funds in the wallet or if the wallet is not yet synced.
217 Everything,
218}
219/// Balance information for a value within a single pool in an account.
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub struct Balance {
222 spendable_value: Zatoshis,
223 locked_value: Zatoshis,
224 change_pending_confirmation: Zatoshis,
225 value_pending_spendability: Zatoshis,
226 uneconomic_value: Zatoshis,
227}
228
229impl Balance {
230 /// The [`Balance`] value having zero values for all its fields.
231 pub const ZERO: Self = Self {
232 spendable_value: Zatoshis::ZERO,
233 locked_value: Zatoshis::ZERO,
234 change_pending_confirmation: Zatoshis::ZERO,
235 value_pending_spendability: Zatoshis::ZERO,
236 uneconomic_value: Zatoshis::ZERO,
237 };
238
239 fn check_total_adding(&self, value: Zatoshis) -> Result<Zatoshis, BalanceError> {
240 (self.spendable_value
241 + self.locked_value
242 + self.change_pending_confirmation
243 + self.value_pending_spendability
244 + value)
245 .ok_or(BalanceError::Overflow)
246 }
247
248 /// Returns the value in the account that may currently be spent; it is possible to compute
249 /// witnesses for all the notes that comprise this value, and all of this value is confirmed to
250 /// the required confirmation depth.
251 pub fn spendable_value(&self) -> Zatoshis {
252 self.spendable_value
253 }
254
255 /// Returns the value in the account that is currently "locked".
256 ///
257 /// The outputs that comprise this balance are seen by the wallet as being committed to be
258 /// spent by a transaction proposal or PCZT.
259 pub fn locked_value(&self) -> Zatoshis {
260 self.locked_value
261 }
262
263 /// Adds the specified value to the spendable total, checking for overflow.
264 pub fn add_spendable_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
265 self.check_total_adding(value)?;
266 self.spendable_value = (self.spendable_value + value).unwrap();
267 Ok(())
268 }
269
270 /// Adds the specified value to the locked total, checking for overflow.
271 pub fn add_locked_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
272 self.check_total_adding(value)?;
273 self.locked_value = (self.locked_value + value).unwrap();
274 Ok(())
275 }
276
277 /// Returns the value in the account of shielded change notes that do not yet have sufficient
278 /// confirmations to be spendable.
279 pub fn change_pending_confirmation(&self) -> Zatoshis {
280 self.change_pending_confirmation
281 }
282
283 /// Adds the specified value to the pending change total, checking for overflow.
284 pub fn add_pending_change_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
285 self.check_total_adding(value)?;
286 self.change_pending_confirmation = (self.change_pending_confirmation + value).unwrap();
287 Ok(())
288 }
289
290 /// Returns the value in the account of all remaining received notes that either do not have
291 /// sufficient confirmations to be spendable, or for which witnesses cannot yet be constructed
292 /// without additional scanning.
293 pub fn value_pending_spendability(&self) -> Zatoshis {
294 self.value_pending_spendability
295 }
296
297 /// Adds the specified value to the pending spendable total, checking for overflow.
298 pub fn add_pending_spendable_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
299 self.check_total_adding(value)?;
300 self.value_pending_spendability = (self.value_pending_spendability + value).unwrap();
301 Ok(())
302 }
303
304 /// Returns the value in the account of notes that have value less than or equal to the marginal
305 /// fee, and consequently cannot be spent except as a grace input.
306 pub fn uneconomic_value(&self) -> Zatoshis {
307 self.uneconomic_value
308 }
309
310 /// Adds the specified value to the uneconomic value total, checking for overflow.
311 pub fn add_uneconomic_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
312 self.uneconomic_value = (self.uneconomic_value + value).ok_or(BalanceError::Overflow)?;
313 Ok(())
314 }
315
316 /// Returns the total value of funds represented by this [`Balance`].
317 pub fn total(&self) -> Zatoshis {
318 (self.spendable_value
319 + self.locked_value
320 + self.change_pending_confirmation
321 + self.value_pending_spendability)
322 .expect("Balance cannot overflow MAX_MONEY")
323 }
324}
325
326impl core::ops::Add<Balance> for Balance {
327 type Output = Result<Balance, BalanceError>;
328
329 fn add(self, rhs: Balance) -> Self::Output {
330 let result = Balance {
331 spendable_value: (self.spendable_value + rhs.spendable_value)
332 .ok_or(BalanceError::Overflow)?,
333 locked_value: (self.locked_value + rhs.locked_value).ok_or(BalanceError::Overflow)?,
334 change_pending_confirmation: (self.change_pending_confirmation
335 + rhs.change_pending_confirmation)
336 .ok_or(BalanceError::Overflow)?,
337 value_pending_spendability: (self.value_pending_spendability
338 + rhs.value_pending_spendability)
339 .ok_or(BalanceError::Overflow)?,
340 uneconomic_value: (self.uneconomic_value + rhs.uneconomic_value)
341 .ok_or(BalanceError::Overflow)?,
342 };
343
344 result.check_total_adding(Zatoshis::ZERO)?;
345
346 Ok(result)
347 }
348}
349
350/// Balance information for a single account. The sum of this struct's fields is the total balance
351/// of the wallet.
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
353pub struct AccountBalance {
354 sapling_balance: Balance,
355 orchard_balance: Balance,
356 ironwood_balance: Balance,
357 unshielded_regular_balance: Balance,
358 unshielded_coinbase_balance: Balance,
359}
360
361impl AccountBalance {
362 /// The [`Balance`] value having zero values for all its fields.
363 pub const ZERO: Self = Self {
364 sapling_balance: Balance::ZERO,
365 orchard_balance: Balance::ZERO,
366 ironwood_balance: Balance::ZERO,
367 unshielded_regular_balance: Balance::ZERO,
368 unshielded_coinbase_balance: Balance::ZERO,
369 };
370
371 fn check_total(&self) -> Result<Zatoshis, BalanceError> {
372 (self.sapling_balance.total()
373 + self.orchard_balance.total()
374 + self.ironwood_balance.total()
375 + self.unshielded_regular_balance.total()
376 + self.unshielded_coinbase_balance.total())
377 .ok_or(BalanceError::Overflow)
378 }
379
380 /// Returns the [`Balance`] of Sapling funds in the account.
381 pub fn sapling_balance(&self) -> &Balance {
382 &self.sapling_balance
383 }
384
385 /// Provides a mutable reference to the [`Balance`] of Sapling funds in the account
386 /// to the specified callback, checking invariants after the callback's action has been
387 /// evaluated.
388 pub fn with_sapling_balance_mut<A, E: From<BalanceError>>(
389 &mut self,
390 f: impl FnOnce(&mut Balance) -> Result<A, E>,
391 ) -> Result<A, E> {
392 let result = f(&mut self.sapling_balance)?;
393 self.check_total()?;
394 Ok(result)
395 }
396
397 /// Returns the [`Balance`] of Orchard funds in the account.
398 pub fn orchard_balance(&self) -> &Balance {
399 &self.orchard_balance
400 }
401
402 /// Provides a mutable reference to the [`Balance`] of Orchard funds in the account
403 /// to the specified callback, checking invariants after the callback's action has been
404 /// evaluated.
405 pub fn with_orchard_balance_mut<A, E: From<BalanceError>>(
406 &mut self,
407 f: impl FnOnce(&mut Balance) -> Result<A, E>,
408 ) -> Result<A, E> {
409 let result = f(&mut self.orchard_balance)?;
410 self.check_total()?;
411 Ok(result)
412 }
413
414 /// Returns the [`Balance`] of Ironwood funds in the account.
415 pub fn ironwood_balance(&self) -> &Balance {
416 &self.ironwood_balance
417 }
418
419 /// Provides a mutable reference to the [`Balance`] of Ironwood funds in the account
420 /// to the specified callback, checking invariants after the callback's action has been
421 /// evaluated.
422 pub fn with_ironwood_balance_mut<A, E: From<BalanceError>>(
423 &mut self,
424 f: impl FnOnce(&mut Balance) -> Result<A, E>,
425 ) -> Result<A, E> {
426 let result = f(&mut self.ironwood_balance)?;
427 self.check_total()?;
428 Ok(result)
429 }
430
431 /// Returns the total value of unspent transparent transaction outputs belonging to the wallet.
432 #[deprecated(
433 note = "this function is deprecated. Please use [`AccountBalance::unshielded_regular_balance`] and [`AccountBalance::unshielded_coinbase_balance`] instead."
434 )]
435 pub fn unshielded(&self) -> Zatoshis {
436 (self.unshielded_regular_balance.total() + self.unshielded_coinbase_balance.total())
437 .expect("Account balance cannot overflow MAX_MONEY")
438 }
439
440 /// Returns the combined [`Balance`] of unshielded funds in the account, computed as the sum
441 /// of the [`unshielded_regular_balance`] and the [`unshielded_coinbase_balance`].
442 ///
443 /// The [`spendable_value`] field of the returned [`Balance`] contains funds that may be spent
444 /// in a shielding transaction: transparent funds that satisfy the wallet's confirmation
445 /// policy, including coinbase funds that have reached maturity. The
446 /// [`value_pending_spendability`] field contains transparent funds that are not yet
447 /// spendable: funds that do not yet have the number of confirmations required by the
448 /// wallet's confirmation policy, and coinbase funds that have not yet reached maturity. The
449 /// [`change_pending_confirmation`] field is currently always zero, because this crate does
450 /// not yet distinguish transparent change from other transparent value awaiting
451 /// confirmation.
452 ///
453 /// [`unshielded_regular_balance`]: AccountBalance::unshielded_regular_balance
454 /// [`unshielded_coinbase_balance`]: AccountBalance::unshielded_coinbase_balance
455 /// [`spendable_value`]: Balance::spendable_value
456 /// [`change_pending_confirmation`]: Balance::change_pending_confirmation
457 /// [`value_pending_spendability`]: Balance::value_pending_spendability
458 pub fn unshielded_balance(&self) -> Balance {
459 (self.unshielded_regular_balance + self.unshielded_coinbase_balance)
460 .expect("Account balance cannot overflow MAX_MONEY")
461 }
462
463 /// Returns the [`Balance`] of regular (non-coinbase) transparent funds in the account.
464 ///
465 /// Transparent outputs whose containing transaction's index within its block is unknown are
466 /// classified as regular (non-coinbase) funds, consistent with the treatment described for
467 /// `CoinbaseFilter`.
468 pub fn unshielded_regular_balance(&self) -> &Balance {
469 &self.unshielded_regular_balance
470 }
471
472 /// Provides a mutable reference to the [`Balance`] of regular (non-coinbase) transparent
473 /// funds in the account to the specified callback, checking invariants after the callback's
474 /// action has been evaluated.
475 pub fn with_unshielded_regular_balance_mut<A, E: From<BalanceError>>(
476 &mut self,
477 f: impl FnOnce(&mut Balance) -> Result<A, E>,
478 ) -> Result<A, E> {
479 let result = f(&mut self.unshielded_regular_balance)?;
480 self.check_total()?;
481 Ok(result)
482 }
483
484 /// Returns the [`Balance`] of funds in coinbase transparent outputs belonging to the
485 /// account.
486 ///
487 /// Coinbase outputs may only be spent by shielding them, and only once they have reached
488 /// coinbase maturity; immature coinbase funds are reported in the
489 /// [`value_pending_spendability`] field of the returned [`Balance`]. Outputs whose
490 /// containing transaction's index within its block is unknown are conservatively classified
491 /// as regular (non-coinbase) funds and do not contribute to this balance; see
492 /// `CoinbaseFilter`.
493 ///
494 /// [`value_pending_spendability`]: Balance::value_pending_spendability
495 pub fn unshielded_coinbase_balance(&self) -> &Balance {
496 &self.unshielded_coinbase_balance
497 }
498
499 /// Provides a mutable reference to the [`Balance`] of transparent coinbase funds in the
500 /// account to the specified callback, checking invariants after the callback's action has
501 /// been evaluated.
502 pub fn with_unshielded_coinbase_balance_mut<A, E: From<BalanceError>>(
503 &mut self,
504 f: impl FnOnce(&mut Balance) -> Result<A, E>,
505 ) -> Result<A, E> {
506 let result = f(&mut self.unshielded_coinbase_balance)?;
507 self.check_total()?;
508 Ok(result)
509 }
510
511 /// Returns the total value of economically relevant notes and UTXOs belonging to the account.
512 pub fn total(&self) -> Zatoshis {
513 (self.sapling_balance.total()
514 + self.orchard_balance.total()
515 + self.ironwood_balance.total()
516 + self.unshielded_regular_balance.total()
517 + self.unshielded_coinbase_balance.total())
518 .expect("Account balance cannot overflow MAX_MONEY")
519 }
520
521 /// Returns the total value of shielded (Sapling, Orchard, and Ironwood) funds that may
522 /// immediately be spent.
523 pub fn spendable_value(&self) -> Zatoshis {
524 (self.sapling_balance.spendable_value
525 + self.orchard_balance.spendable_value
526 + self.ironwood_balance.spendable_value)
527 .expect("Account balance cannot overflow MAX_MONEY")
528 }
529
530 /// Returns the total value of notes and UTXOs that are locked, having been committed to
531 /// an in-flight transaction proposal or PCZT.
532 pub fn locked_value(&self) -> Zatoshis {
533 (self.sapling_balance.locked_value()
534 + self.orchard_balance.locked_value()
535 + self.ironwood_balance.locked_value()
536 + self.unshielded_regular_balance.locked_value()
537 + self.unshielded_coinbase_balance.locked_value())
538 .expect("Account balance cannot overflow MAX_MONEY")
539 }
540
541 /// Returns the total value of change and/or shielding transaction outputs that are awaiting
542 /// sufficient confirmations for spendability.
543 pub fn change_pending_confirmation(&self) -> Zatoshis {
544 (self.sapling_balance.change_pending_confirmation
545 + self.orchard_balance.change_pending_confirmation
546 + self.ironwood_balance.change_pending_confirmation)
547 .expect("Account balance cannot overflow MAX_MONEY")
548 }
549
550 /// Returns the value of shielded funds that are not yet spendable because additional scanning
551 /// is required before it will be possible to derive witnesses for the associated notes.
552 pub fn value_pending_spendability(&self) -> Zatoshis {
553 (self.sapling_balance.value_pending_spendability
554 + self.orchard_balance.value_pending_spendability
555 + self.ironwood_balance.value_pending_spendability)
556 .expect("Account balance cannot overflow MAX_MONEY")
557 }
558
559 /// Returns the value in the account of notes and transparent UTXOs that have value less than
560 /// the marginal fee, and consequently cannot be spent except as a grace input.
561 pub fn uneconomic_value(&self) -> Zatoshis {
562 (self.sapling_balance.uneconomic_value
563 + self.orchard_balance.uneconomic_value
564 + self.ironwood_balance.uneconomic_value
565 + self.unshielded_regular_balance.uneconomic_value
566 + self.unshielded_coinbase_balance.uneconomic_value)
567 .expect("Account balance cannot overflow MAX_MONEY")
568 }
569}
570
571/// Source metadata for a ZIP 32-derived key.
572#[derive(Clone, Debug, PartialEq, Eq, Hash)]
573pub struct Zip32Derivation {
574 seed_fingerprint: SeedFingerprint,
575 account_index: zip32::AccountId,
576 #[cfg(feature = "zcashd-compat")]
577 legacy_address_index: Option<zcashd::LegacyAddressIndex>,
578}
579
580impl Zip32Derivation {
581 /// Constructs new derivation metadata from its constituent parts.
582 pub fn new(
583 seed_fingerprint: SeedFingerprint,
584 account_index: zip32::AccountId,
585 #[cfg(feature = "zcashd-compat")] legacy_address_index: Option<zcashd::LegacyAddressIndex>,
586 ) -> Self {
587 Self {
588 seed_fingerprint,
589 account_index,
590 #[cfg(feature = "zcashd-compat")]
591 legacy_address_index,
592 }
593 }
594
595 /// Returns the seed fingerprint.
596 pub fn seed_fingerprint(&self) -> &SeedFingerprint {
597 &self.seed_fingerprint
598 }
599
600 /// Returns the account-level index in the ZIP 32 derivation path.
601 pub fn account_index(&self) -> zip32::AccountId {
602 self.account_index
603 }
604
605 #[cfg(feature = "zcashd-compat")]
606 pub fn legacy_address_index(&self) -> Option<zcashd::LegacyAddressIndex> {
607 self.legacy_address_index
608 }
609}
610
611/// An enumeration used to control what information is tracked by the wallet for
612/// notes received by a given account.
613#[derive(Clone, Debug, PartialEq, Eq, Hash)]
614pub enum AccountPurpose {
615 /// For spending accounts, the wallet will track information needed to spend
616 /// received notes.
617 Spending { derivation: Option<Zip32Derivation> },
618 /// For view-only accounts, the wallet will not track spend information.
619 ViewOnly,
620}
621
622/// The kinds of accounts supported by `zcash_client_backend`.
623#[derive(Clone, Debug, PartialEq, Eq, Hash)]
624pub enum AccountSource {
625 /// An account derived from a known seed.
626 Derived {
627 derivation: Zip32Derivation,
628 key_source: Option<String>,
629 },
630
631 /// An account imported from a viewing key.
632 Imported {
633 purpose: AccountPurpose,
634 key_source: Option<String>,
635 },
636}
637
638impl AccountSource {
639 /// Returns the key derivation metadata for the account source, if any is available.
640 pub fn key_derivation(&self) -> Option<&Zip32Derivation> {
641 match self {
642 AccountSource::Derived { derivation, .. } => Some(derivation),
643 AccountSource::Imported {
644 purpose: AccountPurpose::Spending { derivation },
645 ..
646 } => derivation.as_ref(),
647 _ => None,
648 }
649 }
650
651 /// Returns the application-level key source identifier.
652 pub fn key_source(&self) -> Option<&str> {
653 match self {
654 AccountSource::Derived { key_source, .. } => key_source.as_ref().map(|s| s.as_str()),
655 AccountSource::Imported { key_source, .. } => key_source.as_ref().map(|s| s.as_str()),
656 }
657 }
658}
659
660/// A set of capabilities that a client account must provide.
661///
662/// An account represents a distinct set of viewing keys within the wallet; the keys for an account
663/// must not be shared with any other account in the wallet, and an application managing wallet
664/// accounts must ensure that it either maintains spending keys that can be used for spending _all_
665/// outputs detectable by the viewing keys of the account, or for none of them (i.e. the account is
666/// view-only.)
667///
668/// Balance information is available for any full-viewing-key based account; for an
669/// incoming-viewing-key only account balance cannot be determined because spends cannot be
670/// detected, and so balance-related APIs and APIs that rely upon spentness checks MUST be
671/// implemented to return errors if invoked for an IVK-only account.
672///
673/// For spending accounts in implementations that support the `transparent-key-import` feature,
674/// care must be taken to ensure that spending keys corresponding to every imported transparent
675/// address in an account are maintained by the application.
676pub trait Account {
677 type AccountId: Copy;
678
679 /// Returns the unique identifier for the account.
680 fn id(&self) -> Self::AccountId;
681
682 /// Returns the human-readable name for the account, if any has been configured.
683 fn name(&self) -> Option<&str>;
684
685 /// Returns the birthday height for the account.
686 fn birthday_height(&self) -> BlockHeight;
687
688 /// Returns whether this account is derived or imported, and the derivation parameters
689 /// if applicable.
690 fn source(&self) -> &AccountSource;
691
692 /// Returns whether the account is a spending account or a view-only account.
693 fn purpose(&self) -> AccountPurpose {
694 match self.source() {
695 AccountSource::Derived { derivation, .. } => AccountPurpose::Spending {
696 derivation: Some(derivation.clone()),
697 },
698 AccountSource::Imported { purpose, .. } => purpose.clone(),
699 }
700 }
701
702 /// Returns the UFVK that the wallet backend has stored for the account, if any.
703 ///
704 /// Accounts for which this returns `None` cannot be used in wallet contexts, because
705 /// they are unable to maintain an accurate balance.
706 fn ufvk(&self) -> Option<&UnifiedFullViewingKey>;
707
708 /// Returns the UIVK that the wallet backend has stored for the account.
709 ///
710 /// All accounts are required to have at least an incoming viewing key. This gives no
711 /// indication about whether an account can be used in a wallet context; for that, use
712 /// [`Account::ufvk`].
713 fn uivk(&self) -> UnifiedIncomingViewingKey;
714}
715
716#[cfg(any(test, feature = "test-dependencies"))]
717impl<A: Copy> Account for (A, UnifiedFullViewingKey, BlockHeight) {
718 type AccountId = A;
719
720 fn id(&self) -> A {
721 self.0
722 }
723
724 fn name(&self) -> Option<&str> {
725 None
726 }
727
728 fn birthday_height(&self) -> BlockHeight {
729 self.2
730 }
731
732 fn source(&self) -> &AccountSource {
733 &AccountSource::Imported {
734 purpose: AccountPurpose::ViewOnly,
735 key_source: None,
736 }
737 }
738
739 fn ufvk(&self) -> Option<&UnifiedFullViewingKey> {
740 Some(&self.1)
741 }
742
743 fn uivk(&self) -> UnifiedIncomingViewingKey {
744 self.1.to_unified_incoming_viewing_key()
745 }
746}
747
748#[cfg(any(test, feature = "test-dependencies"))]
749impl<A: Copy> Account for (A, UnifiedIncomingViewingKey, BlockHeight) {
750 type AccountId = A;
751
752 fn id(&self) -> A {
753 self.0
754 }
755
756 fn name(&self) -> Option<&str> {
757 None
758 }
759
760 fn birthday_height(&self) -> BlockHeight {
761 self.2
762 }
763
764 fn source(&self) -> &AccountSource {
765 &AccountSource::Imported {
766 purpose: AccountPurpose::ViewOnly,
767 key_source: None,
768 }
769 }
770
771 fn ufvk(&self) -> Option<&UnifiedFullViewingKey> {
772 None
773 }
774
775 fn uivk(&self) -> UnifiedIncomingViewingKey {
776 self.1.clone()
777 }
778}
779
780/// Source metadata for an address in the wallet.
781#[derive(Clone, Copy, Debug, PartialEq, Eq)]
782pub enum AddressSource {
783 /// The address was produced by HD derivation via a known path, with the given diversifier
784 /// index.
785 Derived {
786 diversifier_index: DiversifierIndex,
787 #[cfg(feature = "transparent-inputs")]
788 transparent_key_scope: Option<TransparentKeyScope>,
789 },
790 /// No derivation information is available; this is common for imported addresses.
791 #[cfg(feature = "transparent-key-import")]
792 Standalone,
793}
794
795impl AddressSource {
796 /// Returns the transparent key scope at which the address was derived, if this source metadata
797 /// is for a transparent address derived from a UIVK in the wallet.
798 #[cfg(feature = "transparent-inputs")]
799 pub fn transparent_key_scope(&self) -> Option<&TransparentKeyScope> {
800 match self {
801 AddressSource::Derived {
802 transparent_key_scope,
803 ..
804 } => transparent_key_scope.as_ref(),
805 #[cfg(feature = "transparent-key-import")]
806 AddressSource::Standalone => None,
807 }
808 }
809}
810
811/// Information about an address in the wallet.
812#[derive(Clone)]
813pub struct AddressInfo {
814 address: Address,
815 source: AddressSource,
816}
817
818impl AddressInfo {
819 /// Constructs an `AddressInfo` from its constituent parts.
820 pub fn from_parts(address: Address, source: AddressSource) -> Option<Self> {
821 // Only allow `transparent_key_scope` to be set for transparent addresses.
822 #[cfg(feature = "transparent-inputs")]
823 let valid = source.transparent_key_scope().is_none()
824 || matches!(address, Address::Transparent(_) | Address::Tex(_));
825 #[cfg(not(feature = "transparent-inputs"))]
826 let valid = true;
827
828 valid.then_some(Self { address, source })
829 }
830
831 /// Returns the address itself.
832 pub fn address(&self) -> &Address {
833 &self.address
834 }
835
836 /// Returns the source metadata for the address.
837 pub fn source(&self) -> AddressSource {
838 self.source
839 }
840
841 /// Returns the key scope if this is a transparent address.
842 #[cfg(feature = "transparent-inputs")]
843 #[deprecated(
844 since = "0.20.0",
845 note = "use AddressSource::transparent_key_scope instead"
846 )]
847 pub fn transparent_key_scope(&self) -> Option<&TransparentKeyScope> {
848 self.source.transparent_key_scope()
849 }
850}
851
852/// A polymorphic ratio type, usually used for rational numbers.
853#[derive(Clone, Copy, Debug, PartialEq, Eq)]
854pub struct Ratio<T> {
855 numerator: T,
856 denominator: T,
857}
858
859impl<T> Ratio<T> {
860 /// Constructs a new Ratio from a numerator and a denominator.
861 pub fn new(numerator: T, denominator: T) -> Self {
862 Self {
863 numerator,
864 denominator,
865 }
866 }
867
868 /// Returns the numerator of the ratio.
869 pub fn numerator(&self) -> &T {
870 &self.numerator
871 }
872
873 /// Returns the denominator of the ratio.
874 pub fn denominator(&self) -> &T {
875 &self.denominator
876 }
877}
878
879/// A type representing the progress the wallet has made toward detecting all of the funds
880/// belonging to the wallet.
881///
882/// The window over which progress is computed spans from the wallet's birthday to the current
883/// chain tip. It is divided into two regions, the "Scan Window" which covers the region from the
884/// wallet recovery height to the current chain tip, and the "Recovery Window" which covers the
885/// range from the wallet birthday to the wallet recovery height. If no wallet recovery height is
886/// available, the scan window will cover the entire range from the wallet birthday to the chain
887/// tip.
888///
889/// Progress for both scanning and recovery is represented in terms of the ratio between notes
890/// scanned and the total number of notes added to the chain in the relevant window. This ratio
891/// should only be used to compute progress percentages for display, and the numerator and
892/// denominator should not be treated as authoritative note counts. In the case that there are no
893/// notes in a given block range, the denominator of these values will be zero, so callers should always
894/// use checked division when converting the resulting values to percentages.
895#[derive(Debug, Clone, Copy, PartialEq, Eq)]
896pub struct Progress {
897 scan: Ratio<u64>,
898 recovery: Option<Ratio<u64>>,
899}
900
901impl Progress {
902 /// Constructs a new progress value from its constituent parts.
903 pub fn new(scan: Ratio<u64>, recovery: Option<Ratio<u64>>) -> Self {
904 Self { scan, recovery }
905 }
906
907 /// Returns the progress the wallet has made in scanning blocks for shielded notes belonging to
908 /// the wallet between the wallet recovery height (or the wallet birthday if no recovery height
909 /// is set) and the chain tip.
910 pub fn scan(&self) -> Ratio<u64> {
911 self.scan
912 }
913
914 /// Returns the progress the wallet has made in scanning blocks for shielded notes belonging to
915 /// the wallet between the wallet birthday and the block height at which recovery from seed was
916 /// initiated.
917 ///
918 /// Returns `None` if no recovery height is set for the wallet.
919 pub fn recovery(&self) -> Option<Ratio<u64>> {
920 self.recovery
921 }
922}
923
924/// A type representing the potentially-spendable value of unspent outputs in the wallet.
925///
926/// The balances reported using this data structure may overestimate the total spendable value of
927/// the wallet, in the case that the spend of a previously received shielded note has not yet been
928/// detected by the process of scanning the chain. The balances reported using this data structure
929/// can only be certain to be unspent in the case that [`Self::is_synced`] is true, and even in
930/// this circumstance it is possible that a newly created transaction could conflict with a
931/// not-yet-mined transaction in the mempool.
932#[derive(Debug, Clone, PartialEq, Eq)]
933pub struct WalletSummary<AccountId: Eq + Hash> {
934 account_balances: HashMap<AccountId, AccountBalance>,
935 chain_tip_height: BlockHeight,
936 fully_scanned_height: BlockHeight,
937 progress: Progress,
938 next_sapling_subtree_index: u64,
939 #[cfg(feature = "orchard")]
940 next_orchard_subtree_index: u64,
941 #[cfg(feature = "orchard")]
942 next_ironwood_subtree_index: u64,
943}
944
945impl<AccountId: Eq + Hash> WalletSummary<AccountId> {
946 /// Constructs a new [`WalletSummary`] from its constituent parts.
947 pub fn new(
948 account_balances: HashMap<AccountId, AccountBalance>,
949 chain_tip_height: BlockHeight,
950 fully_scanned_height: BlockHeight,
951 progress: Progress,
952 next_sapling_subtree_index: u64,
953 #[cfg(feature = "orchard")] next_orchard_subtree_index: u64,
954 #[cfg(feature = "orchard")] next_ironwood_subtree_index: u64,
955 ) -> Self {
956 Self {
957 account_balances,
958 chain_tip_height,
959 fully_scanned_height,
960 progress,
961 next_sapling_subtree_index,
962 #[cfg(feature = "orchard")]
963 next_orchard_subtree_index,
964 #[cfg(feature = "orchard")]
965 next_ironwood_subtree_index,
966 }
967 }
968
969 /// Returns the balances of accounts in the wallet, keyed by account ID.
970 pub fn account_balances(&self) -> &HashMap<AccountId, AccountBalance> {
971 &self.account_balances
972 }
973
974 /// Returns the height of the current chain tip.
975 pub fn chain_tip_height(&self) -> BlockHeight {
976 self.chain_tip_height
977 }
978
979 /// Returns the height below which all blocks have been scanned by the wallet, ignoring blocks
980 /// below the wallet birthday.
981 pub fn fully_scanned_height(&self) -> BlockHeight {
982 self.fully_scanned_height
983 }
984
985 /// Returns the progress of scanning the chain to bring the wallet up to date.
986 ///
987 /// This progress metric is intended as an indicator of how close the wallet is to
988 /// general usability, including the ability to spend existing funds that were
989 /// previously spendable.
990 ///
991 /// The window over which progress is computed spans from the wallet's birthday to the current
992 /// chain tip. It is divided into two segments: a "recovery" segment, between the wallet
993 /// birthday and the recovery height (currently the height at which recovery from seed was
994 /// initiated, but how this boundary is computed may change in the future), and a "scan"
995 /// segment, between the recovery height and the current chain tip.
996 ///
997 /// When converting the ratios returned here to percentages, checked division must be used in
998 /// order to avoid divide-by-zero errors. A zero denominator in a returned ratio indicates that
999 /// there are no shielded notes to be scanned in the associated block range.
1000 pub fn progress(&self) -> Progress {
1001 self.progress
1002 }
1003
1004 /// Returns the Sapling subtree index that should start the next range of subtree
1005 /// roots passed to [`WalletCommitmentTrees::put_sapling_subtree_roots`].
1006 pub fn next_sapling_subtree_index(&self) -> u64 {
1007 self.next_sapling_subtree_index
1008 }
1009
1010 /// Returns the Orchard subtree index that should start the next range of subtree
1011 /// roots passed to [`WalletCommitmentTrees::put_orchard_subtree_roots`].
1012 #[cfg(feature = "orchard")]
1013 pub fn next_orchard_subtree_index(&self) -> u64 {
1014 self.next_orchard_subtree_index
1015 }
1016
1017 /// Returns the Ironwood subtree index that should start the next range of subtree
1018 /// roots passed to [`WalletCommitmentTrees::put_ironwood_subtree_roots`].
1019 #[cfg(feature = "orchard")]
1020 pub fn next_ironwood_subtree_index(&self) -> u64 {
1021 self.next_ironwood_subtree_index
1022 }
1023
1024 /// Returns whether or not wallet scanning is complete.
1025 pub fn is_synced(&self) -> bool {
1026 self.chain_tip_height == self.fully_scanned_height
1027 }
1028}
1029
1030/// A predicate that can be used to choose whether or not a particular note is retained in note
1031/// selection.
1032pub trait NoteRetention<NoteRef> {
1033 /// Returns whether the specified Sapling note should be retained.
1034 fn should_retain_sapling(&self, note: &ReceivedNote<NoteRef, sapling::Note>) -> bool;
1035 /// Returns whether the specified Orchard note should be retained.
1036 #[cfg(feature = "orchard")]
1037 fn should_retain_orchard(&self, note: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool;
1038 /// Returns whether the specified Ironwood note should be retained. Ironwood notes are
1039 /// Orchard-shaped, so this uses the same note type as Orchard.
1040 #[cfg(feature = "orchard")]
1041 fn should_retain_ironwood(&self, note: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool;
1042}
1043
1044pub(crate) struct SimpleNoteRetention {
1045 pub(crate) sapling: bool,
1046 #[cfg(feature = "orchard")]
1047 pub(crate) orchard: bool,
1048 #[cfg(feature = "orchard")]
1049 pub(crate) ironwood: bool,
1050}
1051
1052impl<NoteRef> NoteRetention<NoteRef> for SimpleNoteRetention {
1053 fn should_retain_sapling(&self, _: &ReceivedNote<NoteRef, sapling::Note>) -> bool {
1054 self.sapling
1055 }
1056
1057 #[cfg(feature = "orchard")]
1058 fn should_retain_orchard(&self, _: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool {
1059 self.orchard
1060 }
1061
1062 #[cfg(feature = "orchard")]
1063 fn should_retain_ironwood(&self, _: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool {
1064 self.ironwood
1065 }
1066}
1067
1068/// Shielded outputs that were received by the wallet.
1069#[derive(Debug)]
1070pub struct ReceivedNotes<NoteRef> {
1071 sapling: Vec<ReceivedNote<NoteRef, sapling::Note>>,
1072 #[cfg(feature = "orchard")]
1073 orchard: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
1074 // Ironwood notes are Orchard-shaped `orchard::note::Note` values (note plaintext version 3),
1075 // but are tracked as a distinct pool so that Orchard and Ironwood value and bundle action
1076 // counts are accounted for separately.
1077 #[cfg(feature = "orchard")]
1078 ironwood: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
1079}
1080
1081impl<NoteRef> ReceivedNotes<NoteRef> {
1082 /// Construct a new empty [`ReceivedNotes`].
1083 pub fn empty() -> Self {
1084 Self::new(
1085 vec![],
1086 #[cfg(feature = "orchard")]
1087 vec![],
1088 #[cfg(feature = "orchard")]
1089 vec![],
1090 )
1091 }
1092
1093 /// Construct a new [`ReceivedNotes`] from its constituent parts.
1094 pub fn new(
1095 sapling: Vec<ReceivedNote<NoteRef, sapling::Note>>,
1096 #[cfg(feature = "orchard")] orchard: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
1097 #[cfg(feature = "orchard")] ironwood: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
1098 ) -> Self {
1099 Self {
1100 sapling,
1101 #[cfg(feature = "orchard")]
1102 orchard,
1103 #[cfg(feature = "orchard")]
1104 ironwood,
1105 }
1106 }
1107
1108 /// Returns the set of spendable Sapling notes.
1109 pub fn sapling(&self) -> &[ReceivedNote<NoteRef, sapling::Note>] {
1110 self.sapling.as_ref()
1111 }
1112
1113 /// Consumes this value and returns the Sapling notes contained within it.
1114 pub fn take_sapling(self) -> Vec<ReceivedNote<NoteRef, sapling::Note>> {
1115 self.sapling
1116 }
1117
1118 /// Returns the set of spendable Orchard notes.
1119 #[cfg(feature = "orchard")]
1120 pub fn orchard(&self) -> &[ReceivedNote<NoteRef, orchard::note::Note>] {
1121 self.orchard.as_ref()
1122 }
1123
1124 /// Consumes this value and returns the Orchard notes contained within it.
1125 #[cfg(feature = "orchard")]
1126 pub fn take_orchard(self) -> Vec<ReceivedNote<NoteRef, orchard::note::Note>> {
1127 self.orchard
1128 }
1129
1130 /// Returns the set of spendable Ironwood notes.
1131 #[cfg(feature = "orchard")]
1132 pub fn ironwood(&self) -> &[ReceivedNote<NoteRef, orchard::note::Note>] {
1133 self.ironwood.as_ref()
1134 }
1135
1136 /// Consumes this value and returns the Ironwood notes contained within it.
1137 #[cfg(feature = "orchard")]
1138 pub fn take_ironwood(self) -> Vec<ReceivedNote<NoteRef, orchard::note::Note>> {
1139 self.ironwood
1140 }
1141
1142 /// Computes the total value of Sapling notes.
1143 pub fn sapling_value(&self) -> Result<Zatoshis, BalanceError> {
1144 self.sapling.iter().try_fold(Zatoshis::ZERO, |acc, n| {
1145 (acc + n.note_value()?).ok_or(BalanceError::Overflow)
1146 })
1147 }
1148
1149 /// Computes the total value of Orchard notes.
1150 #[cfg(feature = "orchard")]
1151 pub fn orchard_value(&self) -> Result<Zatoshis, BalanceError> {
1152 self.orchard.iter().try_fold(Zatoshis::ZERO, |acc, n| {
1153 (acc + n.note_value()?).ok_or(BalanceError::Overflow)
1154 })
1155 }
1156
1157 /// Computes the total value of Ironwood notes.
1158 #[cfg(feature = "orchard")]
1159 pub fn ironwood_value(&self) -> Result<Zatoshis, BalanceError> {
1160 self.ironwood.iter().try_fold(Zatoshis::ZERO, |acc, n| {
1161 (acc + n.note_value()?).ok_or(BalanceError::Overflow)
1162 })
1163 }
1164
1165 /// Computes the total value of spendable inputs
1166 pub fn total_value(&self) -> Result<Zatoshis, BalanceError> {
1167 #[cfg(not(feature = "orchard"))]
1168 return self.sapling_value();
1169
1170 #[cfg(feature = "orchard")]
1171 return (self.sapling_value()? + self.orchard_value()? + self.ironwood_value()?)
1172 .ok_or(BalanceError::Overflow);
1173 }
1174
1175 /// Returns whether the collection contains no notes in any pool.
1176 pub fn is_empty(&self) -> bool {
1177 #[cfg(not(feature = "orchard"))]
1178 return self.sapling.is_empty();
1179
1180 #[cfg(feature = "orchard")]
1181 return self.sapling.is_empty() && self.orchard.is_empty() && self.ironwood.is_empty();
1182 }
1183
1184 /// Consumes this collection, returning one holding only the OLDEST single note whose value
1185 /// alone is at least `value`, drawn from the first pool in `sources` that holds one; the
1186 /// result is empty when no single note qualifies. Age is the note's commitment tree
1187 /// position, which is assigned in strict chain order.
1188 ///
1189 /// This is the best-effort reduction behind the default implementation of
1190 /// [`InputSource::select_single_spendable_note`]: it can only choose among the notes it
1191 /// holds, so a covering note the producing selection did not surface cannot be found here.
1192 pub fn into_single_covering(mut self, value: Zatoshis, sources: &[ShieldedPool]) -> Self {
1193 fn take_oldest_covering<NoteRef, N>(
1194 notes: &mut Vec<ReceivedNote<NoteRef, N>>,
1195 covers: impl Fn(&ReceivedNote<NoteRef, N>) -> bool,
1196 ) -> Option<ReceivedNote<NoteRef, N>> {
1197 let idx = notes
1198 .iter()
1199 .enumerate()
1200 .filter(|(_, n)| covers(n))
1201 .min_by_key(|(_, n)| n.note_commitment_tree_position())
1202 .map(|(idx, _)| idx)?;
1203 Some(notes.swap_remove(idx))
1204 }
1205
1206 for pool in sources {
1207 match pool {
1208 ShieldedPool::Sapling => {
1209 if let Some(note) = take_oldest_covering(&mut self.sapling, |n| {
1210 n.note_value().is_ok_and(|v| v >= value)
1211 }) {
1212 return Self::new(
1213 vec![note],
1214 #[cfg(feature = "orchard")]
1215 vec![],
1216 #[cfg(feature = "orchard")]
1217 vec![],
1218 );
1219 }
1220 }
1221 #[cfg(feature = "orchard")]
1222 ShieldedPool::Orchard => {
1223 if let Some(note) = take_oldest_covering(&mut self.orchard, |n| {
1224 n.note_value().is_ok_and(|v| v >= value)
1225 }) {
1226 return Self::new(vec![], vec![note], vec![]);
1227 }
1228 }
1229 #[cfg(feature = "orchard")]
1230 ShieldedPool::Ironwood => {
1231 if let Some(note) = take_oldest_covering(&mut self.ironwood, |n| {
1232 n.note_value().is_ok_and(|v| v >= value)
1233 }) {
1234 return Self::new(vec![], vec![], vec![note]);
1235 }
1236 }
1237 #[cfg(not(feature = "orchard"))]
1238 ShieldedPool::Orchard | ShieldedPool::Ironwood => {}
1239 }
1240 }
1241 Self::empty()
1242 }
1243
1244 /// Consumes this [`ReceivedNotes`] value and produces a vector of
1245 /// [`ReceivedNote<NoteRef, Note>`] values.
1246 pub fn into_vec(
1247 self,
1248 retention: &impl NoteRetention<NoteRef>,
1249 ) -> Vec<ReceivedNote<NoteRef, Note>> {
1250 let iter = self.sapling.into_iter().filter_map(|n| {
1251 retention
1252 .should_retain_sapling(&n)
1253 .then(|| n.map_note(Note::Sapling))
1254 });
1255
1256 #[cfg(feature = "orchard")]
1257 let iter = iter.chain(self.orchard.into_iter().filter_map(|n| {
1258 retention.should_retain_orchard(&n).then(|| {
1259 n.map_note(|note| Note::Orchard {
1260 note,
1261 pool: orchard::ValuePool::Orchard,
1262 })
1263 })
1264 }));
1265
1266 // Ironwood notes are `orchard::note::Note` values, so they are emitted as `Note::Orchard`;
1267 // the transaction builder routes them to the Ironwood bundle by their version 3 plaintext.
1268 #[cfg(feature = "orchard")]
1269 let iter = iter.chain(self.ironwood.into_iter().filter_map(|n| {
1270 retention.should_retain_ironwood(&n).then(|| {
1271 n.map_note(|note| Note::Orchard {
1272 note,
1273 pool: orchard::ValuePool::Ironwood,
1274 })
1275 })
1276 }));
1277
1278 iter.collect()
1279 }
1280}
1281
1282/// A type describing the mined-ness of transactions that should be returned in response to a
1283/// [`TransactionDataRequest`].
1284#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1285#[cfg(feature = "transparent-inputs")]
1286pub enum TransactionStatusFilter {
1287 /// Only mined transactions should be returned.
1288 Mined,
1289 /// Only mempool transactions should be returned.
1290 Mempool,
1291 /// Both mined transactions and transactions in the mempool should be returned.
1292 All,
1293}
1294
1295/// A type used to filter transactions to be returned in response to a [`TransactionDataRequest`],
1296/// in terms of the spentness of the transaction's transparent outputs.
1297#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1298#[cfg(feature = "transparent-inputs")]
1299pub enum OutputStatusFilter {
1300 /// Only transactions that have currently-unspent transparent outputs should be returned.
1301 Unspent,
1302 /// All transactions corresponding to the data request should be returned, irrespective of
1303 /// whether or not those transactions produce transparent outputs that are currently unspent.
1304 All,
1305}
1306
1307/// Payload data for [`TransactionDataRequest::TransactionsInvolvingAddress`].
1308///
1309/// Values of this type are not constructed directly, but are instead constructed using
1310/// [`TransactionDataRequest::transactions_involving_address`].
1311#[cfg(feature = "transparent-inputs")]
1312#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Getters, CopyGetters)]
1313pub struct TransactionsInvolvingAddress {
1314 /// The address to request transactions and/or UTXOs for.
1315 #[getset(get_copy = "pub")]
1316 address: TransparentAddress,
1317 /// Only transactions mined at heights greater than or equal to this height should be
1318 /// returned.
1319 #[getset(get_copy = "pub")]
1320 block_range_start: BlockHeight,
1321 /// If set, only transactions mined at heights less than this height should be returned.
1322 #[getset(get_copy = "pub")]
1323 block_range_end: Option<BlockHeight>,
1324 /// If a `request_at` time is set, the caller evaluating this request should attempt to
1325 /// retrieve transaction data related to the specified address at a time that is as close
1326 /// as practical to the specified instant, and in a fashion that decorrelates this request
1327 /// to a light wallet server from other requests made by the same caller.
1328 ///
1329 /// This may be ignored by callers that are able to satisfy the request without exposing
1330 /// correlations between addresses to untrusted parties; for example, a wallet application
1331 /// that uses a private, trusted-for-privacy supplier of chain data can safely ignore this
1332 /// field.
1333 #[getset(get_copy = "pub")]
1334 request_at: Option<SystemTime>,
1335 /// The caller should respond to this request only with transactions that conform to the
1336 /// specified transaction status filter.
1337 #[getset(get = "pub")]
1338 tx_status_filter: TransactionStatusFilter,
1339 /// The caller should respond to this request only with transactions containing outputs
1340 /// that conform to the specified output status filter.
1341 #[getset(get = "pub")]
1342 output_status_filter: OutputStatusFilter,
1343}
1344
1345/// A request for transaction data enhancement, spentness check, or discovery
1346/// of spends from a given transparent address within a specific block range.
1347#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1348pub enum TransactionDataRequest {
1349 /// Information about the chain's view of a transaction is requested.
1350 ///
1351 /// The caller evaluating this request on behalf of the wallet backend should respond to this
1352 /// request by determining the status of the specified transaction with respect to the main
1353 /// chain; if using `lightwalletd` for access to chain data, this may be obtained by
1354 /// interpreting the results of the `GetTransaction` RPC method. It should then call
1355 /// [`WalletWrite::set_transaction_status`] to provide the resulting transaction status
1356 /// information to the wallet backend.
1357 GetStatus(TxId),
1358 /// Transaction enhancement (download of complete raw transaction data) is requested.
1359 ///
1360 /// The caller evaluating this request on behalf of the wallet backend should respond to this
1361 /// request by providing complete data for the specified transaction to
1362 /// [`wallet::decrypt_and_store_transaction`]; if using `lightwalletd` for access to chain
1363 /// state, this may be obtained via the `GetTransaction` RPC method. If no data is available
1364 /// for the specified transaction, this should be reported to the backend using
1365 /// [`WalletWrite::set_transaction_status`]. A [`TransactionDataRequest::Enhancement`] request
1366 /// subsumes any previously existing [`TransactionDataRequest::GetStatus`] request.
1367 Enhancement(TxId),
1368 /// Information about transactions that receive or spend funds belonging to the specified
1369 /// transparent address is requested.
1370 ///
1371 /// Fully transparent transactions, and transactions that do not contain either shielded inputs
1372 /// or shielded outputs belonging to the wallet, may not be discovered by the process of
1373 /// out-of-order chain scanning due to race conditions related to advancing the transparent
1374 /// address gap limit; as a consequence, the wallet must actively query to find transactions
1375 /// that spend such funds. Ideally we'd be able to query by [`OutPoint`] but this is not
1376 /// currently functionality that is supported by the light wallet server; for full-node wallets
1377 /// or other arrangements that allow privacy-preserving retrieval of individually identifying
1378 /// information such as backends that support private information retrieval (PIR) consider
1379 /// enabling the `spend-index` feature.
1380 ///
1381 /// The caller evaluating this request on behalf of the wallet backend should respond to this
1382 /// request by detecting transactions involving the specified address within the provided block
1383 /// range; if using `lightwalletd` for access to chain data, this may be performed using the
1384 /// `GetTaddressTxids` RPC method. It should then call [`wallet::decrypt_and_store_transaction`]
1385 /// for each transaction so detected. If no transactions are detected within the given range,
1386 /// the caller should instead invoke [`WalletWrite::notify_address_checked`] with
1387 /// `block_end_height - 1` as the `as_of_height` argument.
1388 #[cfg(feature = "transparent-inputs")]
1389 TransactionsInvolvingAddress(TransactionsInvolvingAddress),
1390 /// The main-chain transaction that spends of a specific transparent output, or confirmation
1391 /// that the output remains unspent, is requested.
1392 ///
1393 /// When the `spend-index` feature is enabled, `GetSpendingTx` requests will be emitted by the
1394 /// backend instead of [`TransactionDataRequest::TransactionsInvolvingAddress`], in
1395 /// circumstances when spentness determination is needed. This feature should only be enabled
1396 /// for wallets whose chain-data source can resolve the spend of an individual outpoint
1397 /// directly — for example a full node that maintains a spent-outpoint index. It avoids needing
1398 /// to retrieve potentially large amounts of transaction history (in the cas of a
1399 /// heavily-reused address) just to discover whether one output was spent.
1400 ///
1401 /// The caller evaluating this request on behalf of the wallet backend should determine whether
1402 /// `outpoint` has been spent on the main chain. Spentness should be taken from an
1403 /// authoritative source (e.g. the node's UTXO set); the spend index is used only to identify
1404 /// the spending transaction. If the output is spent, the caller should provide the spending
1405 /// transaction to [`wallet::decrypt_and_store_transaction`]. If the output is confirmed
1406 /// unspent as of some height, the caller should invoke
1407 /// [`WalletWrite::notify_output_verified_unspent`] with that height. If the output is known to
1408 /// be spent but the spending transaction cannot yet be resolved (e.g. an index is still being
1409 /// built — see ZcashFoundation/zebra#10806), the caller should do nothing, so that the request
1410 /// is re-issued and retried later.
1411 #[cfg(feature = "spend-index")]
1412 GetSpendingTx(OutPoint),
1413}
1414
1415impl TransactionDataRequest {
1416 /// Constructs a request for Information about transactions that receive or spend funds
1417 /// belonging to the specified transparent address.
1418 ///
1419 /// # Parameters:
1420 /// - `address`: The address to request transactions and/or UTXOs for.
1421 /// - `block_range_start`: Only transactions mined at heights greater than or equal to this
1422 /// height should be returned.
1423 /// - `block_range_end`: Only transactions mined at heights less than this height should be
1424 /// returned.
1425 /// - `request_at`: If a `request_at` time is set, the caller evaluating this request should attempt to
1426 /// retrieve transaction data related to the specified address at a time that is as close
1427 /// as practical to the specified instant, and in a fashion that decorrelates this request
1428 /// to a light wallet server from other requests made by the same caller. This may be ignored
1429 /// by callers that are able to satisfy the request without exposing correlations between
1430 /// addresses to untrusted parties; for example, a wallet application that uses a private,
1431 /// trusted-for-privacy supplier of chain data can safely ignore this field.
1432 /// - `tx_status_filter`: The caller should respond to this request only with transactions that
1433 /// conform to the specified transaction status filter.
1434 /// - `output_status_filter: The caller should respond to this request only with transactions
1435 /// containing outputs that conform to the specified output status filter.
1436 ///
1437 /// See [`TransactionDataRequest::TransactionsInvolvingAddress`] for more information.
1438 #[cfg(feature = "transparent-inputs")]
1439 pub fn transactions_involving_address(
1440 address: TransparentAddress,
1441 block_range_start: BlockHeight,
1442 block_range_end: Option<BlockHeight>,
1443 request_at: Option<SystemTime>,
1444 tx_status_filter: TransactionStatusFilter,
1445 output_status_filter: OutputStatusFilter,
1446 ) -> Self {
1447 TransactionDataRequest::TransactionsInvolvingAddress(TransactionsInvolvingAddress {
1448 address,
1449 block_range_start,
1450 block_range_end,
1451 request_at,
1452 tx_status_filter,
1453 output_status_filter,
1454 })
1455 }
1456}
1457
1458/// Metadata about the status of a transaction obtained by inspecting the chain state.
1459#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1460pub enum TransactionStatus {
1461 /// The requested transaction ID was not recognized by the node.
1462 TxidNotRecognized,
1463 /// The requested transaction ID corresponds to a transaction that is recognized by the node,
1464 /// but is in the mempool or is otherwise not mined in the main chain (but may have been mined
1465 /// on a fork that was reorged away).
1466 NotInMainChain,
1467 /// The requested transaction ID corresponds to a transaction that has been included in the
1468 /// block at the provided height.
1469 Mined(BlockHeight),
1470}
1471
1472/// Metadata about the structure of unspent outputs in a single pool within a wallet account.
1473///
1474/// This type is often used to represent a filtered view of outputs in the account that were
1475/// selected according to the conditions imposed by a [`NoteFilter`].
1476#[derive(Debug, Clone)]
1477pub struct PoolMeta {
1478 note_count: usize,
1479 value: Zatoshis,
1480}
1481
1482impl PoolMeta {
1483 /// Constructs a new [`PoolMeta`] value from its constituent parts.
1484 pub fn new(note_count: usize, value: Zatoshis) -> Self {
1485 Self { note_count, value }
1486 }
1487
1488 /// Returns the number of unspent outputs in the account, potentially selected in accordance
1489 /// with some [`NoteFilter`].
1490 pub fn note_count(&self) -> usize {
1491 self.note_count
1492 }
1493
1494 /// Returns the total value of unspent outputs in the account that are accounted for in
1495 /// [`Self::note_count`].
1496 pub fn value(&self) -> Zatoshis {
1497 self.value
1498 }
1499}
1500
1501/// Metadata about the structure of the wallet for a particular account.
1502///
1503/// At present this just contains counts of unspent outputs in each pool, but it may be extended in
1504/// the future to contain note values or other more detailed information about wallet structure.
1505///
1506/// Values of this type are intended to be used in selection of change output values. A value of
1507/// this type may represent filtered data, and may therefore not count all of the unspent notes in
1508/// the wallet.
1509///
1510/// A [`AccountMeta`] value is normally produced by querying the wallet database via passing a
1511/// [`NoteFilter`] to [`InputSource::get_account_metadata`].
1512#[derive(Debug, Clone)]
1513pub struct AccountMeta {
1514 sapling: Option<PoolMeta>,
1515 orchard: Option<PoolMeta>,
1516 ironwood: Option<PoolMeta>,
1517}
1518
1519impl AccountMeta {
1520 /// Constructs a new [`AccountMeta`] value from its constituent parts.
1521 ///
1522 /// Ironwood metadata is tracked separately from Orchard, as Ironwood is a distinct pool.
1523 pub fn new(
1524 sapling: Option<PoolMeta>,
1525 orchard: Option<PoolMeta>,
1526 ironwood: Option<PoolMeta>,
1527 ) -> Self {
1528 Self {
1529 sapling,
1530 orchard,
1531 ironwood,
1532 }
1533 }
1534
1535 /// Returns metadata about Sapling notes belonging to the account for which this was generated.
1536 ///
1537 /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
1538 /// described by a [`NoteFilter`] given the available wallet data.
1539 pub fn sapling(&self) -> Option<&PoolMeta> {
1540 self.sapling.as_ref()
1541 }
1542
1543 /// Returns metadata about Orchard notes belonging to the account for which this was generated.
1544 ///
1545 /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
1546 /// described by a [`NoteFilter`] given the available wallet data.
1547 pub fn orchard(&self) -> Option<&PoolMeta> {
1548 self.orchard.as_ref()
1549 }
1550
1551 /// Returns metadata about Ironwood notes belonging to the account for which this was generated.
1552 ///
1553 /// Ironwood notes are Orchard-shaped but belong to a pool distinct from Orchard. Returns
1554 /// [`None`] if no metadata is available or it was not possible to evaluate the query described
1555 /// by a [`NoteFilter`] given the available wallet data.
1556 pub fn ironwood(&self) -> Option<&PoolMeta> {
1557 self.ironwood.as_ref()
1558 }
1559
1560 fn sapling_note_count(&self) -> Option<usize> {
1561 self.sapling.as_ref().map(|m| m.note_count)
1562 }
1563
1564 fn orchard_note_count(&self) -> Option<usize> {
1565 self.orchard.as_ref().map(|m| m.note_count)
1566 }
1567
1568 fn ironwood_note_count(&self) -> Option<usize> {
1569 self.ironwood.as_ref().map(|m| m.note_count)
1570 }
1571
1572 /// Returns the number of unspent notes in the wallet for the given shielded pool.
1573 pub fn note_count(&self, protocol: ShieldedPool) -> Option<usize> {
1574 match protocol {
1575 ShieldedPool::Sapling => self.sapling_note_count(),
1576 ShieldedPool::Orchard => self.orchard_note_count(),
1577 ShieldedPool::Ironwood => self.ironwood_note_count(),
1578 }
1579 }
1580
1581 /// Returns the total number of unspent shielded notes belonging to the account for which this
1582 /// was generated.
1583 ///
1584 /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
1585 /// described by a [`NoteFilter`] given the available wallet data. If metadata is available
1586 /// only for a single pool, the metadata for that pool will be returned.
1587 pub fn total_note_count(&self) -> Option<usize> {
1588 [
1589 self.sapling_note_count(),
1590 self.orchard_note_count(),
1591 self.ironwood_note_count(),
1592 ]
1593 .into_iter()
1594 .flatten()
1595 .reduce(|a, b| a + b)
1596 }
1597
1598 fn sapling_value(&self) -> Option<Zatoshis> {
1599 self.sapling.as_ref().map(|m| m.value)
1600 }
1601
1602 fn orchard_value(&self) -> Option<Zatoshis> {
1603 self.orchard.as_ref().map(|m| m.value)
1604 }
1605
1606 fn ironwood_value(&self) -> Option<Zatoshis> {
1607 self.ironwood.as_ref().map(|m| m.value)
1608 }
1609
1610 /// Returns the total value of shielded notes represented by [`Self::total_note_count`]
1611 ///
1612 /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
1613 /// described by a [`NoteFilter`] given the available wallet data. If metadata is available
1614 /// only for a single pool, the metadata for that pool will be returned.
1615 pub fn total_value(&self) -> Option<Zatoshis> {
1616 [
1617 self.sapling_value(),
1618 self.orchard_value(),
1619 self.ironwood_value(),
1620 ]
1621 .into_iter()
1622 .flatten()
1623 .reduce(|a, b| (a + b).expect("Does not overflow Zcash maximum value."))
1624 }
1625}
1626
1627/// A `u8` value in the range 0..=MAX
1628#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1629pub struct BoundedU8<const MAX: u8>(u8);
1630
1631impl<const MAX: u8> BoundedU8<MAX> {
1632 /// Creates a constant `BoundedU8` from a [`u8`] value.
1633 ///
1634 /// Panics: if the value is outside the range `0..=MAX`.
1635 pub const fn new_const(value: u8) -> Self {
1636 assert!(value <= MAX);
1637 Self(value)
1638 }
1639
1640 /// Creates a `BoundedU8` from a [`u8`] value.
1641 ///
1642 /// Returns `None` if the provided value is outside the range `0..=MAX`.
1643 pub fn new(value: u8) -> Option<Self> {
1644 if value <= MAX {
1645 Some(Self(value))
1646 } else {
1647 None
1648 }
1649 }
1650
1651 /// Returns the wrapped [`u8`] value.
1652 pub fn value(&self) -> u8 {
1653 self.0
1654 }
1655}
1656
1657impl<const MAX: u8> From<BoundedU8<MAX>> for u8 {
1658 fn from(value: BoundedU8<MAX>) -> Self {
1659 value.0
1660 }
1661}
1662
1663impl<const MAX: u8> From<BoundedU8<MAX>> for usize {
1664 fn from(value: BoundedU8<MAX>) -> Self {
1665 usize::from(value.0)
1666 }
1667}
1668
1669/// A small query language for filtering notes belonging to an account.
1670///
1671/// A filter described using this language is applied to notes individually. It is primarily
1672/// intended for retrieval of account metadata in service of making determinations for how to
1673/// allocate change notes, and is not currently intended for use in broader note selection
1674/// contexts.
1675#[derive(Clone, Debug, PartialEq, Eq)]
1676pub enum NoteFilter {
1677 /// Selects notes having value strictly greater than the provided value.
1678 ExceedsMinValue(Zatoshis),
1679 /// Selects notes having value greater than or equal to approximately the n'th percentile of
1680 /// previously sent notes in the account, irrespective of pool. The wrapped value must be in
1681 /// the range `1..=99`. The value `n` is respected in a best-effort fashion; results are likely
1682 /// to be inaccurate if the account has not yet completed scanning or if insufficient send data
1683 /// is available to establish a distribution.
1684 // TODO: it might be worthwhile to add an optional parameter here that can be used to ignore
1685 // low-valued (test/memo-only) sends when constructing the distribution to be drawn from.
1686 ExceedsPriorSendPercentile(BoundedU8<99>),
1687 /// Selects notes having value greater than or equal to the specified percentage of the account
1688 /// balance across all shielded pools. The wrapped value must be in the range `1..=99`
1689 ExceedsBalancePercentage(BoundedU8<99>),
1690 /// A note will be selected if it satisfies both of the specified conditions.
1691 ///
1692 /// If it is not possible to evaluate one of the conditions (for example,
1693 /// [`NoteFilter::ExceedsPriorSendPercentile`] cannot be evaluated if no sends have been
1694 /// performed) then that condition will be ignored. If neither condition can be evaluated,
1695 /// then the entire condition cannot be evaluated.
1696 Combine(Box<NoteFilter>, Box<NoteFilter>),
1697 /// A note will be selected if it satisfies the first condition; if it is not possible to
1698 /// evaluate that condition (for example, [`NoteFilter::ExceedsPriorSendPercentile`] cannot
1699 /// be evaluated if no sends have been performed) then the second condition will be used for
1700 /// evaluation.
1701 Attempt {
1702 condition: Box<NoteFilter>,
1703 fallback: Box<NoteFilter>,
1704 },
1705}
1706
1707impl NoteFilter {
1708 /// Constructs a [`NoteFilter::Combine`] query node.
1709 pub fn combine(l: NoteFilter, r: NoteFilter) -> Self {
1710 Self::Combine(Box::new(l), Box::new(r))
1711 }
1712
1713 /// Constructs a [`NoteFilter::Attempt`] query node.
1714 pub fn attempt(condition: NoteFilter, fallback: NoteFilter) -> Self {
1715 Self::Attempt {
1716 condition: Box::new(condition),
1717 fallback: Box::new(fallback),
1718 }
1719 }
1720}
1721
1722/// Controls which transparent outputs are eligible for selection. This is an
1723/// input-selection control only; it does not encode any consensus rule.
1724#[cfg(feature = "transparent-inputs")]
1725#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1726pub enum CoinbaseFilter {
1727 /// Select all spendable transparent outputs.
1728 #[default]
1729 AllTransparentOutputs,
1730 /// Select only coinbase transparent outputs.
1731 ///
1732 /// Coinbase transactions are identified by having `tx_index == 0` within
1733 /// their containing block. Outputs for which the transaction index is
1734 /// unknown are conservatively treated as non-coinbase and will be excluded
1735 /// when this filter is active.
1736 CoinbaseOnly,
1737 /// Select only non-coinbase transparent outputs.
1738 ///
1739 /// Used for general (non-shielding) transfers, which may produce transparent
1740 /// change; coinbase funds must instead be shielded via
1741 /// [`propose_shielding_coinbase`](crate::data_api::wallet::propose_shielding_coinbase).
1742 /// Outputs whose transaction index is unknown are treated as non-coinbase
1743 /// and are included.
1744 NonCoinbaseOnly,
1745}
1746
1747/// A trait representing the capability to query a data store for unspent transaction outputs
1748/// belonging to a account.
1749#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
1750pub trait InputSource {
1751 /// The type of errors produced by a wallet backend.
1752 type Error: Debug;
1753
1754 /// Backend-specific account identifier.
1755 ///
1756 /// An account identifier corresponds to at most a single unified spending key's worth of spend
1757 /// authority, such that both received notes and change spendable by that spending authority
1758 /// will be interpreted as belonging to that account. This might be a database identifier type
1759 /// or a UUID.
1760 type AccountId: Copy + Debug + Eq + Hash;
1761
1762 /// Backend-specific note identifier.
1763 ///
1764 /// For example, this might be a database identifier type or a UUID.
1765 type NoteRef: Copy + Debug + Eq + Ord;
1766
1767 /// Fetches a spendable note by indexing into a transaction's shielded outputs for the
1768 /// specified shielded protocol.
1769 ///
1770 /// Returns `Ok(None)` if the note is not known to belong to the wallet or if the note
1771 /// is not spendable as of the given height. Locked outputs are selected according to
1772 /// `lock_filter` (see [`LockFilter`]; a [`LockFilter::Policy`] carrying the default
1773 /// [`LockedInputPolicy::Exclude`] selects none).
1774 ///
1775 /// [`LockedInputPolicy::Exclude`]: crate::data_api::wallet::input_selection::LockedInputPolicy::Exclude
1776 fn get_spendable_note(
1777 &self,
1778 txid: &TxId,
1779 protocol: ShieldedPool,
1780 index: u32,
1781 target_height: TargetHeight,
1782 lock_filter: LockFilter<'_>,
1783 ) -> Result<Option<ReceivedNote<Self::NoteRef, Note>>, Self::Error>;
1784
1785 /// Returns whether an anchor is COMPUTABLE at `height` for spends from the given pool: whether
1786 /// this data source can produce the note commitment tree root, and witnesses to it, as of the
1787 /// end of that block.
1788 ///
1789 /// A height inside the wallet's scanned range need not qualify: tree states are only
1790 /// materialized at the heights the wallet chose to retain, and a wallet that scanned past
1791 /// NU6.3 activation before boundary checkpointing was repaired is permanently missing the
1792 /// anchor-retention boundaries whose blocks carried no shielded outputs. Such a hole cannot be
1793 /// backfilled from local state, so a caller deciding whether to anchor at a retained boundary
1794 /// should consult this before committing to it, and fall back rather than propose a
1795 /// transaction that cannot be built.
1796 fn anchor_computable(
1797 &self,
1798 protocol: ShieldedPool,
1799 height: BlockHeight,
1800 ) -> Result<bool, Self::Error>;
1801
1802 /// Returns a list of spendable notes sufficient to cover the specified target value, if
1803 /// possible. Only spendable notes corresponding to the specified shielded protocol will
1804 /// be included. Locked outputs are selected according to `lock_filter` (see [`LockFilter`];
1805 /// a [`LockFilter::Policy`] carrying the default `Exclude` selects none).
1806 #[allow(clippy::too_many_arguments)]
1807 fn select_spendable_notes(
1808 &self,
1809 account: Self::AccountId,
1810 target_value: TargetValue,
1811 sources: &[ShieldedPool],
1812 target_height: TargetHeight,
1813 confirmations_policy: ConfirmationsPolicy,
1814 exclude: &[Self::NoteRef],
1815 lock_filter: LockFilter<'_>,
1816 ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error>;
1817
1818 /// Returns the OLDEST single spendable note whose value alone is at least `value`, drawn
1819 /// from the first pool in `sources` (in the given preference order) that holds one. The
1820 /// returned collection contains at most one note; it is empty when no single eligible note
1821 /// covers the value.
1822 ///
1823 /// This is the selection primitive behind
1824 /// [`NoteSelection::PreferSingle`](crate::data_api::wallet::input_selection::NoteSelection):
1825 /// a ZIP 318 migration transfer spends exactly one note, so a canonical pool crossing must
1826 /// be funded from one.
1827 ///
1828 /// The default implementation is BEST-EFFORT: it reports a note only when
1829 /// [`Self::select_spendable_notes`] happens to surface one that covers the value on its
1830 /// own. An implementation backed by a queryable store should override it with a direct
1831 /// query, so that a covering note is found whenever one exists.
1832 #[allow(clippy::too_many_arguments)]
1833 fn select_single_spendable_note(
1834 &self,
1835 account: Self::AccountId,
1836 value: Zatoshis,
1837 sources: &[ShieldedPool],
1838 target_height: TargetHeight,
1839 confirmations_policy: ConfirmationsPolicy,
1840 exclude: &[Self::NoteRef],
1841 lock_filter: LockFilter<'_>,
1842 ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error> {
1843 self.select_spendable_notes(
1844 account,
1845 TargetValue::AtLeast(value),
1846 sources,
1847 target_height,
1848 confirmations_policy,
1849 exclude,
1850 lock_filter,
1851 )
1852 .map(|notes| notes.into_single_covering(value, sources))
1853 }
1854
1855 /// Returns the list of notes belonging to the wallet that are unspent as of the specified
1856 /// target height. Locked outputs are selected according to `lock_filter` (see [`LockFilter`];
1857 /// a [`LockFilter::Policy`] carrying the default `Exclude` selects none).
1858 fn select_unspent_notes(
1859 &self,
1860 account: Self::AccountId,
1861 sources: &[ShieldedPool],
1862 target_height: TargetHeight,
1863 exclude: &[Self::NoteRef],
1864 lock_filter: LockFilter<'_>,
1865 ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error>;
1866
1867 /// Returns metadata describing the structure of the wallet for the specified account.
1868 ///
1869 /// The returned metadata value must exclude:
1870 /// - notes that are not considered spendable as of the given `target_height`
1871 /// - unspent notes excluded by the provided selector;
1872 /// - unspent notes identified in the given `exclude` list.
1873 /// - locked notes not admitted by `lock_filter` (see [`LockFilter`]; a [`LockFilter::Policy`]
1874 /// carrying the default `Exclude` admits none).
1875 ///
1876 /// Implementations of this method may limit the complexity of supported queries. Such
1877 /// limitations should be clearly documented for the implementing type.
1878 fn get_account_metadata(
1879 &self,
1880 account: Self::AccountId,
1881 selector: &NoteFilter,
1882 target_height: TargetHeight,
1883 exclude: &[Self::NoteRef],
1884 lock_filter: LockFilter<'_>,
1885 ) -> Result<AccountMeta, Self::Error>;
1886
1887 /// Fetches the transparent output corresponding to the provided `outpoint` if it is considered
1888 /// spendable as of the provided `target_height`.
1889 ///
1890 /// Returns `Ok(None)` if the UTXO is not known to belong to the wallet or would not be
1891 /// spendable in a transaction mined in the block at the target height.
1892 #[cfg(feature = "transparent-inputs")]
1893 fn get_unspent_transparent_output(
1894 &self,
1895 _outpoint: &OutPoint,
1896 _target_height: TargetHeight,
1897 ) -> Result<Option<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
1898 unimplemented!(
1899 "InputSource::get_spendable_transparent_output must be overridden for wallets to use the `transparent-inputs` feature"
1900 )
1901 }
1902
1903 /// Returns the list of unspent transparent outputs received by this wallet at `address`
1904 /// such that, at height `target_height`:
1905 /// * the transaction that produced the output had or will have at least the required number of
1906 /// confirmations according to the provided [`ConfirmationsPolicy`]; and
1907 /// * the output can potentially be spent in a transaction mined in a block at the given
1908 /// `target_height` (also taking into consideration the coinbase maturity rule).
1909 ///
1910 /// The `output_filter` parameter controls which transparent outputs are eligible. When set
1911 /// to [`CoinbaseFilter::CoinbaseOnly`], only outputs from coinbase transactions
1912 /// should be returned.
1913 ///
1914 /// Any output that is potentially spent by an unmined transaction in the mempool should be
1915 /// excluded unless the spending transaction will be expired at `target_height`.
1916 /// Locked outputs are selected according to `lock_filter` (see [`LockFilter`]; a
1917 /// [`LockFilter::Policy`] carrying the default `Exclude` selects none).
1918 #[cfg(feature = "transparent-inputs")]
1919 fn get_spendable_transparent_outputs(
1920 &self,
1921 _address: &TransparentAddress,
1922 _target_height: TargetHeight,
1923 _confirmations_policy: ConfirmationsPolicy,
1924 _output_filter: CoinbaseFilter,
1925 _lock_filter: LockFilter<'_>,
1926 ) -> Result<Vec<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
1927 unimplemented!(
1928 "InputSource::get_spendable_transparent_outputs must be overridden for wallets to use the `transparent-inputs` feature"
1929 )
1930 }
1931
1932 /// Returns the list of spendable transparent outputs received by this wallet at any of the
1933 /// given `addresses`, subject to the same spendability conditions as
1934 /// [`InputSource::get_spendable_transparent_outputs`].
1935 ///
1936 /// This is the batched equivalent of calling
1937 /// [`InputSource::get_spendable_transparent_outputs`] once per address. It exists so that data
1938 /// stores can satisfy a multi-address request with a single query rather than one query per
1939 /// address, which is prohibitively expensive for wallets that hold large numbers of transparent
1940 /// addresses (as occurs when shielding). The default implementation simply iterates over
1941 /// `addresses`; data stores should override it with a batched query where possible.
1942 ///
1943 /// Each returned output identifies its receiving address via
1944 /// [`WalletTransparentOutput::recipient_address`].
1945 #[cfg(feature = "transparent-inputs")]
1946 fn get_spendable_transparent_outputs_for_addresses(
1947 &self,
1948 addresses: &[TransparentAddress],
1949 target_height: TargetHeight,
1950 confirmations_policy: ConfirmationsPolicy,
1951 output_filter: CoinbaseFilter,
1952 lock_filter: LockFilter<'_>,
1953 ) -> Result<Vec<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
1954 let mut outputs = Vec::new();
1955 for address in addresses {
1956 outputs.extend(self.get_spendable_transparent_outputs(
1957 address,
1958 target_height,
1959 confirmations_policy,
1960 output_filter,
1961 lock_filter,
1962 )?);
1963 }
1964 Ok(outputs)
1965 }
1966
1967 /// Returns the spendable transparent outputs received by `account` whose total post-fee
1968 /// value (sum of values minus the cumulative marginal fee cost of the gathered inputs
1969 /// themselves, per `fee_rule`) is at least `target_value`, or `max_inputs` outputs
1970 /// (whichever is reached first).
1971 ///
1972 /// The gather is intended to scale to wallets with large numbers of transparent addresses and
1973 /// UTXOs: it returns a value-bounded subset rather than every spendable output, so the
1974 /// selector does not need to materialize the wallet's full UTXO set. Data stores should
1975 /// implement this with a single query that orders eligible UTXOs by descending value and
1976 /// accumulates them, recomputing the cumulative fee via `fee_rule` at each step, stopping
1977 /// once the post-fee cumulative value meets the bound. This produces a tighter result than a
1978 /// static value bound, without requiring a separate round trip to correct an under-estimated
1979 /// headroom.
1980 ///
1981 /// `max_inputs` bounds the number of transparent inputs a single transaction may consume,
1982 /// independent of `target_value`: even a small requested value could otherwise require an
1983 /// unbounded number of inputs for a wallet holding a very large number of small (e.g. dust)
1984 /// UTXOs. When the cap is reached before the value target, the returned set's post-fee value
1985 /// may be less than `target_value`; the caller's input-selection loop is expected to surface
1986 /// this as an `InsufficientFunds` error, the same as for any other value shortfall.
1987 ///
1988 /// `fee_rule` is fixed to [`StandardFeeRule`] (rather than being generic over the caller's
1989 /// actual [`ChangeStrategy`]) so that implementations of this method do not need to be
1990 /// generic over an arbitrary fee rule type. This is a heuristic bound only: the transaction's
1991 /// real fee is still computed by the caller's actual change strategy, and if this gather's
1992 /// estimate turns out to be insufficient, the caller's input-selection loop will surface an
1993 /// `InsufficientFunds` error and can re-invoke this method with a corrected `target_value`.
1994 ///
1995 /// For `TargetValue::AllFunds`, no value bound is applied and the gather returns every
1996 /// eligible output up to `max_inputs`.
1997 ///
1998 /// When `address_allow_list` is `Some`, only outputs received at one of the listed
1999 /// transparent addresses are eligible; when `None`, outputs received at any of the
2000 /// account's transparent addresses are eligible. The restriction must be applied
2001 /// *within* the gather (not to its results), so that outputs excluded by the allow list
2002 /// do not consume the value bound.
2003 ///
2004 /// This is the value-bounded counterpart to [`InputSource::get_spendable_transparent_outputs`]
2005 /// and [`InputSource::get_spendable_transparent_outputs_for_addresses`], intended for use by
2006 /// general (non-shielding) input selection in `propose_transaction`.
2007 ///
2008 /// [`ChangeStrategy`]: crate::fees::ChangeStrategy
2009 #[cfg(feature = "transparent-inputs")]
2010 #[allow(clippy::too_many_arguments)]
2011 fn select_spendable_transparent_outputs(
2012 &self,
2013 account: Self::AccountId,
2014 target_height: TargetHeight,
2015 confirmations_policy: ConfirmationsPolicy,
2016 output_filter: CoinbaseFilter,
2017 address_allow_list: Option<&[TransparentAddress]>,
2018 target_value: TargetValue,
2019 max_inputs: usize,
2020 fee_rule: &StandardFeeRule,
2021 lock_filter: LockFilter<'_>,
2022 ) -> Result<Vec<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
2023 let _ = (
2024 account,
2025 target_height,
2026 confirmations_policy,
2027 output_filter,
2028 address_allow_list,
2029 target_value,
2030 max_inputs,
2031 fee_rule,
2032 lock_filter,
2033 );
2034 unimplemented!(
2035 "InputSource::select_spendable_transparent_outputs must be overridden for \
2036 wallets to use the value-bounded transparent input gather in propose_transaction"
2037 )
2038 }
2039}
2040
2041/// Read-only operations required for light wallet functions.
2042///
2043/// This trait defines the read-only portion of the storage interface atop which
2044/// higher-level wallet operations are implemented. It serves to allow wallet functions to
2045/// be abstracted away from any particular data storage substrate.
2046#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
2047pub trait WalletRead {
2048 /// The type of errors that may be generated when querying a wallet data store.
2049 type Error: Debug;
2050
2051 /// The type of the account identifier.
2052 ///
2053 /// An account identifier corresponds to at most a single unified spending key's worth of spend
2054 /// authority, such that both received notes and change spendable by that spending authority
2055 /// will be interpreted as belonging to that account.
2056 type AccountId: Copy + Debug + Eq + Hash;
2057
2058 /// The concrete account type used by this wallet backend.
2059 type Account: Account<AccountId = Self::AccountId>;
2060
2061 /// Returns a vector with the IDs of all accounts known to this wallet.
2062 fn get_account_ids(&self) -> Result<Vec<Self::AccountId>, Self::Error>;
2063
2064 /// Returns the account corresponding to the given ID, if any.
2065 fn get_account(
2066 &self,
2067 account_id: Self::AccountId,
2068 ) -> Result<Option<Self::Account>, Self::Error>;
2069
2070 /// Returns the account corresponding to a given [`SeedFingerprint`] and
2071 /// [`zip32::AccountId`], if any.
2072 fn get_derived_account(
2073 &self,
2074 derivation: &Zip32Derivation,
2075 ) -> Result<Option<Self::Account>, Self::Error>;
2076
2077 /// Verifies that the given seed corresponds to the viewing key for the specified account.
2078 ///
2079 /// Returns:
2080 /// - `Ok(true)` if the viewing key for the specified account can be derived from the
2081 /// provided seed.
2082 /// - `Ok(false)` if the derived viewing key does not match, or the specified account is not
2083 /// present in the database.
2084 /// - `Err(_)` if a Unified Spending Key cannot be derived from the seed for the
2085 /// specified account or the account has no known ZIP-32 derivation.
2086 fn validate_seed(
2087 &self,
2088 account_id: Self::AccountId,
2089 seed: &SecretVec<u8>,
2090 ) -> Result<bool, Self::Error>;
2091
2092 /// Checks whether the given seed is relevant to any of the derived accounts (where
2093 /// [`Account::source`] is [`AccountSource::Derived`]) in the wallet.
2094 ///
2095 /// This API does not check whether the seed is relevant to any imported account,
2096 /// because that would require brute-forcing the ZIP 32 account index space.
2097 fn seed_relevance_to_derived_accounts(
2098 &self,
2099 seed: &SecretVec<u8>,
2100 ) -> Result<SeedRelevance<Self::AccountId>, Self::Error>;
2101
2102 /// Returns the account corresponding to a given [`UnifiedFullViewingKey`], if any.
2103 fn get_account_for_ufvk(
2104 &self,
2105 ufvk: &UnifiedFullViewingKey,
2106 ) -> Result<Option<Self::Account>, Self::Error>;
2107
2108 /// Returns information about every address tracked for this account.
2109 fn list_addresses(&self, account: Self::AccountId) -> Result<Vec<AddressInfo>, Self::Error>;
2110
2111 /// Returns the wallet account that controls the given address, if any.
2112 ///
2113 /// Backends that can answer this query from an indexed lookup should implement it
2114 /// directly. Backends without such an index can delegate to
2115 /// [`defaults::find_account_for_address`], which implements the semantics described below
2116 /// using [`UnifiedIncomingViewingKey::decrypt_diversifiers`] and a linear scan over
2117 /// [`Self::get_account_ids`] / [`Self::list_addresses`].
2118 ///
2119 /// # Unified Addresses
2120 ///
2121 /// For a Unified Address each account's [`UnifiedIncomingViewingKey`] is asked, via
2122 /// [`UnifiedIncomingViewingKey::decrypt_diversifiers`], whether it could have derived any
2123 /// shielded receiver of the UA. An account matches if at least one shielded receiver is
2124 /// attributable to it — including receivers that have never been previously exposed by
2125 /// the wallet. If the shielded receivers of the UA are attributable to more than one
2126 /// account, this is treated as an inconsistent ("frankenstein") address and
2127 /// [`FindAccountForAddressError::UnifiedAddressConflict`] is returned rather than
2128 /// arbitrarily selecting one account.
2129 ///
2130 /// Backends are permitted to additionally resolve UAs by exact match against their
2131 /// tracked-address index before (or instead of) running the UIVK-algebra step, provided
2132 /// the exact-match result is consistent with at least one account identified by the
2133 /// algebraic step.
2134 ///
2135 /// # Non-Unified Addresses
2136 ///
2137 /// Backends should resolve bare shielded addresses (Sapling) via the same UIVK-algebraic
2138 /// path where feasible, so that an address derivable from an account's UIVK is resolved
2139 /// whether or not it has been previously exposed. Backends that do not can treat a bare
2140 /// shielded address as an exact-match lookup over their tracked-address index.
2141 ///
2142 /// Transparent and TEX addresses are resolved by exact match against tracked addresses
2143 /// only, since a diversifier index cannot be recovered from a transparent receiver alone.
2144 ///
2145 /// # Returns
2146 ///
2147 /// - `Ok(Some(account_id))` if the address is controlled by a single account known to
2148 /// this wallet.
2149 /// - `Ok(None)` if no receiver of the address is recognized as belonging to any account.
2150 /// - `Err(FindAccountForAddressError::Backend(_))` if the lookup fails due to a
2151 /// backend error.
2152 /// - `Err(FindAccountForAddressError::UnifiedAddressConflict)` if the provided address
2153 /// is a Unified Address whose receiver components map to different accounts.
2154 ///
2155 /// [`UnifiedIncomingViewingKey`]: zcash_keys::keys::UnifiedIncomingViewingKey
2156 /// [`UnifiedIncomingViewingKey::decrypt_diversifiers`]: zcash_keys::keys::UnifiedIncomingViewingKey::decrypt_diversifiers
2157 /// [`FindAccountForAddressError::UnifiedAddressConflict`]: error::FindAccountForAddressError::UnifiedAddressConflict
2158 fn find_account_for_address<P: consensus::Parameters>(
2159 &self,
2160 params: &P,
2161 address: &zcash_keys::address::Address,
2162 ) -> Result<Option<Self::AccountId>, error::FindAccountForAddressError<Self::Error>>;
2163
2164 /// Returns the most recently generated unified address for the specified account that conforms
2165 /// to the specified address filter, if the account identifier specified refers to a valid
2166 /// account for this wallet.
2167 ///
2168 /// This will return `Ok(None)` if no previously generated address conforms to the specified
2169 /// request.
2170 fn get_last_generated_address_matching(
2171 &self,
2172 account: Self::AccountId,
2173 address_filter: UnifiedAddressRequest,
2174 ) -> Result<Option<UnifiedAddress>, Self::Error>;
2175
2176 /// Returns the birthday height for the given account, or an error if the account is not known
2177 /// to the wallet.
2178 fn get_account_birthday(&self, account: Self::AccountId) -> Result<BlockHeight, Self::Error>;
2179
2180 /// Returns the birthday height for the wallet.
2181 ///
2182 /// This returns the earliest birthday height among accounts maintained by this wallet,
2183 /// or `Ok(None)` if the wallet has no initialized accounts.
2184 fn get_wallet_birthday(&self) -> Result<Option<BlockHeight>, Self::Error>;
2185
2186 /// Returns the height at which the wallet as a whole will have exited recovery mode.
2187 ///
2188 /// This returns the latest `recover_until` height among accounts maintained by this
2189 /// wallet (see [`AccountBirthday::recover_until`]), or `Ok(None)` if no account has a
2190 /// recovery horizon set (for example, in a wallet whose accounts were all created at
2191 /// the chain tip rather than restored from backup). Heights below the returned value,
2192 /// exclusive, are in scope for wallet recovery for at least one account.
2193 fn get_wallet_recover_until(&self) -> Result<Option<BlockHeight>, Self::Error>;
2194
2195 /// Returns a [`WalletSummary`] that represents the sync status and the wallet balances as of
2196 /// the chain tip given the specified confirmation policy for all accounts known to the wallet,
2197 /// or `Ok(None)` if the wallet has no summary data available.
2198 fn get_wallet_summary(
2199 &self,
2200 confirmations_policy: ConfirmationsPolicy,
2201 ) -> Result<Option<WalletSummary<Self::AccountId>>, Self::Error>;
2202
2203 /// Returns the height of the chain as known to the wallet as of the most recent call to
2204 /// [`WalletWrite::update_chain_tip`].
2205 ///
2206 /// This will return `Ok(None)` if the height of the current consensus chain tip is unknown.
2207 fn chain_height(&self) -> Result<Option<BlockHeight>, Self::Error>;
2208
2209 /// Returns the interval on which this wallet retains note commitment tree checkpoints as
2210 /// durable anchors.
2211 ///
2212 /// A ZIP 318 pool migration anchors each of its pool-crossing transfers to a boundary of this
2213 /// interval, and proves the transfer long after that boundary has passed; the proof can only be
2214 /// constructed if the wallet kept the boundary's checkpoint. Reading the grid back off the
2215 /// wallet that maintains it — rather than configuring the migration separately — is what
2216 /// guarantees the two agree.
2217 ///
2218 /// The default implementation returns [`AnchorRetentionInterval::ZIP_318`], which matches the
2219 /// retention a backend performs if it does not configure the interval. A backend that DOES make
2220 /// retention configurable must override this to report the interval it actually retains, or
2221 /// migrations over it will draw anchors it has pruned.
2222 ///
2223 /// [`AnchorRetentionInterval::ZIP_318`]: anchor_retention::AnchorRetentionInterval::ZIP_318
2224 fn anchor_retention_interval(&self) -> anchor_retention::AnchorRetentionInterval {
2225 anchor_retention::AnchorRetentionInterval::ZIP_318
2226 }
2227
2228 /// Returns the ZIP 318 pool-migration parameters in force for this wallet: the specified
2229 /// values, with the anchor bucket grid taken from [`Self::anchor_retention_interval`].
2230 ///
2231 /// Every decision that depends on the grid must consult this rather than the network defaults,
2232 /// so that a wallet retaining a non-standard interval is treated consistently: bucketing an
2233 /// anchor and judging the resulting transaction a canonical crossing are the same question
2234 /// asked twice, and they must be asked of the same grid. Overriding
2235 /// [`Self::anchor_retention_interval`] is sufficient; this composes it.
2236 fn pool_migration_params(&self) -> anchor_retention::PoolMigrationParams {
2237 anchor_retention::PoolMigrationParams::new(self.anchor_retention_interval())
2238 }
2239
2240 /// Returns the block hash for the block at the given height, if the
2241 /// associated block data is available. Returns `Ok(None)` if the hash
2242 /// is not found in the database.
2243 fn get_block_hash(&self, block_height: BlockHeight) -> Result<Option<BlockHash>, Self::Error>;
2244
2245 /// Returns the available block metadata for the block at the specified height, if any.
2246 fn block_metadata(&self, height: BlockHeight) -> Result<Option<BlockMetadata>, Self::Error>;
2247
2248 /// Returns the metadata for the block at the height to which the wallet has been fully
2249 /// scanned.
2250 ///
2251 /// This is the height for which the wallet has fully trial-decrypted this and all preceding
2252 /// blocks above the wallet's birthday height. Along with this height, this method returns
2253 /// metadata describing the state of the wallet's note commitment trees as of the end of that
2254 /// block.
2255 fn block_fully_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error>;
2256
2257 /// Returns the block height and hash for the block at the maximum scanned block height.
2258 ///
2259 /// This will return `Ok(None)` if no blocks have been scanned.
2260 fn get_max_height_hash(&self) -> Result<Option<(BlockHeight, BlockHash)>, Self::Error>;
2261
2262 /// Returns block metadata for the maximum height that the wallet has scanned.
2263 ///
2264 /// If the wallet is fully synced, this will be equivalent to `block_fully_scanned`;
2265 /// otherwise the maximal scanned height is likely to be greater than the fully scanned height
2266 /// due to the fact that out-of-order scanning can leave gaps.
2267 fn block_max_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error>;
2268
2269 /// Returns a vector of suggested scan ranges based upon the current wallet state.
2270 ///
2271 /// This method should only be used in cases where the [`CompactBlock`] data that will be made
2272 /// available to `scan_cached_blocks` for the requested block ranges includes note commitment
2273 /// tree size information for each block; or else the scan is likely to fail if notes belonging
2274 /// to the wallet are detected.
2275 ///
2276 /// The returned range(s) may include block heights beyond the current chain tip. Ranges are
2277 /// returned in order of descending priority, and higher-priority ranges should always be
2278 /// scanned before lower-priority ranges; in particular, ranges with [`ScanPriority::Verify`]
2279 /// priority must always be scanned first in order to avoid blockchain continuity errors in the
2280 /// case of a reorg.
2281 ///
2282 /// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
2283 /// [`ScanPriority::Verify`]: crate::data_api::scanning::ScanPriority
2284 fn suggest_scan_ranges(&self) -> Result<Vec<ScanRange>, Self::Error>;
2285
2286 /// Returns the default target height (for the block in which a new
2287 /// transaction would be mined) and anchor height (to use for a new
2288 /// transaction), given the range of block heights that the backend
2289 /// knows about.
2290 ///
2291 /// This will return `Ok(None)` if no block data is present in the database.
2292 fn get_target_and_anchor_heights(
2293 &self,
2294 min_confirmations: NonZeroU32,
2295 ) -> Result<Option<(TargetHeight, BlockHeight)>, Self::Error>;
2296
2297 /// Returns the block height in which the specified transaction was mined, or `Ok(None)` if the
2298 /// transaction is not known to the wallet or not in the main chain.
2299 fn get_tx_height(&self, txid: TxId) -> Result<Option<BlockHeight>, Self::Error>;
2300
2301 /// Returns all unified full viewing keys known to this wallet.
2302 fn get_unified_full_viewing_keys(
2303 &self,
2304 ) -> Result<HashMap<Self::AccountId, UnifiedFullViewingKey>, Self::Error>;
2305
2306 /// Returns the memo for a note.
2307 ///
2308 /// Returns `Ok(None)` if the note is known to the wallet but memo data has not yet been
2309 /// populated for that note, or if the note identifier does not correspond to a note
2310 /// that is known to the wallet.
2311 fn get_memo(&self, note_id: NoteId) -> Result<Option<Memo>, Self::Error>;
2312
2313 /// Returns the transaction with the given txid, if known to the wallet.
2314 ///
2315 /// Returns `None` if the txid is not known to the wallet or if the raw transaction data is not
2316 /// available.
2317 fn get_transaction(&self, txid: TxId) -> Result<Option<Transaction>, Self::Error>;
2318
2319 /// Returns the nullifiers for Sapling notes that the wallet is tracking, along with their
2320 /// associated account IDs, that are either unspent or have not yet been confirmed as spent (in
2321 /// that a spending transaction known to the wallet has not yet been included in a block).
2322 fn get_sapling_nullifiers(
2323 &self,
2324 query: NullifierQuery,
2325 ) -> Result<Vec<(Self::AccountId, sapling::Nullifier)>, Self::Error>;
2326
2327 /// Returns the nullifiers for Orchard notes that the wallet is tracking, along with their
2328 /// associated account IDs, that are either unspent or have not yet been confirmed as spent (in
2329 /// that a spending transaction known to the wallet has not yet been included in a block).
2330 #[cfg(feature = "orchard")]
2331 fn get_orchard_nullifiers(
2332 &self,
2333 _query: NullifierQuery,
2334 ) -> Result<Vec<(Self::AccountId, orchard::note::Nullifier)>, Self::Error> {
2335 unimplemented!(
2336 "WalletRead::get_orchard_nullifiers must be overridden for wallets to use the `orchard` feature"
2337 )
2338 }
2339
2340 /// Returns the nullifiers for Ironwood notes that the wallet is tracking, along with their
2341 /// associated account IDs, that are either unspent or have not yet been confirmed as spent.
2342 /// Ironwood nullifiers are Orchard-shaped but are tracked as a separate pool.
2343 ///
2344 /// This is a required method (like [`WalletRead::get_sapling_nullifiers`]) rather than
2345 /// defaulting to a panic: it is called on the scan path, so a backend that does not override it
2346 /// would abort the process on the first scan. Requiring it surfaces the omission at compile
2347 /// time instead.
2348 #[cfg(feature = "orchard")]
2349 fn get_ironwood_nullifiers(
2350 &self,
2351 query: NullifierQuery,
2352 ) -> Result<Vec<(Self::AccountId, orchard::note::Nullifier)>, Self::Error>;
2353
2354 /// Returns the set of non-ephemeral transparent receivers associated with the given
2355 /// account controlled by this wallet.
2356 ///
2357 /// The set contains all non-ephemeral transparent receivers that are known to have
2358 /// been derived under this account. Wallets should scan the chain for UTXOs sent to
2359 /// these receivers.
2360 ///
2361 /// # Parameters
2362 /// - `account`: The identifier for the account from which transparent receivers should be
2363 /// returned.
2364 /// - `include_change`: A flag indicating whether transparent change addresses should be
2365 /// returned.
2366 /// - `include_standalone`: A flag indicating whether imported standalone addresses associated
2367 /// with the account should be returned. The value of this flag is ignored unless the
2368 /// `transparent-key-import` feature is enabled.
2369 ///
2370 /// Use [`Self::get_ephemeral_transparent_receivers`] to obtain the ephemeral transparent
2371 /// receivers.
2372 #[cfg(feature = "transparent-inputs")]
2373 fn get_transparent_receivers(
2374 &self,
2375 _account: Self::AccountId,
2376 _include_change: bool,
2377 _include_standalone: bool,
2378 ) -> Result<HashMap<TransparentAddress, TransparentAddressMetadata>, Self::Error> {
2379 unimplemented!(
2380 "WalletRead::get_transparent_receivers must be overridden for wallets to use the `transparent-inputs` feature"
2381 )
2382 }
2383
2384 /// Returns the set of previously-exposed ephemeral transparent receivers generated by the given
2385 /// account controlled by this wallet.
2386 ///
2387 /// The set contains all ephemeral transparent receivers that are known to have been derived
2388 /// under this account within `exposure_depth` blocks of the chain tip. Wallets may scan the
2389 /// chain for UTXOs sent to these receivers, but should do so in a fashion that does not reveal
2390 /// that they are controlled by the same wallet. If the [`next_check_time`] field is set for a
2391 /// returned [`TransparentAddressMetadata`], the wallet application should defer any query to
2392 /// any public light wallet server for this address until [`next_check_time`] has passed; when
2393 /// using a light wallet server that is trusted for privacy, this delay may be omitted.
2394 ///
2395 /// # Parameters
2396 /// - `account`: The identifier for the account from which transparent receivers should be
2397 /// returned.
2398 /// - `exposure_depth`: Implementations of this method should return only addresses exposed at
2399 /// heights greater than `chain_tip_height - exposure_depth`.
2400 /// - `exclude_used`: When set to `true`, do not return addresses that are known to have
2401 /// already received funds in a transaction.
2402 ///
2403 /// [`next_check_time`]: TransparentAddressMetadata::next_check_time
2404 #[cfg(feature = "transparent-inputs")]
2405 fn get_ephemeral_transparent_receivers(
2406 &self,
2407 _account: Self::AccountId,
2408 _exposure_depth: u32,
2409 _exclude_used: bool,
2410 ) -> Result<HashMap<TransparentAddress, TransparentAddressMetadata>, Self::Error> {
2411 unimplemented!(
2412 "WalletRead::get_ephemeral_transparent_receivers must be overridden for wallets to use the `transparent-inputs` feature"
2413 )
2414 }
2415
2416 /// Returns a mapping from each transparent receiver associated with the specified account
2417 /// to the key scope for that address and the balance of funds given the specified target
2418 /// height and confirmations policy.
2419 #[cfg(feature = "transparent-inputs")]
2420 fn get_transparent_balances(
2421 &self,
2422 _account: Self::AccountId,
2423 _target_height: TargetHeight,
2424 _confirmations_policy: ConfirmationsPolicy,
2425 ) -> Result<TransparentBalances, Self::Error> {
2426 unimplemented!(
2427 "WalletRead::get_transparent_balances must be overridden for wallets to use the `transparent-inputs` feature"
2428 )
2429 }
2430
2431 /// Returns the metadata associated with a given transparent receiver in an account
2432 /// controlled by this wallet, if available.
2433 ///
2434 /// This is equivalent to (but may be implemented more efficiently than):
2435 /// ```compile_fail
2436 /// Ok(
2437 /// if let Some(result) = self.get_transparent_receivers(account, true)?.get(address) {
2438 /// Some(result.clone())
2439 /// } else {
2440 /// self.get_ephemeral_transparent_receivers(account, u32::MAX, false)?
2441 /// .get(address)
2442 /// .cloned()
2443 /// },
2444 /// )
2445 /// ```
2446 ///
2447 /// Returns `Ok(None)` if the address is not recognized, or we do not have metadata for it.
2448 /// Returns `Ok(Some(metadata))` if we have the metadata.
2449 #[cfg(feature = "transparent-inputs")]
2450 fn get_transparent_address_metadata(
2451 &self,
2452 _account: Self::AccountId,
2453 _address: &TransparentAddress,
2454 ) -> Result<Option<TransparentAddressMetadata>, Self::Error> {
2455 unimplemented!(
2456 "WalletRead::get_transparent_address_metadata must be overridden for wallets to use the `transparent-inputs` feature"
2457 )
2458 }
2459
2460 /// Returns the maximum block height at which a transparent output belonging to the wallet has
2461 /// been observed.
2462 ///
2463 /// We must start looking for UTXOs for addresses within the current gap limit as of the block
2464 /// height at which they might have first been revealed. This would have occurred when the gap
2465 /// advanced as a consequence of a transaction being mined. The address at the start of the current
2466 /// gap was potentially first revealed after the address at index `gap_start - (gap_limit + 1)`
2467 /// received an output in a mined transaction; therefore, we take that height to be where we
2468 /// should start searching for UTXOs.
2469 #[cfg(feature = "transparent-inputs")]
2470 fn utxo_query_height(&self, _account: Self::AccountId) -> Result<BlockHeight, Self::Error> {
2471 unimplemented!(
2472 "WalletRead::utxo_query_height must be overridden for wallets to use the `transparent-inputs` feature"
2473 )
2474 }
2475
2476 /// Returns a vector of [`TransactionDataRequest`] values that describe information needed by
2477 /// the wallet to complete its view of transaction history.
2478 ///
2479 /// Requests for the same transaction data may be returned repeatedly by successive data
2480 /// requests. The caller of this method should consider the latest set of requests returned
2481 /// by this method to be authoritative and to subsume that returned by previous calls.
2482 ///
2483 /// Callers should poll this method on a regular interval, not as part of ordinary chain
2484 /// scanning, which already produces requests for transaction data enhancement. Note that
2485 /// responding to a set of transaction data requests may result in the creation of new
2486 /// transaction data requests, such as when it is necessary to fill in purely-transparent
2487 /// transaction history by walking the chain backwards via transparent inputs.
2488 fn transaction_data_requests(&self) -> Result<Vec<TransactionDataRequest>, Self::Error>;
2489
2490 /// Returns a vector of [`ReceivedTransactionOutput`] values describing the outputs of the
2491 /// specified transaction that were received by the wallet. The number of confirmations until
2492 /// each received output will be considered spendable is determined based upon the specified
2493 /// target height and confirmations policy.
2494 fn get_received_outputs(
2495 &self,
2496 txid: TxId,
2497 target_height: TargetHeight,
2498 confirmations_policy: ConfirmationsPolicy,
2499 ) -> Result<Vec<ReceivedTransactionOutput>, Self::Error>;
2500}
2501
2502/// Read-only operations required for testing light wallet functions.
2503///
2504/// These methods expose internal details or unstable interfaces, primarily to enable use
2505/// of the [`testing`] framework. They should not be used in production software.
2506#[cfg(any(test, feature = "test-dependencies"))]
2507#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
2508pub trait WalletTest: InputSource + WalletRead {
2509 /// Returns a vector of transaction summaries.
2510 ///
2511 /// Currently test-only, as production use could return a very large number of results; either
2512 /// pagination or a streaming design will be necessary to stabilize this feature for production
2513 /// use.
2514 fn get_tx_history(
2515 &self,
2516 ) -> Result<
2517 Vec<testing::TransactionSummary<<Self as WalletRead>::AccountId>>,
2518 <Self as WalletRead>::Error,
2519 >;
2520
2521 /// Returns the note IDs for shielded notes sent by the wallet in a particular
2522 /// transaction.
2523 fn get_sent_note_ids(
2524 &self,
2525 _txid: &TxId,
2526 _protocol: ShieldedPool,
2527 ) -> Result<Vec<NoteId>, <Self as WalletRead>::Error>;
2528
2529 /// Returns the outputs for a transaction sent by the wallet.
2530 #[allow(clippy::type_complexity)]
2531 fn get_sent_outputs(
2532 &self,
2533 txid: &TxId,
2534 ) -> Result<Vec<OutputOfSentTx>, <Self as WalletRead>::Error>;
2535
2536 #[allow(clippy::type_complexity)]
2537 fn get_checkpoint_history(
2538 &self,
2539 protocol: &ShieldedPool,
2540 ) -> Result<
2541 Vec<(BlockHeight, Option<incrementalmerkletree::Position>)>,
2542 <Self as WalletRead>::Error,
2543 >;
2544
2545 /// Fetches the transparent output corresponding to the provided `outpoint`.
2546 /// Allows selecting unspendable outputs for testing purposes.
2547 ///
2548 /// # Parameters
2549 /// - `outpoint`: The identifier for the output to be retrieved.
2550 /// - `spendable_as_of`: The target height of a transaction under construction that will spend the
2551 /// returned output. If this is `None`, no spendability checks are performed.
2552 ///
2553 /// Returns `Ok(None)` if the UTXO is not known to belong to the wallet or if `spendable_as_of`
2554 /// is set and the output is available to be spent by the wallet in a transaction that is
2555 /// intended to be mined at the target height.
2556 #[cfg(feature = "transparent-inputs")]
2557 fn get_transparent_output(
2558 &self,
2559 _outpoint: &OutPoint,
2560 _spendable_as_of: Option<TargetHeight>,
2561 ) -> Result<
2562 Option<WalletTransparentOutput<<Self as WalletRead>::AccountId>>,
2563 <Self as InputSource>::Error,
2564 > {
2565 unimplemented!(
2566 "WalletTest::get_transparent_output must be overridden for wallets to use the `transparent-inputs` feature"
2567 )
2568 }
2569
2570 /// Returns all the notes that have been received by the wallet.
2571 fn get_notes(
2572 &self,
2573 protocol: ShieldedPool,
2574 ) -> Result<Vec<ReceivedNote<Self::NoteRef, Note>>, <Self as InputSource>::Error>;
2575
2576 /// Returns a vector of ephemeral transparent addresses associated with the given
2577 /// account controlled by this wallet, along with their metadata. The result includes
2578 /// reserved addresses, and addresses for the backend's configured gap limit worth
2579 /// of additional indices (capped to the maximum index).
2580 ///
2581 /// If `index_range` is some `Range`, it limits the result to addresses with indices
2582 /// in that range. An `index_range` of `None` is defined to be equivalent to
2583 /// `0..(1u32 << 31)`.
2584 ///
2585 /// Wallets should scan the chain for UTXOs sent to these ephemeral transparent
2586 /// receivers, but do not need to do so regularly. Under expected usage, outputs
2587 /// would only be detected with these receivers in the following situations:
2588 ///
2589 /// - This wallet created a payment to a ZIP 320 (TEX) address, but the second
2590 /// transaction (that spent the output sent to the ephemeral address) did not get
2591 /// mined before it expired.
2592 /// - In this case the output will already be known to the wallet (because it
2593 /// stores the transactions that it creates).
2594 ///
2595 /// - Another wallet app using the same seed phrase created a payment to a ZIP 320
2596 /// address, and this wallet queried for the ephemeral UTXOs after the first
2597 /// transaction was mined but before the second transaction was mined.
2598 /// - In this case, the output should not be considered unspent until the expiry
2599 /// height of the transaction it was received in has passed. Wallets creating
2600 /// payments to TEX addresses generally set the same expiry height for the first
2601 /// and second transactions, meaning that this wallet does not need to observe
2602 /// the second transaction to determine when it would have expired.
2603 ///
2604 /// - A TEX address recipient decided to return funds that the wallet had sent to
2605 /// them.
2606 ///
2607 /// In all cases, the wallet should re-shield the unspent outputs, in a separate
2608 /// transaction per ephemeral address, before re-spending the funds.
2609 #[cfg(feature = "transparent-inputs")]
2610 fn get_known_ephemeral_addresses(
2611 &self,
2612 _account: <Self as WalletRead>::AccountId,
2613 _index_range: Option<Range<NonHardenedChildIndex>>,
2614 ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
2615 {
2616 unimplemented!(
2617 "WalletRead::get_known_ephemeral_addresses must be overridden for wallets to use the `transparent-inputs` feature"
2618 )
2619 }
2620
2621 /// If a given ephemeral address might have been reserved, i.e. would be included in
2622 /// the result of `get_known_ephemeral_addresses(account_id, None)` for any of the
2623 /// wallet's accounts, then return `Ok(Some(account_id))`. Otherwise return `Ok(None)`.
2624 ///
2625 /// This is equivalent to (but may be implemented more efficiently than):
2626 /// ```compile_fail
2627 /// for account_id in self.get_account_ids()? {
2628 /// if self
2629 /// .get_known_ephemeral_addresses(account_id, None)?
2630 /// .into_iter()
2631 /// .any(|(known_addr, _)| &known_addr == address)
2632 /// {
2633 /// return Ok(Some(account_id));
2634 /// }
2635 /// }
2636 /// Ok(None)
2637 /// ```
2638 #[cfg(feature = "transparent-inputs")]
2639 fn find_account_for_ephemeral_address(
2640 &self,
2641 address: &TransparentAddress,
2642 ) -> Result<Option<<Self as WalletRead>::AccountId>, <Self as WalletRead>::Error> {
2643 for account_id in self.get_account_ids()? {
2644 if self
2645 .get_known_ephemeral_addresses(account_id, None)?
2646 .into_iter()
2647 .any(|(known_addr, _)| &known_addr == address)
2648 {
2649 return Ok(Some(account_id));
2650 }
2651 }
2652 Ok(None)
2653 }
2654
2655 /// Performs final checks at the conclusion of each test.
2656 ///
2657 /// This method allows wallet backend developers to perform any necessary consistency
2658 /// checks or cleanup. By default it does nothing.
2659 fn finally(&self) {}
2660}
2661
2662/// The output of a transaction sent by the wallet.
2663///
2664/// This type is opaque, and exists for use by tests defined in this crate.
2665#[cfg(any(test, feature = "test-dependencies"))]
2666#[allow(dead_code)]
2667#[derive(Clone, Debug)]
2668pub struct OutputOfSentTx {
2669 value: Zatoshis,
2670 external_recipient: Option<Address>,
2671 #[cfg(feature = "transparent-inputs")]
2672 ephemeral_address: Option<(Address, NonHardenedChildIndex)>,
2673}
2674
2675#[cfg(any(test, feature = "test-dependencies"))]
2676impl OutputOfSentTx {
2677 /// Constructs an output from its test-relevant parts.
2678 ///
2679 /// If the output is to an ephemeral address, `ephemeral_address` should contain the
2680 /// address along with the `address_index` it was derived from under the BIP 32 path
2681 /// `m/44'/<coin_type>'/<account>'/2/<address_index>`.
2682 pub fn from_parts(
2683 value: Zatoshis,
2684 external_recipient: Option<Address>,
2685 #[cfg(feature = "transparent-inputs")] ephemeral_address: Option<(
2686 Address,
2687 NonHardenedChildIndex,
2688 )>,
2689 ) -> Self {
2690 Self {
2691 value,
2692 external_recipient,
2693 #[cfg(feature = "transparent-inputs")]
2694 ephemeral_address,
2695 }
2696 }
2697
2698 /// Returns the value of the output.
2699 pub fn value(&self) -> Zatoshis {
2700 self.value
2701 }
2702
2703 /// Returns the recipient of the sent output.
2704 pub fn external_recipient(&self) -> Option<&Address> {
2705 self.external_recipient.as_ref()
2706 }
2707
2708 /// Returns the ephemeral address to which the output was sent, along with the non-hardened
2709 /// transparent child index at which that address was derived.
2710 #[cfg(feature = "transparent-inputs")]
2711 pub fn ephemeral_address(&self) -> Option<&(Address, NonHardenedChildIndex)> {
2712 self.ephemeral_address.as_ref()
2713 }
2714}
2715
2716/// The relevance of a seed to a given wallet.
2717///
2718/// This is the return type for [`WalletRead::seed_relevance_to_derived_accounts`].
2719#[derive(Clone, Debug, PartialEq, Eq)]
2720pub enum SeedRelevance<A: Copy> {
2721 /// The seed is relevant to at least one derived account within the wallet.
2722 Relevant { account_ids: NonEmpty<A> },
2723 /// The seed is not relevant to any of the derived accounts within the wallet.
2724 NotRelevant,
2725 /// The wallet contains no derived accounts.
2726 NoDerivedAccounts,
2727 /// The wallet contains no accounts.
2728 NoAccounts,
2729}
2730
2731/// Metadata describing the sizes of the zcash note commitment trees as of a particular block.
2732#[derive(Debug, Clone, Copy)]
2733pub struct BlockMetadata {
2734 block_height: BlockHeight,
2735 block_hash: BlockHash,
2736 sapling_tree_size: Option<u32>,
2737 #[cfg(feature = "orchard")]
2738 orchard_tree_size: Option<u32>,
2739 #[cfg(feature = "orchard")]
2740 ironwood_tree_size: Option<u32>,
2741}
2742
2743impl BlockMetadata {
2744 /// Constructs a new [`BlockMetadata`] value from its constituent parts.
2745 pub fn from_parts(
2746 block_height: BlockHeight,
2747 block_hash: BlockHash,
2748 sapling_tree_size: Option<u32>,
2749 #[cfg(feature = "orchard")] orchard_tree_size: Option<u32>,
2750 #[cfg(feature = "orchard")] ironwood_tree_size: Option<u32>,
2751 ) -> Self {
2752 Self {
2753 block_height,
2754 block_hash,
2755 sapling_tree_size,
2756 #[cfg(feature = "orchard")]
2757 orchard_tree_size,
2758 #[cfg(feature = "orchard")]
2759 ironwood_tree_size,
2760 }
2761 }
2762
2763 /// Returns the block height.
2764 pub fn block_height(&self) -> BlockHeight {
2765 self.block_height
2766 }
2767
2768 /// Returns the hash of the block
2769 pub fn block_hash(&self) -> BlockHash {
2770 self.block_hash
2771 }
2772
2773 /// Returns the size of the Sapling note commitment tree for the final treestate of the block
2774 /// that this [`BlockMetadata`] describes, if available.
2775 pub fn sapling_tree_size(&self) -> Option<u32> {
2776 self.sapling_tree_size
2777 }
2778
2779 /// Returns the size of the Orchard note commitment tree for the final treestate of the block
2780 /// that this [`BlockMetadata`] describes, if available.
2781 #[cfg(feature = "orchard")]
2782 pub fn orchard_tree_size(&self) -> Option<u32> {
2783 self.orchard_tree_size
2784 }
2785
2786 /// Returns the size of the Ironwood note commitment tree for the final treestate of the block
2787 /// that this [`BlockMetadata`] describes, if available.
2788 #[cfg(feature = "orchard")]
2789 pub fn ironwood_tree_size(&self) -> Option<u32> {
2790 self.ironwood_tree_size
2791 }
2792}
2793
2794/// The protocol-specific note commitment and nullifier data extracted from the per-transaction
2795/// shielded bundles in [`CompactBlock`], used by the wallet for note commitment tree maintenance
2796/// and spend detection.
2797///
2798/// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
2799pub struct ScannedBundles<NoteCommitment, NF> {
2800 final_tree_size: u32,
2801 commitments: Vec<(NoteCommitment, Retention<BlockHeight>)>,
2802 nullifier_map: Vec<(TxIndex, TxId, Vec<NF>)>,
2803}
2804
2805impl<NoteCommitment, NF> ScannedBundles<NoteCommitment, NF> {
2806 pub(crate) fn new(
2807 final_tree_size: u32,
2808 commitments: Vec<(NoteCommitment, Retention<BlockHeight>)>,
2809 nullifier_map: Vec<(TxIndex, TxId, Vec<NF>)>,
2810 ) -> Self {
2811 Self {
2812 final_tree_size,
2813 nullifier_map,
2814 commitments,
2815 }
2816 }
2817
2818 /// Returns the size of the note commitment tree as of the end of the scanned block.
2819 pub fn final_tree_size(&self) -> u32 {
2820 self.final_tree_size
2821 }
2822
2823 /// Returns the vector of nullifiers for each transaction in the block.
2824 ///
2825 /// The returned tuple is keyed by both transaction ID and the index of the transaction within
2826 /// the block, so that either the txid or the combination of the block hash available from
2827 /// [`ScannedBlock::block_hash`] and returned transaction index may be used to uniquely
2828 /// identify the transaction, depending upon the needs of the caller.
2829 pub fn nullifier_map(&self) -> &[(TxIndex, TxId, Vec<NF>)] {
2830 &self.nullifier_map
2831 }
2832
2833 /// Returns the ordered list of note commitments to be added to the note commitment
2834 /// tree.
2835 pub fn commitments(&self) -> &[(NoteCommitment, Retention<BlockHeight>)] {
2836 &self.commitments
2837 }
2838}
2839
2840/// A struct used to return the vectors of note commitments for a [`ScannedBlock`]
2841/// as owned values.
2842pub struct ScannedBlockCommitments {
2843 /// The ordered vector of note commitments for Sapling outputs of the block.
2844 pub sapling: Vec<(sapling::Node, Retention<BlockHeight>)>,
2845 /// The ordered vector of note commitments for Orchard outputs of the block.
2846 /// Present only when the `orchard` feature is enabled.
2847 #[cfg(feature = "orchard")]
2848 pub orchard: Vec<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>,
2849 /// The ordered vector of note commitments for Ironwood outputs of the block.
2850 /// Present only when the `orchard` feature is enabled.
2851 #[cfg(feature = "orchard")]
2852 pub ironwood: Vec<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>,
2853}
2854
2855/// The subset of information that is relevant to this wallet that has been
2856/// decrypted and extracted from a [`CompactBlock`].
2857///
2858/// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
2859pub struct ScannedBlock<AccountId> {
2860 block_height: BlockHeight,
2861 block_hash: BlockHash,
2862 block_time: u32,
2863 transactions: Vec<WalletTx<AccountId>>,
2864 sapling: ScannedBundles<sapling::Node, sapling::Nullifier>,
2865 #[cfg(feature = "orchard")]
2866 orchard: ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier>,
2867 #[cfg(feature = "orchard")]
2868 ironwood: ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier>,
2869}
2870
2871impl<AccountId> ScannedBlock<AccountId> {
2872 /// Constructs a new `ScannedBlock`
2873 pub(crate) fn from_parts(
2874 block_height: BlockHeight,
2875 block_hash: BlockHash,
2876 block_time: u32,
2877 transactions: Vec<WalletTx<AccountId>>,
2878 sapling: ScannedBundles<sapling::Node, sapling::Nullifier>,
2879 #[cfg(feature = "orchard")] orchard: ScannedBundles<
2880 orchard::tree::MerkleHashOrchard,
2881 orchard::note::Nullifier,
2882 >,
2883 #[cfg(feature = "orchard")] ironwood: ScannedBundles<
2884 orchard::tree::MerkleHashOrchard,
2885 orchard::note::Nullifier,
2886 >,
2887 ) -> Self {
2888 Self {
2889 block_height,
2890 block_hash,
2891 block_time,
2892 transactions,
2893 sapling,
2894 #[cfg(feature = "orchard")]
2895 orchard,
2896 #[cfg(feature = "orchard")]
2897 ironwood,
2898 }
2899 }
2900
2901 /// Returns the height of the block that was scanned.
2902 pub fn height(&self) -> BlockHeight {
2903 self.block_height
2904 }
2905
2906 /// Returns the block hash of the block that was scanned.
2907 pub fn block_hash(&self) -> BlockHash {
2908 self.block_hash
2909 }
2910
2911 /// Returns the block time of the block that was scanned, as a Unix timestamp in seconds.
2912 pub fn block_time(&self) -> u32 {
2913 self.block_time
2914 }
2915
2916 /// Returns the list of transactions from this block that are relevant to the wallet.
2917 pub fn transactions(&self) -> &[WalletTx<AccountId>] {
2918 &self.transactions
2919 }
2920
2921 /// Returns the Sapling note commitment tree and nullifier data for the block.
2922 pub fn sapling(&self) -> &ScannedBundles<sapling::Node, sapling::Nullifier> {
2923 &self.sapling
2924 }
2925
2926 /// Returns the Orchard note commitment tree and nullifier data for the block.
2927 #[cfg(feature = "orchard")]
2928 pub fn orchard(
2929 &self,
2930 ) -> &ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier> {
2931 &self.orchard
2932 }
2933
2934 /// Returns the Ironwood note commitment tree and nullifier data for the block.
2935 #[cfg(feature = "orchard")]
2936 pub fn ironwood(
2937 &self,
2938 ) -> &ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier> {
2939 &self.ironwood
2940 }
2941
2942 /// Consumes `self` and returns the lists of Sapling, Orchard, and Ironwood note commitments
2943 /// associated with the scanned block as an owned value.
2944 pub fn into_commitments(self) -> ScannedBlockCommitments {
2945 ScannedBlockCommitments {
2946 sapling: self.sapling.commitments,
2947 #[cfg(feature = "orchard")]
2948 orchard: self.orchard.commitments,
2949 #[cfg(feature = "orchard")]
2950 ironwood: self.ironwood.commitments,
2951 }
2952 }
2953
2954 /// Returns the [`BlockMetadata`] corresponding to the scanned block.
2955 pub fn to_block_metadata(&self) -> BlockMetadata {
2956 BlockMetadata {
2957 block_height: self.block_height,
2958 block_hash: self.block_hash,
2959 sapling_tree_size: Some(self.sapling.final_tree_size),
2960 #[cfg(feature = "orchard")]
2961 orchard_tree_size: Some(self.orchard.final_tree_size),
2962 #[cfg(feature = "orchard")]
2963 ironwood_tree_size: Some(self.ironwood.final_tree_size),
2964 }
2965 }
2966}
2967
2968/// A trait representing a decryptable transaction.
2969pub trait DecryptableTransaction<AccountId> {
2970 type DecryptedSaplingOutput;
2971 #[cfg(feature = "orchard")]
2972 type DecryptedOrchardOutput;
2973}
2974
2975impl<AccountId> DecryptableTransaction<AccountId> for Transaction {
2976 type DecryptedSaplingOutput = DecryptedOutput<sapling::Note, AccountId>;
2977 #[cfg(feature = "orchard")]
2978 type DecryptedOrchardOutput = DecryptedOutput<(orchard::Note, orchard::ValuePool), AccountId>;
2979}
2980
2981/// A transaction that was detected during scanning of the blockchain,
2982/// including its decrypted Sapling and/or Orchard outputs.
2983///
2984/// The purpose of this struct is to permit atomic updates of the
2985/// wallet database when transactions are successfully decrypted.
2986pub struct DecryptedTransaction<'a, Tx: DecryptableTransaction<AccountId>, AccountId> {
2987 mined_height: Option<BlockHeight>,
2988 tx: &'a Tx,
2989 sapling_outputs: Vec<Tx::DecryptedSaplingOutput>,
2990 #[cfg(feature = "orchard")]
2991 orchard_outputs: Vec<Tx::DecryptedOrchardOutput>,
2992 #[cfg(feature = "orchard")]
2993 ironwood_outputs: Vec<Tx::DecryptedOrchardOutput>,
2994}
2995
2996impl<'a, Tx: DecryptableTransaction<AccountId>, AccountId> DecryptedTransaction<'a, Tx, AccountId> {
2997 /// Constructs a new [`DecryptedTransaction`] from its constituent parts.
2998 ///
2999 /// Ironwood outputs are Orchard-shaped but belong to a distinct pool, and are passed and
3000 /// tracked separately from Orchard outputs.
3001 pub fn new(
3002 mined_height: Option<BlockHeight>,
3003 tx: &'a Tx,
3004 sapling_outputs: Vec<Tx::DecryptedSaplingOutput>,
3005 #[cfg(feature = "orchard")] orchard_outputs: Vec<Tx::DecryptedOrchardOutput>,
3006 #[cfg(feature = "orchard")] ironwood_outputs: Vec<Tx::DecryptedOrchardOutput>,
3007 ) -> Self {
3008 Self {
3009 mined_height,
3010 tx,
3011 sapling_outputs,
3012 #[cfg(feature = "orchard")]
3013 orchard_outputs,
3014 #[cfg(feature = "orchard")]
3015 ironwood_outputs,
3016 }
3017 }
3018
3019 /// Returns the height at which the transaction was mined, if known.
3020 pub fn mined_height(&self) -> Option<BlockHeight> {
3021 self.mined_height
3022 }
3023 /// Returns the raw transaction data.
3024 pub fn tx(&self) -> &Tx {
3025 self.tx
3026 }
3027 /// Returns the Sapling outputs that were decrypted from the transaction.
3028 pub fn sapling_outputs(&self) -> &[Tx::DecryptedSaplingOutput] {
3029 &self.sapling_outputs
3030 }
3031 /// Returns the Orchard outputs that were decrypted from the transaction.
3032 #[cfg(feature = "orchard")]
3033 pub fn orchard_outputs(&self) -> &[Tx::DecryptedOrchardOutput] {
3034 &self.orchard_outputs
3035 }
3036
3037 /// Returns the Ironwood outputs that were decrypted from the transaction.
3038 ///
3039 /// Ironwood outputs are Orchard-shaped but belong to a pool distinct from Orchard.
3040 #[cfg(feature = "orchard")]
3041 pub fn ironwood_outputs(&self) -> &[Tx::DecryptedOrchardOutput] {
3042 &self.ironwood_outputs
3043 }
3044
3045 /// Returns whether the transaction has decrypted outputs
3046 pub fn has_decrypted_outputs(&self) -> bool {
3047 let has_sapling = !self.sapling_outputs.is_empty();
3048 #[cfg(feature = "orchard")]
3049 let has_orchard = !self.orchard_outputs.is_empty() || !self.ironwood_outputs.is_empty();
3050 #[cfg(not(feature = "orchard"))]
3051 let has_orchard = false;
3052
3053 has_sapling || has_orchard
3054 }
3055}
3056
3057/// A transaction that was constructed and sent by the wallet.
3058///
3059/// The purpose of this struct is to permit atomic updates of the
3060/// wallet database when transactions are created and submitted
3061/// to the network.
3062pub struct SentTransaction<'a, AccountId> {
3063 tx: &'a Transaction,
3064 created: time::OffsetDateTime,
3065 target_height: TargetHeight,
3066 funding_account: AccountId,
3067 outputs: &'a [SentTransactionOutput<AccountId>],
3068 fee_amount: Zatoshis,
3069 #[cfg(feature = "transparent-inputs")]
3070 utxos_spent: &'a [OutPoint],
3071}
3072
3073impl<'a, AccountId> SentTransaction<'a, AccountId> {
3074 /// Constructs a new [`SentTransaction`] from its constituent parts.
3075 ///
3076 /// ### Parameters
3077 /// - `tx`: the raw transaction data
3078 /// - `created`: the system time at which the transaction was created
3079 /// - `target_height`: the target height that was used in the construction of the transaction
3080 /// - `funding_account`: the account that spent funds in creation of the transaction
3081 /// - `outputs`: the outputs created by the transaction, including those sent to external
3082 /// recipients which may not otherwise be recoverable
3083 /// - `fee_amount`: the fee value paid by the transaction
3084 /// - `utxos_spent`: the UTXOs controlled by the wallet that were spent in this transaction
3085 pub fn new(
3086 tx: &'a Transaction,
3087 created: time::OffsetDateTime,
3088 target_height: TargetHeight,
3089 funding_account: AccountId,
3090 outputs: &'a [SentTransactionOutput<AccountId>],
3091 fee_amount: Zatoshis,
3092 #[cfg(feature = "transparent-inputs")] utxos_spent: &'a [OutPoint],
3093 ) -> Self {
3094 Self {
3095 tx,
3096 created,
3097 target_height,
3098 funding_account,
3099 outputs,
3100 fee_amount,
3101 #[cfg(feature = "transparent-inputs")]
3102 utxos_spent,
3103 }
3104 }
3105
3106 /// Returns the transaction that was sent.
3107 pub fn tx(&self) -> &Transaction {
3108 self.tx
3109 }
3110 /// Returns the timestamp of the transaction's creation.
3111 pub fn created(&self) -> time::OffsetDateTime {
3112 self.created
3113 }
3114 /// Returns the id for the account that created the outputs.
3115 pub fn funding_account(&self) -> &AccountId {
3116 &self.funding_account
3117 }
3118 /// Returns the outputs of the transaction.
3119 pub fn outputs(&self) -> &[SentTransactionOutput<AccountId>] {
3120 self.outputs
3121 }
3122 /// Returns the fee paid by the transaction.
3123 pub fn fee_amount(&self) -> Zatoshis {
3124 self.fee_amount
3125 }
3126 /// Returns the list of UTXOs spent in the created transaction.
3127 #[cfg(feature = "transparent-inputs")]
3128 pub fn utxos_spent(&self) -> &[OutPoint] {
3129 self.utxos_spent
3130 }
3131
3132 /// Returns the block height that this transaction was created to target.
3133 pub fn target_height(&self) -> TargetHeight {
3134 self.target_height
3135 }
3136}
3137
3138/// High-level information about the output of a transaction received by the wallet.
3139///
3140/// This type is capable of representing both shielded and transparent outputs. It does not
3141/// internally store the transaction ID, so it must be interpreted in the context of a caller
3142/// having requested output information for a specific transaction.
3143pub struct ReceivedTransactionOutput {
3144 pool_type: PoolType,
3145 output_index: usize,
3146 value: Zatoshis,
3147 confirmations_until_spendable: u32,
3148}
3149
3150impl ReceivedTransactionOutput {
3151 /// Constructs a [`ReceivedTransactionOutput`] from its constituent parts.
3152 pub fn from_parts(
3153 pool_type: PoolType,
3154 output_index: usize,
3155 value: Zatoshis,
3156 confirmations_until_spendable: u32,
3157 ) -> Self {
3158 Self {
3159 pool_type,
3160 output_index,
3161 value,
3162 confirmations_until_spendable,
3163 }
3164 }
3165
3166 /// Returns the pool in which the output value was received.
3167 pub fn pool_type(&self) -> PoolType {
3168 self.pool_type
3169 }
3170
3171 /// Returns the index of the output among the transaction's outputs to the associated pool.
3172 pub fn output_index(&self) -> usize {
3173 self.output_index
3174 }
3175
3176 /// Returns the value of the output.
3177 pub fn value(&self) -> Zatoshis {
3178 self.value
3179 }
3180
3181 /// Returns the number of confirmations required for the output to be treated as spendable,
3182 /// given a [`ConfirmationsPolicy`] that was specified at the time of the request for this
3183 /// data.
3184 pub fn confirmations_until_spendable(&self) -> u32 {
3185 self.confirmations_until_spendable
3186 }
3187}
3188
3189/// Identifies one of the wallet-maintained note commitment trees.
3190#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3191pub enum NoteCommitmentTree {
3192 /// The Sapling note commitment tree.
3193 Sapling,
3194 /// The Orchard note commitment tree.
3195 #[cfg(feature = "orchard")]
3196 Orchard,
3197 /// The Ironwood note commitment tree.
3198 #[cfg(feature = "orchard")]
3199 Ironwood,
3200}
3201
3202/// An output of a transaction generated by the wallet.
3203///
3204/// This type is capable of representing both shielded and transparent outputs.
3205pub struct SentTransactionOutput<AccountId> {
3206 output_index: usize,
3207 note_commitment_tree: Option<NoteCommitmentTree>,
3208 recipient: Recipient<AccountId>,
3209 value: Zatoshis,
3210 memo: Option<MemoBytes>,
3211}
3212
3213impl<AccountId> SentTransactionOutput<AccountId> {
3214 /// Constructs a new [`SentTransactionOutput`] from its constituent parts.
3215 ///
3216 /// ### Fields:
3217 /// * `output_index` - the index of the output or action in the sent transaction
3218 /// * `recipient` - the recipient of the output, either a Zcash address or a
3219 /// wallet-internal account and the note belonging to the wallet created by
3220 /// the output
3221 /// * `value` - the value of the output, in zatoshis
3222 /// * `memo` - the memo that was sent with this output
3223 pub fn from_parts(
3224 output_index: usize,
3225 recipient: Recipient<AccountId>,
3226 value: Zatoshis,
3227 memo: Option<MemoBytes>,
3228 ) -> Self {
3229 Self {
3230 output_index,
3231 note_commitment_tree: None,
3232 recipient,
3233 value,
3234 memo,
3235 }
3236 }
3237
3238 /// Constructs a new [`SentTransactionOutput`] with explicit note commitment tree metadata.
3239 pub(crate) fn from_parts_in_tree(
3240 note_commitment_tree: Option<NoteCommitmentTree>,
3241 output_index: usize,
3242 recipient: Recipient<AccountId>,
3243 value: Zatoshis,
3244 memo: Option<MemoBytes>,
3245 ) -> Self {
3246 Self {
3247 output_index,
3248 note_commitment_tree,
3249 recipient,
3250 value,
3251 memo,
3252 }
3253 }
3254
3255 /// Returns the index within the transaction that contains the recipient output.
3256 ///
3257 /// - If `recipient_address` is a Sapling address, this is an index into the Sapling
3258 /// outputs of the transaction.
3259 /// - If `recipient_address` is a transparent address, this is an index into the
3260 /// transparent outputs of the transaction.
3261 pub fn output_index(&self) -> usize {
3262 self.output_index
3263 }
3264 /// Returns the note commitment tree for this output, if known.
3265 pub fn note_commitment_tree(&self) -> Option<NoteCommitmentTree> {
3266 self.note_commitment_tree
3267 }
3268 /// Returns the recipient address of the transaction, or the account id and
3269 /// resulting note/outpoint for wallet-internal outputs.
3270 pub fn recipient(&self) -> &Recipient<AccountId> {
3271 &self.recipient
3272 }
3273 /// Returns the value of the newly created output.
3274 pub fn value(&self) -> Zatoshis {
3275 self.value
3276 }
3277 /// Returns the memo that was attached to the output, if any. This will only be `None`
3278 /// for transparent outputs.
3279 pub fn memo(&self) -> Option<&MemoBytes> {
3280 self.memo.as_ref()
3281 }
3282}
3283
3284/// A data structure used to set the birthday height for an account, and ensure that the initial
3285/// note commitment tree state is recorded at that height.
3286#[derive(Clone, Debug, PartialEq, Eq)]
3287pub struct AccountBirthday {
3288 prior_chain_state: ChainState,
3289 recover_until: Option<BlockHeight>,
3290}
3291
3292/// Errors that can occur in the construction of an [`AccountBirthday`] from a [`TreeState`].
3293#[derive(Debug)]
3294#[non_exhaustive]
3295pub enum BirthdayError {
3296 /// The block height of the [`TreeState`] was out of range for a [`BlockHeight`].
3297 HeightInvalid(TryFromIntError),
3298 /// The note commitment tree frontiers of the [`TreeState`] could not be decoded.
3299 Decode(io::Error),
3300}
3301
3302impl fmt::Display for BirthdayError {
3303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3304 match self {
3305 BirthdayError::HeightInvalid(e) => {
3306 write!(f, "Invalid block height for account birthday: {e}")
3307 }
3308 BirthdayError::Decode(e) => write!(
3309 f,
3310 "Failed to decode the note commitment tree state for the account birthday: {e}"
3311 ),
3312 }
3313 }
3314}
3315
3316impl std::error::Error for BirthdayError {
3317 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3318 match self {
3319 BirthdayError::HeightInvalid(e) => Some(e),
3320 BirthdayError::Decode(e) => Some(e),
3321 }
3322 }
3323}
3324
3325impl From<TryFromIntError> for BirthdayError {
3326 fn from(value: TryFromIntError) -> Self {
3327 Self::HeightInvalid(value)
3328 }
3329}
3330
3331impl From<io::Error> for BirthdayError {
3332 fn from(value: io::Error) -> Self {
3333 Self::Decode(value)
3334 }
3335}
3336
3337impl AccountBirthday {
3338 /// Constructs a new [`AccountBirthday`] from its constituent parts.
3339 ///
3340 /// * `prior_chain_state`: The chain state prior to the birthday height of the account. The
3341 /// birthday height is defined as the height of the first block to be scanned in wallet
3342 /// recovery.
3343 /// * `recover_until`: An optional height at which the wallet should exit "recovery mode". In
3344 /// order to avoid confusing shifts in wallet balance and spendability that may temporarily be
3345 /// visible to a user during the process of recovering from seed, wallets may optionally set a
3346 /// "recover until" height. The wallet is considered to be in "recovery mode" until there
3347 /// exist no unscanned ranges between the wallet's birthday height and the provided
3348 /// `recover_until` height, exclusive.
3349 pub fn from_parts(prior_chain_state: ChainState, recover_until: Option<BlockHeight>) -> Self {
3350 Self {
3351 prior_chain_state,
3352 recover_until,
3353 }
3354 }
3355
3356 /// Constructs a new [`AccountBirthday`] from a [`TreeState`] returned from `lightwalletd`.
3357 ///
3358 /// * `treestate`: The tree state corresponding to the last block prior to the wallet's
3359 /// birthday height.
3360 /// * `recover_until`: An optional height at which the wallet should exit "recovery mode". In
3361 /// order to avoid confusing shifts in wallet balance and spendability that may temporarily be
3362 /// visible to a user during the process of recovering from seed, wallets may optionally set a
3363 /// "recover until" height. The wallet is considered to be in "recovery mode" until there
3364 /// exist no unscanned ranges between the wallet's birthday height and the provided
3365 /// `recover_until` height, exclusive.
3366 pub fn from_treestate(
3367 treestate: TreeState,
3368 recover_until: Option<BlockHeight>,
3369 ) -> Result<Self, BirthdayError> {
3370 Ok(Self {
3371 prior_chain_state: treestate.to_chain_state()?,
3372 recover_until,
3373 })
3374 }
3375
3376 /// Returns the Sapling note commitment tree frontier as of the end of the block at
3377 /// [`Self::height`].
3378 pub fn sapling_frontier(
3379 &self,
3380 ) -> &Frontier<sapling::Node, { sapling::NOTE_COMMITMENT_TREE_DEPTH }> {
3381 self.prior_chain_state.final_sapling_tree()
3382 }
3383
3384 /// Returns the Orchard note commitment tree frontier as of the end of the block at
3385 /// [`Self::height`].
3386 #[cfg(feature = "orchard")]
3387 pub fn orchard_frontier(
3388 &self,
3389 ) -> &Frontier<orchard::tree::MerkleHashOrchard, { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 }>
3390 {
3391 self.prior_chain_state.final_orchard_tree()
3392 }
3393
3394 /// Returns the birthday height of the account.
3395 pub fn height(&self) -> BlockHeight {
3396 self.prior_chain_state.block_height() + 1
3397 }
3398
3399 /// Returns the height at which the wallet should exit "recovery mode".
3400 pub fn recover_until(&self) -> Option<BlockHeight> {
3401 self.recover_until
3402 }
3403
3404 /// Returns the [`ChainState`] corresponding to the last block prior to the wallet's birthday
3405 pub fn prior_chain_state(&self) -> &ChainState {
3406 &self.prior_chain_state
3407 }
3408
3409 #[cfg(any(test, feature = "test-dependencies"))]
3410 /// Constructs a new [`AccountBirthday`] at the given network upgrade's activation,
3411 /// with no "recover until" height.
3412 ///
3413 /// # Panics
3414 ///
3415 /// Panics if the activation height for the given network upgrade is not set.
3416 pub fn from_activation<P: zcash_protocol::consensus::Parameters>(
3417 params: &P,
3418 network_upgrade: NetworkUpgrade,
3419 prior_block_hash: BlockHash,
3420 ) -> AccountBirthday {
3421 AccountBirthday::from_parts(
3422 ChainState::empty(
3423 params.activation_height(network_upgrade).unwrap() - 1,
3424 prior_block_hash,
3425 ),
3426 None,
3427 )
3428 }
3429
3430 #[cfg(any(test, feature = "test-dependencies"))]
3431 /// Constructs a new [`AccountBirthday`] at Sapling activation, with no
3432 /// "recover until" height.
3433 ///
3434 /// # Panics
3435 ///
3436 /// Panics if the Sapling activation height is not set.
3437 pub fn from_sapling_activation<P: zcash_protocol::consensus::Parameters>(
3438 params: &P,
3439 prior_block_hash: BlockHash,
3440 ) -> AccountBirthday {
3441 Self::from_activation(params, NetworkUpgrade::Sapling, prior_block_hash)
3442 }
3443}
3444
3445/// This trait encapsulates the write capabilities required to update stored wallet data.
3446///
3447/// # Adding accounts
3448///
3449/// This trait provides several methods for adding accounts to the wallet data:
3450/// - [`WalletWrite::create_account`]
3451/// - [`WalletWrite::import_account_hd`]
3452/// - [`WalletWrite::import_account_ufvk`]
3453///
3454/// All of these methods take an [`AccountBirthday`]. The birthday height is defined as
3455/// the minimum block height that will be scanned for funds belonging to the wallet. If
3456/// `birthday.height()` is below the current chain tip, the account addition operation
3457/// will trigger a re-scan of the blocks at and above the provided height.
3458///
3459/// The order in which you call these methods will affect the resulting wallet structure:
3460/// - If only [`WalletWrite::create_account`] is used, the resulting accounts will have
3461/// sequential [ZIP 32] account indices within each given seed.
3462/// - If [`WalletWrite::import_account_hd`] is used to import accounts with non-sequential
3463/// ZIP 32 account indices from the same seed, a call to [`WalletWrite::create_account`]
3464/// will use the ZIP 32 account index just after the highest-numbered existing account.
3465/// - If an account is added to the wallet, and then a later call to one of the methods
3466/// would produce a UFVK that collides with that account on any FVK component (i.e.
3467/// Sapling, Orchard, or transparent), an error will be returned. This can occur in the
3468/// following cases:
3469/// - An account is created via [`WalletWrite::create_account`] with an auto-selected
3470/// ZIP 32 account index, and that index is later imported explicitly via either
3471/// [`WalletWrite::import_account_ufvk`] or [`WalletWrite::import_account_hd`].
3472/// - An account is imported via [`WalletWrite::import_account_ufvk`] or
3473/// [`WalletWrite::import_account_hd`], and then the ZIP 32 account index
3474/// corresponding to that account's UFVK is later imported either implicitly
3475/// via [`WalletWrite::create_account`], or explicitly via a call to
3476/// [`WalletWrite::import_account_ufvk`] or [`WalletWrite::import_account_hd`].
3477///
3478/// Note that an error will be returned on an FVK collision even if the UFVKs do not
3479/// match exactly, e.g. if they have different subsets of components.
3480///
3481/// An account is treated as having a single root of spending authority that spans the shielded and
3482/// transparent rules for the purpose of balance, transaction listing, and so forth. However,
3483/// transparent keys imported via `WalletWrite::import_standalone_transparent_pubkey` or
3484/// `WalletWrite::import_standalone_transparent_script` (available with the
3485/// `transparent-key-import` feature) break this abstraction slightly, so wallets using this API
3486/// need to be cautious to enforce the invariant that the wallet either maintains access to the
3487/// keys required to spend **ALL** outputs received by the account, or that it **DOES NOT** offer
3488/// any spending capability for the account, i.e. the account is treated as view-only for all
3489/// user-facing operations.
3490///
3491/// A future change to this trait might introduce a method to "upgrade" an imported
3492/// account with derivation information. See [zcash/librustzcash#1284] for details.
3493///
3494/// Users of the `WalletWrite` trait should generally distinguish in their APIs and wallet UIs
3495/// between creating a new account, and importing an account that previously existed. By
3496/// convention, wallets should only allow a new account to be generated for a seed after confirmed
3497/// funds have been received by the newest existing account for that seed; this allows automated
3498/// account recovery to discover and recover all funds within a particular seed.
3499///
3500/// # Creating a new wallet
3501///
3502/// To create a new wallet:
3503/// - Generate a new [BIP 39] mnemonic phrase, using a crate like [`bip0039`].
3504/// - Derive the corresponding seed from the mnemonic phrase.
3505/// - Use [`WalletWrite::create_account`] with the resulting seed.
3506///
3507/// Callers should construct the [`AccountBirthday`] using [`AccountBirthday::from_treestate`] for
3508/// the block at height `chain_tip_height - 100`. Setting the birthday height to a tree state below
3509/// the pruning depth ensures that reorgs cannot cause funds intended for the wallet to be missed;
3510/// otherwise, if the chain tip height were used for the wallet birthday, a transaction targeted at
3511/// a height greater than the chain tip could be mined at a height below that tip as part of a
3512/// reorg.
3513///
3514/// # Restoring a wallet from backup
3515///
3516/// To restore a backed-up wallet:
3517/// - Derive the seed from its BIP 39 mnemonic phrase.
3518/// - Use [`WalletWrite::import_account_hd`] once for each ZIP 32 account index that the
3519/// user wants to restore.
3520/// - If the highest previously-used ZIP 32 account index was _not_ restored by the user,
3521/// remember this index separately as `index_max`. The first time the user wants to
3522/// generate a new account, use [`WalletWrite::import_account_hd`] to create the account
3523/// `index_max + 1`.
3524/// - [`WalletWrite::create_account`] can be used to generate subsequent new accounts in
3525/// the restored wallet.
3526///
3527/// Automated account recovery has not yet been implemented by this crate. A wallet app
3528/// that supports multiple accounts can implement it manually by tracking account balances
3529/// relative to [`WalletSummary::fully_scanned_height`], and creating new accounts as
3530/// funds appear in existing accounts.
3531///
3532/// If the number of accounts is known in advance, the wallet should create all accounts before
3533/// scanning the chain so that the scan can be done in a single pass for all accounts.
3534///
3535/// [ZIP 32]: https://zips.z.cash/zip-0032
3536/// [zcash/librustzcash#1284]: https://github.com/zcash/librustzcash/issues/1284
3537/// [BIP 39]: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
3538/// [`bip0039`]: https://crates.io/crates/bip0039
3539#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
3540pub trait WalletWrite:
3541 WalletRead
3542 + OutputLockStore<
3543 AccountId = <Self as WalletRead>::AccountId,
3544 Error = <Self as WalletRead>::Error,
3545 >
3546{
3547 /// The type of identifiers used to look up transparent UTXOs.
3548 type UtxoRef;
3549
3550 /// Tells the wallet to track the next available account-level spend authority for the provided
3551 /// seed value, given the current set of [ZIP 316] account identifiers known to the wallet database.
3552 ///
3553 /// The "next available account" is defined as the ZIP-32 account index immediately following
3554 /// the highest existing account index among all accounts in the wallet that share the given
3555 /// seed. Users of the [`WalletWrite`] trait that only call this method are guaranteed to have
3556 /// accounts with sequential indices.
3557 ///
3558 /// Returns the account identifier for the newly-created wallet database entry, along with the
3559 /// associated [`UnifiedSpendingKey`]. Note that the unique account identifier should *not* be
3560 /// assumed equivalent to the ZIP 32 account index. It is an opaque identifier for a pool of
3561 /// funds or set of outputs controlled by a single spending authority.
3562 ///
3563 /// The ZIP-32 account index may be obtained by calling [`WalletRead::get_account`]
3564 /// with the returned account identifier.
3565 ///
3566 /// The [`WalletWrite`] trait documentation has more details about account creation and import.
3567 ///
3568 /// # Arguments
3569 /// - `account_name`: A human-readable name for the account.
3570 /// - `seed`: The 256-byte (at least) HD seed from which to derive the account UFVK.
3571 /// - `birthday`: Metadata about where to start scanning blocks to find transactions intended
3572 /// for the account.
3573 /// - `key_source`: A string identifier or other metadata describing the source of the seed.
3574 /// This is treated as opaque metadata by the wallet backend; it is provided for use by
3575 /// applications which need to track additional identifying information for an account.
3576 ///
3577 /// # Implementation notes
3578 ///
3579 /// Implementations of this method **MUST NOT** "fill in gaps" by selecting an account index
3580 /// that is lower than any existing account index among all accounts in the wallet that share
3581 /// the given seed.
3582 ///
3583 /// # Panics
3584 ///
3585 /// Panics if the length of the seed is not between 32 and 252 bytes inclusive.
3586 ///
3587 /// [ZIP 316]: https://zips.z.cash/zip-0316
3588 fn create_account(
3589 &mut self,
3590 account_name: &str,
3591 seed: &SecretVec<u8>,
3592 birthday: &AccountBirthday,
3593 key_source: Option<&str>,
3594 ) -> Result<(<Self as WalletRead>::AccountId, UnifiedSpendingKey), <Self as WalletRead>::Error>;
3595
3596 /// Tells the wallet to track a specific account index for a given seed.
3597 ///
3598 /// Returns details about the imported account, including the unique account identifier for
3599 /// the newly-created wallet database entry, along with the associated [`UnifiedSpendingKey`].
3600 /// Note that the unique account identifier should *not* be assumed equivalent to the ZIP 32
3601 /// account index. It is an opaque identifier for a pool of funds or set of outputs controlled
3602 /// by a single spending authority.
3603 ///
3604 /// Import accounts with indices that are exactly one greater than the highest existing account
3605 /// index to ensure account indices are contiguous, thereby facilitating automated account
3606 /// recovery.
3607 ///
3608 /// The [`WalletWrite`] trait documentation has more details about account creation and import.
3609 ///
3610 /// # Arguments
3611 /// - `account_name`: A human-readable name for the account.
3612 /// - `seed`: The 256-byte (at least) HD seed from which to derive the account UFVK.
3613 /// - `account_index`: The ZIP 32 account-level component of the HD derivation path at
3614 /// which to derive the account's UFVK.
3615 /// - `birthday`: Metadata about where to start scanning blocks to find transactions intended
3616 /// for the account.
3617 /// - `key_source`: A string identifier or other metadata describing the source of the seed.
3618 /// This is treated as opaque metadata by the wallet backend; it is provided for use by
3619 /// applications which need to track additional identifying information for an account.
3620 ///
3621 /// # Panics
3622 ///
3623 /// Panics if the length of the seed is not between 32 and 252 bytes inclusive.
3624 ///
3625 /// [ZIP 316]: https://zips.z.cash/zip-0316
3626 fn import_account_hd(
3627 &mut self,
3628 account_name: &str,
3629 seed: &SecretVec<u8>,
3630 account_index: zip32::AccountId,
3631 birthday: &AccountBirthday,
3632 key_source: Option<&str>,
3633 ) -> Result<(Self::Account, UnifiedSpendingKey), <Self as WalletRead>::Error>;
3634
3635 /// Tells the wallet to track an account using a unified full viewing key.
3636 ///
3637 /// Returns details about the imported account, including the unique account identifier for
3638 /// the newly-created wallet database entry. Unlike the other account creation APIs
3639 /// ([`Self::create_account`] and [`Self::import_account_hd`]), no spending key is returned
3640 /// because the wallet has no information about how the UFVK was derived.
3641 ///
3642 /// Certain optimizations are possible for accounts which will never be used to spend funds. If
3643 /// `spending_key_available` is `false`, the wallet may choose to optimize for this case, in
3644 /// which case any attempt to spend funds from the account will result in an error.
3645 ///
3646 /// The [`WalletWrite`] trait documentation has more details about account creation and import.
3647 ///
3648 /// # Arguments
3649 /// - `account_name`: A human-readable name for the account.
3650 /// - `unified_key`: The UFVK used to detect transactions involving the account.
3651 /// - `birthday`: Metadata about where to start scanning blocks to find transactions intended
3652 /// for the account.
3653 /// - `purpose`: Metadata describing whether or not data required for spending should be
3654 /// tracked by the wallet.
3655 /// - `key_source`: A string identifier or other metadata describing the source of the seed.
3656 /// This is treated as opaque metadata by the wallet backend; it is provided for use by
3657 /// applications which need to track additional identifying information for an account.
3658 fn import_account_ufvk(
3659 &mut self,
3660 account_name: &str,
3661 unified_key: &UnifiedFullViewingKey,
3662 birthday: &AccountBirthday,
3663 purpose: AccountPurpose,
3664 key_source: Option<&str>,
3665 ) -> Result<Self::Account, <Self as WalletRead>::Error>;
3666
3667 /// Deletes the specified account, and all transactions that exclusively involve it, from the
3668 /// wallet database.
3669 ///
3670 /// WARNING: This is a destructive operation and may result in the permanent loss of
3671 /// potentially important information that is not recoverable from chain data, including:
3672 /// * Data about transactions sent by the account for which [`OvkPolicy::Discard`] (or
3673 /// [`OvkPolicy::Custom`] with random OVKs) was used;
3674 /// * Data related to transactions that the account attempted to send that expired or were
3675 /// otherwise invalidated without having been mined in the main chain;
3676 /// * Data related to transactions that were observed in the mempool as having inputs or
3677 /// outputs that involved the account, but that were never mined in the main chain;
3678 /// * Data related to transactions that were received by the wallet in a mined block, where
3679 /// that block was later un-mined in a chain reorg and the transaction was either invalidated
3680 /// or was never re-mined.
3681 ///
3682 /// [`OvkPolicy::Discard`]: crate::wallet::OvkPolicy::Discard
3683 /// [`OvkPolicy::Custom`]: crate::wallet::OvkPolicy::Custom
3684 fn delete_account(
3685 &mut self,
3686 account: <Self as WalletRead>::AccountId,
3687 ) -> Result<(), <Self as WalletRead>::Error>;
3688
3689 /// Imports the given pubkey into the account without key derivation information, and adds the
3690 /// associated transparent p2pkh address.
3691 ///
3692 /// The imported address will contribute to the balance of the account (for UFVK-based
3693 /// accounts), but spending funds held by this address requires the associated spending keys to
3694 /// be provided explicitly when calling [`create_proposed_transactions`]. By extension, calls
3695 /// to [`propose_shielding`] must only include addresses for which the spending application
3696 /// holds or can obtain the spending keys.
3697 ///
3698 /// [`create_proposed_transactions`]: crate::data_api::wallet::create_proposed_transactions
3699 /// [`propose_shielding`]: crate::data_api::wallet::propose_shielding
3700 #[cfg(feature = "transparent-key-import")]
3701 fn import_standalone_transparent_pubkey(
3702 &mut self,
3703 _account: <Self as WalletRead>::AccountId,
3704 _pubkey: secp256k1::PublicKey,
3705 ) -> Result<(), <Self as WalletRead>::Error> {
3706 unimplemented!(
3707 "WalletWrite::import_standalone_transparent_pubkey must be overridden for wallets to use the `transparent-key-import` feature"
3708 )
3709 }
3710
3711 /// Imports a batch of standalone transparent pubkeys into the account, adding the associated
3712 /// transparent p2pkh addresses. See [`import_standalone_transparent_pubkey`] for the semantics
3713 /// and spending limitations that apply to each imported pubkey.
3714 ///
3715 /// This is equivalent to calling [`import_standalone_transparent_pubkey`] once per pubkey, but
3716 /// implementations may validate the target account a single time for the whole batch. The
3717 /// default implementation calls [`import_standalone_transparent_pubkey`] for each pubkey; a
3718 /// pubkey whose receiver address is already known to the wallet is skipped.
3719 ///
3720 /// [`import_standalone_transparent_pubkey`]: Self::import_standalone_transparent_pubkey
3721 #[cfg(feature = "transparent-key-import")]
3722 fn import_standalone_transparent_pubkeys(
3723 &mut self,
3724 account: <Self as WalletRead>::AccountId,
3725 pubkeys: &[secp256k1::PublicKey],
3726 ) -> Result<(), <Self as WalletRead>::Error> {
3727 for pubkey in pubkeys {
3728 self.import_standalone_transparent_pubkey(account, *pubkey)?;
3729 }
3730 Ok(())
3731 }
3732
3733 /// Imports the given redeem script into the account without key derivation information, and
3734 /// adds the associated transparent p2sh address.
3735 ///
3736 /// The imported address will contribute to the balance of the account (for UFVK-based
3737 /// accounts), but spending funds held by this address requires the associated spending keys to
3738 /// be provided explicitly when calling [`create_proposed_transactions`]. By extension, calls
3739 /// to [`propose_shielding`] must only include addresses for which the spending application
3740 /// holds or can obtain the spending keys.
3741 ///
3742 /// [`create_proposed_transactions`]: crate::data_api::wallet::create_proposed_transactions
3743 /// [`propose_shielding`]: crate::data_api::wallet::propose_shielding
3744 ///
3745 /// # Spending limitations
3746 ///
3747 /// P2PKH-in-P2SH scripts are unsupported by PCZT at this time, so the only way to spend
3748 /// from such an address is to use the [`create_proposed_transactions`] signing path.
3749 #[cfg(feature = "transparent-key-import")]
3750 fn import_standalone_transparent_script(
3751 &mut self,
3752 _account: <Self as WalletRead>::AccountId,
3753 _script: zcash_script::script::Redeem,
3754 ) -> Result<(), <Self as WalletRead>::Error> {
3755 unimplemented!(
3756 "WalletWrite::import_standalone_transparent_script must be overridden for wallets to use the `transparent-key-import` feature"
3757 )
3758 }
3759
3760 /// Generates, persists, and marks as exposed the next available diversified address for the
3761 /// specified account, given the current addresses known to the wallet.
3762 ///
3763 /// Returns `Ok(None)` if the account identifier does not correspond to a known
3764 /// account.
3765 fn get_next_available_address(
3766 &mut self,
3767 account: <Self as WalletRead>::AccountId,
3768 request: UnifiedAddressRequest,
3769 ) -> Result<Option<(UnifiedAddress, DiversifierIndex)>, <Self as WalletRead>::Error>;
3770
3771 /// Generates, persists, and marks as exposed a diversified address for the specified account
3772 /// at the provided diversifier index.
3773 ///
3774 /// Returns `Ok(None)` in the case that it is not possible to generate an address conforming
3775 /// to the provided request at the specified diversifier index. Such a result might arise from
3776 /// the diversifier index not being valid for a [`ReceiverRequirement::Require`]'ed receiver.
3777 /// Some implementations of this trait may return `Err(_)` in some cases to expose more
3778 /// information, which is only accessible in a backend-specific context.
3779 ///
3780 /// Address generation should fail if an address has already been exposed for the given
3781 /// diversifier index and the given request produced an address having different receivers than
3782 /// what was originally exposed.
3783 ///
3784 /// # WARNINGS
3785 /// If an address generated using this method has a transparent receiver and the
3786 /// chosen diversifier index would be outside the wallet's internally-configured gap limit,
3787 /// funds sent to these address are **likely to not be discovered on recovery from seed**. It
3788 /// up to the caller of this method to either ensure that they only request transparent
3789 /// receivers with indices within the range of a reasonable gap limit, or that they ensure that
3790 /// their wallet provides backup facilities that can be used to ensure that funds sent to such
3791 /// addresses are recoverable after a loss of wallet data.
3792 ///
3793 /// [`ReceiverRequirement::Require`]: zcash_keys::keys::ReceiverRequirement::Require
3794 fn get_address_for_index(
3795 &mut self,
3796 account: <Self as WalletRead>::AccountId,
3797 diversifier_index: DiversifierIndex,
3798 request: UnifiedAddressRequest,
3799 ) -> Result<Option<UnifiedAddress>, <Self as WalletRead>::Error>;
3800
3801 /// Updates the wallet's view of the blockchain.
3802 ///
3803 /// This method is used to provide the wallet with information about the state of the
3804 /// blockchain, and detect any previously scanned data that needs to be re-validated
3805 /// before proceeding with scanning. It should be called at wallet startup prior to calling
3806 /// [`WalletRead::suggest_scan_ranges`] in order to provide the wallet with the information it
3807 /// needs to correctly prioritize scanning operations.
3808 fn update_chain_tip(
3809 &mut self,
3810 tip_height: BlockHeight,
3811 ) -> Result<(), <Self as WalletRead>::Error>;
3812
3813 /// Drops the scan work queued below `height`, except where retained by
3814 /// `retain_with_priority`. Returns the number of queue entries removed or altered.
3815 ///
3816 /// If `retain_with_priority` is `None`, no entries below `height` are retained,
3817 /// irrespective of their priority. If it is `Some(priority)`, entries with that
3818 /// priority and greater are retained (left untouched, even where they straddle
3819 /// `height`), as are entries with the bookkeeping priorities
3820 /// [`ScanPriority::Scanned`] and [`ScanPriority::Ignored`] — those record which
3821 /// regions of the chain the backend has already covered or deliberately skips, and
3822 /// removing them would cause the backend to forget coverage state it maintains
3823 /// itself (use the `None` form when that full reset is the intent). Entries with
3824 /// priorities between the bookkeeping ones and the retained threshold are pruned.
3825 ///
3826 /// Pruning must not leave a gap in the queue's coverage: implementations are required
3827 /// to preserve contiguity across whatever remains below `height`, which in general
3828 /// means demoting pruned ranges to [`ScanPriority::Ignored`] rather than deleting them
3829 /// outright. Only coverage below the lowest retained entry may be deleted, since that
3830 /// merely raises the floor of the queue. A caller may therefore observe that the total
3831 /// span of the queue is unchanged and that the pruned region is now `Ignored`.
3832 ///
3833 /// This is a queue-hygiene operation. The primary use case is discarding historic scan
3834 /// ranges that no remaining account justifies: [`WalletWrite::delete_account`] does not
3835 /// modify the scan queue, so the deep ranges queued for a since-deleted account's
3836 /// birthday would otherwise still be scanned even though no remaining account can have
3837 /// notes below its own birthday. In that case, pass the wallet birthday
3838 /// ([`WalletRead::get_wallet_birthday`]) as `height` and retain
3839 /// [`ScanPriority::OpenAdjacent`] and greater — the priorities that may legitimately
3840 /// reach below the wallet birthday in service of note witnesses.
3841 fn prune_scan_queue_below(
3842 &mut self,
3843 height: BlockHeight,
3844 retain_with_priority: Option<ScanPriority>,
3845 ) -> Result<u64, <Self as WalletRead>::Error>;
3846
3847 /// Updates the state of the wallet database by persisting the provided block information,
3848 /// along with the note commitments that were detected when scanning the block for transactions
3849 /// pertaining to this wallet.
3850 ///
3851 /// ### Arguments
3852 /// - `from_state` must be the chain state for the block height prior to the first
3853 /// block in `blocks`.
3854 /// - `blocks` must be sequential, in order of increasing block height.
3855 fn put_blocks(
3856 &mut self,
3857 from_state: &ChainState,
3858 blocks: Vec<ScannedBlock<<Self as WalletRead>::AccountId>>,
3859 ) -> Result<(), <Self as WalletRead>::Error>;
3860
3861 /// Adds a transparent UTXO received by the wallet to the data store.
3862 fn put_received_transparent_utxo(
3863 &mut self,
3864 output: &WalletTransparentOutput<<Self as WalletRead>::AccountId>,
3865 ) -> Result<Self::UtxoRef, <Self as WalletRead>::Error>;
3866
3867 /// Caches a decrypted transaction in the persistent wallet store.
3868 fn store_decrypted_tx(
3869 &mut self,
3870 received_tx: DecryptedTransaction<Transaction, <Self as WalletRead>::AccountId>,
3871 ) -> Result<(), <Self as WalletRead>::Error>;
3872
3873 /// Sets the trust status of the given transaction to either trusted or untrusted.
3874 ///
3875 /// The outputs of a trusted transaction will be available for spending with
3876 /// [`ConfirmationsPolicy::trusted`] confirmations even if the output is not wallet-internal.
3877 fn set_tx_trust(
3878 &mut self,
3879 txid: TxId,
3880 trusted: bool,
3881 ) -> Result<(), <Self as WalletRead>::Error>;
3882
3883 /// Saves information about transactions constructed by the wallet to the persistent
3884 /// wallet store.
3885 ///
3886 /// This must be called before the transactions are sent to the network.
3887 ///
3888 /// Transactions that have been stored by this method should be retransmitted while it
3889 /// is still possible that they could be mined.
3890 ///
3891 /// Implementations must unlock any locked outputs that are recorded as spent by the
3892 /// stored transactions. Once spend records exist, the outputs are protected from
3893 /// double-selection by the spend tracking mechanism, so the explicit locks are no
3894 /// longer needed.
3895 fn store_transactions_to_be_sent(
3896 &mut self,
3897 transactions: &[SentTransaction<<Self as WalletRead>::AccountId>],
3898 ) -> Result<(), <Self as WalletRead>::Error>;
3899
3900 /// Truncates the wallet database to at most the specified height.
3901 ///
3902 /// Implementations of this method may choose a lower block height to which the data store will
3903 /// be truncated if it is not possible to truncate exactly to the specified height. Upon
3904 /// successful truncation, this method returns the height to which the data store was actually
3905 /// truncated.
3906 ///
3907 /// This method assumes that the state of the underlying data store is consistent up to a
3908 /// particular block height. Since it is possible that a chain reorg might invalidate some
3909 /// stored state, this method must be implemented in order to allow users of this API to
3910 /// "reset" the data store to correctly represent chainstate as of at most the requested block
3911 /// height.
3912 ///
3913 /// After calling this method, the block at the returned height will be the most recent block
3914 /// and all other operations will treat this block as the chain tip for balance determination
3915 /// purposes.
3916 ///
3917 /// There may be restrictions on heights to which it is possible to truncate. Specifically, it
3918 /// will only be possible to truncate to heights at which is is possible to create a witness
3919 /// given the current state of the wallet's note commitment tree.
3920 fn truncate_to_height(
3921 &mut self,
3922 max_height: BlockHeight,
3923 ) -> Result<BlockHeight, <Self as WalletRead>::Error>;
3924
3925 /// Truncates the wallet database to the specified chain state.
3926 ///
3927 /// In contrast to [`truncate_to_height`], this method allows the caller to truncate the wallet
3928 /// database to a precise height by providing additional chain state information needed for
3929 /// note commitment tree maintenance after the truncation.
3930 ///
3931 /// [`truncate_to_height`]: WalletWrite::truncate_to_height
3932 fn truncate_to_chain_state(
3933 &mut self,
3934 chain_state: ChainState,
3935 ) -> Result<(), <Self as WalletRead>::Error>;
3936
3937 /// Rewinds the wallet to the specified chain state, preserving wallet data which has been
3938 /// confirmed beyond the pruning depth, and lowering the birthday height of selected accounts
3939 /// to the block following the chain state.
3940 ///
3941 /// In contrast to [`truncate_to_chain_state`], which unconditionally removes wallet state
3942 /// above `chain_state.block_height()`, this rewinds the scan queue to the target height but
3943 /// only rewinds blocks, note commitment trees, transactions, transparent UTXO observations,
3944 /// and nullifier-map entries as far back as the implementation's pruning floor; data at or
3945 /// below that floor is preserved.
3946 ///
3947 /// `reset_account_birthdays` selects which accounts (if any) may have their birthday
3948 /// metadata lowered as a result of this rewind. The semantics are:
3949 ///
3950 /// - Every account in `reset_account_birthdays` has its birthday metadata updated to
3951 /// `chain_state.block_height() + 1` (with corresponding tree sizes taken from
3952 /// `chain_state`) if and only if the new birthday is less than the account's existing
3953 /// birthday. Existing birthdays are never raised by this method.
3954 /// - Accounts that are *not* in `reset_account_birthdays` are never modified, regardless of
3955 /// the rewind target. Note that this only governs per-account birthday metadata:
3956 /// rescanning of blocks that re-enter the scan queue applies to *all* accounts in the
3957 /// wallet, since scanning is performed against all viewing keys.
3958 /// - If `reset_account_birthdays` is empty and *every* account in the wallet has a birthday
3959 /// greater than `chain_state.block_height() + 1` (the value to which a reset birthday
3960 /// would be lowered), this method returns [`RewindError::RewindBeyondBirthdays`] and no
3961 /// other state is modified. So long as at least one account in the wallet already has a
3962 /// birthday at or below `chain_state.block_height() + 1`, this error is not returned —
3963 /// such an account already provides the wallet with an anchor at or below the new
3964 /// birthday floor, so no reset is required. The reported map contains every account in
3965 /// the wallet along with its existing birthday height; the caller may re-invoke the
3966 /// method with any subset of those accounts included in `reset_account_birthdays`.
3967 ///
3968 /// Implementations may also return an [`Err`] (typically via [`RewindError::DataSource`])
3969 /// if `reset_account_birthdays` contains identifiers that do not correspond to accounts in
3970 /// the wallet.
3971 ///
3972 /// [`truncate_to_chain_state`]: WalletWrite::truncate_to_chain_state
3973 fn rewind_to_chain_state(
3974 &mut self,
3975 chain_state: ChainState,
3976 reset_account_birthdays: HashSet<<Self as WalletRead>::AccountId>,
3977 ) -> Result<(), RewindError<<Self as WalletRead>::AccountId, <Self as WalletRead>::Error>>;
3978
3979 /// Reserves the next `n` available ephemeral addresses for the given account.
3980 /// This cannot be undone, so as far as possible, errors associated with transaction
3981 /// construction should have been reported before calling this method.
3982 ///
3983 /// To ensure that sufficient information is stored on-chain to allow recovering
3984 /// funds sent back to any of the used addresses, a "gap limit" of 20 addresses
3985 /// should be observed as described in [BIP 44].
3986 ///
3987 /// Returns an error if there is insufficient space within the gap limit to allocate
3988 /// the given number of addresses, or if the account identifier does not correspond
3989 /// to a known account.
3990 ///
3991 /// [BIP 44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#user-content-Address_gap_limit
3992 #[cfg(feature = "transparent-inputs")]
3993 fn reserve_next_n_ephemeral_addresses(
3994 &mut self,
3995 _account_id: <Self as WalletRead>::AccountId,
3996 _n: usize,
3997 ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
3998 {
3999 unimplemented!(
4000 "WalletWrite::reserve_next_n_ephemeral_addresses must be overridden for wallets to use the `transparent-inputs` feature"
4001 )
4002 }
4003
4004 /// Reserves the next `n` available internal-scope (change) transparent addresses for
4005 /// the given account, as described in [BIP 44] under the `change` path level. This
4006 /// cannot be undone, so as far as possible, errors associated with transaction
4007 /// construction should have been reported before calling this method.
4008 ///
4009 /// Internal-scope transparent addresses are used to receive change for transactions
4010 /// having fully-transparent value flows, when the change strategy in use is configured
4011 /// with [`TransparentChangePolicy::TransparentChangeAllowed`].
4012 ///
4013 /// To ensure that funds sent to internal-scope addresses are recoverable, implementations
4014 /// of this method should observe a gap limit as described in [BIP 44]; change addresses
4015 /// receive funds immediately upon reservation, so a smaller gap limit than the one used
4016 /// for external addresses may be observed.
4017 ///
4018 /// Returns an error if there is insufficient space within the gap limit to allocate
4019 /// the given number of addresses, or if the account identifier does not correspond
4020 /// to a known account.
4021 ///
4022 /// [BIP 44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
4023 /// [`TransparentChangePolicy::TransparentChangeAllowed`]: crate::fees::TransparentChangePolicy::TransparentChangeAllowed
4024 #[cfg(feature = "transparent-inputs")]
4025 fn reserve_next_n_internal_addresses(
4026 &mut self,
4027 _account_id: <Self as WalletRead>::AccountId,
4028 _n: usize,
4029 ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
4030 {
4031 unimplemented!(
4032 "WalletWrite::reserve_next_n_internal_addresses must be overridden for wallets to \
4033 create transactions that produce transparent change"
4034 )
4035 }
4036
4037 /// Updates the wallet backend with respect to the status of a specific transaction, from the
4038 /// perspective of the main chain.
4039 ///
4040 /// Fully transparent transactions, and transactions that do not contain either shielded inputs
4041 /// or shielded outputs belonging to the wallet, may not be discovered by the process of chain
4042 /// scanning; as a consequence, the wallet must actively query to determine whether such
4043 /// transactions have been mined.
4044 fn set_transaction_status(
4045 &mut self,
4046 _txid: TxId,
4047 _status: TransactionStatus,
4048 ) -> Result<(), <Self as WalletRead>::Error>;
4049
4050 /// Schedules a UTXO check for the given address at a random time that has an expected value of
4051 /// `offset_seconds` from the current system time.
4052 ///
4053 /// Returns the time at which the check has been scheduled, or `None` if the address is not
4054 /// being tracked by the wallet.
4055 #[cfg(feature = "transparent-inputs")]
4056 fn schedule_next_check(
4057 &mut self,
4058 _address: &TransparentAddress,
4059 _offset_seconds: u32,
4060 ) -> Result<Option<SystemTime>, <Self as WalletRead>::Error> {
4061 unimplemented!(
4062 "WalletWrite::schedule_next_check must be overridden for wallets to use the `transparent-inputs` feature"
4063 )
4064 }
4065
4066 /// Informs the wallet backend that the given transparent addresses are known to have been
4067 /// exposed externally at or before the block height paired with each address.
4068 ///
4069 /// This method is intended for use when a wallet has learned, through means outside the
4070 /// observation of the chain by this backend, that addresses under the wallet's control have
4071 /// been disclosed to an external party. Calling this method ensures that the wallet's exposure
4072 /// metadata accounts for the earlier disclosures.
4073 ///
4074 /// If the wallet already tracks an earlier exposure for an address, the earlier height is
4075 /// retained.
4076 ///
4077 /// The operation is atomic: if any address in `exposures` is not known to the wallet,
4078 /// implementations must roll back all updates performed during the call and return an
4079 /// implementation-defined error identifying the first unrecognized address.
4080 /// Passing an empty slice is a no-op.
4081 #[cfg(feature = "transparent-inputs")]
4082 fn mark_transparent_addresses_exposed(
4083 &mut self,
4084 _exposures: &[(TransparentAddress, BlockHeight)],
4085 ) -> Result<(), <Self as WalletRead>::Error> {
4086 unimplemented!(
4087 "WalletWrite::mark_transparent_addresses_exposed must be overridden for wallets to use the `transparent-inputs` feature"
4088 )
4089 }
4090
4091 /// Notifies the wallet backend that the given query for transactions involving a particular
4092 /// address has completed evaluation.
4093 ///
4094 /// # Arguments
4095 /// - `request`: the [`TransactionsInvolvingAddress`] request that was executed.
4096 /// - `as_of_height`: The maximum height among blocks that were inspected in the process of
4097 /// performing the requested check.
4098 #[cfg(feature = "transparent-inputs")]
4099 fn notify_address_checked(
4100 &mut self,
4101 _request: TransactionsInvolvingAddress,
4102 _as_of_height: BlockHeight,
4103 ) -> Result<(), <Self as WalletRead>::Error> {
4104 unimplemented!(
4105 "WalletWrite::notify_address_checked must be overridden for wallets to use the `transparent-inputs` feature"
4106 )
4107 }
4108
4109 /// Notifies the wallet backend that a specific transparent output was confirmed unspent as of
4110 /// the given height, in response to a [`TransactionDataRequest::GetSpendingTx`]
4111 /// request.
4112 ///
4113 /// # Arguments
4114 /// - `outpoint`: the transparent outpoint whose spend status was checked.
4115 /// - `as_of_height`: the maximum height among blocks that were inspected, and through which
4116 /// the outpoint is confirmed to remain unspent.
4117 #[cfg(feature = "spend-index")]
4118 fn notify_output_verified_unspent(
4119 &mut self,
4120 _outpoint: OutPoint,
4121 _as_of_height: BlockHeight,
4122 ) -> Result<(), <Self as WalletRead>::Error> {
4123 unimplemented!(
4124 "WalletWrite::notify_output_verified_unspent must be overridden for wallets to use the `spend-index` feature"
4125 )
4126 }
4127}
4128
4129/// Applies a batch of note commitment tree changes — shards, an optional replacement tree
4130/// cap, and a checkpoint delta — directly to the given tree's backing [`ShardStore`].
4131///
4132/// `shards` must be in ascending shard-index order; stores may reject sequences that would
4133/// leave gaps in the tree. Checkpoint removals are applied before additions, so that a
4134/// checkpoint whose data has changed may appear in both lists.
4135///
4136/// This is the shared implementation of the [`WalletCommitmentTrees`] `put_*_shards`
4137/// provided methods.
4138///
4139/// NOTE: This procedure must be called only within a the context of a transaction, such as
4140/// in the scope of a `with_*_tree_mut` call; otherwise, failure of an intermediate step could
4141/// lead to data corruption.
4142fn apply_tree_changes<H, S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
4143 tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
4144 shards: &[shardtree::LocatedPrunableTree<H>],
4145 cap: Option<&shardtree::PrunableTree<H>>,
4146 checkpoints_remove: &[BlockHeight],
4147 checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
4148) -> Result<(), ShardTreeError<S::Error>>
4149where
4150 H: incrementalmerkletree::Hashable + Clone + PartialEq,
4151 S: ShardStore<H = H, CheckpointId = BlockHeight>,
4152{
4153 for shard in shards {
4154 tree.store_mut()
4155 .put_shard(shard.clone())
4156 .map_err(ShardTreeError::Storage)?;
4157 }
4158 if let Some(cap) = cap {
4159 tree.store_mut()
4160 .put_cap(cap.clone())
4161 .map_err(ShardTreeError::Storage)?;
4162 }
4163 for height in checkpoints_remove {
4164 tree.store_mut()
4165 .remove_checkpoint(height)
4166 .map_err(ShardTreeError::Storage)?;
4167 }
4168 for (height, checkpoint) in checkpoints_add {
4169 tree.store_mut()
4170 .add_checkpoint(*height, checkpoint.clone())
4171 .map_err(ShardTreeError::Storage)?;
4172 }
4173 Ok(())
4174}
4175
4176/// This trait describes a capability for manipulating wallet note commitment trees.
4177#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
4178pub trait WalletCommitmentTrees {
4179 type Error: Debug;
4180
4181 /// The type of the backing [`ShardStore`] for the Sapling note commitment tree.
4182 type SaplingShardStore<'a>: ShardStore<H = sapling::Node, CheckpointId = BlockHeight, Error = Self::Error>;
4183
4184 /// Evaluates the given callback function with a reference to the Sapling
4185 /// note commitment tree maintained by the wallet.
4186 fn with_sapling_tree_mut<F, A, E>(&mut self, callback: F) -> Result<A, E>
4187 where
4188 for<'a> F: FnMut(
4189 &'a mut ShardTree<
4190 Self::SaplingShardStore<'a>,
4191 { sapling::NOTE_COMMITMENT_TREE_DEPTH },
4192 SAPLING_SHARD_HEIGHT,
4193 >,
4194 ) -> Result<A, E>,
4195 E: From<ShardTreeError<Self::Error>>;
4196
4197 /// Adds a sequence of Sapling note commitment tree subtree roots to the data store.
4198 ///
4199 /// Each such value should be the Merkle root of a subtree of the Sapling note commitment tree
4200 /// containing 2^[`SAPLING_SHARD_HEIGHT`] note commitments.
4201 fn put_sapling_subtree_roots(
4202 &mut self,
4203 start_index: u64,
4204 roots: &[CommitmentTreeRoot<sapling::Node>],
4205 ) -> Result<(), ShardTreeError<Self::Error>>;
4206
4207 /// Returns the stored root hash of the completed Sapling subtree with the given index,
4208 /// or `Ok(None)` if no root is recorded for that subtree.
4209 ///
4210 /// This is the store's record of the subtree root as most recently provided via
4211 /// [`WalletCommitmentTrees::put_sapling_subtree_roots`] (i.e. the chain-authoritative
4212 /// root obtained from a chain data provider), or as recorded when a locally-completed
4213 /// subtree was persisted.
4214 fn get_sapling_subtree_root(
4215 &mut self,
4216 index: u64,
4217 ) -> Result<Option<sapling::Node>, ShardTreeError<Self::Error>>;
4218
4219 /// The type of the backing [`ShardStore`] for the Orchard note commitment tree.
4220 #[cfg(feature = "orchard")]
4221 type OrchardShardStore<'a>: ShardStore<
4222 H = orchard::tree::MerkleHashOrchard,
4223 CheckpointId = BlockHeight,
4224 Error = Self::Error,
4225 >;
4226
4227 /// Evaluates the given callback function with a reference to the Orchard
4228 /// note commitment tree maintained by the wallet.
4229 #[cfg(feature = "orchard")]
4230 fn with_orchard_tree_mut<F, A, E>(&mut self, callback: F) -> Result<A, E>
4231 where
4232 for<'a> F: FnMut(
4233 &'a mut ShardTree<
4234 Self::OrchardShardStore<'a>,
4235 { ORCHARD_SHARD_HEIGHT * 2 },
4236 ORCHARD_SHARD_HEIGHT,
4237 >,
4238 ) -> Result<A, E>,
4239 E: From<ShardTreeError<Self::Error>>;
4240
4241 /// Adds a sequence of Orchard note commitment tree subtree roots to the data store.
4242 ///
4243 /// Each such value should be the Merkle root of a subtree of the Orchard note commitment tree
4244 /// containing 2^[`ORCHARD_SHARD_HEIGHT`] note commitments.
4245 #[cfg(feature = "orchard")]
4246 fn put_orchard_subtree_roots(
4247 &mut self,
4248 start_index: u64,
4249 roots: &[CommitmentTreeRoot<orchard::tree::MerkleHashOrchard>],
4250 ) -> Result<(), ShardTreeError<Self::Error>>;
4251
4252 /// Returns the stored root hash of the completed Orchard subtree with the given index,
4253 /// or `Ok(None)` if no root is recorded for that subtree.
4254 ///
4255 /// This is the store's record of the subtree root as most recently provided via
4256 /// [`WalletCommitmentTrees::put_orchard_subtree_roots`] (i.e. the chain-authoritative
4257 /// root obtained from a chain data provider), or as recorded when a locally-completed
4258 /// subtree was persisted.
4259 #[cfg(feature = "orchard")]
4260 fn get_orchard_subtree_root(
4261 &mut self,
4262 index: u64,
4263 ) -> Result<Option<orchard::tree::MerkleHashOrchard>, ShardTreeError<Self::Error>>;
4264
4265 /// Evaluates the given callback with the Ironwood note commitment tree
4266 /// maintained by the wallet, if this backend has one.
4267 ///
4268 /// The default implementation reports that no Ironwood tree is available.
4269 /// Backends that track Ironwood note commitments should override this and
4270 /// provide their separate Ironwood tree.
4271 #[cfg(feature = "orchard")]
4272 fn with_ironwood_tree_mut<F, A, E>(&mut self, _callback: F) -> Result<Option<A>, E>
4273 where
4274 for<'a> F: FnMut(
4275 &'a mut ShardTree<
4276 Self::OrchardShardStore<'a>,
4277 { ORCHARD_SHARD_HEIGHT * 2 },
4278 ORCHARD_SHARD_HEIGHT,
4279 >,
4280 ) -> Result<A, E>,
4281 E: From<ShardTreeError<Self::Error>>,
4282 {
4283 Ok(None)
4284 }
4285
4286 /// Adds a sequence of Ironwood note commitment tree subtree roots to the data store, if this
4287 /// backend tracks an Ironwood tree.
4288 ///
4289 /// Each such value should be the Merkle root of a subtree of the Ironwood note commitment tree
4290 /// containing 2^[`ORCHARD_SHARD_HEIGHT`] note commitments; Ironwood shares the Orchard note
4291 /// commitment tree's shape, so the same shard height applies.
4292 ///
4293 /// The default implementation is a no-op, for backends that do not track an Ironwood tree
4294 /// (mirroring [`WalletCommitmentTrees::with_ironwood_tree_mut`]). Backends that track Ironwood
4295 /// note commitments should override this.
4296 #[cfg(feature = "orchard")]
4297 fn put_ironwood_subtree_roots(
4298 &mut self,
4299 _start_index: u64,
4300 _roots: &[CommitmentTreeRoot<orchard::tree::MerkleHashOrchard>],
4301 ) -> Result<(), ShardTreeError<Self::Error>> {
4302 Ok(())
4303 }
4304
4305 /// Returns the stored root hash of the completed Ironwood subtree with the given
4306 /// index, or `Ok(None)` if no root is recorded for that subtree (in particular, if
4307 /// this backend does not track an Ironwood tree — the default implementation).
4308 #[cfg(feature = "orchard")]
4309 fn get_ironwood_subtree_root(
4310 &mut self,
4311 _index: u64,
4312 ) -> Result<Option<orchard::tree::MerkleHashOrchard>, ShardTreeError<Self::Error>> {
4313 Ok(None)
4314 }
4315
4316 /// Applies a batch of changes — shards, an optional replacement tree cap, and a
4317 /// checkpoint delta — to the wallet's Sapling note commitment tree.
4318 ///
4319 /// `shards` must be in ascending shard-index order; stores may reject sequences that
4320 /// would leave gaps in the tree. Checkpoint removals are applied before additions, so
4321 /// that a checkpoint whose data has changed may appear in both lists.
4322 ///
4323 /// This is intended for wallet stores that accumulate note commitment tree updates
4324 /// outside the backing store (for example, in an in-memory tree) and flush them in
4325 /// batches. The default implementation applies the changes through
4326 /// [`WalletCommitmentTrees::with_sapling_tree_mut`].
4327 fn put_sapling_shards(
4328 &mut self,
4329 shards: &[shardtree::LocatedPrunableTree<sapling::Node>],
4330 cap: Option<&shardtree::PrunableTree<sapling::Node>>,
4331 checkpoints_remove: &[BlockHeight],
4332 checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
4333 ) -> Result<(), ShardTreeError<Self::Error>> {
4334 self.with_sapling_tree_mut(|tree| {
4335 apply_tree_changes(tree, shards, cap, checkpoints_remove, checkpoints_add)
4336 })
4337 }
4338
4339 /// Applies a batch of changes — shards, an optional replacement tree cap, and a
4340 /// checkpoint delta — to the wallet's Orchard note commitment tree.
4341 ///
4342 /// `shards` must be in ascending shard-index order; stores may reject sequences that
4343 /// would leave gaps in the tree. Checkpoint removals are applied before additions, so
4344 /// that a checkpoint whose data has changed may appear in both lists.
4345 ///
4346 /// This is intended for wallet stores that accumulate note commitment tree updates
4347 /// outside the backing store (for example, in an in-memory tree) and flush them in
4348 /// batches. The default implementation applies the changes through
4349 /// [`WalletCommitmentTrees::with_orchard_tree_mut`].
4350 #[cfg(feature = "orchard")]
4351 fn put_orchard_shards(
4352 &mut self,
4353 shards: &[shardtree::LocatedPrunableTree<orchard::tree::MerkleHashOrchard>],
4354 cap: Option<&shardtree::PrunableTree<orchard::tree::MerkleHashOrchard>>,
4355 checkpoints_remove: &[BlockHeight],
4356 checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
4357 ) -> Result<(), ShardTreeError<Self::Error>> {
4358 self.with_orchard_tree_mut(|tree| {
4359 apply_tree_changes(tree, shards, cap, checkpoints_remove, checkpoints_add)
4360 })
4361 }
4362
4363 /// Applies a batch of changes — shards, an optional replacement tree cap, and a
4364 /// checkpoint delta — to the wallet's Ironwood note commitment tree, if this backend
4365 /// tracks one.
4366 ///
4367 /// `shards` must be in ascending shard-index order; stores may reject sequences that
4368 /// would leave gaps in the tree. Checkpoint removals are applied before additions, so
4369 /// that a checkpoint whose data has changed may appear in both lists.
4370 ///
4371 /// The default implementation applies the changes through
4372 /// [`WalletCommitmentTrees::with_ironwood_tree_mut`]; for backends that do not track an
4373 /// Ironwood tree (see that method's documentation), the changes are ignored.
4374 #[cfg(feature = "orchard")]
4375 fn put_ironwood_shards(
4376 &mut self,
4377 shards: &[shardtree::LocatedPrunableTree<orchard::tree::MerkleHashOrchard>],
4378 cap: Option<&shardtree::PrunableTree<orchard::tree::MerkleHashOrchard>>,
4379 checkpoints_remove: &[BlockHeight],
4380 checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
4381 ) -> Result<(), ShardTreeError<Self::Error>> {
4382 self.with_ironwood_tree_mut(|tree| {
4383 apply_tree_changes(tree, shards, cap, checkpoints_remove, checkpoints_add)
4384 })?;
4385 Ok(())
4386 }
4387
4388 /// Releases all retained ("anchor") checkpoints with height strictly less than `max_height`
4389 /// from the wallet's note commitment trees, allowing them to be pruned normally.
4390 ///
4391 /// Anchor checkpoints are established during scanning (and may be created directly via
4392 /// [`ShardTree::ensure_retained`]); they are otherwise exempt from automatic pruning of excess
4393 /// checkpoints. This releases the retention of those that have aged below `max_height` in the
4394 /// Sapling and (when the `orchard` feature is enabled) the Orchard and Ironwood trees.
4395 fn remove_retained_checkpoints_below(
4396 &mut self,
4397 max_height: BlockHeight,
4398 ) -> Result<(), ShardTreeError<Self::Error>> {
4399 self.with_sapling_tree_mut(|tree| {
4400 for height in tree
4401 .store()
4402 .retained_checkpoints()
4403 .map_err(ShardTreeError::Storage)?
4404 {
4405 if height < max_height {
4406 tree.remove_retained_checkpoint(&height)?;
4407 }
4408 }
4409 Ok::<_, ShardTreeError<Self::Error>>(())
4410 })?;
4411
4412 #[cfg(feature = "orchard")]
4413 self.with_orchard_tree_mut(|tree| {
4414 for height in tree
4415 .store()
4416 .retained_checkpoints()
4417 .map_err(ShardTreeError::Storage)?
4418 {
4419 if height < max_height {
4420 tree.remove_retained_checkpoint(&height)?;
4421 }
4422 }
4423 Ok::<_, ShardTreeError<Self::Error>>(())
4424 })?;
4425
4426 // A backend that does not track an Ironwood tree returns `None` here and is left unchanged.
4427 #[cfg(feature = "orchard")]
4428 self.with_ironwood_tree_mut(|tree| {
4429 for height in tree
4430 .store()
4431 .retained_checkpoints()
4432 .map_err(ShardTreeError::Storage)?
4433 {
4434 if height < max_height {
4435 tree.remove_retained_checkpoint(&height)?;
4436 }
4437 }
4438 Ok::<_, ShardTreeError<Self::Error>>(())
4439 })?;
4440
4441 Ok(())
4442 }
4443}
4444
4445/// Property tests for the [`Balance`] bucket arithmetic.
4446///
4447/// These pin the accounting semantics the locked-value bucket joined: every bucket except
4448/// `uneconomic_value` participates in [`Balance::total`] and in the shared overflow guard,
4449/// while `uneconomic_value` is guarded only against its own overflow and never contributes
4450/// to the total.
4451#[cfg(test)]
4452mod balance_tests {
4453 use proptest::prelude::*;
4454 use zcash_protocol::value::{BalanceError, MAX_MONEY, Zatoshis};
4455
4456 use super::Balance;
4457
4458 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4459 enum Bucket {
4460 Spendable = 0,
4461 Locked = 1,
4462 PendingChange = 2,
4463 PendingSpendable = 3,
4464 Uneconomic = 4,
4465 }
4466 use Bucket::*;
4467
4468 const ALL_BUCKETS: [Bucket; 5] = [
4469 Spendable,
4470 Locked,
4471 PendingChange,
4472 PendingSpendable,
4473 Uneconomic,
4474 ];
4475 /// The buckets that participate in `Balance::total` and its overflow guard.
4476 const TOTAL_BUCKETS: [Bucket; 4] = [Spendable, Locked, PendingChange, PendingSpendable];
4477
4478 fn apply(balance: &mut Balance, bucket: Bucket, value: Zatoshis) -> Result<(), BalanceError> {
4479 match bucket {
4480 Spendable => balance.add_spendable_value(value),
4481 Locked => balance.add_locked_value(value),
4482 PendingChange => balance.add_pending_change_value(value),
4483 PendingSpendable => balance.add_pending_spendable_value(value),
4484 Uneconomic => balance.add_uneconomic_value(value),
4485 }
4486 }
4487
4488 fn get(balance: &Balance, bucket: Bucket) -> Zatoshis {
4489 match bucket {
4490 Spendable => balance.spendable_value(),
4491 Locked => balance.locked_value(),
4492 PendingChange => balance.change_pending_confirmation(),
4493 PendingSpendable => balance.value_pending_spendability(),
4494 Uneconomic => balance.uneconomic_value(),
4495 }
4496 }
4497
4498 fn arb_bucket() -> impl Strategy<Value = Bucket> {
4499 prop_oneof![
4500 Just(Spendable),
4501 Just(Locked),
4502 Just(PendingChange),
4503 Just(PendingSpendable),
4504 Just(Uneconomic),
4505 ]
4506 }
4507
4508 /// A bucket and a value to add to it. Values are mostly small (so most sequences stay
4509 /// within `MAX_MONEY`) with occasional near-cap draws to exercise the overflow guards.
4510 fn arb_add() -> impl Strategy<Value = (Bucket, u64)> {
4511 (
4512 arb_bucket(),
4513 prop_oneof![
4514 3 => 0u64..=1_000_000,
4515 1 => 0u64..=MAX_MONEY,
4516 ],
4517 )
4518 }
4519
4520 proptest! {
4521 /// Bucket adds succeed exactly while their overflow guard permits, mutate only the
4522 /// requested bucket, and leave the balance untouched on failure. `total()` is always
4523 /// the sum of the four participating buckets. (In particular this establishes that
4524 /// the `unwrap` inside each guarded add is unreachable.)
4525 #[test]
4526 fn add_total_consistency(adds in proptest::collection::vec(arb_add(), 0..12)) {
4527 let mut balance = Balance::ZERO;
4528 // The model: per-bucket totals, indexed by bucket discriminant.
4529 let mut model = [0u64; 5];
4530
4531 for (bucket, v) in adds {
4532 let value = Zatoshis::from_u64(v).unwrap();
4533 let before = balance;
4534 let result = apply(&mut balance, bucket, value);
4535
4536 let total: u64 = TOTAL_BUCKETS.iter().map(|b| model[*b as usize]).sum();
4537 let expect_ok = match bucket {
4538 Uneconomic => model[Uneconomic as usize] + v <= MAX_MONEY,
4539 _ => total + v <= MAX_MONEY,
4540 };
4541 if expect_ok {
4542 prop_assert!(result.is_ok());
4543 model[bucket as usize] += v;
4544 } else {
4545 prop_assert!(result.is_err());
4546 prop_assert_eq!(
4547 balance, before,
4548 "a failed add must leave the balance unchanged"
4549 );
4550 }
4551
4552 let total: u64 = TOTAL_BUCKETS.iter().map(|b| model[*b as usize]).sum();
4553 prop_assert_eq!(balance.total(), Zatoshis::from_u64(total).unwrap());
4554 for b in ALL_BUCKETS {
4555 prop_assert_eq!(
4556 get(&balance, b),
4557 Zatoshis::from_u64(model[b as usize]).unwrap()
4558 );
4559 }
4560 }
4561 }
4562
4563 /// `Balance + Balance` is componentwise addition: it succeeds exactly when the
4564 /// combined total and the combined uneconomic value each remain within `MAX_MONEY`,
4565 /// and on success every bucket of the sum is the sum of the corresponding buckets.
4566 #[test]
4567 fn balance_addition_is_componentwise(
4568 a in proptest::collection::vec(arb_add(), 0..6),
4569 b in proptest::collection::vec(arb_add(), 0..6),
4570 ) {
4571 let build = |adds: &[(Bucket, u64)]| {
4572 let mut balance = Balance::ZERO;
4573 for (bucket, v) in adds {
4574 let _ = apply(&mut balance, *bucket, Zatoshis::from_u64(*v).unwrap());
4575 }
4576 balance
4577 };
4578 let ba = build(&a);
4579 let bb = build(&b);
4580
4581 let combined_total = u64::from(ba.total()) + u64::from(bb.total());
4582 let combined_uneconomic =
4583 u64::from(ba.uneconomic_value()) + u64::from(bb.uneconomic_value());
4584 match ba + bb {
4585 Ok(sum) => {
4586 prop_assert!(combined_total <= MAX_MONEY);
4587 prop_assert!(combined_uneconomic <= MAX_MONEY);
4588 for bucket in ALL_BUCKETS {
4589 prop_assert_eq!(
4590 u64::from(get(&sum, bucket)),
4591 u64::from(get(&ba, bucket)) + u64::from(get(&bb, bucket))
4592 );
4593 }
4594 prop_assert_eq!(u64::from(sum.total()), combined_total);
4595 }
4596 Err(_) => {
4597 prop_assert!(
4598 combined_total > MAX_MONEY || combined_uneconomic > MAX_MONEY,
4599 "balance addition failed although no component overflows"
4600 );
4601 }
4602 }
4603 }
4604 }
4605}
4606
4607#[cfg(test)]
4608mod tests {
4609 use incrementalmerkletree::{
4610 Address as TreeAddress, Hashable, Level, Marking, Position, Retention,
4611 };
4612 use shardtree::store::{Checkpoint, memory::MemoryShardStore};
4613 use zcash_keys::{
4614 address::{Address, UnifiedAddress},
4615 keys::UnifiedAddressRequest,
4616 };
4617
4618 use super::*;
4619
4620 #[cfg(feature = "orchard")]
4621 use crate::data_api::error::FindAccountForAddressError;
4622 use crate::data_api::testing::{
4623 MockWalletDb, pool::ShieldedPoolTester, sapling::SaplingPoolTester,
4624 };
4625
4626 use transparent::address::TransparentAddress;
4627 use zip32::DiversifierIndex;
4628
4629 #[test]
4630 fn put_sapling_shards_flushes_through_the_interface() {
4631 let mut db = MockWalletDb::new(zcash_protocol::consensus::Network::TestNetwork);
4632
4633 // Build a shard-rooted subtree the same way `put_blocks` does, with a checkpoint on
4634 // the final leaf.
4635 let leaf = <sapling::Node as Hashable>::empty_leaf();
4636 let checkpoint_height = BlockHeight::from(3);
4637 let commitments = (0u64..4).map(|i| {
4638 (
4639 leaf,
4640 if i == 3 {
4641 Retention::Checkpoint {
4642 id: checkpoint_height,
4643 marking: Marking::None,
4644 }
4645 } else {
4646 Retention::Ephemeral
4647 },
4648 )
4649 });
4650 let built = shardtree::LocatedTree::from_iter(
4651 Position::from(0)..Position::from(4),
4652 Level::from(SAPLING_SHARD_HEIGHT),
4653 commitments,
4654 )
4655 .expect("commitments produce a subtree");
4656 let checkpoints_add = built
4657 .checkpoints
4658 .iter()
4659 .map(|(height, position)| (*height, Checkpoint::at_position(*position)))
4660 .collect::<Vec<_>>();
4661
4662 db.put_sapling_shards(&[built.subtree], None, &[], &checkpoints_add)
4663 .expect("bulk flush succeeds");
4664
4665 // The shard and checkpoint are visible through the standard tree access path.
4666 db.with_sapling_tree_mut(|tree| {
4667 assert!(
4668 tree.store()
4669 .get_shard(TreeAddress::from_parts(
4670 Level::from(SAPLING_SHARD_HEIGHT),
4671 0
4672 ))
4673 .map_err(ShardTreeError::Storage)?
4674 .is_some()
4675 );
4676 assert_eq!(
4677 tree.store()
4678 .max_checkpoint_id()
4679 .map_err(ShardTreeError::Storage)?,
4680 Some(checkpoint_height)
4681 );
4682 Ok::<_, ShardTreeError<_>>(())
4683 })
4684 .expect("tree reads succeed");
4685
4686 // Removals are applied before additions, so a checkpoint set can be replaced in a
4687 // single call.
4688 let new_height = BlockHeight::from(7);
4689 db.put_sapling_shards(
4690 &[],
4691 None,
4692 &[checkpoint_height],
4693 &[(new_height, Checkpoint::tree_empty())],
4694 )
4695 .expect("checkpoint replacement succeeds");
4696
4697 db.with_sapling_tree_mut(|tree| {
4698 assert_eq!(
4699 tree.store()
4700 .max_checkpoint_id()
4701 .map_err(ShardTreeError::Storage)?,
4702 Some(new_height)
4703 );
4704 assert_eq!(
4705 tree.store()
4706 .checkpoint_count()
4707 .map_err(ShardTreeError::Storage)?,
4708 1
4709 );
4710 Ok::<_, ShardTreeError<_>>(())
4711 })
4712 .expect("tree reads succeed");
4713 }
4714
4715 /// Exercises [`apply_tree_changes`] — the shared implementation of the `put_*_shards`
4716 /// provided methods — directly over a [`MemoryShardStore`] of the given node type.
4717 ///
4718 /// [`MemoryShardStore`]: shardtree::store::memory::MemoryShardStore
4719 fn check_apply_tree_changes<H>()
4720 where
4721 H: incrementalmerkletree::Hashable + Clone + PartialEq + core::fmt::Debug,
4722 {
4723 let mut tree: ShardTree<
4724 MemoryShardStore<H, BlockHeight>,
4725 { SAPLING_SHARD_HEIGHT * 2 },
4726 SAPLING_SHARD_HEIGHT,
4727 > = ShardTree::new(MemoryShardStore::empty(), 100);
4728
4729 // Build a shard-rooted subtree the same way `put_blocks` does, with a checkpoint on
4730 // the final leaf.
4731 let leaf = H::empty_leaf();
4732 let checkpoint_height = BlockHeight::from(3);
4733 let commitments = (0u64..4).map(|i| {
4734 (
4735 leaf.clone(),
4736 if i == 3 {
4737 Retention::Checkpoint {
4738 id: checkpoint_height,
4739 marking: Marking::None,
4740 }
4741 } else {
4742 Retention::Ephemeral
4743 },
4744 )
4745 });
4746 let built = shardtree::LocatedTree::from_iter(
4747 Position::from(0)..Position::from(4),
4748 Level::from(SAPLING_SHARD_HEIGHT),
4749 commitments,
4750 )
4751 .expect("commitments produce a subtree");
4752 let checkpoints_add = built
4753 .checkpoints
4754 .iter()
4755 .map(|(height, position)| (*height, Checkpoint::at_position(*position)))
4756 .collect::<Vec<_>>();
4757
4758 apply_tree_changes(&mut tree, &[built.subtree], None, &[], &checkpoints_add)
4759 .expect("bulk flush succeeds");
4760
4761 assert!(
4762 tree.store()
4763 .get_shard(TreeAddress::from_parts(
4764 Level::from(SAPLING_SHARD_HEIGHT),
4765 0
4766 ))
4767 .expect("shard read succeeds")
4768 .is_some()
4769 );
4770 assert_eq!(
4771 tree.store()
4772 .max_checkpoint_id()
4773 .expect("checkpoint read succeeds"),
4774 Some(checkpoint_height)
4775 );
4776
4777 // Removals are applied before additions, so a checkpoint set can be replaced in a
4778 // single call.
4779 let new_height = BlockHeight::from(7);
4780 apply_tree_changes(
4781 &mut tree,
4782 &[],
4783 None,
4784 &[checkpoint_height],
4785 &[(new_height, Checkpoint::tree_empty())],
4786 )
4787 .expect("checkpoint replacement succeeds");
4788
4789 assert_eq!(
4790 tree.store()
4791 .max_checkpoint_id()
4792 .expect("checkpoint read succeeds"),
4793 Some(new_height)
4794 );
4795 assert_eq!(
4796 tree.store()
4797 .checkpoint_count()
4798 .expect("checkpoint read succeeds"),
4799 1
4800 );
4801 }
4802
4803 #[test]
4804 fn apply_tree_changes_supports_every_pool_node_type() {
4805 check_apply_tree_changes::<sapling::Node>();
4806 // Orchard and Ironwood both use `MerkleHashOrchard` trees of the same shape.
4807 #[cfg(feature = "orchard")]
4808 check_apply_tree_changes::<orchard::tree::MerkleHashOrchard>();
4809 }
4810
4811 #[cfg(feature = "orchard")]
4812 #[test]
4813 fn put_ironwood_shards_is_ignored_without_an_ironwood_tree() {
4814 // `MockWalletDb` does not track an Ironwood tree, so the default
4815 // `with_ironwood_tree_mut` reports no tree and the changes are ignored rather than
4816 // returning an error.
4817 let mut db = MockWalletDb::new(zcash_protocol::consensus::Network::TestNetwork);
4818 db.put_ironwood_shards(
4819 &[],
4820 None,
4821 &[],
4822 &[(BlockHeight::from(1), Checkpoint::tree_empty())],
4823 )
4824 .expect("ignored on backends without an Ironwood tree");
4825 }
4826
4827 #[test]
4828 fn account_meta_totals_include_ironwood() {
4829 let meta = AccountMeta::new(
4830 Some(PoolMeta::new(2, Zatoshis::const_from_u64(200))),
4831 Some(PoolMeta::new(3, Zatoshis::const_from_u64(300))),
4832 Some(PoolMeta::new(5, Zatoshis::const_from_u64(500))),
4833 );
4834 assert_eq!(meta.note_count(ShieldedPool::Ironwood), Some(5));
4835 assert_eq!(meta.total_note_count(), Some(10));
4836 assert_eq!(meta.total_value(), Some(Zatoshis::const_from_u64(1000)));
4837
4838 // With metadata for only the Ironwood pool, the totals reflect that pool alone.
4839 let ironwood_only = AccountMeta::new(
4840 None,
4841 None,
4842 Some(PoolMeta::new(4, Zatoshis::const_from_u64(400))),
4843 );
4844 assert_eq!(ironwood_only.note_count(ShieldedPool::Ironwood), Some(4));
4845 assert_eq!(ironwood_only.total_note_count(), Some(4));
4846 assert_eq!(
4847 ironwood_only.total_value(),
4848 Some(Zatoshis::const_from_u64(400))
4849 );
4850 }
4851
4852 fn derived_source() -> AddressSource {
4853 AddressSource::Derived {
4854 diversifier_index: DiversifierIndex::default(),
4855 #[cfg(feature = "transparent-inputs")]
4856 transparent_key_scope: None,
4857 }
4858 }
4859
4860 fn address_info_of(address: Address) -> AddressInfo {
4861 AddressInfo::from_parts(address, derived_source())
4862 .expect("test address metadata must be valid")
4863 }
4864
4865 fn transparent_address_for_tag(tag: u8) -> TransparentAddress {
4866 TransparentAddress::PublicKeyHash([tag; 20])
4867 }
4868
4869 fn sapling_address_for_tag(tag: u8) -> sapling::PaymentAddress {
4870 match SaplingPoolTester::sk_default_address(&SaplingPoolTester::sk(&[tag; 32])) {
4871 Address::Sapling(pa) => pa,
4872 other => panic!("expected Sapling address, got {other:?}"),
4873 }
4874 }
4875
4876 fn unified_account_with(
4877 transparent: Option<TransparentAddress>,
4878 sapling: Option<sapling::PaymentAddress>,
4879 #[cfg(feature = "orchard")] orchard: Option<orchard::Address>,
4880 ) -> Address {
4881 UnifiedAddress::from_receivers(
4882 #[cfg(feature = "orchard")]
4883 Some(orchard).flatten(),
4884 Some(sapling).flatten(),
4885 transparent,
4886 )
4887 .expect("test UA must be valid")
4888 .into()
4889 }
4890
4891 #[test]
4892 fn find_account_for_transparent_address_returns_matching_account() {
4893 let wallet = MockWalletDb::from_account_addresses(
4894 zcash_protocol::consensus::Network::MainNetwork,
4895 [
4896 (
4897 1,
4898 vec![address_info_of(Address::Transparent(
4899 transparent_address_for_tag(1),
4900 ))],
4901 ),
4902 (
4903 2,
4904 vec![address_info_of(Address::Transparent(
4905 transparent_address_for_tag(2),
4906 ))],
4907 ),
4908 ],
4909 );
4910 let result = wallet.find_account_for_address(
4911 &zcash_protocol::consensus::Network::MainNetwork,
4912 &Address::Transparent(transparent_address_for_tag(1)),
4913 );
4914 assert_eq!(result.unwrap(), Some(1));
4915 }
4916
4917 #[test]
4918 fn find_account_for_transparent_receiver_in_unified_address_returns_matching_account() {
4919 let transparent = transparent_address_for_tag(1);
4920 let sapling_address = sapling_address_for_tag(11);
4921
4922 #[cfg(feature = "orchard")]
4923 {
4924 let wallet = MockWalletDb::from_account_addresses(
4925 zcash_protocol::consensus::Network::MainNetwork,
4926 [(
4927 1,
4928 vec![address_info_of(unified_account_with(
4929 Some(transparent),
4930 Some(sapling_address),
4931 None,
4932 ))],
4933 )],
4934 );
4935 let result = wallet.find_account_for_address(
4936 &zcash_protocol::consensus::Network::MainNetwork,
4937 &Address::Transparent(transparent),
4938 );
4939 assert_eq!(result.unwrap(), Some(1));
4940 }
4941 #[cfg(not(feature = "orchard"))]
4942 {
4943 let wallet = MockWalletDb::from_account_addresses(
4944 zcash_protocol::consensus::Network::MainNetwork,
4945 [(
4946 1,
4947 vec![address_info_of(unified_account_with(
4948 Some(transparent),
4949 Some(sapling_address),
4950 ))],
4951 )],
4952 );
4953 let result = wallet.find_account_for_address(
4954 &zcash_protocol::consensus::Network::MainNetwork,
4955 &Address::Transparent(transparent),
4956 );
4957 assert_eq!(result.unwrap(), Some(1));
4958 }
4959 }
4960
4961 #[test]
4962 fn find_account_for_address_returns_none_when_simple_address_is_unknown() {
4963 let address = Address::Transparent(transparent_address_for_tag(1));
4964 let wallet = MockWalletDb::from_account_addresses(
4965 zcash_protocol::consensus::Network::MainNetwork,
4966 [(1, vec![address_info_of(address)])],
4967 );
4968
4969 let other_address = Address::Transparent(transparent_address_for_tag(9));
4970 let result = wallet.find_account_for_address(
4971 &zcash_protocol::consensus::Network::MainNetwork,
4972 &other_address,
4973 );
4974
4975 assert_eq!(result.unwrap(), None);
4976 }
4977
4978 fn test_ufvk(seed_tag: u8) -> zcash_keys::keys::UnifiedFullViewingKey {
4979 zcash_keys::keys::UnifiedSpendingKey::from_seed(
4980 &zcash_protocol::consensus::Network::MainNetwork,
4981 &[seed_tag; 32],
4982 zip32::AccountId::ZERO,
4983 )
4984 .expect("valid seed")
4985 .to_unified_full_viewing_key()
4986 }
4987
4988 #[test]
4989 fn find_account_for_unified_address_returns_account_when_receivers_map_to_same_account() {
4990 let ufvk = test_ufvk(1);
4991 let wallet = MockWalletDb::from_account_ufvks(
4992 zcash_protocol::consensus::Network::MainNetwork,
4993 [(1, ufvk.clone())],
4994 );
4995
4996 let (ua, _) = ufvk
4997 .default_address(UnifiedAddressRequest::AllAvailableKeys)
4998 .expect("default address must be derivable");
4999
5000 let result = wallet.find_account_for_address(
5001 &zcash_protocol::consensus::Network::MainNetwork,
5002 &Address::Unified(ua),
5003 );
5004
5005 assert_eq!(result.unwrap(), Some(1));
5006 }
5007
5008 #[test]
5009 fn find_account_for_unified_address_returns_none_when_no_receiver_matches() {
5010 let wallet = MockWalletDb::from_account_ufvks(
5011 zcash_protocol::consensus::Network::MainNetwork,
5012 [(1, test_ufvk(1))],
5013 );
5014
5015 // A UA derived from a different seed — no account in the wallet owns any of its
5016 // shielded receivers.
5017 let (ua_from_other_seed, _) = test_ufvk(99)
5018 .default_address(UnifiedAddressRequest::AllAvailableKeys)
5019 .expect("default address must be derivable");
5020
5021 let result = wallet.find_account_for_address(
5022 &zcash_protocol::consensus::Network::MainNetwork,
5023 &Address::Unified(ua_from_other_seed),
5024 );
5025
5026 assert_eq!(result.unwrap(), None);
5027 }
5028
5029 #[test]
5030 fn find_account_for_sapling_address_resolves_via_uivk_algebra_when_not_previously_exposed() {
5031 // A bare Sapling address derivable from an account's UIVK must resolve even when the
5032 // wallet has never stored (and therefore never "exposed") that address.
5033 let ufvk = test_ufvk(1);
5034 let wallet = MockWalletDb::from_account_ufvks(
5035 zcash_protocol::consensus::Network::MainNetwork,
5036 [(1, ufvk.clone())],
5037 );
5038
5039 let (ua, _) = ufvk
5040 .default_address(UnifiedAddressRequest::AllAvailableKeys)
5041 .expect("default address must be derivable");
5042 let sapling_pa = *ua.sapling().expect("sapling receiver");
5043
5044 // `wallet` has no stored addresses: only the account's UFVK. The list_addresses scan
5045 // would therefore miss this address; only the synthesized-UA algebraic path can
5046 // resolve it.
5047 let result = wallet.find_account_for_address(
5048 &zcash_protocol::consensus::Network::MainNetwork,
5049 &Address::Sapling(sapling_pa),
5050 );
5051
5052 assert_eq!(result.unwrap(), Some(1));
5053 }
5054
5055 #[test]
5056 fn find_account_for_address_returns_none_for_empty_wallet() {
5057 let wallet = MockWalletDb::from_account_addresses(
5058 zcash_protocol::consensus::Network::MainNetwork,
5059 std::iter::empty(),
5060 );
5061
5062 let result = wallet.find_account_for_address(
5063 &zcash_protocol::consensus::Network::MainNetwork,
5064 &Address::Transparent(transparent_address_for_tag(1)),
5065 );
5066 assert_eq!(result.unwrap(), None);
5067
5068 let result = wallet.find_account_for_address(
5069 &zcash_protocol::consensus::Network::MainNetwork,
5070 &Address::Sapling(sapling_address_for_tag(1)),
5071 );
5072 assert_eq!(result.unwrap(), None);
5073 }
5074
5075 #[cfg(feature = "orchard")]
5076 #[test]
5077 fn find_account_for_unified_address_errors_when_receivers_map_to_different_accounts() {
5078 let ufvk1 = test_ufvk(1);
5079 let ufvk2 = test_ufvk(2);
5080 let wallet = MockWalletDb::from_account_ufvks(
5081 zcash_protocol::consensus::Network::MainNetwork,
5082 [(1, ufvk1.clone()), (2, ufvk2.clone())],
5083 );
5084
5085 let (ua1, _) = ufvk1
5086 .default_address(UnifiedAddressRequest::AllAvailableKeys)
5087 .expect("default address must be derivable");
5088 let (ua2, _) = ufvk2
5089 .default_address(UnifiedAddressRequest::AllAvailableKeys)
5090 .expect("default address must be derivable");
5091
5092 // A frankenstein UA whose Sapling receiver is from account 1 and whose Orchard
5093 // receiver is from account 2.
5094 let frankenstein = UnifiedAddress::from_receivers(
5095 Some(ua2.orchard().copied().expect("orchard receiver")),
5096 Some(ua1.sapling().copied().expect("sapling receiver")),
5097 None,
5098 )
5099 .expect("sapling+orchard UA must be valid");
5100
5101 let result = wallet.find_account_for_address(
5102 &zcash_protocol::consensus::Network::MainNetwork,
5103 &Address::Unified(frankenstein),
5104 );
5105
5106 assert!(matches!(
5107 result,
5108 Err(FindAccountForAddressError::UnifiedAddressConflict)
5109 ));
5110 }
5111
5112 /// Each unshielded mutator updates only its own bucket, and transparent mutations leave the
5113 /// shielded aggregates untouched.
5114 #[test]
5115 fn account_balance_unshielded_split_mutators() {
5116 let mut balance = AccountBalance::ZERO;
5117
5118 let regular_value = Zatoshis::const_from_u64(100_000);
5119 let coinbase_value = Zatoshis::const_from_u64(50_000);
5120
5121 balance
5122 .with_unshielded_regular_balance_mut(|bal| bal.add_spendable_value(regular_value))
5123 .unwrap();
5124 balance
5125 .with_unshielded_coinbase_balance_mut(|bal| {
5126 bal.add_pending_spendable_value(coinbase_value)
5127 })
5128 .unwrap();
5129
5130 // The regular bucket contains only the regular value.
5131 assert_eq!(
5132 balance.unshielded_regular_balance().spendable_value(),
5133 regular_value
5134 );
5135 assert_eq!(balance.unshielded_regular_balance().total(), regular_value);
5136 assert_eq!(
5137 balance
5138 .unshielded_regular_balance()
5139 .value_pending_spendability(),
5140 Zatoshis::ZERO
5141 );
5142
5143 // The coinbase bucket contains only the coinbase value, as pending.
5144 assert_eq!(
5145 balance.unshielded_coinbase_balance().spendable_value(),
5146 Zatoshis::ZERO
5147 );
5148 assert_eq!(
5149 balance
5150 .unshielded_coinbase_balance()
5151 .value_pending_spendability(),
5152 coinbase_value
5153 );
5154 assert_eq!(
5155 balance.unshielded_coinbase_balance().total(),
5156 coinbase_value
5157 );
5158
5159 // The shielded-only aggregates are unaffected by transparent mutations.
5160 assert_eq!(balance.spendable_value(), Zatoshis::ZERO);
5161 assert_eq!(balance.change_pending_confirmation(), Zatoshis::ZERO);
5162 assert_eq!(balance.value_pending_spendability(), Zatoshis::ZERO);
5163 assert_eq!(balance.sapling_balance(), &Balance::ZERO);
5164 assert_eq!(balance.orchard_balance(), &Balance::ZERO);
5165 assert_eq!(balance.ironwood_balance(), &Balance::ZERO);
5166 }
5167
5168 /// `unshielded_balance` returns the sum of the regular and coinbase buckets, and the
5169 /// account-level aggregates include both buckets.
5170 #[test]
5171 fn account_balance_unshielded_balance_is_sum() {
5172 let mut balance = AccountBalance::ZERO;
5173
5174 let regular_spendable = Zatoshis::const_from_u64(100_000);
5175 let regular_dust = Zatoshis::const_from_u64(100);
5176 let coinbase_pending = Zatoshis::const_from_u64(625_000_000);
5177 let coinbase_dust = Zatoshis::const_from_u64(42);
5178
5179 balance
5180 .with_unshielded_regular_balance_mut(|bal| {
5181 bal.add_spendable_value(regular_spendable)?;
5182 bal.add_uneconomic_value(regular_dust)
5183 })
5184 .unwrap();
5185 balance
5186 .with_unshielded_coinbase_balance_mut(|bal| {
5187 bal.add_pending_spendable_value(coinbase_pending)?;
5188 bal.add_uneconomic_value(coinbase_dust)
5189 })
5190 .unwrap();
5191
5192 // The by-value combined balance is the field-wise sum of both buckets.
5193 let combined = balance.unshielded_balance();
5194 assert_eq!(
5195 combined,
5196 (*balance.unshielded_regular_balance() + *balance.unshielded_coinbase_balance())
5197 .unwrap()
5198 );
5199 assert_eq!(combined.spendable_value(), regular_spendable);
5200 assert_eq!(combined.value_pending_spendability(), coinbase_pending);
5201 assert_eq!(
5202 combined.uneconomic_value(),
5203 (regular_dust + coinbase_dust).unwrap()
5204 );
5205
5206 // The deprecated accessor reports the sum of both buckets' totals.
5207 #[allow(deprecated)]
5208 let unshielded = balance.unshielded();
5209 assert_eq!(
5210 unshielded,
5211 (balance.unshielded_regular_balance().total()
5212 + balance.unshielded_coinbase_balance().total())
5213 .unwrap()
5214 );
5215
5216 // The account total and uneconomic value include both buckets. (`Balance::total`
5217 // excludes uneconomic value, so the dust does not appear in the account total.)
5218 assert_eq!(
5219 balance.total(),
5220 (regular_spendable + coinbase_pending).unwrap()
5221 );
5222 assert_eq!(
5223 balance.uneconomic_value(),
5224 (regular_dust + coinbase_dust).unwrap()
5225 );
5226 }
5227
5228 /// The `check_total` invariant rejects mutations that would cause the sum of the regular and
5229 /// coinbase transparent buckets to exceed `MAX_MONEY`.
5230 #[test]
5231 fn account_balance_unshielded_overflow_rejected() {
5232 let max_money = Zatoshis::const_from_u64(zcash_protocol::value::MAX_MONEY);
5233 let mut balance = AccountBalance::ZERO;
5234
5235 // Fill the regular bucket up to MAX_MONEY; this is fine on its own.
5236 balance
5237 .with_unshielded_regular_balance_mut(|bal| bal.add_spendable_value(max_money))
5238 .unwrap();
5239 assert_eq!(balance.total(), max_money);
5240
5241 // Any further value in the coinbase bucket must be rejected by the account-level
5242 // invariant check, even though the coinbase bucket does not overflow on its own.
5243 let result: Result<(), BalanceError> =
5244 balance.with_unshielded_coinbase_balance_mut(|bal| {
5245 bal.add_pending_spendable_value(Zatoshis::const_from_u64(1))
5246 });
5247 assert!(matches!(result, Err(BalanceError::Overflow)));
5248 }
5249}