-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathchain.rs
More file actions
2742 lines (2469 loc) · 106 KB
/
Copy pathchain.rs
File metadata and controls
2742 lines (2469 loc) · 106 KB
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
//! [`Chain`] implements a single non-finalized blockchain,
//! starting at the finalized tip.
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
ops::{Deref, DerefMut, RangeInclusive},
sync::Arc,
};
use chrono::{DateTime, Utc};
use mset::MultiSet;
use tracing::instrument;
use zebra_chain::{
amount::{Amount, NegativeAllowed, NonNegative},
block::{self, Height},
block_info::BlockInfo,
history_tree::HistoryTree,
ironwood, orchard,
parallel::tree::NoteCommitmentTrees,
parameters::Network,
primitives::zcash_history::BlockCommitmentTreeRoots,
primitives::Groth16Proof,
sapling,
serialization::ZcashSerialize as _,
sprout,
subtree::{NoteCommitmentSubtree, NoteCommitmentSubtreeData, NoteCommitmentSubtreeIndex},
transaction::{
self,
Transaction::{self, *},
},
transparent,
value_balance::ValueBalance,
work::difficulty::PartialCumulativeWork,
};
use crate::{
request::Treestate, service::check, ContextuallyVerifiedBlock, HashOrHeight, OutputLocation,
TransactionLocation, ValidateContextError,
};
#[cfg(feature = "indexer")]
use crate::request::Spend;
use self::index::TransparentTransfers;
pub mod index;
/// A single non-finalized partial chain, from the child of the finalized tip,
/// to a non-finalized chain tip.
#[derive(Clone, Debug, Default)]
pub struct Chain {
// Config
//
/// The configured network for this chain.
network: Network,
/// The internal state of this chain.
inner: ChainInner,
// Diagnostics
//
/// The last height this chain forked at. Diagnostics only.
///
/// This field is only used for metrics. It is not consensus-critical, and it is not checked for
/// equality.
///
/// We keep the same last fork height in both sides of a clone, because every new block clones a
/// chain, even if it's just growing that chain.
///
/// # Note
///
/// Most diagnostics are implemented on the `NonFinalizedState`, rather than each chain. Some
/// diagnostics only use the best chain, and others need to modify the Chain state, but that's
/// difficult with `Arc<Chain>`s.
pub(super) last_fork_height: Option<Height>,
}
/// Spending transaction id type when the `indexer` feature is selected.
#[cfg(feature = "indexer")]
pub(crate) type SpendingTransactionId = transaction::Hash;
/// Spending transaction id type when the `indexer` feature is not selected.
#[cfg(not(feature = "indexer"))]
pub(crate) type SpendingTransactionId = ();
/// The internal state of [`Chain`].
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ChainInner {
// Blocks, heights, hashes, and transaction locations
//
/// The contextually valid blocks which form this non-finalized partial chain, in height order.
pub(crate) blocks: BTreeMap<block::Height, ContextuallyVerifiedBlock>,
/// An index of block heights for each block hash in `blocks`.
pub height_by_hash: HashMap<block::Hash, block::Height>,
/// An index of [`TransactionLocation`]s for each transaction hash in `blocks`.
pub tx_loc_by_hash: HashMap<transaction::Hash, TransactionLocation>,
// Transparent outputs and spends
//
/// The [`transparent::Utxo`]s created by `blocks`.
///
/// Note that these UTXOs may not be unspent.
/// Outputs can be spent by later transactions or blocks in the chain.
//
// TODO: replace OutPoint with OutputLocation?
pub(crate) created_utxos: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
/// The spending transaction ids by [`transparent::OutPoint`]s spent by `blocks`,
/// including spent outputs created by earlier transactions or blocks in the chain.
///
/// Note: Spending transaction ids are only tracked when the `indexer` feature is selected.
pub(crate) spent_utxos: HashMap<transparent::OutPoint, SpendingTransactionId>,
// Note commitment trees
//
/// The Sprout note commitment tree for each anchor.
/// This is required for interstitial states.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) sprout_trees_by_anchor:
HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>>,
/// The Sprout note commitment tree for each height.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip tree.
/// This extra tree is removed when the first non-finalized block is committed.
pub(crate) sprout_trees_by_height:
BTreeMap<block::Height, Arc<sprout::tree::NoteCommitmentTree>>,
/// The Sapling note commitment tree for each height.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip tree.
/// This extra tree is removed when the first non-finalized block is committed.
pub(crate) sapling_trees_by_height:
BTreeMap<block::Height, Arc<sapling::tree::NoteCommitmentTree>>,
/// The Orchard note commitment tree for each height.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip tree.
/// This extra tree is removed when the first non-finalized block is committed.
pub(crate) orchard_trees_by_height:
BTreeMap<block::Height, Arc<orchard::tree::NoteCommitmentTree>>,
/// The Ironwood note commitment tree for each height (NU6.3).
///
/// Ironwood reuses the Orchard tree type. When a chain is forked from the finalized tip, also
/// contains the finalized tip tree, which is removed when the first non-finalized block is
/// committed.
pub(crate) ironwood_trees_by_height:
BTreeMap<block::Height, Arc<orchard::tree::NoteCommitmentTree>>,
// History trees
//
/// The ZIP-221 history tree for each height, including all finalized blocks,
/// and the non-finalized `blocks` below that height in this chain.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip tree.
/// This extra tree is removed when the first non-finalized block is committed.
pub(crate) history_trees_by_height: BTreeMap<block::Height, Arc<HistoryTree>>,
// Anchors
//
/// The Sprout anchors created by `blocks`.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) sprout_anchors: MultiSet<sprout::tree::Root>,
/// The Sprout anchors created by each block in `blocks`.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) sprout_anchors_by_height: BTreeMap<block::Height, sprout::tree::Root>,
/// The Sapling anchors created by `blocks`.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) sapling_anchors: MultiSet<sapling::tree::Root>,
/// The Sapling anchors created by each block in `blocks`.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) sapling_anchors_by_height: BTreeMap<block::Height, sapling::tree::Root>,
/// A list of Sapling subtrees completed in the non-finalized state
pub(crate) sapling_subtrees:
BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<sapling_crypto::Node>>,
/// The Orchard anchors created by `blocks`.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) orchard_anchors: MultiSet<orchard::tree::Root>,
/// The Orchard anchors created by each block in `blocks`.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root.
/// This extra root is removed when the first non-finalized block is committed.
pub(crate) orchard_anchors_by_height: BTreeMap<block::Height, orchard::tree::Root>,
/// A list of Orchard subtrees completed in the non-finalized state
pub(crate) orchard_subtrees:
BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>>,
/// The Ironwood anchors created by `blocks` (NU6.3). Reuses the Orchard tree root type.
///
/// When a chain is forked from the finalized tip, also contains the finalized tip root, which
/// is removed when the first non-finalized block is committed.
pub(crate) ironwood_anchors: MultiSet<orchard::tree::Root>,
/// The Ironwood anchors created by each block in `blocks`.
pub(crate) ironwood_anchors_by_height: BTreeMap<block::Height, orchard::tree::Root>,
/// A list of Ironwood subtrees completed in the non-finalized state.
pub(crate) ironwood_subtrees:
BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>>,
// Nullifiers
//
/// The Sprout nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
/// the id of the transaction that revealed them.
pub(crate) sprout_nullifiers: HashMap<sprout::Nullifier, SpendingTransactionId>,
/// The Sapling nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
/// the id of the transaction that revealed them.
pub(crate) sapling_nullifiers: HashMap<sapling::Nullifier, SpendingTransactionId>,
/// The Orchard nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
/// the id of the transaction that revealed them.
pub(crate) orchard_nullifiers: HashMap<orchard::Nullifier, SpendingTransactionId>,
/// The Ironwood nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
/// the id of the transaction that revealed them.
pub(crate) ironwood_nullifiers: HashMap<ironwood::Nullifier, SpendingTransactionId>,
// Transparent Transfers
// TODO: move to the transparent section
//
/// Partial transparent address index data from `blocks`.
pub(super) partial_transparent_transfers: HashMap<transparent::Address, TransparentTransfers>,
// Chain Work
//
/// The cumulative work represented by `blocks`.
///
/// Since the best chain is determined by the largest cumulative work,
/// the work represented by finalized blocks can be ignored,
/// because they are common to all non-finalized chains.
pub(super) partial_cumulative_work: PartialCumulativeWork,
// Chain Pools
//
/// The chain value pool balances of the tip of this [`Chain`], including the block value pool
/// changes from all finalized blocks, and the non-finalized blocks in this chain.
///
/// When a new chain is created from the finalized tip, it is initialized with the finalized tip
/// chain value pool balances.
pub(crate) chain_value_pools: ValueBalance<NonNegative>,
/// The block info after the given block height.
pub(crate) block_info_by_height: BTreeMap<block::Height, BlockInfo>,
}
impl Chain {
/// Create a new Chain with the given finalized tip trees and network.
///
/// The subtree fields of `note_commitment_trees` are unused: a forked chain starts tracking
/// subtrees from empty and fills them from its own block commits.
pub(crate) fn new(
network: &Network,
finalized_tip_height: Height,
note_commitment_trees: NoteCommitmentTrees,
history_tree: Arc<HistoryTree>,
finalized_tip_chain_value_pools: ValueBalance<NonNegative>,
) -> Self {
// Passing the trees in a named struct (rather than four adjacent positional arguments, two
// of them the same `Arc<orchard::tree::NoteCommitmentTree>` type) makes an orchard/ironwood
// swap a compile error instead of silent tree corruption.
let NoteCommitmentTrees {
sprout: sprout_note_commitment_tree,
sapling: sapling_note_commitment_tree,
orchard: orchard_note_commitment_tree,
ironwood: ironwood_note_commitment_tree,
..
} = note_commitment_trees;
let inner = ChainInner {
blocks: Default::default(),
height_by_hash: Default::default(),
tx_loc_by_hash: Default::default(),
created_utxos: Default::default(),
spent_utxos: Default::default(),
sprout_anchors: MultiSet::new(),
sprout_anchors_by_height: Default::default(),
sprout_trees_by_anchor: Default::default(),
sprout_trees_by_height: Default::default(),
sapling_anchors: MultiSet::new(),
sapling_anchors_by_height: Default::default(),
sapling_trees_by_height: Default::default(),
sapling_subtrees: Default::default(),
orchard_anchors: MultiSet::new(),
orchard_anchors_by_height: Default::default(),
orchard_trees_by_height: Default::default(),
orchard_subtrees: Default::default(),
ironwood_anchors: MultiSet::new(),
ironwood_anchors_by_height: Default::default(),
ironwood_trees_by_height: Default::default(),
ironwood_subtrees: Default::default(),
sprout_nullifiers: Default::default(),
sapling_nullifiers: Default::default(),
orchard_nullifiers: Default::default(),
ironwood_nullifiers: Default::default(),
partial_transparent_transfers: Default::default(),
partial_cumulative_work: Default::default(),
history_trees_by_height: Default::default(),
chain_value_pools: finalized_tip_chain_value_pools,
block_info_by_height: Default::default(),
};
let mut chain = Self {
network: network.clone(),
inner,
last_fork_height: None,
};
chain.add_sprout_tree_and_anchor(finalized_tip_height, sprout_note_commitment_tree);
chain.add_sapling_tree_and_anchor(finalized_tip_height, sapling_note_commitment_tree);
chain.add_orchard_tree_and_anchor(finalized_tip_height, orchard_note_commitment_tree);
chain.add_ironwood_tree_and_anchor(finalized_tip_height, ironwood_note_commitment_tree);
chain.add_history_tree(finalized_tip_height, history_tree);
chain
}
/// Is the internal state of `self` the same as `other`?
///
/// [`Chain`] has custom [`Eq`] and [`Ord`] implementations based on proof of work,
/// which are used to select the best chain. So we can't derive [`Eq`] for [`Chain`].
///
/// Unlike the custom trait impls, this method returns `true` if the entire internal state
/// of two chains is equal.
///
/// If the internal states are different, it returns `false`,
/// even if the blocks in the two chains are equal.
#[cfg(any(test, feature = "proptest-impl"))]
pub fn eq_internal_state(&self, other: &Chain) -> bool {
self.inner == other.inner
}
/// Returns the last fork height if that height is still in the non-finalized state.
/// Otherwise, if that fork has been finalized, returns `None`.
#[allow(dead_code)]
pub fn recent_fork_height(&self) -> Option<Height> {
self.last_fork_height
.filter(|last| last >= &self.non_finalized_root_height())
}
/// Returns this chain fork's length, if its fork is still in the non-finalized state.
/// Otherwise, if the fork has been finalized, returns `None`.
#[allow(dead_code)]
pub fn recent_fork_length(&self) -> Option<u32> {
let fork_length = self.non_finalized_tip_height() - self.recent_fork_height()?;
// If the fork is above the tip, it is invalid, so just return `None`
// (Ignoring invalid data is ok because this is metrics-only code.)
fork_length.try_into().ok()
}
/// Push a contextually valid non-finalized block into this chain as the new tip.
///
/// If the block is invalid, drops this chain, and returns an error.
///
/// Note: a [`ContextuallyVerifiedBlock`] isn't actually contextually valid until
/// [`Self::update_chain_tip_with`] returns success.
#[instrument(level = "debug", skip(self, block), fields(block = %block.block))]
pub fn push(mut self, block: ContextuallyVerifiedBlock) -> Result<Chain, ValidateContextError> {
// update cumulative data members
self.update_chain_tip_with(&block)?;
tracing::debug!(block = %block.block, "adding block to chain");
self.blocks.insert(block.height, block);
Ok(self)
}
/// Pops the lowest height block of the non-finalized portion of a chain,
/// and returns it with its associated treestate.
#[instrument(level = "debug", skip(self))]
pub(crate) fn pop_root(&mut self) -> (ContextuallyVerifiedBlock, Treestate) {
// Obtain the lowest height.
let block_height = self.non_finalized_root_height();
// Obtain the treestate associated with the block being finalized.
let treestate = self
.treestate(block_height.into())
.expect("The treestate must be present for the root height.");
if treestate.note_commitment_trees.sapling_subtree.is_some() {
self.sapling_subtrees.pop_first();
}
if treestate.note_commitment_trees.orchard_subtree.is_some() {
self.orchard_subtrees.pop_first();
}
if treestate.note_commitment_trees.ironwood_subtree.is_some() {
self.ironwood_subtrees.pop_first();
}
// Remove the lowest height block from `self.blocks`.
let block = self
.blocks
.remove(&block_height)
.expect("only called while blocks is populated");
// Update cumulative data members.
self.revert_chain_with(&block, RevertPosition::Root);
(block, treestate)
}
/// Returns the block at the provided height and all of its descendant blocks.
pub fn child_blocks(&self, block_height: &block::Height) -> Vec<ContextuallyVerifiedBlock> {
self.blocks
.range(block_height..)
.map(|(_h, b)| b.clone())
.collect()
}
/// Returns a new chain without the invalidated block or its descendants.
pub fn invalidate_block(
&self,
block_hash: block::Hash,
) -> Option<(Self, Vec<ContextuallyVerifiedBlock>)> {
let block_height = self.height_by_hash(block_hash)?;
let mut new_chain = self.fork(block_hash)?;
new_chain.pop_tip();
new_chain.last_fork_height = self.last_fork_height.min(Some(block_height));
Some((new_chain, self.child_blocks(&block_height)))
}
/// Returns the height of the chain root.
pub fn non_finalized_root_height(&self) -> block::Height {
self.blocks
.keys()
.next()
.cloned()
.expect("only called while blocks is populated")
}
/// Fork and return a chain at the block with the given `fork_tip`, if it is part of this
/// chain. Otherwise, if this chain does not contain `fork_tip`, returns `None`.
pub fn fork(&self, fork_tip: block::Hash) -> Option<Self> {
if !self.height_by_hash.contains_key(&fork_tip) {
return None;
}
let mut forked = self.clone();
// Revert blocks above the fork
while forked.non_finalized_tip_hash() != fork_tip {
forked.pop_tip();
forked.last_fork_height = Some(forked.non_finalized_tip_height());
}
Some(forked)
}
/// Returns the [`Network`] for this chain.
pub fn network(&self) -> Network {
self.network.clone()
}
/// Returns the [`ContextuallyVerifiedBlock`] with [`block::Hash`] or
/// [`Height`], if it exists in this chain.
pub fn block(&self, hash_or_height: HashOrHeight) -> Option<&ContextuallyVerifiedBlock> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
self.blocks.get(&height)
}
/// Returns the [`Transaction`] with [`transaction::Hash`], if it exists in this chain.
pub fn transaction(
&self,
hash: transaction::Hash,
) -> Option<(&Arc<Transaction>, block::Height, DateTime<Utc>)> {
self.tx_loc_by_hash.get(&hash).map(|tx_loc| {
(
&self.blocks[&tx_loc.height].block.transactions[tx_loc.index.as_usize()],
tx_loc.height,
self.blocks[&tx_loc.height].block.header.time,
)
})
}
/// Returns the [`Transaction`] at [`TransactionLocation`], if it exists in this chain.
#[allow(dead_code)]
pub fn transaction_by_loc(&self, tx_loc: TransactionLocation) -> Option<&Arc<Transaction>> {
self.blocks
.get(&tx_loc.height)?
.block
.transactions
.get(tx_loc.index.as_usize())
}
/// Returns the [`transaction::Hash`] for the transaction at [`TransactionLocation`],
/// if it exists in this chain.
#[allow(dead_code)]
pub fn transaction_hash_by_loc(
&self,
tx_loc: TransactionLocation,
) -> Option<&transaction::Hash> {
self.blocks
.get(&tx_loc.height)?
.transaction_hashes
.get(tx_loc.index.as_usize())
}
/// Returns the [`transaction::Hash`]es in the block with `hash_or_height`,
/// if it exists in this chain.
///
/// Hashes are returned in block order.
///
/// Returns `None` if the block is not found.
pub fn transaction_hashes_for_block(
&self,
hash_or_height: HashOrHeight,
) -> Option<Arc<[transaction::Hash]>> {
let transaction_hashes = self.block(hash_or_height)?.transaction_hashes.clone();
Some(transaction_hashes)
}
/// Returns the [`block::Hash`] for `height`, if it exists in this chain.
pub fn hash_by_height(&self, height: Height) -> Option<block::Hash> {
let hash = self.blocks.get(&height)?.hash;
Some(hash)
}
/// Returns the [`Height`] for `hash`, if it exists in this chain.
pub fn height_by_hash(&self, hash: block::Hash) -> Option<Height> {
self.height_by_hash.get(&hash).cloned()
}
/// Returns true is the chain contains the given block hash.
/// Returns false otherwise.
pub fn contains_block_hash(&self, hash: block::Hash) -> bool {
self.height_by_hash.contains_key(&hash)
}
/// Returns true is the chain contains the given block height.
/// Returns false otherwise.
pub fn contains_block_height(&self, height: Height) -> bool {
self.blocks.contains_key(&height)
}
/// Returns true is the chain contains the given block hash or height.
/// Returns false otherwise.
#[allow(dead_code)]
pub fn contains_hash_or_height(&self, hash_or_height: impl Into<HashOrHeight>) -> bool {
use HashOrHeight::*;
let hash_or_height = hash_or_height.into();
match hash_or_height {
Hash(hash) => self.contains_block_hash(hash),
Height(height) => self.contains_block_height(height),
}
}
/// Returns the non-finalized tip block height and hash.
pub fn non_finalized_tip(&self) -> (Height, block::Hash) {
(
self.non_finalized_tip_height(),
self.non_finalized_tip_hash(),
)
}
/// Returns the non-finalized tip block height, hash, and total pool value balances.
pub fn non_finalized_tip_with_value_balance(
&self,
) -> (Height, block::Hash, ValueBalance<NonNegative>) {
(
self.non_finalized_tip_height(),
self.non_finalized_tip_hash(),
self.chain_value_pools,
)
}
/// Returns the total pool balance after the block specified by
/// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
pub fn block_info(&self, hash_or_height: HashOrHeight) -> Option<BlockInfo> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
self.block_info_by_height.get(&height).cloned()
}
/// Returns the Sprout note commitment tree of the tip of this [`Chain`],
/// including all finalized notes, and the non-finalized notes in this chain.
///
/// If the chain is empty, instead returns the tree of the finalized tip,
/// which was supplied in [`Chain::new()`]
///
/// # Panics
///
/// If this chain has no sprout trees. (This should be impossible.)
pub fn sprout_note_commitment_tree_for_tip(&self) -> Arc<sprout::tree::NoteCommitmentTree> {
self.sprout_trees_by_height
.last_key_value()
.expect("only called while sprout_trees_by_height is populated")
.1
.clone()
}
/// Returns the Sprout [`NoteCommitmentTree`](sprout::tree::NoteCommitmentTree) specified by
/// a [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
pub fn sprout_tree(
&self,
hash_or_height: HashOrHeight,
) -> Option<Arc<sprout::tree::NoteCommitmentTree>> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
self.sprout_trees_by_height
.range(..=height)
.next_back()
.map(|(_height, tree)| tree.clone())
}
/// Adds the Sprout `tree` to the tree and anchor indexes at `height`.
///
/// `height` can be either:
///
/// - the height of a new block that has just been added to the chain tip, or
/// - the finalized tip height—the height of the parent of the first block of a new chain.
///
/// Stores only the first tree in each series of identical trees.
///
/// # Panics
///
/// - If there's a tree already stored at `height`.
/// - If there's an anchor already stored at `height`.
fn add_sprout_tree_and_anchor(
&mut self,
height: Height,
tree: Arc<sprout::tree::NoteCommitmentTree>,
) {
// Having updated all the note commitment trees and nullifier sets in
// this block, the roots of the note commitment trees as of the last
// transaction are the anchor treestates of this block.
//
// Use the previously cached root which was calculated in parallel.
let anchor = tree.root();
trace!(?height, ?anchor, "adding sprout tree");
// Add the new tree only if:
//
// - it differs from the previous one, or
// - there's no previous tree.
if height.is_min()
|| self
.sprout_tree(height.previous().expect("prev height").into())
.is_none_or(|prev_tree| prev_tree != tree)
{
assert_eq!(
self.sprout_trees_by_height.insert(height, tree.clone()),
None,
"incorrect overwrite of sprout tree: trees must be reverted then inserted",
);
}
// Store the root.
assert_eq!(
self.sprout_anchors_by_height.insert(height, anchor),
None,
"incorrect overwrite of sprout anchor: anchors must be reverted then inserted",
);
// Multiple inserts are expected here,
// because the anchors only change if a block has shielded transactions.
self.sprout_anchors.insert(anchor);
self.sprout_trees_by_anchor.insert(anchor, tree);
}
/// Removes the Sprout tree and anchor indexes at `height`.
///
/// `height` can be at two different [`RevertPosition`]s in the chain:
///
/// - a tip block above a chain fork—only the tree and anchor at that height are removed, or
/// - a root block—all trees and anchors at and below that height are removed, including
/// temporary finalized tip trees.
///
/// # Panics
///
/// - If the anchor being removed is not present.
/// - If there is no tree at `height`.
fn remove_sprout_tree_and_anchor(&mut self, position: RevertPosition, height: Height) {
let (removed_heights, highest_removed_tree) = if position == RevertPosition::Root {
(
// Remove all trees and anchors at or below the removed block.
// This makes sure the temporary trees from finalized tip forks are removed.
self.sprout_anchors_by_height
.keys()
.cloned()
.filter(|index_height| *index_height <= height)
.collect(),
// Cache the highest (rightmost) tree before its removal.
self.sprout_tree(height.into()),
)
} else {
// Just remove the reverted tip trees and anchors.
// We don't need to cache the highest (rightmost) tree.
(vec![height], None)
};
for height in &removed_heights {
let anchor = self
.sprout_anchors_by_height
.remove(height)
.expect("Sprout anchor must be present if block was added to chain");
self.sprout_trees_by_height.remove(height);
trace!(?height, ?position, ?anchor, "removing sprout tree");
// Multiple removals are expected here,
// because the anchors only change if a block has shielded transactions.
assert!(
self.sprout_anchors.remove(&anchor),
"Sprout anchor must be present if block was added to chain"
);
if !self.sprout_anchors.contains(&anchor) {
self.sprout_trees_by_anchor.remove(&anchor);
}
}
// # Invariant
//
// The height following after the removed heights in a non-empty non-finalized state must
// always have its tree.
//
// The loop above can violate the invariant, and if `position` is [`RevertPosition::Root`],
// it will always violate the invariant. We restore the invariant by storing the highest
// (rightmost) removed tree just above `height` if there is no tree at that height.
if !self.is_empty() && height < self.non_finalized_tip_height() {
let next_height = height
.next()
.expect("Zebra should never reach the max height in normal operation.");
self.sprout_trees_by_height
.entry(next_height)
.or_insert_with(|| {
highest_removed_tree.expect("There should be a cached removed tree.")
});
}
}
/// Returns the Sapling note commitment tree of the tip of this [`Chain`],
/// including all finalized notes, and the non-finalized notes in this chain.
///
/// If the chain is empty, instead returns the tree of the finalized tip,
/// which was supplied in [`Chain::new()`]
///
/// # Panics
///
/// If this chain has no sapling trees. (This should be impossible.)
pub fn sapling_note_commitment_tree_for_tip(&self) -> Arc<sapling::tree::NoteCommitmentTree> {
self.sapling_trees_by_height
.last_key_value()
.expect("only called while sapling_trees_by_height is populated")
.1
.clone()
}
/// Returns the Sapling [`NoteCommitmentTree`](sapling::tree::NoteCommitmentTree) specified
/// by a [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
pub fn sapling_tree(
&self,
hash_or_height: HashOrHeight,
) -> Option<Arc<sapling::tree::NoteCommitmentTree>> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
self.sapling_trees_by_height
.range(..=height)
.next_back()
.map(|(_height, tree)| tree.clone())
}
/// Returns the Sapling [`NoteCommitmentSubtree`] that was completed at a block with
/// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
///
/// # Concurrency
///
/// This method should not be used to get subtrees in concurrent code by height,
/// because the same heights in different chain forks can have different subtrees.
pub fn sapling_subtree(
&self,
hash_or_height: HashOrHeight,
) -> Option<NoteCommitmentSubtree<sapling_crypto::Node>> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
self.sapling_subtrees
.iter()
.find(|(_index, subtree)| subtree.end_height == height)
.map(|(index, subtree)| subtree.with_index(*index))
}
/// Returns a list of Sapling [`NoteCommitmentSubtree`]s in the provided range.
///
/// Unlike the finalized state and `ReadRequest::SaplingSubtrees`, the returned subtrees
/// can start after `start_index`. These subtrees are continuous up to the tip.
///
/// There is no API for retrieving single subtrees by index, because it can accidentally be
/// used to create an inconsistent list of subtrees after concurrent non-finalized and
/// finalized updates.
pub fn sapling_subtrees_in_range(
&self,
range: impl std::ops::RangeBounds<NoteCommitmentSubtreeIndex>,
) -> BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<sapling_crypto::Node>> {
self.sapling_subtrees
.range(range)
.map(|(index, subtree)| (*index, *subtree))
.collect()
}
/// Returns the Sapling [`NoteCommitmentSubtree`] if it was completed at the tip height.
pub fn sapling_subtree_for_tip(&self) -> Option<NoteCommitmentSubtree<sapling_crypto::Node>> {
if !self.is_empty() {
let tip = self.non_finalized_tip_height();
self.sapling_subtree(tip.into())
} else {
None
}
}
/// Adds the Sapling `tree` to the tree and anchor indexes at `height`.
///
/// `height` can be either:
///
/// - the height of a new block that has just been added to the chain tip, or
/// - the finalized tip height—the height of the parent of the first block of a new chain.
///
/// Stores only the first tree in each series of identical trees.
///
/// # Panics
///
/// - If there's a tree already stored at `height`.
/// - If there's an anchor already stored at `height`.
fn add_sapling_tree_and_anchor(
&mut self,
height: Height,
tree: Arc<sapling::tree::NoteCommitmentTree>,
) {
let anchor = tree.root();
trace!(?height, ?anchor, "adding sapling tree");
// Add the new tree only if:
//
// - it differs from the previous one, or
// - there's no previous tree.
if height.is_min()
|| self
.sapling_tree(height.previous().expect("prev height").into())
.is_none_or(|prev_tree| prev_tree != tree)
{
assert_eq!(
self.sapling_trees_by_height.insert(height, tree),
None,
"incorrect overwrite of sapling tree: trees must be reverted then inserted",
);
}
// Store the root.
assert_eq!(
self.sapling_anchors_by_height.insert(height, anchor),
None,
"incorrect overwrite of sapling anchor: anchors must be reverted then inserted",
);
// Multiple inserts are expected here,
// because the anchors only change if a block has shielded transactions.
self.sapling_anchors.insert(anchor);
}
/// Removes the Sapling tree and anchor indexes at `height`.
///
/// `height` can be at two different [`RevertPosition`]s in the chain:
///
/// - a tip block above a chain fork—only the tree and anchor at that height are removed, or
/// - a root block—all trees and anchors at and below that height are removed, including
/// temporary finalized tip trees.
///
/// # Panics
///
/// - If the anchor being removed is not present.
/// - If there is no tree at `height`.
fn remove_sapling_tree_and_anchor(&mut self, position: RevertPosition, height: Height) {
let (removed_heights, highest_removed_tree) = if position == RevertPosition::Root {
(
// Remove all trees and anchors at or below the removed block.
// This makes sure the temporary trees from finalized tip forks are removed.
self.sapling_anchors_by_height
.keys()
.cloned()
.filter(|index_height| *index_height <= height)
.collect(),
// Cache the highest (rightmost) tree before its removal.
self.sapling_tree(height.into()),
)
} else {
// Just remove the reverted tip trees and anchors.
// We don't need to cache the highest (rightmost) tree.
(vec![height], None)
};
for height in &removed_heights {
let anchor = self
.sapling_anchors_by_height
.remove(height)
.expect("Sapling anchor must be present if block was added to chain");
self.sapling_trees_by_height.remove(height);
trace!(?height, ?position, ?anchor, "removing sapling tree");
// Multiple removals are expected here,
// because the anchors only change if a block has shielded transactions.
assert!(
self.sapling_anchors.remove(&anchor),
"Sapling anchor must be present if block was added to chain"
);
}
// # Invariant
//
// The height following after the removed heights in a non-empty non-finalized state must
// always have its tree.
//
// The loop above can violate the invariant, and if `position` is [`RevertPosition::Root`],
// it will always violate the invariant. We restore the invariant by storing the highest
// (rightmost) removed tree just above `height` if there is no tree at that height.
if !self.is_empty() && height < self.non_finalized_tip_height() {
let next_height = height
.next()
.expect("Zebra should never reach the max height in normal operation.");
self.sapling_trees_by_height
.entry(next_height)
.or_insert_with(|| {
highest_removed_tree.expect("There should be a cached removed tree.")
});
}
}
/// Returns the Orchard note commitment tree of the tip of this [`Chain`],
/// including all finalized notes, and the non-finalized notes in this chain.
///
/// If the chain is empty, instead returns the tree of the finalized tip,
/// which was supplied in [`Chain::new()`]
///
/// # Panics
///
/// If this chain has no orchard trees. (This should be impossible.)
pub fn orchard_note_commitment_tree_for_tip(&self) -> Arc<orchard::tree::NoteCommitmentTree> {
self.orchard_trees_by_height
.last_key_value()
.expect("only called while orchard_trees_by_height is populated")
.1
.clone()
}
/// Returns the Orchard
/// [`NoteCommitmentTree`](orchard::tree::NoteCommitmentTree) specified by a
/// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
pub fn orchard_tree(
&self,
hash_or_height: HashOrHeight,
) -> Option<Arc<orchard::tree::NoteCommitmentTree>> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
self.orchard_trees_by_height
.range(..=height)
.next_back()
.map(|(_height, tree)| tree.clone())
}
/// Returns the Orchard [`NoteCommitmentSubtree`] that was completed at a block with
/// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
///
/// # Concurrency
///
/// This method should not be used to get subtrees in concurrent code by height,
/// because the same heights in different chain forks can have different subtrees.
pub fn orchard_subtree(
&self,
hash_or_height: HashOrHeight,
) -> Option<NoteCommitmentSubtree<orchard::tree::Node>> {
let height =
hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;