1use 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
50pub trait ScanningKeyOps<D: Domain, AccountId, Nf> {
65 fn prepare(&self) -> D::IncomingViewingKey;
67
68 fn account_id(&self) -> &AccountId;
73
74 fn key_scope(&self) -> Option<Scope>;
76
77 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
144pub 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 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#[cfg(feature = "orchard")]
239pub(crate) type IronwoodDomain = orchard::note_encryption::IronwoodDomain;
240
241#[cfg(feature = "orchard")]
244pub(crate) type IronwoodNullifier = orchard::note::Nullifier;
245
246#[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
274pub 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 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 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 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 #[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 #[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 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 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
453pub 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 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 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 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 pub fn sapling(&self) -> &[(AccountId, sapling::Nullifier)] {
510 self.sapling.as_ref()
511 }
512
513 #[cfg(feature = "orchard")]
515 pub fn orchard(&self) -> &[(AccountId, orchard::note::Nullifier)] {
516 self.orchard.as_ref()
517 }
518
519 #[cfg(feature = "orchard")]
521 pub fn ironwood(&self) -> &[(AccountId, IronwoodNullifier)] {
522 self.ironwood.as_ref()
523 }
524
525 pub(crate) fn retain_sapling(&mut self, f: impl Fn(&(AccountId, sapling::Nullifier)) -> bool) {
528 self.sapling.retain(f);
529 }
530
531 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 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
625pub struct SpendIdentifiers<AccountId> {
642 shielded: Nullifiers<AccountId>,
643 #[cfg(feature = "transparent-inputs")]
644 transparent: HashMap<OutPoint, AccountId>,
645}
646
647impl<AccountId> SpendIdentifiers<AccountId> {
648 pub fn empty() -> Self {
650 Self {
651 shielded: Nullifiers::empty(),
652 #[cfg(feature = "transparent-inputs")]
653 transparent: HashMap::new(),
654 }
655 }
656
657 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 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 pub fn shielded(&self) -> &Nullifiers<AccountId> {
682 &self.shielded
683 }
684
685 #[cfg(feature = "transparent-inputs")]
688 pub fn transparent(&self) -> &HashMap<OutPoint, AccountId> {
689 &self.transparent
690 }
691}
692
693impl<AccountId: Copy> SpendIdentifiers<AccountId> {
694 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#[derive(Clone, Debug)]
729#[non_exhaustive]
730pub enum ScanError {
731 EncodingInvalid {
733 at_height: BlockHeight,
734 txid: TxId,
735 pool_type: ShieldedPool,
736 index: usize,
737 },
738
739 PrevHashMismatch { at_height: BlockHeight },
742
743 BlockHashMismatch {
746 at_height: BlockHeight,
748 stored: BlockHash,
750 scanned: BlockHash,
752 },
753
754 CommitmentTreeConflict {
757 pool: ShieldedPool,
759 at_height: BlockHeight,
761 address: Address,
763 },
764
765 BlockHeightDiscontinuity {
768 prev_height: BlockHeight,
769 new_height: BlockHeight,
770 },
771
772 TreeSizeMismatch {
775 protocol: ShieldedPool,
776 at_height: BlockHeight,
777 given: u32,
778 computed: u32,
779 },
780
781 TreeSizeUnknown {
785 protocol: ShieldedPool,
786 at_height: BlockHeight,
787 },
788
789 TreeSizeInvalid {
793 protocol: ShieldedPool,
794 at_height: BlockHeight,
795 },
796
797 TreeSizeOverflow {
800 protocol: ShieldedPool,
801 at_height: BlockHeight,
802 },
803
804 #[cfg(feature = "transparent-inputs")]
810 TransparentPrevoutInvalid {
811 at_height: BlockHeight,
812 txid: TxId,
813 index: usize,
814 },
815}
816
817impl ScanError {
818 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 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#[derive(Debug)]
952#[non_exhaustive]
953pub enum ScanBlockError<E> {
954 Scan(ScanError),
956 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
988pub 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
1025struct 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
1065fn 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 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 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 unlinked_nullifiers.push(spend_nf);
1105 }
1106 }
1107
1108 (found_spent, unlinked_nullifiers)
1109}
1110
1111#[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 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 let node = extract_note_commitment(output);
1219 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 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(¬e, 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 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 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 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 {
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 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 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}