Skip to main content

zcash_client_backend/data_api/
ll.rs

1//! Low-level data API
2//!
3//! This module provides default implementations for several common client operations that rely on
4//! lower-level and more granular access to data. Client implementers should consider using the
5//! utility functions in this module when implementing traits such as [`WalletRead`] and
6//! [`WalletWrite`] in order to provide a consistent and robust user experience.
7//!
8//! [`WalletRead`]: super::WalletRead
9//! [`WalletWrite`]: super::WalletWrite
10
11use core::hash::Hash;
12use std::{collections::HashSet, ops::Range};
13
14use incrementalmerkletree::Position;
15use transparent::bundle::OutPoint;
16use zcash_address::ZcashAddress;
17use zcash_keys::address::Receiver;
18use zcash_primitives::{
19    block::BlockHash,
20    transaction::{Transaction, TransactionData},
21};
22use zcash_protocol::{
23    ShieldedPool, TxId,
24    consensus::{BlockHeight, TxIndex},
25    memo::MemoBytes,
26    value::{BalanceError, Zatoshis},
27    zip318::Zip318Classification,
28};
29use zip32::Scope;
30
31use super::{Account, TransactionStatus, wallet::TargetHeight};
32use crate::{
33    DecryptedOutput, TransferType,
34    wallet::{Recipient, WalletSaplingOutput, WalletTx},
35};
36
37#[cfg(feature = "transparent-inputs")]
38use {
39    crate::wallet::WalletTransparentOutput,
40    transparent::address::TransparentAddress,
41    zcash_keys::keys::{
42        UnifiedAddressRequest,
43        transparent::{TransparentKeyScope, gap_limits::GapLimits},
44    },
45};
46
47#[cfg(feature = "orchard")]
48use crate::wallet::WalletOrchardOutput;
49
50pub mod wallet;
51
52/// A trait for types that can provide information about outputs spent by and fees that were paid
53/// for a given transaction.
54pub trait TxMeta {
55    /// Returns an iterator over the references to transparent outputs spent in this transaction.
56    #[cfg(feature = "transparent-inputs")]
57    fn transparent_spends(&self) -> impl Iterator<Item = &OutPoint>;
58
59    /// Returns an iterator over the nullifiers of Sapling notes spent in this transaction.
60    fn sapling_spent_note_nullifiers(&self) -> impl Iterator<Item = &::sapling::Nullifier>;
61
62    /// Returns an iterator over the nullifiers of Orchard notes spent in this transaction.
63    #[cfg(feature = "orchard")]
64    fn orchard_spent_note_nullifiers(&self) -> impl Iterator<Item = &::orchard::note::Nullifier>;
65
66    /// Returns an iterator over the nullifiers of Ironwood notes spent in this transaction.
67    ///
68    /// Ironwood nullifiers share the Orchard nullifier type, but identify notes in the Ironwood
69    /// pool (the transaction's Ironwood bundle, distinct from its Orchard bundle).
70    #[cfg(feature = "orchard")]
71    fn ironwood_spent_note_nullifiers(&self) -> impl Iterator<Item = &::orchard::note::Nullifier>;
72
73    /// Returns the fee paid by this transaction, given a function that can retrieve the value of
74    /// prior transparent outputs spent in the transaction.
75    ///
76    /// Returns `Ok(None)` if insufficient information is available for computing the fee. This
77    /// can occur when:
78    /// - The transaction has transparent inputs whose values are not known to the wallet (e.g.,
79    ///   the wallet has not yet retrieved the transactions that created those outputs).
80    /// - The wallet scanned the chain using compact blocks, which do not include transparent
81    ///   input information. In this case, the wallet cannot determine whether the transaction
82    ///   has any transparent inputs, and thus cannot know if the fee is computable from
83    ///   shielded data alone.
84    fn fee_paid<E, F>(&self, get_prevout: F) -> Result<Option<Zatoshis>, E>
85    where
86        E: From<BalanceError>,
87        F: FnMut(&OutPoint) -> Result<Option<Zatoshis>, E>;
88}
89
90impl TxMeta for Transaction {
91    #[cfg(feature = "transparent-inputs")]
92    fn transparent_spends(&self) -> impl Iterator<Item = &OutPoint> {
93        self.transparent_bundle()
94            .into_iter()
95            .flat_map(|bundle| bundle.vin.iter().map(|txin| txin.prevout()))
96    }
97
98    fn sapling_spent_note_nullifiers(&self) -> impl Iterator<Item = &::sapling::Nullifier> {
99        self.sapling_bundle().into_iter().flat_map(|bundle| {
100            bundle
101                .shielded_spends()
102                .iter()
103                .map(|spend| spend.nullifier())
104        })
105    }
106
107    #[cfg(feature = "orchard")]
108    fn orchard_spent_note_nullifiers(&self) -> impl Iterator<Item = &::orchard::note::Nullifier> {
109        self.orchard_bundle()
110            .into_iter()
111            .flat_map(|bundle| bundle.actions().iter().map(|action| action.nullifier()))
112    }
113
114    #[cfg(feature = "orchard")]
115    fn ironwood_spent_note_nullifiers(&self) -> impl Iterator<Item = &::orchard::note::Nullifier> {
116        self.ironwood_bundle()
117            .into_iter()
118            .flat_map(|bundle| bundle.actions().iter().map(|action| action.nullifier()))
119    }
120
121    fn fee_paid<E, F>(&self, get_prevout: F) -> Result<Option<Zatoshis>, E>
122    where
123        E: From<BalanceError>,
124        F: FnMut(&OutPoint) -> Result<Option<Zatoshis>, E>,
125    {
126        TransactionData::fee_paid(self, get_prevout)
127    }
128}
129
130/// A capability trait that provides low-level wallet database read operations. These operations
131/// are used to provide standard implementations for certain [`WalletWrite`] trait methods.
132///
133/// [`WalletWrite`]: super::WalletWrite
134pub trait LowLevelWalletRead {
135    /// The type of errors that may be generated when querying a wallet data store.
136    type Error;
137
138    /// The type of the account identifier.
139    ///
140    /// An account identifier corresponds to at most a single unified spending key's worth of spend
141    /// authority, such that both received notes and change spendable by that spending authority
142    /// will be interpreted as belonging to that account.
143    type AccountId: Copy + Eq + Hash;
144
145    /// A wallet-internal account identifier, used for efficient lookups within the data store.
146    ///
147    /// Unlike [`AccountId`](Self::AccountId), this type is not intended for use in external
148    /// contexts; it is an ephemeral handle that may change across database migrations or
149    /// backend implementations.
150    type AccountRef: Copy + Eq + Hash;
151
152    /// The type of account records returned by the wallet backend, providing access to
153    /// the account's viewing keys and capabilities.
154    type Account: Account;
155
156    /// A wallet-internal transaction identifier.
157    type TxRef: Copy + Eq + Hash;
158
159    /// Returns the height to which the wallet has been fully scanned: the greatest height
160    /// for which the wallet has trial-decrypted this and all preceding blocks above the
161    /// wallet's birthday height, or `Ok(None)` if no such height exists.
162    fn block_fully_scanned_height(
163        &self,
164    ) -> Result<Option<zcash_protocol::consensus::BlockHeight>, Self::Error>;
165
166    /// Returns the set of account identifiers for accounts that spent notes and/or UTXOs in the
167    /// construction of the given transaction.
168    fn get_funding_accounts<T: TxMeta>(
169        &self,
170        tx: &T,
171    ) -> Result<HashSet<Self::AccountId>, Self::Error> {
172        let mut funding_accounts = HashSet::new();
173
174        #[cfg(feature = "transparent-inputs")]
175        funding_accounts.extend(self.detect_accounts_transparent(tx.transparent_spends())?);
176
177        funding_accounts.extend(self.detect_accounts_sapling(tx.sapling_spent_note_nullifiers())?);
178
179        #[cfg(feature = "orchard")]
180        funding_accounts.extend(self.detect_accounts_orchard(tx.orchard_spent_note_nullifiers())?);
181
182        #[cfg(feature = "orchard")]
183        funding_accounts
184            .extend(self.detect_accounts_ironwood(tx.ironwood_spent_note_nullifiers())?);
185
186        Ok(funding_accounts)
187    }
188
189    /// Returns the most likely wallet address that corresponds to the protocol-level receiver of a
190    /// note or UTXO.
191    ///
192    /// If the wallet database has stored a wallet address that contains the given receiver, then
193    /// that address is returned; otherwise, the most likely address containing that receiver
194    /// will be returned. The "most likely" address should be produced by generating the "standard"
195    /// address (a transparent address if the receiver is transparent, or the default Unified
196    /// address for the account) derived at the receiver's diviersifier index if the receiver is
197    /// for a shielded pool.
198    ///
199    /// Returns `Ok(None)` if the receiver cannot be determined to belong to an address produced by
200    /// this account.
201    fn select_receiving_address(
202        &self,
203        account: Self::AccountId,
204        receiver: &Receiver,
205    ) -> Result<Option<ZcashAddress>, Self::Error>;
206
207    /// Detects and returns the identifier for the account to which the address belongs, if any.
208    ///
209    /// In addition, for HD-derived addresses, the change-level key scope used to derive the
210    /// address is returned, so that the caller is able to determine whether any special handling
211    /// rules apply to the address for the purposes of preserving user privacy (by limiting address
212    /// linking, etc.).
213    #[cfg(feature = "transparent-inputs")]
214    #[allow(clippy::type_complexity)]
215    fn find_account_for_transparent_address(
216        &self,
217        address: &TransparentAddress,
218    ) -> Result<Option<(Self::AccountId, Option<TransparentKeyScope>)>, Self::Error>;
219
220    /// Finds the set of accounts that either provide inputs to or receive outputs from any of the
221    /// provided transactions.
222    #[cfg(feature = "transparent-inputs")]
223    #[allow(clippy::type_complexity)]
224    fn find_involved_accounts(
225        &self,
226        tx_refs: impl IntoIterator<Item = Self::TxRef>,
227    ) -> Result<HashSet<(Self::AccountId, Option<TransparentKeyScope>)>, Self::Error>;
228
229    /// Detects the set of accounts that received transparent outputs corresponding to the provided
230    /// [`OutPoint`]s. This is used to determine which account(s) funded a given transaction.
231    ///
232    /// [`OutPoint`]: transparent::bundle::OutPoint
233    #[cfg(feature = "transparent-inputs")]
234    fn detect_accounts_transparent<'a>(
235        &self,
236        spends: impl Iterator<Item = &'a transparent::bundle::OutPoint>,
237    ) -> Result<HashSet<Self::AccountId>, Self::Error>;
238
239    /// Detects the set of accounts that received Sapling outputs that, when spent, reveal(ed) the
240    /// given [`Nullifier`]s. This is used to determine which account(s) funded a given
241    /// transaction.
242    ///
243    /// [`Nullifier`]: sapling::Nullifier
244    fn detect_accounts_sapling<'a>(
245        &self,
246        spends: impl Iterator<Item = &'a sapling::Nullifier>,
247    ) -> Result<HashSet<Self::AccountId>, Self::Error>;
248
249    /// Detects the set of accounts that received Orchard outputs that, when spent, reveal(ed) the
250    /// given [`Nullifier`]s. This is used to determine which account(s) funded a given
251    /// transaction.
252    ///
253    /// [`Nullifier`]: orchard::note::Nullifier
254    #[cfg(feature = "orchard")]
255    fn detect_accounts_orchard<'a>(
256        &self,
257        spends: impl Iterator<Item = &'a orchard::note::Nullifier>,
258    ) -> Result<HashSet<Self::AccountId>, Self::Error>;
259
260    /// Detects the set of accounts that received Ironwood outputs that, when spent, reveal(ed) the
261    /// given [`Nullifier`]s. This is used to determine which account(s) funded a given
262    /// transaction.
263    ///
264    /// Ironwood notes share the Orchard nullifier type but are tracked separately, so this is
265    /// distinct from [`LowLevelWalletRead::detect_accounts_orchard`].
266    ///
267    /// [`Nullifier`]: orchard::note::Nullifier
268    #[cfg(feature = "orchard")]
269    fn detect_accounts_ironwood<'a>(
270        &self,
271        spends: impl Iterator<Item = &'a orchard::note::Nullifier>,
272    ) -> Result<HashSet<Self::AccountId>, Self::Error>;
273
274    /// Get information about a transparent output controlled by the wallet.
275    ///
276    /// # Parameters
277    /// - `outpoint`: The identifier for the output to be retrieved.
278    /// - `target_height`: The target height of a transaction under construction that will spend the
279    ///   returned output. If this is `None`, no spendability checks are performed.
280    #[cfg(feature = "transparent-inputs")]
281    fn get_wallet_transparent_output(
282        &self,
283        outpoint: &OutPoint,
284        target_height: Option<TargetHeight>,
285    ) -> Result<Option<WalletTransparentOutput<Self::AccountId>>, Self::Error>;
286
287    /// Returns the transactions that spend a transparent output of the referenced transaction,
288    /// for which the fee is unknown and the raw transaction data is available.
289    ///
290    /// Conflicted transactions, and transactions that expired without being mined, are included.
291    /// [`wallet::store_decrypted_tx`] uses this to set the fees of these transactions once the
292    /// values of all their inputs are known.
293    fn get_unknown_fee_spenders_of(
294        &self,
295        tx_ref: Self::TxRef,
296    ) -> Result<Vec<(Self::TxRef, Transaction)>, Self::Error>;
297
298    /// Finds the reference to the transaction that reveals the given Sapling nullifier in the
299    /// backing data store, if known.
300    fn detect_sapling_spend(
301        &self,
302        nf: &::sapling::Nullifier,
303    ) -> Result<Option<Self::TxRef>, Self::Error>;
304
305    /// Finds the reference to the transaction that reveals the given Orchard nullifier in the
306    /// backing data store, if known.
307    #[cfg(feature = "orchard")]
308    fn detect_orchard_spend(
309        &self,
310        nf: &::orchard::note::Nullifier,
311    ) -> Result<Option<Self::TxRef>, Self::Error>;
312
313    /// Finds the reference to the transaction that reveals the given Ironwood nullifier in the
314    /// backing data store, if known. Ironwood nullifiers are Orchard-shaped but are tracked as a
315    /// separate pool.
316    #[cfg(feature = "orchard")]
317    fn detect_ironwood_spend(
318        &self,
319        nf: &::orchard::note::Nullifier,
320    ) -> Result<Option<Self::TxRef>, Self::Error>;
321
322    /// Returns the wallet-internal account reference for the given external account identifier.
323    ///
324    /// This is used to translate between the stable external [`AccountId`](Self::AccountId)
325    /// and the ephemeral internal [`AccountRef`](Self::AccountRef) used for efficient lookups.
326    #[cfg(feature = "transparent-inputs")]
327    fn get_account_ref(
328        &self,
329        account_uuid: Self::AccountId,
330    ) -> Result<Self::AccountRef, Self::Error>;
331
332    /// Returns the full account record for the given wallet-internal account reference.
333    #[cfg(feature = "transparent-inputs")]
334    fn get_account_internal(
335        &self,
336        account_id: Self::AccountRef,
337    ) -> Result<Option<Self::Account>, Self::Error>;
338}
339
340/// An error returned by [`LowLevelWalletWrite::put_block_meta`].
341#[derive(Debug)]
342#[non_exhaustive]
343pub enum PutBlockMetaError<E> {
344    /// The wallet data store already holds a block at the given height with a different hash.
345    /// The chain has reorganized below the wallet's scanned range.
346    HashMismatch {
347        /// The hash that the wallet data store holds at the given height.
348        stored: BlockHash,
349    },
350    /// The wallet data store failed.
351    Storage(E),
352}
353
354/// A capability trait that provides low-level wallet write operations. These operations are used
355/// to provide standard implementations for certain [`WalletWrite`] trait methods.
356///
357/// [`WalletWrite`]: super::WalletWrite
358pub trait LowLevelWalletWrite: LowLevelWalletRead {
359    /// Add metadata about a block to the wallet data store.
360    ///
361    /// # Errors
362    ///
363    /// Returns [`PutBlockMetaError::HashMismatch`], and stores nothing, if the wallet data store
364    /// already holds a block at `block_height` whose hash is not `block_hash`.
365    #[allow(clippy::too_many_arguments)]
366    fn put_block_meta(
367        &mut self,
368        block_height: BlockHeight,
369        block_hash: BlockHash,
370        block_time: u32,
371        sapling_commitment_tree_size: u32,
372        sapling_output_count: u32,
373        #[cfg(feature = "orchard")] orchard_commitment_tree_size: u32,
374        #[cfg(feature = "orchard")] orchard_action_count: u32,
375        #[cfg(feature = "orchard")] ironwood_commitment_tree_size: u32,
376        #[cfg(feature = "orchard")] ironwood_action_count: u32,
377    ) -> Result<(), PutBlockMetaError<Self::Error>>;
378
379    /// Add metadata about a transaction to the wallet data store.
380    fn put_tx_meta(
381        &mut self,
382        tx: &WalletTx<Self::AccountId>,
383        height: BlockHeight,
384    ) -> Result<Self::TxRef, Self::Error>;
385
386    /// Adds the given transaction to the wallet.
387    ///
388    /// # Parameters
389    /// - `tx`: The transaction to store.
390    /// - `fee`: The fee paid by the transaction, if known. This may be `None` if the wallet
391    ///   does not have sufficient information to compute the fee (see [`TxMeta::fee_paid`]).
392    /// - `created_at`: The time the transaction was created, if known.
393    /// - `target_height`: The target height for the transaction, if it was created by this
394    ///   wallet.
395    /// - `observed_height`: The height at which the transaction was first observed. For mined
396    ///   transactions, this is the mined height; for unmined transactions, this is typically
397    ///   the chain tip height at the time of observation.
398    fn put_tx_data(
399        &mut self,
400        tx: &Transaction,
401        fee: Option<Zatoshis>,
402        created_at: Option<time::OffsetDateTime>,
403        target_height: Option<TargetHeight>,
404        observed_height: BlockHeight,
405    ) -> Result<Self::TxRef, Self::Error>;
406
407    /// Updates transaction metadata to reflect that the given transaction status has been
408    /// observed.
409    ///
410    /// For [`TransactionStatus::Mined`], the mined height must be the height of a block on the main chain. If it is above the
411    /// wallet's chain tip, the wallet's chain tip becomes that height, and the wallet treats the
412    /// blocks above the previous chain tip as not yet scanned.
413    fn set_transaction_status(
414        &mut self,
415        txid: TxId,
416        status: TransactionStatus,
417    ) -> Result<(), Self::Error>;
418
419    /// Records how a transaction classifies against [ZIP 318], so that a wallet can label a
420    /// migration transaction in its history without consulting a migration plan.
421    ///
422    /// A store persists this rather than recomputing it, because the evidence it rests on is only
423    /// all present at once while the transaction is being decrypted. A store that has not been
424    /// given a classification for a transaction MUST report it as
425    /// [`Zip318Classification::Unknown`] rather than as
426    /// [`Nonconforming`](Zip318Classification::Nonconforming): the two mean "we never looked" and
427    /// "we looked and it is not one", and presenting the first as the second asserts a judgement
428    /// the wallet has not made.
429    ///
430    /// This is called at most once per transaction. Every input to the classification is fixed by
431    /// the time a transaction is decrypted, so the value never needs revisiting; in particular it
432    /// does not depend on the mined height, which would otherwise make it change under the store.
433    ///
434    /// [ZIP 318]: https://zips.z.cash/zip-0318
435    fn put_zip318_classification(
436        &mut self,
437        tx_ref: Self::TxRef,
438        classification: Zip318Classification,
439    ) -> Result<(), Self::Error>;
440
441    /// Adds information about a received Sapling note to the wallet, or updates any existing
442    /// record for that output.
443    fn put_received_sapling_note<T: ReceivedSaplingOutput<AccountId = Self::AccountId>>(
444        &mut self,
445        output: &T,
446        tx_ref: Self::TxRef,
447        target_or_mined_height: Option<BlockHeight>,
448        spent_in: Option<Self::TxRef>,
449    ) -> Result<(), Self::Error>;
450
451    /// Updates the backing store to indicate that the Sapling output having the given nullifier is
452    /// spent in the transaction referenced by `spent_in_tx`. This may result in multiple distinct
453    /// transactions being recorded as having spent the note; only one of these transactions will
454    /// end up having been mined (by consensus). If an attempt is made to associate a nullifier
455    /// with a mined transaction, and another mined transaction reveals the same nullifier,
456    /// implementations of this method must return an error.
457    ///
458    /// Returns `Ok(true)` if a a new record was added to the data store.
459    fn mark_sapling_note_spent(
460        &mut self,
461        nf: &::sapling::Nullifier,
462        spent_in_tx: Self::TxRef,
463    ) -> Result<bool, Self::Error>;
464
465    /// Causes the given Sapling output nullifiers to be tracked by the wallet.
466    ///
467    /// When scanning the chain out-of-order, it is necessary to store any nullifiers observed
468    /// after a gap in the scanned blocks until the blocks in that gap have been fully scanned, in
469    /// order to be able to immediately detect that a received output has already been spent. The
470    /// data store should track a mapping from each nullifier to the block, the index of the
471    /// transaction in the block, and the transaction ID, so when a note is received within that
472    /// "gap" its spentness can be determined by checking in the store. For space efficiency, the
473    /// backing store may use the combination of block height and index within the block instead of
474    /// the txid for transaction identification.
475    ///
476    /// # Parameters
477    /// - `block_height`: The height of the block containing the nullifiers.
478    /// - `nfs`: A slice of tuples, where each tuple contains:
479    ///   - The transaction ID of the transaction revealing the nullifiers.
480    ///   - The index of the transaction within the block.
481    ///   - The vector of nullifiers revealed by the spends in that transaction.
482    fn track_block_sapling_nullifiers(
483        &mut self,
484        block_height: BlockHeight,
485        nfs: &[(TxIndex, TxId, Vec<::sapling::Nullifier>)],
486    ) -> Result<(), Self::Error>;
487
488    /// Adds information about a received Orchard note to the wallet, or updates any existing
489    /// record for that output.
490    #[cfg(feature = "orchard")]
491    fn put_received_orchard_note<T: ReceivedOrchardOutput<AccountId = Self::AccountId>>(
492        &mut self,
493        output: &T,
494        tx_ref: Self::TxRef,
495        target_or_mined_height: Option<BlockHeight>,
496        spent_in: Option<Self::TxRef>,
497    ) -> Result<(), Self::Error>;
498
499    /// Adds information about a received Ironwood note to the wallet, or updates any existing
500    /// record for that output. Ironwood notes are Orchard-shaped but are stored as a separate
501    /// pool.
502    #[cfg(feature = "orchard")]
503    fn put_received_ironwood_note<T: ReceivedOrchardOutput<AccountId = Self::AccountId>>(
504        &mut self,
505        output: &T,
506        tx_ref: Self::TxRef,
507        target_or_mined_height: Option<BlockHeight>,
508        spent_in: Option<Self::TxRef>,
509    ) -> Result<(), Self::Error>;
510
511    /// Updates the backing store to indicate that the Orchard output having the given nullifier is
512    /// spent in the transaction referenced by `spent_in_tx`. This may result in multiple distinct
513    /// transactions being recorded as having spent the note; only one of these transactions will
514    /// end up having been mined (by consensus). If an attempt is made to associate a nullifier
515    /// with a mined transaction, and another mined transaction reveals the same nullifier,
516    /// implementations of this method must return an error.
517    ///
518    /// Returns `Ok(true)` if a a new record was added to the data store.
519    #[cfg(feature = "orchard")]
520    fn mark_orchard_note_spent(
521        &mut self,
522        nf: &::orchard::note::Nullifier,
523        tx_ref: Self::TxRef,
524    ) -> Result<bool, Self::Error>;
525
526    /// Updates the backing store to indicate that the Ironwood output having the given nullifier is
527    /// spent in the transaction referenced by `spent_in_tx`. Behaves like
528    /// [`mark_orchard_note_spent`](Self::mark_orchard_note_spent) but for the Ironwood pool.
529    #[cfg(feature = "orchard")]
530    fn mark_ironwood_note_spent(
531        &mut self,
532        nf: &::orchard::note::Nullifier,
533        tx_ref: Self::TxRef,
534    ) -> Result<bool, Self::Error>;
535
536    /// Causes the given Orchard output nullifiers to be tracked by the wallet.
537    ///
538    /// When scanning the chain out-of-order, it is necessary to store any nullifiers observed
539    /// after a gap in the scanned blocks until the blocks in that gap have been fully scanned, in
540    /// order to be able to immediately detect that a received output has already been spent. The
541    /// data store should track a mapping from each nullifier to the block, the index of the
542    /// transaction in the block, and the transaction ID, so when a note is received within that
543    /// "gap" its spentness can be determined by checking in the store. For space efficiency, the
544    /// backing store may use the combination of block height and index within the block instead of
545    /// the txid for transaction identification.
546    ///
547    /// # Parameters
548    /// - `block_height`: The height of the block containing the nullifiers.
549    /// - `nfs`: A slice of tuples, where each tuple contains:
550    ///   - The transaction ID of the transaction revealing the nullifiers.
551    ///   - The index of the transaction within the block.
552    ///   - The vector of nullifiers revealed by the actions in that transaction.
553    #[cfg(feature = "orchard")]
554    fn track_block_orchard_nullifiers(
555        &mut self,
556        block_height: BlockHeight,
557        nfs: &[(TxIndex, TxId, Vec<::orchard::note::Nullifier>)],
558    ) -> Result<(), Self::Error>;
559
560    /// Causes the given Ironwood output nullifiers to be tracked by the wallet. Behaves like
561    /// [`track_block_orchard_nullifiers`](Self::track_block_orchard_nullifiers) but for the
562    /// Ironwood pool.
563    #[cfg(feature = "orchard")]
564    fn track_block_ironwood_nullifiers(
565        &mut self,
566        block_height: BlockHeight,
567        nfs: &[(TxIndex, TxId, Vec<::orchard::note::Nullifier>)],
568    ) -> Result<(), Self::Error>;
569
570    /// Causes the given transparent spends to be tracked by the wallet.
571    ///
572    /// This is the transparent counterpart of the `track_block_*_nullifiers` methods
573    /// ([`track_block_sapling_nullifiers`](Self::track_block_sapling_nullifiers) and its Orchard
574    /// and Ironwood equivalents), and exists for the same reason: a transparent output created
575    /// in a block range the wallet has not yet scanned cannot be recognized as its own at the
576    /// time its spend is observed, so the spending transaction must be recorded against the
577    /// outpoint and resolved if the output is later discovered.
578    ///
579    /// The spending transactions here are in general not transactions the wallet stores, so an
580    /// implementation must be able to record them without a corresponding transaction record; for
581    /// space efficiency it may use the combination of block height and index within the block
582    /// instead of the txid, as for the nullifier maps. Entries are removed by
583    /// [`prune_tracked_spends`](Self::prune_tracked_spends).
584    ///
585    /// # Parameters
586    /// - `block_height`: The height of the block containing the spending transactions.
587    /// - `spends`: A slice of tuples, where each tuple contains:
588    ///   - The index of the transaction within the block.
589    ///   - The transaction ID of the transaction effecting the spends.
590    ///   - The outpoints spent by that transaction's transparent inputs that do not spend any
591    ///     output the wallet already knows of.
592    #[cfg(feature = "transparent-inputs")]
593    fn track_block_transparent_spends(
594        &mut self,
595        block_height: BlockHeight,
596        spends: &[(TxIndex, TxId, Vec<OutPoint>)],
597    ) -> Result<(), Self::Error>;
598
599    /// Removes tracked spends that are no longer needed for spend detection.
600    ///
601    /// This function prunes the entries recorded by
602    /// [`track_block_sapling_nullifiers`](Self::track_block_sapling_nullifiers) and its
603    /// per-pool counterparts, and by
604    /// [`track_block_transparent_spends`](Self::track_block_transparent_spends), that were
605    /// recorded at block heights less than `(fully_scanned_height - pruning_depth)`, where
606    /// `fully_scanned_height` is the height of the wallet's fully scanned chain state. These
607    /// entries are no longer needed because any wallet output they could have spent would
608    /// already have been discovered during scanning.
609    ///
610    /// # Parameters
611    /// - `pruning_depth`: The number of blocks below the fully scanned height at which to
612    ///   prune tracked spends.
613    fn prune_tracked_spends(&mut self, pruning_depth: u32) -> Result<(), Self::Error>;
614
615    /// Records information about a transaction output that your wallet created, from the constituent
616    /// properties of that output.
617    ///
618    /// # Parameters
619    /// - `tx_ref`: The identifier for the transaction that produced the output.
620    /// - `output_index`: The index of the output in the bundle corresponding to the pool where the
621    ///   output was created.
622    /// - `recipient`: Information about the address or account that the output is being sent to.
623    /// - `value`: The value of the output.
624    /// - `memo`: The memo attached to the output, if any.
625    fn put_sent_output(
626        &mut self,
627        from_account_uuid: Self::AccountId,
628        tx_ref: Self::TxRef,
629        output_index: usize,
630        recipient: &Recipient<Self::AccountId>,
631        value: Zatoshis,
632        memo: Option<&MemoBytes>,
633    ) -> Result<(), Self::Error>;
634
635    /// Updates the wallet's view of a transaction to indicate the miner's fee paid by the
636    /// transaction.
637    fn update_tx_fee(&mut self, tx_ref: Self::TxRef, fee: Zatoshis) -> Result<(), Self::Error>;
638
639    /// Adds a transparent output observed by the wallet to the data store, or updates any existing
640    /// record for that output.
641    ///
642    /// # Parameters
643    /// - `output`: The output data.
644    /// - `observation_height`: This should be set to the mined height, if known. If the TXO is
645    ///   known to be mined but the height at which it was mined is unknown, this should be set to
646    ///   the chain tip height at the time of the observation; if the utxo is known to be unmined,
647    ///   this should be set to the mempool height.
648    /// - `known_unspent`: Set to `true` if the output is known to be a member of the UTXO set as
649    ///   of the given observation height.
650    #[cfg(feature = "transparent-inputs")]
651    fn put_transparent_output(
652        &mut self,
653        output: &crate::wallet::WalletTransparentOutput<Self::AccountId>,
654        observation_height: BlockHeight,
655        known_unspent: bool,
656    ) -> Result<(Self::AccountId, Option<TransparentKeyScope>), Self::Error>;
657
658    /// Records the transparent addresses that the given transaction's transparent data names,
659    /// including addresses the wallet does not control.
660    ///
661    /// The wallet's recognition of a transaction is the join of its stored transaction data with
662    /// its address book. Checking a transaction against the book at the moment the transaction
663    /// is stored maintains only one side of that join; this method maintains the other, by
664    /// keeping the involvement durable so that an address added later can be checked against it.
665    ///
666    /// `tx_ref` must name a transaction that the wallet has determined to involve it: the
667    /// observations of a transaction with no wallet involvement are unbounded in number and
668    /// carry no information the wallet can act on.
669    ///
670    /// Each observation is keyed by `tx_ref` together with the direction and index reported by
671    /// [`TransparentAddressObservation`], and an implementation MUST record it as an idempotent
672    /// upsert on that key. A transaction may be observed repeatedly and at differing fidelity —
673    /// compact block data yields output observations only, full transaction data yields both
674    /// directions — so any order of calls must converge to the same recorded state.
675    ///
676    /// [`TransparentAddressObservation`]: crate::wallet::TransparentAddressObservation
677    #[cfg(feature = "transparent-inputs")]
678    fn put_transparent_address_observations(
679        &mut self,
680        tx_ref: Self::TxRef,
681        observations: &[crate::wallet::TransparentAddressObservation],
682    ) -> Result<(), Self::Error>;
683
684    /// Updates the backing store to indicate that the UTXO referred to by `outpoint` is spent
685    /// in the transaction referenced by `spent_in_tx`.
686    #[cfg(feature = "transparent-inputs")]
687    fn mark_transparent_utxo_spent(
688        &mut self,
689        outpoint: &OutPoint,
690        spent_in_tx: Self::TxRef,
691    ) -> Result<bool, Self::Error>;
692
693    /// Updates the wallet backend by generating and caching addresses for the given key scope such
694    /// that at least the backend's configured gap limit worth of addresses exist at indices
695    /// successive from that of the last address that received a mined transaction.
696    ///
697    /// # Parameters
698    /// - `account_id`: The ID of the account holding the UFVK from which addresses should be
699    ///   generated.
700    /// - `key_scope`: The transparent key scope for addresses to generate. Implementations may
701    ///   choose to only support the `external`, `internal`, and `ephemeral` key scopes and return
702    ///   an error if an unrecognized scope is used.
703    /// - `request`: A request for the Unified Address that will be generated with a diversifier
704    ///   index equal to the [`BIP 44`] `address_index` of each generated address.
705    ///
706    /// [`BIP 44`]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
707    #[cfg(feature = "transparent-inputs")]
708    fn generate_transparent_gap_addresses(
709        &mut self,
710        account_id: Self::AccountId,
711        key_scope: TransparentKeyScope,
712        request: UnifiedAddressRequest,
713    ) -> Result<(), Self::Error>;
714
715    /// Adds a [`TransactionDataRequest::Enhancement`] request for the enhancement of the given
716    /// transaction to the transaction data request queue. The `dependent_tx_ref` parameter
717    /// specifies the transaction that caused this request to be generated, likely as part of the
718    /// process of traversing the transparent transaction graph by inspecting the inputs of a
719    /// transaction with outputs that were received by the wallet.
720    ///
721    /// [`TransactionDataRequest::Enhancement`]: super::TransactionDataRequest
722    fn queue_tx_retrieval(
723        &mut self,
724        txids: impl Iterator<Item = TxId>,
725        dependent_tx_ref: Option<Self::TxRef>,
726    ) -> Result<(), Self::Error>;
727
728    /// Adds a [`TransactionDataRequest::GetStatus`] request for a transaction whose mined status
729    /// cannot be learned through ordinary compact-block scanning.
730    ///
731    /// The request intent must remain durable while the transaction is mined, so that it becomes
732    /// active again if a chain rewind un-mines the transaction.
733    ///
734    /// [`TransactionDataRequest::GetStatus`]: super::TransactionDataRequest
735    fn queue_tx_status(&mut self, txid: TxId) -> Result<(), Self::Error>;
736
737    /// Adds a [`TransactionDataRequest::TransactionsInvolvingAddress`] request to the transaction
738    /// data request queue. When the transparent output of `tx_ref` at output index `output_index`
739    /// (which must have been received at `receiving_address`) is detected as having been spent,
740    /// this request will be considered fulfilled.
741    ///
742    /// NOTE: The somewhat awkward API of this method is a historical artifact; if the light wallet
743    /// protocol is in the future updated to expose a mechanism to find the transaction that spends
744    /// a particular `OutPoint`, the `TransactionsInvolvingAddress` variant and this method will
745    /// likely be removed.
746    ///
747    /// [`TransactionDataRequest::TransactionsInvolvingAddress`]: super::TransactionDataRequest
748    #[cfg(feature = "transparent-inputs")]
749    fn queue_transparent_spend_detection(
750        &mut self,
751        receiving_address: TransparentAddress,
752        tx_ref: Self::TxRef,
753        output_index: u32,
754    ) -> Result<(), Self::Error>;
755
756    /// Adds [`TransactionDataRequest::Enhancement`] requests for transactions that generated the
757    /// transparent inputs to the provided [`DecryptedTransaction`] to the transaction data request
758    /// queue.
759    ///
760    /// [`TransactionDataRequest::Enhancement`]: super::TransactionDataRequest
761    /// [`DecryptedTransaction`]: super::DecryptedTransaction
762    #[cfg(feature = "transparent-inputs")]
763    fn queue_transparent_input_retrieval(
764        &mut self,
765        tx_ref: Self::TxRef,
766        d_tx: &super::DecryptedTransaction<Transaction, Self::AccountId>,
767    ) -> Result<(), Self::Error>;
768
769    /// Deletes the [`TransactionDataRequest::Enhancement`] request for the given transaction ID
770    /// from the transaction data request queue, without removing any durable status-observation
771    /// intent for the transaction.
772    ///
773    /// [`TransactionDataRequest::Enhancement`]: super::TransactionDataRequest
774    fn delete_retrieval_queue_entries(&mut self, txid: TxId) -> Result<(), Self::Error>;
775
776    /// Updates the state of the wallet backend to indicate that the given range of blocks has been
777    /// fully scanned, identifying the position in the note commitment tree of any notes belonging
778    /// to the wallet that were discovered in the process of scanning.
779    fn notify_scan_complete(
780        &mut self,
781        range: Range<BlockHeight>,
782        wallet_note_positions: &[(ShieldedPool, Position)],
783    ) -> Result<(), Self::Error>;
784
785    #[cfg(feature = "transparent-inputs")]
786    fn update_gap_limits(
787        &mut self,
788        gap_limits: &GapLimits,
789        txid: TxId,
790        observation_height: BlockHeight,
791    ) -> Result<(), Self::Error>;
792}
793
794/// This trait provides a generalization over output representations.
795pub trait ReceivedShieldedOutput {
796    type AccountId;
797    type Note;
798    type Nullifier;
799
800    /// Returns the index of the output within its corresponding bundle.
801    fn index(&self) -> usize;
802    /// Returns the account ID for the account that received this output.
803    fn account_id(&self) -> Self::AccountId;
804    /// Returns the note.
805    fn note(&self) -> &Self::Note;
806    /// Returns the received note, as a [`Note`].
807    ///
808    /// [`Note`]: crate::wallet::Note
809    fn to_wallet_note(&self) -> crate::wallet::Note;
810    /// Returns any memo associated with the output.
811    fn memo(&self) -> Option<&MemoBytes>;
812    /// Returns a [`TransferType`] value that is determined based upon what type of key was used to
813    /// decrypt the transaction.
814    fn transfer_type(&self) -> TransferType;
815    /// Returns whether or not the received output is counted as wallet-internal change, for the
816    /// purpose of display.
817    fn is_change(&self) -> bool;
818    /// Returns the nullifier that will be revealed when the note is spent, if the output was
819    /// observed using a key that provides the capability for nullifier computation.
820    fn nullifier(&self) -> Option<&Self::Nullifier>;
821    /// Returns the position of the note in the note commitment tree, if the transaction that
822    /// produced the output has been mined.
823    fn note_commitment_tree_position(&self) -> Option<Position>;
824    /// Returns the HD derivation scope of the viewing key that decrypted the note, if known.
825    fn recipient_key_scope(&self) -> Option<Scope>;
826}
827
828/// This trait provides a generalization over shielded Sapling output representations.
829pub trait ReceivedSaplingOutput:
830    ReceivedShieldedOutput<Note = ::sapling::Note, Nullifier = ::sapling::Nullifier>
831{
832}
833impl<T: ReceivedShieldedOutput<Note = ::sapling::Note, Nullifier = ::sapling::Nullifier>>
834    ReceivedSaplingOutput for T
835{
836}
837
838impl<AccountId: Copy> ReceivedShieldedOutput for WalletSaplingOutput<AccountId> {
839    type AccountId = AccountId;
840    type Note = ::sapling::Note;
841    type Nullifier = ::sapling::Nullifier;
842
843    fn index(&self) -> usize {
844        self.index()
845    }
846    fn account_id(&self) -> Self::AccountId {
847        *WalletSaplingOutput::account_id(self)
848    }
849    fn note(&self) -> &Self::Note {
850        WalletSaplingOutput::note(self)
851    }
852    fn to_wallet_note(&self) -> crate::wallet::Note {
853        crate::wallet::Note::Sapling(self.note().clone())
854    }
855    fn memo(&self) -> Option<&MemoBytes> {
856        None
857    }
858    fn transfer_type(&self) -> TransferType {
859        if self.is_change() {
860            TransferType::AccountInternal
861        } else {
862            TransferType::Incoming
863        }
864    }
865    fn is_change(&self) -> bool {
866        WalletSaplingOutput::is_change(self)
867    }
868    fn nullifier(&self) -> Option<&::sapling::Nullifier> {
869        self.nf()
870    }
871    fn note_commitment_tree_position(&self) -> Option<Position> {
872        Some(WalletSaplingOutput::note_commitment_tree_position(self))
873    }
874    fn recipient_key_scope(&self) -> Option<Scope> {
875        self.recipient_key_scope()
876    }
877}
878
879impl<AccountId: Copy> ReceivedShieldedOutput for DecryptedOutput<::sapling::Note, AccountId> {
880    type AccountId = AccountId;
881    type Note = ::sapling::Note;
882    type Nullifier = ::sapling::Nullifier;
883
884    fn index(&self) -> usize {
885        self.index()
886    }
887    fn account_id(&self) -> Self::AccountId {
888        *self.account()
889    }
890    fn note(&self) -> &Self::Note {
891        DecryptedOutput::note(self)
892    }
893    fn to_wallet_note(&self) -> crate::wallet::Note {
894        crate::wallet::Note::Sapling(self.note().clone())
895    }
896    fn memo(&self) -> Option<&MemoBytes> {
897        Some(self.memo())
898    }
899    fn transfer_type(&self) -> TransferType {
900        self.transfer_type()
901    }
902    fn is_change(&self) -> bool {
903        self.transfer_type() == TransferType::AccountInternal
904    }
905    fn nullifier(&self) -> Option<&::sapling::Nullifier> {
906        None
907    }
908    fn note_commitment_tree_position(&self) -> Option<Position> {
909        None
910    }
911    fn recipient_key_scope(&self) -> Option<Scope> {
912        if self.transfer_type() == TransferType::AccountInternal {
913            Some(Scope::Internal)
914        } else {
915            Some(Scope::External)
916        }
917    }
918}
919
920/// This trait provides a generalization over shielded Orchard output representations.
921#[cfg(feature = "orchard")]
922pub trait ReceivedOrchardOutput:
923    ReceivedShieldedOutput<Note = ::orchard::Note, Nullifier = ::orchard::note::Nullifier>
924{
925}
926#[cfg(feature = "orchard")]
927impl<T: ReceivedShieldedOutput<Note = ::orchard::Note, Nullifier = ::orchard::note::Nullifier>>
928    ReceivedOrchardOutput for T
929{
930}
931
932#[cfg(feature = "orchard")]
933impl<AccountId: Copy> ReceivedShieldedOutput for WalletOrchardOutput<AccountId> {
934    type AccountId = AccountId;
935    type Note = ::orchard::Note;
936    type Nullifier = ::orchard::note::Nullifier;
937
938    fn index(&self) -> usize {
939        self.index()
940    }
941    fn account_id(&self) -> Self::AccountId {
942        *WalletOrchardOutput::account_id(self)
943    }
944    fn note(&self) -> &Self::Note {
945        &self.note().0
946    }
947    fn to_wallet_note(&self) -> crate::wallet::Note {
948        let (note, pool) = self.note();
949        crate::wallet::Note::Orchard {
950            note: *note,
951            pool: *pool,
952        }
953    }
954    fn memo(&self) -> Option<&MemoBytes> {
955        None
956    }
957    fn transfer_type(&self) -> TransferType {
958        if self.is_change() {
959            TransferType::AccountInternal
960        } else {
961            TransferType::Incoming
962        }
963    }
964    fn is_change(&self) -> bool {
965        WalletOrchardOutput::is_change(self)
966    }
967    fn nullifier(&self) -> Option<&::orchard::note::Nullifier> {
968        self.nf()
969    }
970    fn note_commitment_tree_position(&self) -> Option<Position> {
971        Some(WalletOrchardOutput::note_commitment_tree_position(self))
972    }
973    fn recipient_key_scope(&self) -> Option<Scope> {
974        self.recipient_key_scope()
975    }
976}
977
978#[cfg(feature = "orchard")]
979impl<AccountId: Copy> ReceivedShieldedOutput
980    for DecryptedOutput<(::orchard::Note, ::orchard::ValuePool), AccountId>
981{
982    type AccountId = AccountId;
983    type Note = ::orchard::Note;
984    type Nullifier = ::orchard::note::Nullifier;
985
986    fn index(&self) -> usize {
987        self.index()
988    }
989    fn account_id(&self) -> Self::AccountId {
990        *self.account()
991    }
992    fn note(&self) -> &Self::Note {
993        &self.note().0
994    }
995    fn to_wallet_note(&self) -> crate::wallet::Note {
996        let (note, pool) = self.note();
997        crate::wallet::Note::Orchard {
998            note: *note,
999            pool: *pool,
1000        }
1001    }
1002    fn memo(&self) -> Option<&MemoBytes> {
1003        Some(self.memo())
1004    }
1005    fn transfer_type(&self) -> TransferType {
1006        self.transfer_type()
1007    }
1008    fn is_change(&self) -> bool {
1009        self.transfer_type() == TransferType::AccountInternal
1010    }
1011    fn nullifier(&self) -> Option<&::orchard::note::Nullifier> {
1012        None
1013    }
1014    fn note_commitment_tree_position(&self) -> Option<Position> {
1015        None
1016    }
1017    fn recipient_key_scope(&self) -> Option<Scope> {
1018        if self.transfer_type() == TransferType::AccountInternal {
1019            Some(Scope::Internal)
1020        } else {
1021            Some(Scope::External)
1022        }
1023    }
1024}