Skip to main content

zcash_client_backend/
scanning.rs

1//! Tools for scanning a compact representation of the Zcash block chain.
2
3// The `ScanError` accessors below match on its variants bare.
4use ScanError::*;
5
6use core::{
7    convert::TryFrom,
8    fmt::{self, Debug},
9};
10use std::{
11    collections::{HashMap, HashSet},
12    hash::Hash,
13};
14
15use incrementalmerkletree::{Address, Marking, Position, Retention};
16use sapling::{SaplingIvk, note_encryption::SaplingDomain};
17use subtle::{ConditionallySelectable, ConstantTimeEq, CtOption};
18
19use zcash_keys::keys::UnifiedFullViewingKey;
20use zcash_note_encryption::{BatchDomain, Domain, ShieldedOutput};
21use zcash_primitives::{block::BlockHash, transaction::TxId};
22use zcash_protocol::{
23    ShieldedPool,
24    consensus::{self, BlockHeight},
25};
26use zip32::Scope;
27
28use crate::{
29    data_api::{BlockMetadata, NullifierQuery, ScannedBlock, WalletRead},
30    proto::compact_formats::CompactBlock,
31    scan::DecryptedOutput,
32    wallet::WalletOutput,
33};
34
35#[cfg(feature = "transparent-inputs")]
36use crate::wallet::WalletTransparentSpend;
37
38#[cfg(feature = "orchard")]
39use orchard::note_encryption::OrchardDomain;
40
41#[cfg(feature = "transparent-inputs")]
42use {
43    transparent::{address::TransparentAddress, bundle::OutPoint},
44    zcash_keys::keys::transparent::TransparentKeyScope,
45};
46
47pub(crate) mod compact;
48pub mod full;
49
50/// A key that can be used to perform trial decryption and nullifier
51/// computation for a [`CompactSaplingOutput`] or [`CompactOrchardAction`].
52///
53/// The purpose of this trait is to enable [`scan_block`]
54/// and related methods to be used with either incoming viewing keys
55/// or full viewing keys, with the data returned from trial decryption
56/// being dependent upon the type of key used. In the case that an
57/// incoming viewing key is used, only the note and payment address
58/// will be returned; in the case of a full viewing key, the
59/// nullifier for the note can also be obtained.
60///
61/// [`CompactSaplingOutput`]: crate::proto::compact_formats::CompactSaplingOutput
62/// [`CompactOrchardAction`]: crate::proto::compact_formats::CompactOrchardAction
63/// [`scan_block`]: crate::scanning::scan_block
64pub trait ScanningKeyOps<D: Domain, AccountId, Nf> {
65    /// Prepare the key for use in batch trial decryption.
66    fn prepare(&self) -> D::IncomingViewingKey;
67
68    /// Returns the account identifier for this key. An account identifier corresponds
69    /// to at most a single unified spending key's worth of spend authority, such that
70    /// both received notes and change spendable by that spending authority will be
71    /// interpreted as belonging to that account.
72    fn account_id(&self) -> &AccountId;
73
74    /// Returns the [`zip32::Scope`] for which this key was derived, if known.
75    fn key_scope(&self) -> Option<Scope>;
76
77    /// Produces the nullifier for the specified note and witness, if possible.
78    ///
79    /// IVK-based implementations of this trait cannot successfully derive
80    /// nullifiers, in which this function will always return `None`.
81    fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf>;
82}
83
84impl<D: Domain, AccountId, Nf, K: ScanningKeyOps<D, AccountId, Nf>> ScanningKeyOps<D, AccountId, Nf>
85    for &K
86{
87    fn prepare(&self) -> D::IncomingViewingKey {
88        (*self).prepare()
89    }
90
91    fn account_id(&self) -> &AccountId {
92        (*self).account_id()
93    }
94
95    fn key_scope(&self) -> Option<Scope> {
96        (*self).key_scope()
97    }
98
99    fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf> {
100        (*self).nf(note, note_position)
101    }
102}
103
104impl<D: Domain, AccountId, Nf> ScanningKeyOps<D, AccountId, Nf>
105    for Box<dyn ScanningKeyOps<D, AccountId, Nf>>
106{
107    fn prepare(&self) -> D::IncomingViewingKey {
108        self.as_ref().prepare()
109    }
110
111    fn account_id(&self) -> &AccountId {
112        self.as_ref().account_id()
113    }
114
115    fn key_scope(&self) -> Option<Scope> {
116        self.as_ref().key_scope()
117    }
118
119    fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf> {
120        self.as_ref().nf(note, note_position)
121    }
122}
123
124impl<D: Domain, AccountId: Send + Sync, Nf> ScanningKeyOps<D, AccountId, Nf>
125    for Box<dyn ScanningKeyOps<D, AccountId, Nf> + Send + Sync>
126{
127    fn prepare(&self) -> D::IncomingViewingKey {
128        self.as_ref().prepare()
129    }
130
131    fn account_id(&self) -> &AccountId {
132        self.as_ref().account_id()
133    }
134
135    fn key_scope(&self) -> Option<Scope> {
136        self.as_ref().key_scope()
137    }
138
139    fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf> {
140        self.as_ref().nf(note, note_position)
141    }
142}
143
144/// An incoming viewing key, paired with an optional nullifier key and key source metadata.
145pub struct ScanningKey<Ivk, Nk, AccountId> {
146    ivk: Ivk,
147    nk: Option<Nk>,
148    account_id: AccountId,
149    key_scope: Option<Scope>,
150}
151
152impl<Ivk, Nk, AccountId> ScanningKey<Ivk, Nk, AccountId> {
153    /// Constructs a new `ScanningKey` from its constituent parts.
154    pub fn new(ivk: Ivk, nk: Option<Nk>, account_id: AccountId, key_scope: Option<Scope>) -> Self {
155        Self {
156            ivk,
157            nk,
158            account_id,
159            key_scope,
160        }
161    }
162}
163
164impl<AccountId> ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>
165    for ScanningKey<sapling::SaplingIvk, sapling::NullifierDerivingKey, AccountId>
166{
167    fn prepare(&self) -> sapling::note_encryption::PreparedIncomingViewingKey {
168        sapling::note_encryption::PreparedIncomingViewingKey::new(&self.ivk)
169    }
170
171    fn nf(&self, note: &sapling::Note, position: Position) -> Option<sapling::Nullifier> {
172        self.nk.as_ref().map(|key| note.nf(key, position.into()))
173    }
174
175    fn account_id(&self) -> &AccountId {
176        &self.account_id
177    }
178
179    fn key_scope(&self) -> Option<Scope> {
180        self.key_scope
181    }
182}
183
184impl<AccountId> ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>
185    for (AccountId, SaplingIvk)
186{
187    fn prepare(&self) -> sapling::note_encryption::PreparedIncomingViewingKey {
188        sapling::note_encryption::PreparedIncomingViewingKey::new(&self.1)
189    }
190
191    fn nf(&self, _note: &sapling::Note, _position: Position) -> Option<sapling::Nullifier> {
192        None
193    }
194
195    fn account_id(&self) -> &AccountId {
196        &self.0
197    }
198
199    fn key_scope(&self) -> Option<Scope> {
200        None
201    }
202}
203
204#[cfg(feature = "orchard")]
205impl<AccountId> ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>
206    for ScanningKey<orchard::keys::IncomingViewingKey, orchard::keys::FullViewingKey, AccountId>
207{
208    fn prepare(&self) -> orchard::keys::PreparedIncomingViewingKey {
209        orchard::keys::PreparedIncomingViewingKey::new(&self.ivk)
210    }
211
212    fn nf(
213        &self,
214        note: &orchard::note::Note,
215        _position: Position,
216    ) -> Option<orchard::note::Nullifier> {
217        self.nk.as_ref().map(|key| note.nullifier(key))
218    }
219
220    fn account_id(&self) -> &AccountId {
221        &self.account_id
222    }
223
224    fn key_scope(&self) -> Option<Scope> {
225        self.key_scope
226    }
227}
228
229/// The note-encryption domain used to trial-decrypt Ironwood outputs.
230///
231/// Ironwood ([ZIP 2005], NU6.3) is a distinct shielded pool. Its notes are Orchard-shaped and use
232/// the Orchard commitment and nullifier types, and are decrypted with the same Orchard viewing
233/// keys, but they carry version 3 note plaintexts and so require the Ironwood note-encryption
234/// domain, which is distinct from [`OrchardDomain`] (that domain accepts only version 2
235/// plaintexts). This is why Ironwood is a separate pool rather than a variant of Orchard.
236///
237/// [ZIP 2005]: https://zips.z.cash/zip-2005
238#[cfg(feature = "orchard")]
239pub(crate) type IronwoodDomain = orchard::note_encryption::IronwoodDomain;
240
241/// The nullifier type for Ironwood notes. This is the Orchard nullifier type, which does not
242/// depend on the note plaintext version. See [`IronwoodDomain`].
243#[cfg(feature = "orchard")]
244pub(crate) type IronwoodNullifier = orchard::note::Nullifier;
245
246/// An Orchard viewing key trial-decrypts Ironwood outputs under the Ironwood note-encryption
247/// domain. The key material is the same as for Orchard; only the domain (and thus the accepted
248/// note plaintext version) differs.
249#[cfg(feature = "orchard")]
250impl<AccountId> ScanningKeyOps<IronwoodDomain, AccountId, orchard::note::Nullifier>
251    for ScanningKey<orchard::keys::IncomingViewingKey, orchard::keys::FullViewingKey, AccountId>
252{
253    fn prepare(&self) -> orchard::keys::PreparedIncomingViewingKey {
254        orchard::keys::PreparedIncomingViewingKey::new(&self.ivk)
255    }
256
257    fn nf(
258        &self,
259        note: &orchard::note::Note,
260        _position: Position,
261    ) -> Option<orchard::note::Nullifier> {
262        self.nk.as_ref().map(|key| note.nullifier(key))
263    }
264
265    fn account_id(&self) -> &AccountId {
266        &self.account_id
267    }
268
269    fn key_scope(&self) -> Option<Scope> {
270        self.key_scope
271    }
272}
273
274/// A set of keys to be used in scanning for decryptable transaction outputs.
275pub struct ScanningKeys<AccountId, IvkTag> {
276    sapling: HashMap<
277        IvkTag,
278        Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier> + Send + Sync>,
279    >,
280    #[cfg(feature = "orchard")]
281    orchard: HashMap<
282        IvkTag,
283        Box<dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier> + Send + Sync>,
284    >,
285    #[cfg(feature = "orchard")]
286    ironwood: HashMap<
287        IvkTag,
288        Box<dyn ScanningKeyOps<IronwoodDomain, AccountId, IronwoodNullifier> + Send + Sync>,
289    >,
290}
291
292impl<AccountId, IvkTag> ScanningKeys<AccountId, IvkTag> {
293    /// Constructs a new set of scanning keys.
294    pub fn new(
295        sapling: HashMap<
296            IvkTag,
297            Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier> + Send + Sync>,
298        >,
299        #[cfg(feature = "orchard")] orchard: HashMap<
300            IvkTag,
301            Box<
302                dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>
303                    + Send
304                    + Sync,
305            >,
306        >,
307        #[cfg(feature = "orchard")] ironwood: HashMap<
308            IvkTag,
309            Box<dyn ScanningKeyOps<IronwoodDomain, AccountId, IronwoodNullifier> + Send + Sync>,
310        >,
311    ) -> Self {
312        Self {
313            sapling,
314            #[cfg(feature = "orchard")]
315            orchard,
316            #[cfg(feature = "orchard")]
317            ironwood,
318        }
319    }
320
321    /// Constructs a new empty set of scanning keys.
322    pub fn empty() -> Self {
323        Self {
324            sapling: HashMap::new(),
325            #[cfg(feature = "orchard")]
326            orchard: HashMap::new(),
327            #[cfg(feature = "orchard")]
328            ironwood: HashMap::new(),
329        }
330    }
331
332    /// Returns the Sapling keys to be used for incoming note detection.
333    pub fn sapling(
334        &self,
335    ) -> &HashMap<
336        IvkTag,
337        Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier> + Send + Sync>,
338    > {
339        &self.sapling
340    }
341
342    /// Returns the Orchard keys to be used for incoming note detection.
343    #[cfg(feature = "orchard")]
344    pub fn orchard(
345        &self,
346    ) -> &HashMap<
347        IvkTag,
348        Box<dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier> + Send + Sync>,
349    > {
350        &self.orchard
351    }
352
353    /// Returns the Ironwood keys to be used for incoming note detection.
354    ///
355    /// Ironwood outputs are trial-decrypted with the account's Orchard viewing keys (see
356    /// [`orchard::note_encryption::IronwoodDomain`]), but are tracked as a separate pool from
357    /// Orchard.
358    #[cfg(feature = "orchard")]
359    pub fn ironwood(
360        &self,
361    ) -> &HashMap<
362        IvkTag,
363        Box<dyn ScanningKeyOps<IronwoodDomain, AccountId, IronwoodNullifier> + Send + Sync>,
364    > {
365        &self.ironwood
366    }
367}
368
369impl<AccountId: Copy + Eq + Hash + Send + Sync + 'static>
370    ScanningKeys<AccountId, (AccountId, Scope)>
371{
372    /// Constructs a [`ScanningKeys`] from an iterator of [`UnifiedFullViewingKey`]s,
373    /// along with the account identifiers corresponding to those UFVKs.
374    pub fn from_account_ufvks(
375        ufvks: impl IntoIterator<Item = (AccountId, UnifiedFullViewingKey)>,
376    ) -> Self {
377        #![allow(clippy::type_complexity)]
378
379        let mut sapling: HashMap<
380            (AccountId, Scope),
381            Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier> + Send + Sync>,
382        > = HashMap::new();
383        #[cfg(feature = "orchard")]
384        let mut orchard: HashMap<
385            (AccountId, Scope),
386            Box<
387                dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>
388                    + Send
389                    + Sync,
390            >,
391        > = HashMap::new();
392        #[cfg(feature = "orchard")]
393        let mut ironwood: HashMap<
394            (AccountId, Scope),
395            Box<dyn ScanningKeyOps<IronwoodDomain, AccountId, IronwoodNullifier> + Send + Sync>,
396        > = HashMap::new();
397
398        for (account_id, ufvk) in ufvks {
399            if let Some(dfvk) = ufvk.sapling() {
400                for scope in [Scope::External, Scope::Internal] {
401                    sapling.insert(
402                        (account_id, scope),
403                        Box::new(ScanningKey {
404                            ivk: dfvk.to_ivk(scope),
405                            nk: Some(dfvk.to_nk(scope)),
406                            account_id,
407                            key_scope: Some(scope),
408                        }),
409                    );
410                }
411            }
412
413            #[cfg(feature = "orchard")]
414            if let Some(fvk) = ufvk.orchard() {
415                for scope in [Scope::External, Scope::Internal] {
416                    orchard.insert(
417                        (account_id, scope),
418                        Box::new(ScanningKey {
419                            ivk: fvk.to_ivk(scope),
420                            nk: Some(fvk.clone()),
421                            account_id,
422                            key_scope: Some(scope),
423                        }),
424                    );
425                }
426
427                // Ironwood outputs are decrypted with the same Orchard viewing keys, but are
428                // tracked as a separate pool.
429                for scope in [Scope::External, Scope::Internal] {
430                    ironwood.insert(
431                        (account_id, scope),
432                        Box::new(ScanningKey {
433                            ivk: fvk.to_ivk(scope),
434                            nk: Some(fvk.clone()),
435                            account_id,
436                            key_scope: Some(scope),
437                        }),
438                    );
439                }
440            }
441        }
442
443        Self {
444            sapling,
445            #[cfg(feature = "orchard")]
446            orchard,
447            #[cfg(feature = "orchard")]
448            ironwood,
449        }
450    }
451}
452
453/// The nullifiers of the wallet's unspent shielded notes, whose appearance in a scanned block
454/// reveals a spend of wallet funds.
455///
456/// Nullifiers are held in flat vectors because `find_spent` compares them in constant time, so
457/// that a local side-channel observer does not learn which of a block's nullifiers are the
458/// wallet's. That mitigation is partial: the comparison runs once per tracked nullifier, so its
459/// duration still discloses how many notes the wallet holds.
460pub struct Nullifiers<AccountId> {
461    sapling: Vec<(AccountId, sapling::Nullifier)>,
462    #[cfg(feature = "orchard")]
463    orchard: Vec<(AccountId, orchard::note::Nullifier)>,
464    #[cfg(feature = "orchard")]
465    ironwood: Vec<(AccountId, IronwoodNullifier)>,
466}
467
468impl<AccountId> Nullifiers<AccountId> {
469    /// Constructs a new empty set of nullifiers.
470    pub fn empty() -> Self {
471        Self {
472            sapling: vec![],
473            #[cfg(feature = "orchard")]
474            orchard: vec![],
475            #[cfg(feature = "orchard")]
476            ironwood: vec![],
477        }
478    }
479
480    /// Fetches the nullifiers of the unspent notes being tracked by the given wallet.
481    pub fn unspent<DbT: WalletRead<AccountId = AccountId>>(
482        db_data: &DbT,
483    ) -> Result<Self, DbT::Error> {
484        Ok(Self::new(
485            db_data.get_sapling_nullifiers(NullifierQuery::Unspent)?,
486            #[cfg(feature = "orchard")]
487            db_data.get_orchard_nullifiers(NullifierQuery::Unspent)?,
488            #[cfg(feature = "orchard")]
489            db_data.get_ironwood_nullifiers(NullifierQuery::Unspent)?,
490        ))
491    }
492
493    /// Constructs a nullifier set from its constituent parts.
494    pub(crate) fn new(
495        sapling: Vec<(AccountId, sapling::Nullifier)>,
496        #[cfg(feature = "orchard")] orchard: Vec<(AccountId, orchard::note::Nullifier)>,
497        #[cfg(feature = "orchard")] ironwood: Vec<(AccountId, IronwoodNullifier)>,
498    ) -> Self {
499        Self {
500            sapling,
501            #[cfg(feature = "orchard")]
502            orchard,
503            #[cfg(feature = "orchard")]
504            ironwood,
505        }
506    }
507
508    /// Returns the Sapling nullifiers for notes that the wallet is tracking.
509    pub fn sapling(&self) -> &[(AccountId, sapling::Nullifier)] {
510        self.sapling.as_ref()
511    }
512
513    /// Returns the Orchard nullifiers for notes that the wallet is tracking.
514    #[cfg(feature = "orchard")]
515    pub fn orchard(&self) -> &[(AccountId, orchard::note::Nullifier)] {
516        self.orchard.as_ref()
517    }
518
519    /// Returns the Ironwood nullifiers for notes that the wallet is tracking.
520    #[cfg(feature = "orchard")]
521    pub fn ironwood(&self) -> &[(AccountId, IronwoodNullifier)] {
522        self.ironwood.as_ref()
523    }
524
525    /// Discards Sapling nullifiers from the tracked nullifier set, retaining only those that
526    /// satisfy the given predicate.
527    pub(crate) fn retain_sapling(&mut self, f: impl Fn(&(AccountId, sapling::Nullifier)) -> bool) {
528        self.sapling.retain(f);
529    }
530
531    /// Adds the given nullifiers to the tracked nullifier set.
532    pub(crate) fn extend_sapling(
533        &mut self,
534        nfs: impl IntoIterator<Item = (AccountId, sapling::Nullifier)>,
535    ) {
536        self.sapling.extend(nfs);
537    }
538
539    #[cfg(feature = "orchard")]
540    pub(crate) fn retain_orchard(
541        &mut self,
542        f: impl Fn(&(AccountId, orchard::note::Nullifier)) -> bool,
543    ) {
544        self.orchard.retain(f);
545    }
546
547    #[cfg(feature = "orchard")]
548    pub(crate) fn extend_orchard(
549        &mut self,
550        nfs: impl IntoIterator<Item = (AccountId, orchard::note::Nullifier)>,
551    ) {
552        self.orchard.extend(nfs);
553    }
554
555    #[cfg(feature = "orchard")]
556    pub(crate) fn retain_ironwood(&mut self, f: impl Fn(&(AccountId, IronwoodNullifier)) -> bool) {
557        self.ironwood.retain(f);
558    }
559
560    #[cfg(feature = "orchard")]
561    pub(crate) fn extend_ironwood(
562        &mut self,
563        nfs: impl IntoIterator<Item = (AccountId, IronwoodNullifier)>,
564    ) {
565        self.ironwood.extend(nfs);
566    }
567}
568
569impl<AccountId: Copy> Nullifiers<AccountId> {
570    /// Updates this set of unspent nullifiers based on the results of scanning a block.
571    ///
572    /// This is intended for use when scanning multiple sequential blocks in memory, prior
573    /// to updating the wallet's state (after which [`Self::unspent`] would produce the
574    /// same set).
575    ///
576    /// - Notes spent by the wallet in this block will have their nullifiers removed from
577    ///   the set, so that they are not matched again.
578    /// - Notes received by the wallet in this block will have their nullifiers added to
579    ///   the set, enabling spend detection in subsequent blocks.
580    pub fn update_with(&mut self, scanned_block: &ScannedBlock<AccountId>) {
581        let sapling_spent_nf: Vec<&sapling::Nullifier> = scanned_block
582            .transactions()
583            .iter()
584            .flat_map(|tx| tx.sapling_spends().iter().map(|spend| spend.nf()))
585            .collect();
586
587        self.retain_sapling(|(_, nf)| !sapling_spent_nf.contains(&nf));
588        self.extend_sapling(scanned_block.transactions().iter().flat_map(|tx| {
589            tx.sapling_outputs()
590                .iter()
591                .flat_map(|out| out.nf().into_iter().map(|nf| (*out.account_id(), *nf)))
592        }));
593
594        #[cfg(feature = "orchard")]
595        {
596            let orchard_spent_nf: Vec<&orchard::note::Nullifier> = scanned_block
597                .transactions()
598                .iter()
599                .flat_map(|tx| tx.orchard_spends().iter().map(|spend| spend.nf()))
600                .collect();
601
602            self.retain_orchard(|(_, nf)| !orchard_spent_nf.contains(&nf));
603            self.extend_orchard(scanned_block.transactions().iter().flat_map(|tx| {
604                tx.orchard_outputs()
605                    .iter()
606                    .flat_map(|out| out.nf().into_iter().map(|nf| (*out.account_id(), *nf)))
607            }));
608
609            let ironwood_spent_nf: Vec<&IronwoodNullifier> = scanned_block
610                .transactions()
611                .iter()
612                .flat_map(|tx| tx.ironwood_spends().iter().map(|spend| spend.nf()))
613                .collect();
614
615            self.retain_ironwood(|(_, nf)| !ironwood_spent_nf.contains(&nf));
616            self.extend_ironwood(scanned_block.transactions().iter().flat_map(|tx| {
617                tx.ironwood_outputs()
618                    .iter()
619                    .flat_map(|out| out.nf().into_iter().map(|nf| (*out.account_id(), *nf)))
620            }));
621        }
622    }
623}
624
625/// The set of identifiers whose appearance in a scanned block reveals a spend of wallet funds:
626/// the [`Nullifiers`] of the wallet's unspent shielded notes, together with the outpoints of its
627/// unspent transparent outputs.
628///
629/// Transparent outpoints are held in a hash map, and matching them is not constant-time. This is
630/// not because the data is public — an outpoint is public, but the wallet's association with it
631/// is exactly what a wallet rotating addresses and shielding promptly needs to keep private.
632/// It is because the transparent path cannot deliver the property at this point alone:
633/// recognizing a transparent output requires resolving its address against the wallet's address
634/// set, and that lookup, whether a hash-map probe or a storage backend's indexed query, already
635/// takes time that depends on whether the address is the wallet's. Constant-time matching here
636/// would leave that larger channel open while costing a linear scan of what may be a large UTXO
637/// set. Closing it properly requires addressing both paths together.
638// TODO: Recognize transparent outputs and spends in constant time, across both the address
639// resolution and spend matching paths.
640// https://github.com/zcash/librustzcash/issues/2994
641pub struct SpendIdentifiers<AccountId> {
642    shielded: Nullifiers<AccountId>,
643    #[cfg(feature = "transparent-inputs")]
644    transparent: HashMap<OutPoint, AccountId>,
645}
646
647impl<AccountId> SpendIdentifiers<AccountId> {
648    /// Constructs a new empty set of spend identifiers.
649    pub fn empty() -> Self {
650        Self {
651            shielded: Nullifiers::empty(),
652            #[cfg(feature = "transparent-inputs")]
653            transparent: HashMap::new(),
654        }
655    }
656
657    /// Fetches the spend identifiers of the unspent outputs being tracked by the given wallet.
658    pub fn unspent<DbT: WalletRead<AccountId = AccountId>>(
659        db_data: &DbT,
660    ) -> Result<Self, DbT::Error> {
661        Ok(Self::new(
662            Nullifiers::unspent(db_data)?,
663            #[cfg(feature = "transparent-inputs")]
664            db_data.get_unspent_transparent_outpoints()?,
665        ))
666    }
667
668    /// Constructs a spend identifier set from its constituent parts.
669    pub(crate) fn new(
670        shielded: Nullifiers<AccountId>,
671        #[cfg(feature = "transparent-inputs")] transparent: HashMap<OutPoint, AccountId>,
672    ) -> Self {
673        Self {
674            shielded,
675            #[cfg(feature = "transparent-inputs")]
676            transparent,
677        }
678    }
679
680    /// Returns the nullifiers of the shielded notes that the wallet is tracking.
681    pub fn shielded(&self) -> &Nullifiers<AccountId> {
682        &self.shielded
683    }
684
685    /// Returns the outpoints of the unspent transparent outputs that the wallet is tracking,
686    /// each mapped to the account that received it.
687    #[cfg(feature = "transparent-inputs")]
688    pub fn transparent(&self) -> &HashMap<OutPoint, AccountId> {
689        &self.transparent
690    }
691}
692
693impl<AccountId: Copy> SpendIdentifiers<AccountId> {
694    /// Updates this set of spend identifiers based on the results of scanning a block.
695    ///
696    /// The shielded nullifiers are updated as by [`Nullifiers::update_with`]. Likewise, the
697    /// outpoints of transparent outputs the wallet spent in this block are removed, and those
698    /// of the transparent outputs it received are added, so that their spends are detected in
699    /// subsequent blocks.
700    pub fn update_with(&mut self, scanned_block: &ScannedBlock<AccountId>) {
701        self.shielded.update_with(scanned_block);
702
703        #[cfg(feature = "transparent-inputs")]
704        {
705            for spend in scanned_block
706                .transactions()
707                .iter()
708                .flat_map(|tx| tx.transparent_spends())
709            {
710                self.transparent.remove(spend.outpoint());
711            }
712
713            self.transparent.extend(
714                scanned_block
715                    .transactions()
716                    .iter()
717                    .flat_map(|tx| tx.transparent_outputs())
718                    .filter_map(|out| {
719                        out.recipient_account()
720                            .map(|account_id| (out.outpoint().clone(), *account_id))
721                    }),
722            );
723        }
724    }
725}
726
727/// Errors that may occur in chain scanning
728#[derive(Clone, Debug)]
729#[non_exhaustive]
730pub enum ScanError {
731    /// The encoding of a compact Sapling output or compact Orchard action was invalid.
732    EncodingInvalid {
733        at_height: BlockHeight,
734        txid: TxId,
735        pool_type: ShieldedPool,
736        index: usize,
737    },
738
739    /// The hash of the parent block given by a proposed new chain tip does not match the hash of
740    /// the current chain tip.
741    PrevHashMismatch { at_height: BlockHeight },
742
743    /// A block at a height the wallet has already scanned carries a hash other than the one the
744    /// wallet recorded there: the chain has reorganized below the scanned range.
745    BlockHashMismatch {
746        /// The height of the conflicting block.
747        at_height: BlockHeight,
748        /// The hash that the wallet recorded at `at_height`.
749        stored: BlockHash,
750        /// The hash of the block that was scanned at `at_height`.
751        scanned: BlockHash,
752    },
753
754    /// The note commitment data of a batch of scanned blocks, or the chain state the batch
755    /// extends, conflicts with note commitment tree state the wallet already holds.
756    CommitmentTreeConflict {
757        /// The shielded pool whose note commitment tree rejected the data.
758        pool: ShieldedPool,
759        /// The height of the first block of the rejected batch.
760        at_height: BlockHeight,
761        /// The address of the tree node at which the conflict was detected.
762        address: Address,
763    },
764
765    /// The block height field of the proposed new block is not equal to the height of the previous
766    /// block + 1.
767    BlockHeightDiscontinuity {
768        prev_height: BlockHeight,
769        new_height: BlockHeight,
770    },
771
772    /// The note commitment tree size for the given protocol at the proposed new block is not equal
773    /// to the size at the previous block plus the count of this block's outputs.
774    TreeSizeMismatch {
775        protocol: ShieldedPool,
776        at_height: BlockHeight,
777        given: u32,
778        computed: u32,
779    },
780
781    /// The size of the note commitment tree for the given protocol was not provided as part of a
782    /// [`CompactBlock`] being scanned, making it impossible to construct the nullifier for a
783    /// detected note.
784    TreeSizeUnknown {
785        protocol: ShieldedPool,
786        at_height: BlockHeight,
787    },
788
789    /// We were provided chain metadata for a block containing note commitment tree metadata
790    /// that is invalidated by the data in the block itself. This may be caused by the presence
791    /// of default values in the chain metadata.
792    TreeSizeInvalid {
793        protocol: ShieldedPool,
794        at_height: BlockHeight,
795    },
796
797    /// The size of the note commitment tree for the given protocol would exceed the
798    /// `u32` range as a result of applying the outputs in the block being scanned.
799    TreeSizeOverflow {
800        protocol: ShieldedPool,
801        at_height: BlockHeight,
802    },
803
804    /// The prevout reference of a compact transparent input could not be decoded.
805    ///
806    /// Scanning fails rather than skipping such an input: without its prevout the wallet cannot
807    /// determine whether the input spends one of its own outputs, and treating it as unrelated
808    /// would silently overstate the wallet's balance.
809    #[cfg(feature = "transparent-inputs")]
810    TransparentPrevoutInvalid {
811        at_height: BlockHeight,
812        txid: TxId,
813        index: usize,
814    },
815}
816
817impl ScanError {
818    /// Returns whether this error is the result of a failed continuity check
819    pub fn is_continuity_error(&self) -> bool {
820        match self {
821            EncodingInvalid { .. } => false,
822            PrevHashMismatch { .. } => true,
823            BlockHashMismatch { .. } => true,
824            CommitmentTreeConflict { .. } => true,
825            BlockHeightDiscontinuity { .. } => true,
826            TreeSizeMismatch { .. } => true,
827            TreeSizeUnknown { .. } => false,
828            TreeSizeInvalid { .. } => false,
829            TreeSizeOverflow { .. } => false,
830            #[cfg(feature = "transparent-inputs")]
831            TransparentPrevoutInvalid { .. } => false,
832        }
833    }
834
835    /// Returns the block height at which the scan error occurred
836    pub fn at_height(&self) -> BlockHeight {
837        match self {
838            EncodingInvalid { at_height, .. } => *at_height,
839            PrevHashMismatch { at_height } => *at_height,
840            BlockHashMismatch { at_height, .. } => *at_height,
841            CommitmentTreeConflict { at_height, .. } => *at_height,
842            BlockHeightDiscontinuity { new_height, .. } => *new_height,
843            TreeSizeMismatch { at_height, .. } => *at_height,
844            TreeSizeUnknown { at_height, .. } => *at_height,
845            TreeSizeInvalid { at_height, .. } => *at_height,
846            TreeSizeOverflow { at_height, .. } => *at_height,
847            #[cfg(feature = "transparent-inputs")]
848            TransparentPrevoutInvalid { at_height, .. } => *at_height,
849        }
850    }
851}
852
853impl fmt::Display for ScanError {
854    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
855        match &self {
856            EncodingInvalid {
857                txid,
858                pool_type,
859                index,
860                ..
861            } => write!(
862                f,
863                "{pool_type:?} output {index} of transaction {txid} was improperly encoded."
864            ),
865            PrevHashMismatch { at_height } => write!(
866                f,
867                "The parent hash of proposed block does not correspond to the block hash at height {at_height}."
868            ),
869            BlockHashMismatch {
870                at_height,
871                stored,
872                scanned,
873            } => write!(
874                f,
875                "The block at height {at_height} has hash {scanned}, but the wallet recorded {stored} at that height."
876            ),
877            CommitmentTreeConflict {
878                pool,
879                at_height,
880                address,
881            } => write!(
882                f,
883                "The {pool:?} note commitment data of the batch of blocks beginning at height {at_height} conflicts with the wallet's note commitment tree at {address:?}."
884            ),
885            BlockHeightDiscontinuity {
886                prev_height,
887                new_height,
888            } => {
889                write!(
890                    f,
891                    "Block height discontinuity at height {new_height}; previous height was: {prev_height}"
892                )
893            }
894            TreeSizeMismatch {
895                protocol,
896                at_height,
897                given,
898                computed,
899            } => {
900                write!(
901                    f,
902                    "The {protocol:?} note commitment tree size provided by a compact block did not match the expected size at height {at_height}; given {given}, expected {computed}"
903                )
904            }
905            TreeSizeUnknown {
906                protocol,
907                at_height,
908            } => {
909                write!(
910                    f,
911                    "Unable to determine {protocol:?} note commitment tree size at height {at_height}"
912                )
913            }
914            TreeSizeInvalid {
915                protocol,
916                at_height,
917            } => {
918                write!(
919                    f,
920                    "Received invalid (potentially default) {protocol:?} note commitment tree size metadata at height {at_height}"
921                )
922            }
923            TreeSizeOverflow {
924                protocol,
925                at_height,
926            } => {
927                write!(
928                    f,
929                    "The {protocol:?} note commitment tree size at height {at_height} would exceed the `u32` range."
930                )
931            }
932            #[cfg(feature = "transparent-inputs")]
933            TransparentPrevoutInvalid {
934                txid,
935                index,
936                at_height,
937            } => {
938                write!(
939                    f,
940                    "The prevout of transparent input {index} of transaction {txid} at height {at_height} was improperly encoded."
941                )
942            }
943        }
944    }
945}
946
947impl core::error::Error for ScanError {}
948
949/// Errors that can occur while scanning a block, including those arising from the wallet
950/// lookups that transparent output detection requires.
951#[derive(Debug)]
952#[non_exhaustive]
953pub enum ScanBlockError<E> {
954    /// A structural or continuity error in the block being scanned.
955    Scan(ScanError),
956    /// An error occurred while looking up the wallet account associated with a
957    /// transparent address.
958    AddressLookup(E),
959}
960
961impl<E> From<ScanError> for ScanBlockError<E> {
962    fn from(e: ScanError) -> Self {
963        ScanBlockError::Scan(e)
964    }
965}
966
967impl<E: fmt::Display> fmt::Display for ScanBlockError<E> {
968    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
969        match self {
970            ScanBlockError::Scan(e) => write!(f, "Error scanning block: {e}"),
971            ScanBlockError::AddressLookup(e) => write!(
972                f,
973                "Error looking up the wallet account for a transparent address: {e}"
974            ),
975        }
976    }
977}
978
979impl<E: std::error::Error + 'static> std::error::Error for ScanBlockError<E> {
980    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
981        match self {
982            ScanBlockError::Scan(e) => Some(e),
983            ScanBlockError::AddressLookup(e) => Some(e),
984        }
985    }
986}
987
988/// Scans a [`CompactBlock`] with a set of [`ScanningKeys`].
989///
990/// Returns a vector of [`WalletTx`]s decryptable by any of the given keys. If an output is
991/// decrypted by a full viewing key, the nullifiers of that output will also be computed.
992///
993/// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
994/// [`WalletTx`]: crate::wallet::WalletTx
995pub fn scan_block<P, AccountId, IvkTag, E>(
996    params: &P,
997    block: CompactBlock,
998    scanning_keys: &ScanningKeys<AccountId, IvkTag>,
999    spend_ids: &SpendIdentifiers<AccountId>,
1000    prior_block_metadata: Option<&BlockMetadata>,
1001    #[cfg(feature = "transparent-inputs")] find_account_for_address: impl Fn(
1002        &TransparentAddress,
1003    ) -> Result<
1004        Option<(AccountId, Option<TransparentKeyScope>)>,
1005        E,
1006    >,
1007) -> Result<ScannedBlock<AccountId>, ScanBlockError<E>>
1008where
1009    P: consensus::Parameters + Send + 'static,
1010    AccountId: Default + Eq + Hash + ConditionallySelectable + Send + Sync + 'static,
1011    IvkTag: Copy + std::hash::Hash + Eq + Send + 'static,
1012{
1013    compact::scan_block_with_runners::<_, _, _, (), (), (), _>(
1014        params,
1015        block,
1016        scanning_keys,
1017        spend_ids,
1018        prior_block_metadata,
1019        None,
1020        #[cfg(feature = "transparent-inputs")]
1021        find_account_for_address,
1022    )
1023}
1024
1025/// Tracks the scanner's position within the note commitment trees, in order to calculate
1026/// received note positions.
1027///
1028/// Construction for compact blocks is handled in the [`compact`] submodule, and for full
1029/// blocks in the [`full`] submodule; each provides its own `PositionTracker` constructor.
1030struct PositionTracker {
1031    sapling_tree_position: u32,
1032    sapling_final_tree_size: u32,
1033    #[cfg(feature = "orchard")]
1034    orchard_tree_position: u32,
1035    #[cfg(feature = "orchard")]
1036    orchard_final_tree_size: u32,
1037    #[cfg(feature = "orchard")]
1038    ironwood_tree_position: u32,
1039    #[cfg(feature = "orchard")]
1040    ironwood_final_tree_size: u32,
1041}
1042
1043impl PositionTracker {
1044    fn sapling_note_position(&self, output_idx: usize) -> Position {
1045        Position::from(u64::from(
1046            self.sapling_tree_position + u32::try_from(output_idx).unwrap(),
1047        ))
1048    }
1049
1050    #[cfg(feature = "orchard")]
1051    fn orchard_note_position(&self, output_idx: usize) -> Position {
1052        Position::from(u64::from(
1053            self.orchard_tree_position + u32::try_from(output_idx).unwrap(),
1054        ))
1055    }
1056
1057    #[cfg(feature = "orchard")]
1058    fn ironwood_note_position(&self, output_idx: usize) -> Position {
1059        Position::from(u64::from(
1060            self.ironwood_tree_position + u32::try_from(output_idx).unwrap(),
1061        ))
1062    }
1063}
1064
1065/// Check for spent notes. The comparison against known-unspent nullifiers is done
1066/// in constant time.
1067fn find_spent<'a, I, AccountId, Spend, Nf, WS>(
1068    spends: I,
1069    nullifiers: &[(AccountId, Nf)],
1070    extract_nf: impl Fn(&Spend) -> Nf,
1071    construct_wallet_spend: impl Fn(usize, Nf, AccountId) -> WS,
1072) -> (Vec<WS>, Vec<Nf>)
1073where
1074    I: IntoIterator<Item = &'a Spend>,
1075    I::IntoIter: ExactSizeIterator,
1076    Spend: 'a,
1077    AccountId: ConditionallySelectable + Default,
1078    Nf: ConstantTimeEq + Copy,
1079{
1080    let spends = spends.into_iter();
1081    // TODO: this is O(|nullifiers| * |notes|); does using constant-time operations here really
1082    // make sense?
1083    let mut found_spent = vec![];
1084    let mut unlinked_nullifiers = Vec::with_capacity(spends.len());
1085    for (index, spend) in spends.enumerate() {
1086        let spend_nf = extract_nf(spend);
1087
1088        // Find whether any tracked nullifier that matches this spend, and produce a
1089        // WalletShieldedSpend in constant time.
1090        let ct_spend = nullifiers
1091            .iter()
1092            .map(|&(account, nf)| CtOption::new(account, nf.ct_eq(&spend_nf)))
1093            .fold(
1094                CtOption::new(AccountId::default(), 0.into()),
1095                |first, next| CtOption::conditional_select(&next, &first, first.is_some()),
1096            )
1097            .map(|account| construct_wallet_spend(index, spend_nf, account));
1098
1099        if let Some(spend) = ct_spend.into() {
1100            found_spent.push(spend);
1101        } else {
1102            // This nullifier didn't match any we are currently tracking; save it in
1103            // case it matches an earlier block range we haven't scanned yet.
1104            unlinked_nullifiers.push(spend_nf);
1105        }
1106    }
1107
1108    (found_spent, unlinked_nullifiers)
1109}
1110
1111/// Partitions a transaction's transparent inputs into those that spend an output the wallet is
1112/// tracking and those that do not, returning the wallet's spends alongside the prevouts of the
1113/// remaining inputs.
1114///
1115/// The unmatched prevouts are not known to be unrelated to the wallet: an input spending an output
1116/// created in a block range the wallet has not yet scanned cannot be recognized here, because the
1117/// wallet does not yet know the output exists. They are returned so that the caller can record
1118/// them against the spending transaction and resolve the spend if that output is discovered later.
1119///
1120/// Unlike [`find_spent`], the comparison is not constant-time; see [`SpendIdentifiers`] for why
1121/// the transparent path does not attempt that property.
1122#[cfg(feature = "transparent-inputs")]
1123fn find_transparent_spends<AccountId: Copy>(
1124    prevouts: impl IntoIterator<Item = OutPoint>,
1125    tracked: &HashMap<OutPoint, AccountId>,
1126) -> (Vec<WalletTransparentSpend<AccountId>>, Vec<OutPoint>) {
1127    let mut found_spent = vec![];
1128    let mut unlinked_prevouts = vec![];
1129
1130    for (index, prevout) in prevouts.into_iter().enumerate() {
1131        match tracked.get(&prevout) {
1132            Some(account_id) => found_spent.push(WalletTransparentSpend::from_parts(
1133                index,
1134                prevout,
1135                *account_id,
1136            )),
1137            None => unlinked_prevouts.push(prevout),
1138        }
1139    }
1140
1141    (found_spent, unlinked_prevouts)
1142}
1143
1144#[allow(clippy::too_many_arguments)]
1145#[allow(clippy::type_complexity)]
1146fn find_received<
1147    AccountId: Copy + Eq + Hash,
1148    D: BatchDomain,
1149    M,
1150    Nf,
1151    IvkTag: Copy + std::hash::Hash + Eq + Send + 'static,
1152    SK: ScanningKeyOps<D, AccountId, Nf>,
1153    Output: ShieldedOutput<D>,
1154    NoteCommitment,
1155    Note,
1156>(
1157    block_height: BlockHeight,
1158    last_commitments_in_block: bool,
1159    txid: TxId,
1160    note_position: impl Fn(usize) -> Position,
1161    keys: &HashMap<IvkTag, SK>,
1162    spent_from_accounts: &HashSet<AccountId>,
1163    decoded: &[(D, Output)],
1164    batch_results: Option<impl FnOnce(TxId) -> HashMap<usize, DecryptedOutput<IvkTag, D, M>>>,
1165    decrypt_inline: impl FnOnce(
1166        &[D::IncomingViewingKey],
1167        &[(D, Output)],
1168    ) -> Vec<Option<((D::Note, D::Recipient, M), usize)>>,
1169    extract_note_commitment: impl Fn(&Output) -> NoteCommitment,
1170    enrich_note: impl Fn(D::Note) -> Note,
1171) -> (
1172    Vec<WalletOutput<Note, Nf, AccountId>>,
1173    Vec<(NoteCommitment, Retention<BlockHeight>)>,
1174) {
1175    // Check for incoming notes while incrementing tree and witnesses
1176    let (decrypted_opts, decrypted_len) = if let Some(collect_results) = batch_results {
1177        let mut decrypted = collect_results(txid);
1178        let decrypted_len = decrypted.len();
1179        (
1180            (0..decoded.len())
1181                .map(|i| {
1182                    decrypted
1183                        .remove(&i)
1184                        .map(|d_out| (d_out.ivk_tag, d_out.note))
1185                })
1186                .collect::<Vec<_>>(),
1187            decrypted_len,
1188        )
1189    } else {
1190        let mut ivks = Vec::with_capacity(keys.len());
1191        let mut ivk_lookup = Vec::with_capacity(keys.len());
1192        for (key_id, key) in keys.iter() {
1193            ivks.push(key.prepare());
1194            ivk_lookup.push(key_id);
1195        }
1196
1197        let mut decrypted_len = 0;
1198        (
1199            decrypt_inline(&ivks, decoded)
1200                .into_iter()
1201                .map(|v| {
1202                    v.map(|((note, _, _), ivk_idx)| {
1203                        decrypted_len += 1;
1204                        (*ivk_lookup[ivk_idx], note)
1205                    })
1206                })
1207                .collect::<Vec<_>>(),
1208            decrypted_len,
1209        )
1210    };
1211
1212    let mut shielded_outputs = Vec::with_capacity(decrypted_len);
1213    let mut note_commitments = Vec::with_capacity(decoded.len());
1214    for (output_idx, ((_, output), decrypted_note)) in
1215        decoded.iter().zip(decrypted_opts).enumerate()
1216    {
1217        // Collect block note commitments
1218        let node = extract_note_commitment(output);
1219        // If the commitment is the last in the block, ensure that is retained as a checkpoint
1220        let is_checkpoint = output_idx + 1 == decoded.len() && last_commitments_in_block;
1221        let retention = match (decrypted_note.is_some(), is_checkpoint) {
1222            (is_marked, true) => Retention::Checkpoint {
1223                id: block_height,
1224                marking: if is_marked {
1225                    Marking::Marked
1226                } else {
1227                    Marking::None
1228                },
1229            },
1230            (true, false) => Retention::Marked,
1231            (false, false) => Retention::Ephemeral,
1232        };
1233
1234        if let Some((key_id, note)) = decrypted_note {
1235            let key = keys
1236                .get(&key_id)
1237                .expect("Key is available for decrypted output");
1238
1239            // A note is marked as "change" if the account that received it
1240            // also spent notes in the same transaction. This will catch,
1241            // for instance:
1242            // - Change created by spending fractions of notes.
1243            // - Notes created by consolidation transactions.
1244            // - Notes sent from one account to itself.
1245            let is_change = spent_from_accounts.contains(key.account_id());
1246            let note_commitment_tree_position = note_position(output_idx);
1247            let nf = key.nf(&note, note_commitment_tree_position);
1248
1249            shielded_outputs.push(WalletOutput::from_parts(
1250                output_idx,
1251                output.ephemeral_key(),
1252                enrich_note(note),
1253                is_change,
1254                note_commitment_tree_position,
1255                nf,
1256                *key.account_id(),
1257                key.key_scope(),
1258            ));
1259        }
1260
1261        note_commitments.push((node, retention))
1262    }
1263
1264    (shielded_outputs, note_commitments)
1265}
1266
1267#[cfg(any(test, feature = "test-dependencies"))]
1268pub mod testing {
1269    use group::{
1270        GroupEncoding,
1271        ff::{Field, PrimeField},
1272    };
1273    use rand::{Rng, rand_core::UnwrapErr, rngs::SysRng};
1274    use sapling::{
1275        Nullifier,
1276        constants::SPENDING_KEY_GENERATOR,
1277        note_encryption::{COMPACT_NOTE_SIZE, SaplingDomain, sapling_note_encryption},
1278        util::generate_random_rseed,
1279        value::NoteValue,
1280        zip32::DiversifiableFullViewingKey,
1281    };
1282    use zcash_note_encryption::Domain;
1283    use zcash_primitives::{
1284        block::BlockHash, transaction::components::sapling::zip212_enforcement,
1285    };
1286    use zcash_protocol::{
1287        consensus::{BlockHeight, Network},
1288        memo::MemoBytes,
1289        value::Zatoshis,
1290    };
1291
1292    use crate::proto::compact_formats::{
1293        self as compact, CompactBlock, CompactSaplingOutput, CompactSaplingSpend, CompactTx,
1294    };
1295
1296    fn random_compact_tx(mut rng: impl Rng) -> CompactTx {
1297        let fake_nf = {
1298            let mut nf = vec![0; 32];
1299            rng.fill_bytes(&mut nf);
1300            nf
1301        };
1302        let fake_cmu = {
1303            let fake_cmu = bls12_381::Scalar::random(&mut rng);
1304            fake_cmu.to_repr().to_vec()
1305        };
1306        let fake_epk = {
1307            let mut buffer = [0; 64];
1308            rng.fill_bytes(&mut buffer);
1309            let fake_esk = jubjub::Fr::from_bytes_wide(&buffer);
1310            let fake_epk = SPENDING_KEY_GENERATOR * fake_esk;
1311            fake_epk.to_bytes().to_vec()
1312        };
1313        let cspend = CompactSaplingSpend { nf: fake_nf };
1314        let cout = CompactSaplingOutput {
1315            cmu: fake_cmu,
1316            ephemeral_key: fake_epk,
1317            ciphertext: vec![0; COMPACT_NOTE_SIZE],
1318        };
1319        let mut ctx = CompactTx::default();
1320        let mut txid = vec![0; 32];
1321        rng.fill_bytes(&mut txid);
1322        ctx.txid = txid;
1323        ctx.spends.push(cspend);
1324        ctx.outputs.push(cout);
1325        ctx
1326    }
1327
1328    /// Create a fake CompactBlock at the given height, with a transaction containing a
1329    /// single spend of the given nullifier and a single output paying the given address.
1330    /// Returns the CompactBlock.
1331    ///
1332    /// Set `initial_tree_sizes` to `None` to simulate a `CompactBlock` retrieved
1333    /// from a `lightwalletd` that is not currently tracking note commitment tree sizes.
1334    pub fn fake_compact_block(
1335        height: BlockHeight,
1336        prev_hash: BlockHash,
1337        nf: Nullifier,
1338        dfvk: &DiversifiableFullViewingKey,
1339        value: Zatoshis,
1340        tx_after: bool,
1341        initial_tree_sizes: Option<(u32, u32)>,
1342    ) -> CompactBlock {
1343        let zip212_enforcement = zip212_enforcement(&Network::TestNetwork, height);
1344        let to = dfvk.default_address().1;
1345
1346        // Create a fake Note for the account
1347        let mut rng = UnwrapErr(SysRng);
1348        let rseed = generate_random_rseed(zip212_enforcement, &mut rng);
1349        let note = sapling::Note::from_parts(to, NoteValue::from_raw(value.into()), rseed);
1350        let encryptor = sapling_note_encryption(
1351            Some(dfvk.fvk().ovk),
1352            note.clone(),
1353            MemoBytes::empty().into_bytes(),
1354            &mut rng,
1355        );
1356        let cmu = note.cmu().to_bytes().to_vec();
1357        let ephemeral_key = SaplingDomain::epk_bytes(encryptor.epk()).0.to_vec();
1358        let enc_ciphertext = encryptor.encrypt_note_plaintext();
1359
1360        // Create a fake CompactBlock containing the note
1361        let mut cb = CompactBlock {
1362            hash: {
1363                let mut hash = vec![0; 32];
1364                rng.fill_bytes(&mut hash);
1365                hash
1366            },
1367            prev_hash: prev_hash.0.to_vec(),
1368            height: height.into(),
1369            ..Default::default()
1370        };
1371
1372        // Add a random Sapling tx before ours
1373        {
1374            let mut tx = random_compact_tx(&mut rng);
1375            tx.index = cb.vtx.len() as u64;
1376            cb.vtx.push(tx);
1377        }
1378
1379        let cspend = CompactSaplingSpend { nf: nf.0.to_vec() };
1380        let cout = CompactSaplingOutput {
1381            cmu,
1382            ephemeral_key,
1383            ciphertext: enc_ciphertext.0[..COMPACT_NOTE_SIZE].to_vec(),
1384        };
1385        let mut ctx = CompactTx::default();
1386        let mut txid = vec![0; 32];
1387        rng.fill_bytes(&mut txid);
1388        ctx.txid = txid;
1389        ctx.spends.push(cspend);
1390        ctx.outputs.push(cout);
1391        ctx.index = cb.vtx.len() as u64;
1392        cb.vtx.push(ctx);
1393
1394        // Optionally add another random Sapling tx after ours
1395        if tx_after {
1396            let mut tx = random_compact_tx(&mut rng);
1397            tx.index = cb.vtx.len() as u64;
1398            cb.vtx.push(tx);
1399        }
1400
1401        cb.chain_metadata =
1402            initial_tree_sizes.map(|(initial_sapling_tree_size, initial_orchard_tree_size)| {
1403                compact::ChainMetadata {
1404                    sapling_commitment_tree_size: initial_sapling_tree_size
1405                        + cb.vtx.iter().map(|tx| tx.outputs.len() as u32).sum::<u32>(),
1406                    orchard_commitment_tree_size: initial_orchard_tree_size
1407                        + cb.vtx.iter().map(|tx| tx.actions.len() as u32).sum::<u32>(),
1408                    // The test framework does not generate Ironwood notes.
1409                    ironwood_commitment_tree_size: 0,
1410                }
1411            });
1412
1413        cb
1414    }
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419    use std::{sync::Arc, thread::spawn};
1420
1421    use super::ScanningKeys;
1422
1423    #[test]
1424    fn arc_scanning_keys() {
1425        let keys = Arc::new(ScanningKeys::<(), ()>::empty());
1426        spawn(move || {
1427            let _ = keys.sapling().get(&());
1428        });
1429    }
1430}