-
Notifications
You must be signed in to change notification settings - Fork 257
/
Copy pathscanning.rs
1539 lines (1391 loc) · 53.6 KB
/
scanning.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Tools for scanning a compact representation of the Zcash block chain.
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt::{self, Debug};
use std::hash::Hash;
use incrementalmerkletree::{Marking, Position, Retention};
use sapling::{
note_encryption::{CompactOutputDescription, SaplingDomain},
SaplingIvk,
};
use subtle::{ConditionallySelectable, ConstantTimeEq, CtOption};
use tracing::{debug, trace};
use zcash_keys::keys::UnifiedFullViewingKey;
use zcash_note_encryption::{batch, BatchDomain, Domain, ShieldedOutput, COMPACT_NOTE_SIZE};
use zcash_primitives::transaction::{components::sapling::zip212_enforcement, TxId};
use zcash_protocol::{
consensus::{self, BlockHeight, NetworkUpgrade},
ShieldedProtocol,
};
use zip32::Scope;
use crate::{
data_api::{BlockMetadata, ScannedBlock, ScannedBundles},
proto::compact_formats::CompactBlock,
scan::{Batch, BatchRunner, CompactDecryptor, DecryptedOutput, Tasks},
wallet::{WalletOutput, WalletSpend, WalletTx},
};
#[cfg(feature = "orchard")]
use orchard::{
note_encryption::{CompactAction, OrchardDomain},
tree::MerkleHashOrchard,
};
#[cfg(not(feature = "orchard"))]
use std::marker::PhantomData;
/// A key that can be used to perform trial decryption and nullifier
/// computation for a [`CompactSaplingOutput`] or [`CompactOrchardAction`].
///
/// The purpose of this trait is to enable [`scan_block`]
/// and related methods to be used with either incoming viewing keys
/// or full viewing keys, with the data returned from trial decryption
/// being dependent upon the type of key used. In the case that an
/// incoming viewing key is used, only the note and payment address
/// will be returned; in the case of a full viewing key, the
/// nullifier for the note can also be obtained.
///
/// [`CompactSaplingOutput`]: crate::proto::compact_formats::CompactSaplingOutput
/// [`CompactOrchardAction`]: crate::proto::compact_formats::CompactOrchardAction
/// [`scan_block`]: crate::scanning::scan_block
pub trait ScanningKeyOps<D: Domain, AccountId, Nf> {
/// Prepare the key for use in batch trial decryption.
fn prepare(&self) -> D::IncomingViewingKey;
/// Returns the account identifier for this key. An account identifier corresponds
/// to at most a single unified spending key's worth of spend authority, such that
/// both received notes and change spendable by that spending authority will be
/// interpreted as belonging to that account.
fn account_id(&self) -> &AccountId;
/// Returns the [`zip32::Scope`] for which this key was derived, if known.
fn key_scope(&self) -> Option<Scope>;
/// Produces the nullifier for the specified note and witness, if possible.
///
/// IVK-based implementations of this trait cannot successfully derive
/// nullifiers, in which this function will always return `None`.
fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf>;
}
impl<D: Domain, AccountId, Nf, K: ScanningKeyOps<D, AccountId, Nf>> ScanningKeyOps<D, AccountId, Nf>
for &K
{
fn prepare(&self) -> D::IncomingViewingKey {
(*self).prepare()
}
fn account_id(&self) -> &AccountId {
(*self).account_id()
}
fn key_scope(&self) -> Option<Scope> {
(*self).key_scope()
}
fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf> {
(*self).nf(note, note_position)
}
}
impl<D: Domain, AccountId, Nf> ScanningKeyOps<D, AccountId, Nf>
for Box<dyn ScanningKeyOps<D, AccountId, Nf>>
{
fn prepare(&self) -> D::IncomingViewingKey {
self.as_ref().prepare()
}
fn account_id(&self) -> &AccountId {
self.as_ref().account_id()
}
fn key_scope(&self) -> Option<Scope> {
self.as_ref().key_scope()
}
fn nf(&self, note: &D::Note, note_position: Position) -> Option<Nf> {
self.as_ref().nf(note, note_position)
}
}
/// An incoming viewing key, paired with an optional nullifier key and key source metadata.
pub struct ScanningKey<Ivk, Nk, AccountId> {
ivk: Ivk,
nk: Option<Nk>,
account_id: AccountId,
key_scope: Option<Scope>,
}
impl<AccountId> ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>
for ScanningKey<sapling::SaplingIvk, sapling::NullifierDerivingKey, AccountId>
{
fn prepare(&self) -> sapling::note_encryption::PreparedIncomingViewingKey {
sapling::note_encryption::PreparedIncomingViewingKey::new(&self.ivk)
}
fn nf(&self, note: &sapling::Note, position: Position) -> Option<sapling::Nullifier> {
self.nk.as_ref().map(|key| note.nf(key, position.into()))
}
fn account_id(&self) -> &AccountId {
&self.account_id
}
fn key_scope(&self) -> Option<Scope> {
self.key_scope
}
}
impl<AccountId> ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>
for (AccountId, SaplingIvk)
{
fn prepare(&self) -> sapling::note_encryption::PreparedIncomingViewingKey {
sapling::note_encryption::PreparedIncomingViewingKey::new(&self.1)
}
fn nf(&self, _note: &sapling::Note, _position: Position) -> Option<sapling::Nullifier> {
None
}
fn account_id(&self) -> &AccountId {
&self.0
}
fn key_scope(&self) -> Option<Scope> {
None
}
}
#[cfg(feature = "orchard")]
impl<AccountId> ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>
for ScanningKey<orchard::keys::IncomingViewingKey, orchard::keys::FullViewingKey, AccountId>
{
fn prepare(&self) -> orchard::keys::PreparedIncomingViewingKey {
orchard::keys::PreparedIncomingViewingKey::new(&self.ivk)
}
fn nf(
&self,
note: &orchard::note::Note,
_position: Position,
) -> Option<orchard::note::Nullifier> {
self.nk.as_ref().map(|key| note.nullifier(key))
}
fn account_id(&self) -> &AccountId {
&self.account_id
}
fn key_scope(&self) -> Option<Scope> {
self.key_scope
}
}
/// A set of keys to be used in scanning for decryptable transaction outputs.
pub struct ScanningKeys<AccountId, IvkTag> {
sapling: HashMap<IvkTag, Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>>>,
#[cfg(feature = "orchard")]
orchard: HashMap<
IvkTag,
Box<dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>>,
>,
}
impl<AccountId, IvkTag> ScanningKeys<AccountId, IvkTag> {
/// Constructs a new set of scanning keys.
pub fn new(
sapling: HashMap<
IvkTag,
Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>>,
>,
#[cfg(feature = "orchard")] orchard: HashMap<
IvkTag,
Box<dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>>,
>,
) -> Self {
Self {
sapling,
#[cfg(feature = "orchard")]
orchard,
}
}
/// Constructs a new empty set of scanning keys.
pub fn empty() -> Self {
Self {
sapling: HashMap::new(),
#[cfg(feature = "orchard")]
orchard: HashMap::new(),
}
}
/// Returns the Sapling keys to be used for incoming note detection.
pub fn sapling(
&self,
) -> &HashMap<IvkTag, Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>>>
{
&self.sapling
}
/// Returns the Orchard keys to be used for incoming note detection.
#[cfg(feature = "orchard")]
pub fn orchard(
&self,
) -> &HashMap<IvkTag, Box<dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>>>
{
&self.orchard
}
}
impl<AccountId: Copy + Eq + Hash + 'static> ScanningKeys<AccountId, (AccountId, Scope)> {
/// Constructs a [`ScanningKeys`] from an iterator of [`UnifiedFullViewingKey`]s,
/// along with the account identifiers corresponding to those UFVKs.
pub fn from_account_ufvks(
ufvks: impl IntoIterator<Item = (AccountId, UnifiedFullViewingKey)>,
) -> Self {
#![allow(clippy::type_complexity)]
let mut sapling: HashMap<
(AccountId, Scope),
Box<dyn ScanningKeyOps<SaplingDomain, AccountId, sapling::Nullifier>>,
> = HashMap::new();
#[cfg(feature = "orchard")]
let mut orchard: HashMap<
(AccountId, Scope),
Box<dyn ScanningKeyOps<OrchardDomain, AccountId, orchard::note::Nullifier>>,
> = HashMap::new();
for (account_id, ufvk) in ufvks {
if let Some(dfvk) = ufvk.sapling() {
for scope in [Scope::External, Scope::Internal] {
sapling.insert(
(account_id, scope),
Box::new(ScanningKey {
ivk: dfvk.to_ivk(scope),
nk: Some(dfvk.to_nk(scope)),
account_id,
key_scope: Some(scope),
}),
);
}
}
#[cfg(feature = "orchard")]
if let Some(fvk) = ufvk.orchard() {
for scope in [Scope::External, Scope::Internal] {
orchard.insert(
(account_id, scope),
Box::new(ScanningKey {
ivk: fvk.to_ivk(scope),
nk: Some(fvk.clone()),
account_id,
key_scope: Some(scope),
}),
);
}
}
}
Self {
sapling,
#[cfg(feature = "orchard")]
orchard,
}
}
}
/// The set of nullifiers being tracked by a wallet.
pub struct Nullifiers<AccountId> {
sapling: Vec<(AccountId, sapling::Nullifier)>,
#[cfg(feature = "orchard")]
orchard: Vec<(AccountId, orchard::note::Nullifier)>,
}
impl<AccountId> Nullifiers<AccountId> {
/// Constructs a new empty set of nullifiers
pub fn empty() -> Self {
Self {
sapling: vec![],
#[cfg(feature = "orchard")]
orchard: vec![],
}
}
/// Construct a nullifier set from its constituent parts.
pub(crate) fn new(
sapling: Vec<(AccountId, sapling::Nullifier)>,
#[cfg(feature = "orchard")] orchard: Vec<(AccountId, orchard::note::Nullifier)>,
) -> Self {
Self {
sapling,
#[cfg(feature = "orchard")]
orchard,
}
}
/// Returns the Sapling nullifiers for notes that the wallet is tracking.
pub fn sapling(&self) -> &[(AccountId, sapling::Nullifier)] {
self.sapling.as_ref()
}
/// Returns the Orchard nullifiers for notes that the wallet is tracking.
#[cfg(feature = "orchard")]
pub fn orchard(&self) -> &[(AccountId, orchard::note::Nullifier)] {
self.orchard.as_ref()
}
/// Discards Sapling nullifiers from the tracked nullifier set, retaining only those that
/// satisfy the given predicate.
pub(crate) fn retain_sapling(&mut self, f: impl Fn(&(AccountId, sapling::Nullifier)) -> bool) {
self.sapling.retain(f);
}
/// Adds the given nullifiers to the tracked nullifier set.
pub(crate) fn extend_sapling(
&mut self,
nfs: impl IntoIterator<Item = (AccountId, sapling::Nullifier)>,
) {
self.sapling.extend(nfs);
}
#[cfg(feature = "orchard")]
pub(crate) fn retain_orchard(
&mut self,
f: impl Fn(&(AccountId, orchard::note::Nullifier)) -> bool,
) {
self.orchard.retain(f);
}
#[cfg(feature = "orchard")]
pub(crate) fn extend_orchard(
&mut self,
nfs: impl IntoIterator<Item = (AccountId, orchard::note::Nullifier)>,
) {
self.orchard.extend(nfs);
}
}
/// Errors that may occur in chain scanning
#[derive(Clone, Debug)]
pub enum ScanError {
/// The encoding of a compact Sapling output or compact Orchard action was invalid.
EncodingInvalid {
at_height: BlockHeight,
txid: TxId,
pool_type: ShieldedProtocol,
index: usize,
},
/// The hash of the parent block given by a proposed new chain tip does not match the hash of
/// the current chain tip.
PrevHashMismatch { at_height: BlockHeight },
/// The block height field of the proposed new block is not equal to the height of the previous
/// block + 1.
BlockHeightDiscontinuity {
prev_height: BlockHeight,
new_height: BlockHeight,
},
/// The note commitment tree size for the given protocol at the proposed new block is not equal
/// to the size at the previous block plus the count of this block's outputs.
TreeSizeMismatch {
protocol: ShieldedProtocol,
at_height: BlockHeight,
given: u32,
computed: u32,
},
/// The size of the note commitment tree for the given protocol was not provided as part of a
/// [`CompactBlock`] being scanned, making it impossible to construct the nullifier for a
/// detected note.
TreeSizeUnknown {
protocol: ShieldedProtocol,
at_height: BlockHeight,
},
/// We were provided chain metadata for a block containing note commitment tree metadata
/// that is invalidated by the data in the block itself. This may be caused by the presence
/// of default values in the chain metadata.
TreeSizeInvalid {
protocol: ShieldedProtocol,
at_height: BlockHeight,
},
}
impl ScanError {
/// Returns whether this error is the result of a failed continuity check
pub fn is_continuity_error(&self) -> bool {
use ScanError::*;
match self {
EncodingInvalid { .. } => false,
PrevHashMismatch { .. } => true,
BlockHeightDiscontinuity { .. } => true,
TreeSizeMismatch { .. } => true,
TreeSizeUnknown { .. } => false,
TreeSizeInvalid { .. } => false,
}
}
/// Returns the block height at which the scan error occurred
pub fn at_height(&self) -> BlockHeight {
use ScanError::*;
match self {
EncodingInvalid { at_height, .. } => *at_height,
PrevHashMismatch { at_height } => *at_height,
BlockHeightDiscontinuity { new_height, .. } => *new_height,
TreeSizeMismatch { at_height, .. } => *at_height,
TreeSizeUnknown { at_height, .. } => *at_height,
TreeSizeInvalid { at_height, .. } => *at_height,
}
}
}
impl fmt::Display for ScanError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use ScanError::*;
match &self {
EncodingInvalid { txid, pool_type, index, .. } => write!(
f,
"{:?} output {} of transaction {} was improperly encoded.",
pool_type, index, txid
),
PrevHashMismatch { at_height } => write!(
f,
"The parent hash of proposed block does not correspond to the block hash at height {}.",
at_height
),
BlockHeightDiscontinuity { prev_height, new_height } => {
write!(f, "Block height discontinuity at height {}; previous height was: {}", new_height, prev_height)
}
TreeSizeMismatch { protocol, at_height, given, computed } => {
write!(f, "The {:?} note commitment tree size provided by a compact block did not match the expected size at height {}; given {}, expected {}", protocol, at_height, given, computed)
}
TreeSizeUnknown { protocol, at_height } => {
write!(f, "Unable to determine {:?} note commitment tree size at height {}", protocol, at_height)
}
TreeSizeInvalid { protocol, at_height } => {
write!(f, "Received invalid (potentially default) {:?} note commitment tree size metadata at height {}", protocol, at_height)
}
}
}
}
/// Scans a [`CompactBlock`] with a set of [`ScanningKeys`].
///
/// Returns a vector of [`WalletTx`]s decryptable by any of the given keys. If an output is
/// decrypted by a full viewing key, the nullifiers of that output will also be computed.
///
/// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
/// [`WalletTx`]: crate::wallet::WalletTx
pub fn scan_block<P, AccountId, IvkTag>(
params: &P,
block: CompactBlock,
scanning_keys: &ScanningKeys<AccountId, IvkTag>,
nullifiers: &Nullifiers<AccountId>,
prior_block_metadata: Option<&BlockMetadata>,
) -> Result<ScannedBlock<AccountId>, ScanError>
where
P: consensus::Parameters + Send + 'static,
AccountId: Default + Eq + Hash + ConditionallySelectable + Send + 'static,
IvkTag: Copy + std::hash::Hash + Eq + Send + 'static,
{
scan_block_with_runners::<_, _, _, (), ()>(
params,
block,
scanning_keys,
nullifiers,
prior_block_metadata,
None,
)
}
type TaggedSaplingBatch<IvkTag> = Batch<
IvkTag,
SaplingDomain,
sapling::note_encryption::CompactOutputDescription,
CompactDecryptor,
>;
type TaggedSaplingBatchRunner<IvkTag, Tasks> = BatchRunner<
IvkTag,
SaplingDomain,
sapling::note_encryption::CompactOutputDescription,
CompactDecryptor,
Tasks,
>;
#[cfg(feature = "orchard")]
type TaggedOrchardBatch<IvkTag> =
Batch<IvkTag, OrchardDomain, orchard::note_encryption::CompactAction, CompactDecryptor>;
#[cfg(feature = "orchard")]
type TaggedOrchardBatchRunner<IvkTag, Tasks> = BatchRunner<
IvkTag,
OrchardDomain,
orchard::note_encryption::CompactAction,
CompactDecryptor,
Tasks,
>;
pub(crate) trait SaplingTasks<IvkTag>: Tasks<TaggedSaplingBatch<IvkTag>> {}
impl<IvkTag, T: Tasks<TaggedSaplingBatch<IvkTag>>> SaplingTasks<IvkTag> for T {}
#[cfg(not(feature = "orchard"))]
pub(crate) trait OrchardTasks<IvkTag> {}
#[cfg(not(feature = "orchard"))]
impl<IvkTag, T> OrchardTasks<IvkTag> for T {}
#[cfg(feature = "orchard")]
pub(crate) trait OrchardTasks<IvkTag>: Tasks<TaggedOrchardBatch<IvkTag>> {}
#[cfg(feature = "orchard")]
impl<IvkTag, T: Tasks<TaggedOrchardBatch<IvkTag>>> OrchardTasks<IvkTag> for T {}
pub(crate) struct BatchRunners<IvkTag, TS: SaplingTasks<IvkTag>, TO: OrchardTasks<IvkTag>> {
sapling: TaggedSaplingBatchRunner<IvkTag, TS>,
#[cfg(feature = "orchard")]
orchard: TaggedOrchardBatchRunner<IvkTag, TO>,
#[cfg(not(feature = "orchard"))]
orchard: PhantomData<TO>,
}
impl<IvkTag, TS, TO> BatchRunners<IvkTag, TS, TO>
where
IvkTag: Clone + Send + 'static,
TS: SaplingTasks<IvkTag>,
TO: OrchardTasks<IvkTag>,
{
pub(crate) fn for_keys<AccountId>(
batch_size_threshold: usize,
scanning_keys: &ScanningKeys<AccountId, IvkTag>,
) -> Self {
BatchRunners {
sapling: BatchRunner::new(
batch_size_threshold,
scanning_keys
.sapling()
.iter()
.map(|(id, key)| (id.clone(), key.prepare())),
),
#[cfg(feature = "orchard")]
orchard: BatchRunner::new(
batch_size_threshold,
scanning_keys
.orchard()
.iter()
.map(|(id, key)| (id.clone(), key.prepare())),
),
#[cfg(not(feature = "orchard"))]
orchard: PhantomData,
}
}
pub(crate) fn flush(&mut self) {
self.sapling.flush();
#[cfg(feature = "orchard")]
self.orchard.flush();
}
#[tracing::instrument(skip_all, fields(height = block.height))]
pub(crate) fn add_block<P>(&mut self, params: &P, block: CompactBlock) -> Result<(), ScanError>
where
P: consensus::Parameters + Send + 'static,
IvkTag: Copy + Send + 'static,
{
let block_hash = block.hash();
let block_height = block.height();
let zip212_enforcement = zip212_enforcement(params, block_height);
for tx in block.vtx.into_iter() {
let txid = tx.txid();
self.sapling.add_outputs(
block_hash,
txid,
|_| SaplingDomain::new(zip212_enforcement),
&tx.outputs
.iter()
.enumerate()
.map(|(i, output)| {
CompactOutputDescription::try_from(output).map_err(|_| {
ScanError::EncodingInvalid {
at_height: block_height,
txid,
pool_type: ShieldedProtocol::Sapling,
index: i,
}
})
})
.collect::<Result<Vec<_>, _>>()?,
);
#[cfg(feature = "orchard")]
self.orchard.add_outputs(
block_hash,
txid,
OrchardDomain::for_compact_action,
&tx.actions
.iter()
.enumerate()
.map(|(i, action)| {
CompactAction::try_from(action).map_err(|_| ScanError::EncodingInvalid {
at_height: block_height,
txid,
pool_type: ShieldedProtocol::Orchard,
index: i,
})
})
.collect::<Result<Vec<_>, _>>()?,
);
}
Ok(())
}
}
#[tracing::instrument(skip_all, fields(height = block.height))]
pub(crate) fn scan_block_with_runners<P, AccountId, IvkTag, TS, TO>(
params: &P,
block: CompactBlock,
scanning_keys: &ScanningKeys<AccountId, IvkTag>,
nullifiers: &Nullifiers<AccountId>,
prior_block_metadata: Option<&BlockMetadata>,
mut batch_runners: Option<&mut BatchRunners<IvkTag, TS, TO>>,
) -> Result<ScannedBlock<AccountId>, ScanError>
where
P: consensus::Parameters + Send + 'static,
AccountId: Default + Eq + Hash + ConditionallySelectable + Send + 'static,
IvkTag: Copy + std::hash::Hash + Eq + Send + 'static,
TS: SaplingTasks<IvkTag> + Sync,
TO: OrchardTasks<IvkTag> + Sync,
{
fn check_hash_continuity(
block: &CompactBlock,
prior_block_metadata: Option<&BlockMetadata>,
) -> Option<ScanError> {
if let Some(prev) = prior_block_metadata {
if block.height() != prev.block_height() + 1 {
debug!(
"Block height discontinuity at {:?}, previous was {:?} ",
block.height(),
prev.block_height()
);
return Some(ScanError::BlockHeightDiscontinuity {
prev_height: prev.block_height(),
new_height: block.height(),
});
}
if block.prev_hash() != prev.block_hash() {
debug!("Block hash discontinuity at {:?}", block.height());
return Some(ScanError::PrevHashMismatch {
at_height: block.height(),
});
}
}
None
}
if let Some(scan_error) = check_hash_continuity(&block, prior_block_metadata) {
return Err(scan_error);
}
trace!("Block continuity okay at {:?}", block.height());
let cur_height = block.height();
let cur_hash = block.hash();
let zip212_enforcement = zip212_enforcement(params, cur_height);
let mut sapling_commitment_tree_size = prior_block_metadata
.and_then(|m| m.sapling_tree_size())
.map_or_else(
|| {
block.chain_metadata.as_ref().map_or_else(
|| {
// If we're below Sapling activation, or Sapling activation is not set, the tree size is zero
params
.activation_height(NetworkUpgrade::Sapling)
.map_or_else(
|| Ok(0),
|sapling_activation| {
if cur_height < sapling_activation {
Ok(0)
} else {
Err(ScanError::TreeSizeUnknown {
protocol: ShieldedProtocol::Sapling,
at_height: cur_height,
})
}
},
)
},
|m| {
let sapling_output_count: u32 = block
.vtx
.iter()
.map(|tx| tx.outputs.len())
.sum::<usize>()
.try_into()
.expect("Sapling output count cannot exceed a u32");
// The default for m.sapling_commitment_tree_size is zero, so we need to check
// that the subtraction will not underflow; if it would do so, we were given
// invalid chain metadata for a block with Sapling outputs.
m.sapling_commitment_tree_size
.checked_sub(sapling_output_count)
.ok_or(ScanError::TreeSizeInvalid {
protocol: ShieldedProtocol::Sapling,
at_height: cur_height,
})
},
)
},
Ok,
)?;
let sapling_final_tree_size = sapling_commitment_tree_size
+ block
.vtx
.iter()
.map(|tx| u32::try_from(tx.outputs.len()).unwrap())
.sum::<u32>();
#[cfg(feature = "orchard")]
let mut orchard_commitment_tree_size = prior_block_metadata
.and_then(|m| m.orchard_tree_size())
.map_or_else(
|| {
block.chain_metadata.as_ref().map_or_else(
|| {
// If we're below Orchard activation, or Orchard activation is not set, the tree size is zero
params.activation_height(NetworkUpgrade::Nu5).map_or_else(
|| Ok(0),
|orchard_activation| {
if cur_height < orchard_activation {
Ok(0)
} else {
Err(ScanError::TreeSizeUnknown {
protocol: ShieldedProtocol::Orchard,
at_height: cur_height,
})
}
},
)
},
|m| {
let orchard_action_count: u32 = block
.vtx
.iter()
.map(|tx| tx.actions.len())
.sum::<usize>()
.try_into()
.expect("Orchard action count cannot exceed a u32");
// The default for m.orchard_commitment_tree_size is zero, so we need to check
// that the subtraction will not underflow; if it would do so, we were given
// invalid chain metadata for a block with Orchard actions.
m.orchard_commitment_tree_size
.checked_sub(orchard_action_count)
.ok_or(ScanError::TreeSizeInvalid {
protocol: ShieldedProtocol::Orchard,
at_height: cur_height,
})
},
)
},
Ok,
)?;
#[cfg(feature = "orchard")]
let orchard_final_tree_size = orchard_commitment_tree_size
+ block
.vtx
.iter()
.map(|tx| u32::try_from(tx.actions.len()).unwrap())
.sum::<u32>();
let mut wtxs: Vec<WalletTx<AccountId>> = vec![];
let mut sapling_nullifier_map = Vec::with_capacity(block.vtx.len());
let mut sapling_note_commitments: Vec<(sapling::Node, Retention<BlockHeight>)> = vec![];
#[cfg(feature = "orchard")]
let mut orchard_nullifier_map = Vec::with_capacity(block.vtx.len());
#[cfg(feature = "orchard")]
let mut orchard_note_commitments: Vec<(MerkleHashOrchard, Retention<BlockHeight>)> = vec![];
for tx in block.vtx.into_iter() {
let txid = tx.txid();
let tx_index =
u16::try_from(tx.index).expect("Cannot fit more than 2^16 transactions in a block");
let (sapling_spends, sapling_unlinked_nullifiers) = find_spent(
&tx.spends,
&nullifiers.sapling,
|spend| {
spend.nf().expect(
"Could not deserialize nullifier for spend from protobuf representation.",
)
},
WalletSpend::from_parts,
);
sapling_nullifier_map.push((txid, tx_index, sapling_unlinked_nullifiers));
#[cfg(feature = "orchard")]
let orchard_spends = {
let (orchard_spends, orchard_unlinked_nullifiers) = find_spent(
&tx.actions,
&nullifiers.orchard,
|spend| {
spend.nf().expect(
"Could not deserialize nullifier for spend from protobuf representation.",
)
},
WalletSpend::from_parts,
);
orchard_nullifier_map.push((txid, tx_index, orchard_unlinked_nullifiers));
orchard_spends
};
// Collect the set of accounts that were spent from in this transaction
let spent_from_accounts = sapling_spends.iter().map(|spend| spend.account_id());
#[cfg(feature = "orchard")]
let spent_from_accounts =
spent_from_accounts.chain(orchard_spends.iter().map(|spend| spend.account_id()));
let spent_from_accounts = spent_from_accounts.copied().collect::<HashSet<_>>();
let (sapling_outputs, mut sapling_nc) = find_received(
cur_height,
sapling_final_tree_size
== sapling_commitment_tree_size + u32::try_from(tx.outputs.len()).unwrap(),
txid,
sapling_commitment_tree_size,
&scanning_keys.sapling,
&spent_from_accounts,
&tx.outputs
.iter()
.enumerate()
.map(|(i, output)| {
Ok((
SaplingDomain::new(zip212_enforcement),
CompactOutputDescription::try_from(output).map_err(|_| {
ScanError::EncodingInvalid {
at_height: cur_height,
txid,
pool_type: ShieldedProtocol::Sapling,
index: i,
}
})?,
))
})
.collect::<Result<Vec<_>, _>>()?,
batch_runners
.as_mut()
.map(|runners| |txid| runners.sapling.collect_results(cur_hash, txid)),
|output| sapling::Node::from_cmu(&output.cmu),
);
sapling_note_commitments.append(&mut sapling_nc);
let has_sapling = !(sapling_spends.is_empty() && sapling_outputs.is_empty());
#[cfg(feature = "orchard")]
let (orchard_outputs, mut orchard_nc) = find_received(
cur_height,
orchard_final_tree_size
== orchard_commitment_tree_size + u32::try_from(tx.actions.len()).unwrap(),
txid,
orchard_commitment_tree_size,
&scanning_keys.orchard,
&spent_from_accounts,
&tx.actions
.iter()
.enumerate()
.map(|(i, action)| {
let action = CompactAction::try_from(action).map_err(|_| {
ScanError::EncodingInvalid {
at_height: cur_height,
txid,
pool_type: ShieldedProtocol::Orchard,
index: i,
}
})?;
Ok((OrchardDomain::for_compact_action(&action), action))
})
.collect::<Result<Vec<_>, _>>()?,
batch_runners
.as_mut()
.map(|runners| |txid| runners.orchard.collect_results(cur_hash, txid)),
|output| MerkleHashOrchard::from_cmx(&output.cmx()),
);
#[cfg(feature = "orchard")]
orchard_note_commitments.append(&mut orchard_nc);
#[cfg(feature = "orchard")]
let has_orchard = !(orchard_spends.is_empty() && orchard_outputs.is_empty());
#[cfg(not(feature = "orchard"))]
let has_orchard = false;
if has_sapling || has_orchard {
wtxs.push(WalletTx::new(
txid,
tx_index as usize,
sapling_spends,
sapling_outputs,
#[cfg(feature = "orchard")]
orchard_spends,
#[cfg(feature = "orchard")]
orchard_outputs,
));
}
sapling_commitment_tree_size +=
u32::try_from(tx.outputs.len()).expect("Sapling output count cannot exceed a u32");
#[cfg(feature = "orchard")]
{
orchard_commitment_tree_size +=
u32::try_from(tx.actions.len()).expect("Orchard action count cannot exceed a u32");
}
}
if let Some(chain_meta) = block.chain_metadata {
if chain_meta.sapling_commitment_tree_size != sapling_commitment_tree_size {
return Err(ScanError::TreeSizeMismatch {
protocol: ShieldedProtocol::Sapling,
at_height: cur_height,
given: chain_meta.sapling_commitment_tree_size,
computed: sapling_commitment_tree_size,
});
}
#[cfg(feature = "orchard")]
if chain_meta.orchard_commitment_tree_size != orchard_commitment_tree_size {
return Err(ScanError::TreeSizeMismatch {
protocol: ShieldedProtocol::Orchard,
at_height: cur_height,
given: chain_meta.orchard_commitment_tree_size,
computed: orchard_commitment_tree_size,
});
}
}
Ok(ScannedBlock::from_parts(
cur_height,
cur_hash,
block.time,
wtxs,
ScannedBundles::new(
sapling_commitment_tree_size,
sapling_note_commitments,
sapling_nullifier_map,
),
#[cfg(feature = "orchard")]
ScannedBundles::new(
orchard_commitment_tree_size,
orchard_note_commitments,
orchard_nullifier_map,
),
))
}
/// Check for spent notes. The comparison against known-unspent nullifiers is done
/// in constant time.
fn find_spent<
AccountId: ConditionallySelectable + Default,
Spend,
Nf: ConstantTimeEq + Copy,
WS,
>(
spends: &[Spend],
nullifiers: &[(AccountId, Nf)],
extract_nf: impl Fn(&Spend) -> Nf,