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