-
Notifications
You must be signed in to change notification settings - Fork 992
/
Copy pathlib.rs
1581 lines (1451 loc) · 59.1 KB
/
lib.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
//! Ledger's state storage with key-value backed store and a merkle tree
pub mod wl_storage;
pub mod write_log;
use core::fmt::Debug;
use std::cmp::Ordering;
use std::format;
use namada_core::borsh::{BorshDeserialize, BorshSerialize, BorshSerializeExt};
use namada_core::tendermint::merkle::proof::ProofOps;
use namada_core::types::address::{
Address, EstablishedAddressGen, InternalAddress,
};
use namada_core::types::chain::{ChainId, CHAIN_ID_LENGTH};
use namada_core::types::eth_bridge_pool::is_pending_transfer_key;
use namada_core::types::hash::{Error as HashError, Hash};
pub use namada_core::types::hash::{Sha256Hasher, StorageHasher};
pub use namada_core::types::storage::{
BlockHash, BlockHeight, BlockResults, Epoch, Epochs, EthEventsQueue,
Header, Key, KeySeg, TxIndex, BLOCK_HASH_LENGTH, BLOCK_HEIGHT_LENGTH,
EPOCH_TYPE_LENGTH,
};
use namada_core::types::time::DateTimeUtc;
pub use namada_core::types::token::ConversionState;
use namada_core::types::{encode, ethereum_structs, storage};
use namada_gas::{
MEMORY_ACCESS_GAS_PER_BYTE, STORAGE_ACCESS_GAS_PER_BYTE,
STORAGE_WRITE_GAS_PER_BYTE,
};
pub use namada_merkle_tree::{
self as merkle_tree, ics23_specs, MembershipProof, MerkleTree,
MerkleTreeStoresRead, MerkleTreeStoresWrite, StoreRef, StoreType,
};
use namada_merkle_tree::{Error as MerkleTreeError, MerkleRoot};
use namada_parameters::{self, EpochDuration, Parameters};
pub use namada_storage::{Error as StorageError, Result as StorageResult, *};
use thiserror::Error;
use tx_queue::{ExpiredTxsQueue, TxQueue};
pub use wl_storage::{
iter_prefix_post, iter_prefix_pre, PrefixIter, TempWlStorage, WlStorage,
};
/// A result of a function that may fail
pub type Result<T> = std::result::Result<T, Error>;
/// We delay epoch change 2 blocks to keep it in sync with Tendermint, because
/// it has 2 blocks delay on validator set update.
pub const EPOCH_SWITCH_BLOCKS_DELAY: u32 = 2;
/// The ledger's state
#[derive(Debug)]
pub struct State<D, H>
where
D: DB + for<'iter> DBIter<'iter>,
H: StorageHasher,
{
/// The database for the storage
pub db: D,
/// The ID of the chain
pub chain_id: ChainId,
/// The address of the native token - this is not stored in DB, but read
/// from genesis
pub native_token: Address,
/// Block storage data
pub block: BlockStorage<H>,
/// During `FinalizeBlock`, this is the header of the block that is
/// going to be committed. After a block is committed, this is reset to
/// `None` until the next `FinalizeBlock` phase is reached.
pub header: Option<Header>,
/// The most recently committed block, if any.
pub last_block: Option<LastBlock>,
/// The epoch of the most recently committed block. If it is `Epoch(0)`,
/// then no block may have been committed for this chain yet.
pub last_epoch: Epoch,
/// Minimum block height at which the next epoch may start
pub next_epoch_min_start_height: BlockHeight,
/// Minimum block time at which the next epoch may start
pub next_epoch_min_start_time: DateTimeUtc,
/// The current established address generator
pub address_gen: EstablishedAddressGen,
/// We delay the switch to a new epoch by the number of blocks set in here.
/// This is `Some` when minimum number of blocks has been created and
/// minimum time has passed since the beginning of the last epoch.
/// Once the value is `Some(0)`, we're ready to switch to a new epoch and
/// this is reset back to `None`.
pub update_epoch_blocks_delay: Option<u32>,
/// The shielded transaction index
pub tx_index: TxIndex,
/// The currently saved conversion state
pub conversion_state: ConversionState,
/// Wrapper txs to be decrypted in the next block proposal
pub tx_queue: TxQueue,
/// Queue of expired transactions that need to be retransmitted.
///
/// These transactions do not need to be persisted, as they are
/// retransmitted at the **COMMIT** phase immediately following
/// the block when they were queued.
pub expired_txs_queue: ExpiredTxsQueue,
/// The latest block height on Ethereum processed, if
/// the bridge is enabled.
pub ethereum_height: Option<ethereum_structs::BlockHeight>,
/// The queue of Ethereum events to be processed in order.
pub eth_events_queue: EthEventsQueue,
/// How many block heights in the past can the storage be queried
pub storage_read_past_height_limit: Option<u64>,
/// Static merkle tree storage key filter
pub merkle_tree_key_filter: fn(&storage::Key) -> bool,
}
/// Last committed block
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize)]
pub struct LastBlock {
/// Block height
pub height: BlockHeight,
/// Block hash
pub hash: BlockHash,
/// Block time
pub time: DateTimeUtc,
}
/// The block storage data
#[derive(Debug)]
pub struct BlockStorage<H: StorageHasher> {
/// Merkle tree of all the other data in block storage
pub tree: MerkleTree<H>,
/// During `FinalizeBlock`, this is updated to be the hash of the block
/// that is going to be committed. If it is `BlockHash::default()`,
/// then no `FinalizeBlock` stage has been reached yet.
pub hash: BlockHash,
/// From the start of `FinalizeBlock` until the end of `Commit`, this is
/// height of the block that is going to be committed. Otherwise, it is the
/// height of the most recently committed block, or `BlockHeight::sentinel`
/// (0) if no block has been committed yet.
pub height: BlockHeight,
/// From the start of `FinalizeBlock` until the end of `Commit`, this is
/// height of the block that is going to be committed. Otherwise it is the
/// epoch of the most recently committed block, or `Epoch(0)` if no block
/// has been committed yet.
pub epoch: Epoch,
/// Results of applying transactions
pub results: BlockResults,
/// Predecessor block epochs
pub pred_epochs: Epochs,
}
pub fn merklize_all_keys(_key: &storage::Key) -> bool {
true
}
#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum Error {
#[error("TEMPORARY error: {error}")]
Temporary { error: String },
#[error("Found an unknown key: {key}")]
UnknownKey { key: String },
#[error("Storage key error {0}")]
KeyError(namada_core::types::storage::Error),
#[error("Coding error: {0}")]
CodingError(#[from] namada_core::types::DecodeError),
#[error("Merkle tree error: {0}")]
MerkleTreeError(MerkleTreeError),
#[error("DB error: {0}")]
DBError(String),
#[error("Borsh (de)-serialization error: {0}")]
BorshCodingError(std::io::Error),
#[error("Merkle tree at the height {height} is not stored")]
NoMerkleTree { height: BlockHeight },
#[error("Code hash error: {0}")]
InvalidCodeHash(HashError),
#[error("DB error: {0}")]
DbError(#[from] namada_storage::DbError),
}
impl<D, H> State<D, H>
where
D: DB + for<'iter> DBIter<'iter>,
H: StorageHasher,
{
/// open up a new instance of the storage given path to db and chain id
pub fn open(
db_path: impl AsRef<std::path::Path>,
chain_id: ChainId,
native_token: Address,
cache: Option<&D::Cache>,
storage_read_past_height_limit: Option<u64>,
merkle_tree_key_filter: fn(&storage::Key) -> bool,
) -> Self {
let block = BlockStorage {
tree: MerkleTree::default(),
hash: BlockHash::default(),
height: BlockHeight::default(),
epoch: Epoch::default(),
pred_epochs: Epochs::default(),
results: BlockResults::default(),
};
State::<D, H> {
db: D::open(db_path, cache),
chain_id,
block,
header: None,
last_block: None,
last_epoch: Epoch::default(),
next_epoch_min_start_height: BlockHeight::default(),
next_epoch_min_start_time: DateTimeUtc::now(),
address_gen: EstablishedAddressGen::new(
"Privacy is a function of liberty.",
),
update_epoch_blocks_delay: None,
tx_index: TxIndex::default(),
conversion_state: ConversionState::default(),
tx_queue: TxQueue::default(),
expired_txs_queue: ExpiredTxsQueue::default(),
native_token,
ethereum_height: None,
eth_events_queue: EthEventsQueue::default(),
storage_read_past_height_limit,
merkle_tree_key_filter,
}
}
/// Load the full state at the last committed height, if any. Returns the
/// Merkle root hash and the height of the committed block.
pub fn load_last_state(&mut self) -> Result<()> {
if let Some(BlockStateRead {
merkle_tree_stores,
hash,
height,
time,
epoch,
pred_epochs,
next_epoch_min_start_height,
next_epoch_min_start_time,
update_epoch_blocks_delay,
results,
address_gen,
conversion_state,
tx_queue,
ethereum_height,
eth_events_queue,
}) = self.db.read_last_block()?
{
self.block.hash = hash.clone();
self.block.height = height;
self.block.epoch = epoch;
self.block.results = results;
self.block.pred_epochs = pred_epochs;
self.last_block = Some(LastBlock { height, hash, time });
self.last_epoch = epoch;
self.next_epoch_min_start_height = next_epoch_min_start_height;
self.next_epoch_min_start_time = next_epoch_min_start_time;
self.update_epoch_blocks_delay = update_epoch_blocks_delay;
self.address_gen = address_gen;
// Rebuild Merkle tree
self.block.tree = MerkleTree::new(merkle_tree_stores)
.or_else(|_| self.rebuild_full_merkle_tree(height))?;
self.conversion_state = conversion_state;
self.tx_queue = tx_queue;
self.ethereum_height = ethereum_height;
self.eth_events_queue = eth_events_queue;
tracing::debug!("Loaded storage from DB");
} else {
tracing::info!("No state could be found");
}
Ok(())
}
/// Returns the Merkle root hash and the height of the committed block. If
/// no block exists, returns None.
pub fn get_state(&self) -> Option<(MerkleRoot, u64)> {
if self.block.height.0 != 0 {
Some((self.block.tree.root(), self.block.height.0))
} else {
None
}
}
/// Persist the current block's state to the database
pub fn commit_block(&mut self, mut batch: D::WriteBatch) -> Result<()> {
// All states are written only when the first height or a new epoch
let is_full_commit =
self.block.height.0 == 1 || self.last_epoch != self.block.epoch;
// For convenience in tests, fill-in a header if it's missing.
// Normally, the header is added in `FinalizeBlock`.
#[cfg(any(test, feature = "testing"))]
{
if self.header.is_none() {
self.header = Some(Header {
hash: Hash::default(),
time: DateTimeUtc::now(),
next_validators_hash: Hash::default(),
});
}
}
let state = BlockStateWrite {
merkle_tree_stores: self.block.tree.stores(),
header: self.header.as_ref(),
hash: &self.block.hash,
height: self.block.height,
time: self
.header
.as_ref()
.expect("Must have a block header on commit")
.time,
epoch: self.block.epoch,
results: &self.block.results,
pred_epochs: &self.block.pred_epochs,
next_epoch_min_start_height: self.next_epoch_min_start_height,
next_epoch_min_start_time: self.next_epoch_min_start_time,
update_epoch_blocks_delay: self.update_epoch_blocks_delay,
address_gen: &self.address_gen,
conversion_state: &self.conversion_state,
tx_queue: &self.tx_queue,
ethereum_height: self.ethereum_height.as_ref(),
eth_events_queue: &self.eth_events_queue,
};
self.db
.add_block_to_batch(state, &mut batch, is_full_commit)?;
let header = self
.header
.take()
.expect("Must have a block header on commit");
self.last_block = Some(LastBlock {
height: self.block.height,
hash: header.hash.into(),
time: header.time,
});
self.last_epoch = self.block.epoch;
if is_full_commit {
// prune old merkle tree stores
self.prune_merkle_tree_stores(&mut batch)?;
}
self.db.exec_batch(batch)?;
Ok(())
}
/// Find the root hash of the merkle tree
pub fn merkle_root(&self) -> MerkleRoot {
self.block.tree.root()
}
/// Check if the given key is present in storage. Returns the result and the
/// gas cost.
pub fn has_key(&self, key: &Key) -> Result<(bool, u64)> {
Ok((
self.db.read_subspace_val(key)?.is_some(),
key.len() as u64 * STORAGE_ACCESS_GAS_PER_BYTE,
))
}
/// Returns a value from the specified subspace and the gas cost
pub fn read(&self, key: &Key) -> Result<(Option<Vec<u8>>, u64)> {
tracing::debug!("storage read key {}", key);
match self.db.read_subspace_val(key)? {
Some(v) => {
let gas =
(key.len() + v.len()) as u64 * STORAGE_ACCESS_GAS_PER_BYTE;
Ok((Some(v), gas))
}
None => Ok((None, key.len() as u64 * STORAGE_ACCESS_GAS_PER_BYTE)),
}
}
/// Returns a value from the specified subspace at the given height (or the
/// last committed height when 0) and the gas cost.
pub fn read_with_height(
&self,
key: &Key,
height: BlockHeight,
) -> Result<(Option<Vec<u8>>, u64)> {
// `0` means last committed height
if height == BlockHeight(0) || height >= self.get_last_block_height() {
self.read(key)
} else {
if !(self.merkle_tree_key_filter)(key) {
return Ok((None, 0));
}
match self.db.read_subspace_val_with_height(
key,
height,
self.get_last_block_height(),
)? {
Some(v) => {
let gas = (key.len() + v.len()) as u64
* STORAGE_ACCESS_GAS_PER_BYTE;
Ok((Some(v), gas))
}
None => {
Ok((None, key.len() as u64 * STORAGE_ACCESS_GAS_PER_BYTE))
}
}
}
}
/// WARNING: This only works for values that have been committed to DB.
/// To be able to see values written or deleted, but not yet committed,
/// use the `StorageWithWriteLog`.
///
/// Returns a prefix iterator, ordered by storage keys, and the gas cost.
pub fn iter_prefix(
&self,
prefix: &Key,
) -> (<D as DBIter<'_>>::PrefixIter, u64) {
(
self.db.iter_prefix(Some(prefix)),
prefix.len() as u64 * STORAGE_ACCESS_GAS_PER_BYTE,
)
}
/// Returns an iterator over the block results
pub fn iter_results(&self) -> (<D as DBIter<'_>>::PrefixIter, u64) {
(self.db.iter_results(), 0)
}
/// Write a value to the specified subspace and returns the gas cost and the
/// size difference
pub fn write(
&mut self,
key: &Key,
value: impl AsRef<[u8]>,
) -> Result<(u64, i64)> {
// Note that this method is the same as `StorageWrite::write_bytes`,
// but with gas and storage bytes len diff accounting
tracing::debug!("storage write key {}", key,);
let value = value.as_ref();
let is_key_merklized = (self.merkle_tree_key_filter)(key);
if is_pending_transfer_key(key) {
// The tree of the bright pool stores the current height for the
// pending transfer
let height = self.block.height.serialize_to_vec();
self.block.tree.update(key, height)?;
} else {
// Update the merkle tree
if is_key_merklized {
self.block.tree.update(key, value)?;
}
}
let len = value.len();
let gas = (key.len() + len) as u64 * STORAGE_WRITE_GAS_PER_BYTE;
let size_diff = self.db.write_subspace_val(
self.block.height,
key,
value,
is_key_merklized,
)?;
Ok((gas, size_diff))
}
/// Delete the specified subspace and returns the gas cost and the size
/// difference
pub fn delete(&mut self, key: &Key) -> Result<(u64, i64)> {
// Note that this method is the same as `StorageWrite::delete`,
// but with gas and storage bytes len diff accounting
let mut deleted_bytes_len = 0;
if self.has_key(key)?.0 {
let is_key_merklized = (self.merkle_tree_key_filter)(key);
if is_key_merklized {
self.block.tree.delete(key)?;
}
deleted_bytes_len = self.db.delete_subspace_val(
self.block.height,
key,
is_key_merklized,
)?;
}
let gas = (key.len() + deleted_bytes_len as usize) as u64
* STORAGE_WRITE_GAS_PER_BYTE;
Ok((gas, deleted_bytes_len))
}
/// Set the block header.
/// The header is not in the Merkle tree as it's tracked by Tendermint.
/// Hence, we don't update the tree when this is set.
pub fn set_header(&mut self, header: Header) -> Result<()> {
self.header = Some(header);
Ok(())
}
/// Block data is in the Merkle tree as it's tracked by Tendermint in the
/// block header. Hence, we don't update the tree when this is set.
pub fn begin_block(
&mut self,
hash: BlockHash,
height: BlockHeight,
) -> Result<()> {
self.block.hash = hash;
self.block.height = height;
Ok(())
}
/// Get the hash of a validity predicate for the given account address and
/// the gas cost for reading it.
pub fn validity_predicate(
&self,
addr: &Address,
) -> Result<(Option<Hash>, u64)> {
let key = if let Address::Implicit(_) = addr {
namada_parameters::storage::get_implicit_vp_key()
} else {
Key::validity_predicate(addr)
};
match self.read(&key)? {
(Some(value), gas) => {
let vp_code_hash = Hash::try_from(&value[..])
.map_err(Error::InvalidCodeHash)?;
Ok((Some(vp_code_hash), gas))
}
(None, gas) => Ok((None, gas)),
}
}
#[allow(dead_code)]
/// Check if the given address exists on chain and return the gas cost.
pub fn exists(&self, addr: &Address) -> Result<(bool, u64)> {
let key = Key::validity_predicate(addr);
self.has_key(&key)
}
/// Get the chain ID as a raw string
pub fn get_chain_id(&self) -> (String, u64) {
(
self.chain_id.to_string(),
CHAIN_ID_LENGTH as u64 * MEMORY_ACCESS_GAS_PER_BYTE,
)
}
/// Get the block height
pub fn get_block_height(&self) -> (BlockHeight, u64) {
(
self.block.height,
BLOCK_HEIGHT_LENGTH as u64 * MEMORY_ACCESS_GAS_PER_BYTE,
)
}
/// Get the block hash
pub fn get_block_hash(&self) -> (BlockHash, u64) {
(
self.block.hash.clone(),
BLOCK_HASH_LENGTH as u64 * MEMORY_ACCESS_GAS_PER_BYTE,
)
}
/// Rebuild full Merkle tree after [`read_last_block()`]
fn rebuild_full_merkle_tree(
&self,
height: BlockHeight,
) -> Result<MerkleTree<H>> {
self.get_merkle_tree(height, None)
}
/// Rebuild Merkle tree with diffs in the DB.
/// Base tree and the specified `store_type` subtree is rebuilt.
/// If `store_type` isn't given, full Merkle tree is restored.
pub fn get_merkle_tree(
&self,
height: BlockHeight,
store_type: Option<StoreType>,
) -> Result<MerkleTree<H>> {
// `0` means last committed height
let height = if height == BlockHeight(0) {
self.get_last_block_height()
} else {
height
};
let epoch = self
.block
.pred_epochs
.get_epoch(height)
.unwrap_or(Epoch::default());
let epoch_start_height =
match self.block.pred_epochs.get_start_height_of_epoch(epoch) {
Some(height) if height == BlockHeight(0) => BlockHeight(1),
Some(height) => height,
None => BlockHeight(1),
};
let stores = self
.db
.read_merkle_tree_stores(epoch, epoch_start_height, store_type)?
.ok_or(Error::NoMerkleTree { height })?;
let prefix = store_type.and_then(|st| st.provable_prefix());
let mut tree = match store_type {
Some(_) => MerkleTree::<H>::new_partial(stores),
None => MerkleTree::<H>::new(stores).expect("invalid stores"),
};
// Restore the tree state with diffs
let mut target_height = epoch_start_height;
while target_height < height {
target_height = target_height.next_height();
let mut old_diff_iter =
self.db.iter_old_diffs(target_height, prefix.as_ref());
let mut new_diff_iter =
self.db.iter_new_diffs(target_height, prefix.as_ref());
let mut old_diff = old_diff_iter.next();
let mut new_diff = new_diff_iter.next();
loop {
match (&old_diff, &new_diff) {
(Some(old), Some(new)) => {
let old_key = Key::parse(old.0.clone())
.expect("the key should be parsable");
let new_key = Key::parse(new.0.clone())
.expect("the key should be parsable");
// compare keys as String
match old.0.cmp(&new.0) {
Ordering::Equal => {
// the value was updated
if (self.merkle_tree_key_filter)(&new_key) {
tree.update(
&new_key,
if is_pending_transfer_key(&new_key) {
target_height.serialize_to_vec()
} else {
new.1.clone()
},
)?;
}
old_diff = old_diff_iter.next();
new_diff = new_diff_iter.next();
}
Ordering::Less => {
// the value was deleted
if (self.merkle_tree_key_filter)(&old_key) {
tree.delete(&old_key)?;
}
old_diff = old_diff_iter.next();
}
Ordering::Greater => {
// the value was inserted
if (self.merkle_tree_key_filter)(&new_key) {
tree.update(
&new_key,
if is_pending_transfer_key(&new_key) {
target_height.serialize_to_vec()
} else {
new.1.clone()
},
)?;
}
new_diff = new_diff_iter.next();
}
}
}
(Some(old), None) => {
// the value was deleted
let key = Key::parse(old.0.clone())
.expect("the key should be parsable");
if (self.merkle_tree_key_filter)(&key) {
tree.delete(&key)?;
}
old_diff = old_diff_iter.next();
}
(None, Some(new)) => {
// the value was inserted
let key = Key::parse(new.0.clone())
.expect("the key should be parsable");
if (self.merkle_tree_key_filter)(&key) {
tree.update(
&key,
if is_pending_transfer_key(&key) {
target_height.serialize_to_vec()
} else {
new.1.clone()
},
)?;
}
new_diff = new_diff_iter.next();
}
(None, None) => break,
}
}
}
if let Some(st) = store_type {
// Add the base tree with the given height
let mut stores = self
.db
.read_merkle_tree_stores(epoch, height, Some(StoreType::Base))?
.ok_or(Error::NoMerkleTree { height })?;
let restored_stores = tree.stores();
// Set the root and store of the rebuilt subtree
stores.set_root(&st, *restored_stores.root(&st));
stores.set_store(restored_stores.store(&st).to_owned());
tree = MerkleTree::<H>::new_partial(stores);
}
Ok(tree)
}
/// Get a Tendermint-compatible existence proof.
///
/// Proofs from the Ethereum bridge pool are not
/// Tendermint-compatible. Requesting for a key
/// belonging to the bridge pool will cause this
/// method to error.
pub fn get_existence_proof(
&self,
key: &Key,
value: namada_merkle_tree::StorageBytes,
height: BlockHeight,
) -> Result<ProofOps> {
use std::array;
// `0` means last committed height
let height = if height == BlockHeight(0) {
self.get_last_block_height()
} else {
height
};
if height > self.get_last_block_height() {
if let MembershipProof::ICS23(proof) = self
.block
.tree
.get_sub_tree_existence_proof(array::from_ref(key), vec![value])
.map_err(Error::MerkleTreeError)?
{
self.block
.tree
.get_sub_tree_proof(key, proof)
.map(Into::into)
.map_err(Error::MerkleTreeError)
} else {
Err(Error::MerkleTreeError(MerkleTreeError::TendermintProof))
}
} else {
let (store_type, _) = StoreType::sub_key(key)?;
let tree = self.get_merkle_tree(height, Some(store_type))?;
if let MembershipProof::ICS23(proof) = tree
.get_sub_tree_existence_proof(array::from_ref(key), vec![value])
.map_err(Error::MerkleTreeError)?
{
tree.get_sub_tree_proof(key, proof)
.map(Into::into)
.map_err(Error::MerkleTreeError)
} else {
Err(Error::MerkleTreeError(MerkleTreeError::TendermintProof))
}
}
}
/// Get the non-existence proof
pub fn get_non_existence_proof(
&self,
key: &Key,
height: BlockHeight,
) -> Result<ProofOps> {
// `0` means last committed height
let height = if height == BlockHeight(0) {
self.get_last_block_height()
} else {
height
};
if height > self.get_last_block_height() {
Err(Error::Temporary {
error: format!(
"The block at the height {} hasn't committed yet",
height,
),
})
} else {
let (store_type, _) = StoreType::sub_key(key)?;
self.get_merkle_tree(height, Some(store_type))?
.get_non_existence_proof(key)
.map(Into::into)
.map_err(Error::MerkleTreeError)
}
}
/// Get the current (yet to be committed) block epoch
pub fn get_current_epoch(&self) -> (Epoch, u64) {
(
self.block.epoch,
EPOCH_TYPE_LENGTH as u64 * MEMORY_ACCESS_GAS_PER_BYTE,
)
}
/// Get the epoch of the last committed block
pub fn get_last_epoch(&self) -> (Epoch, u64) {
(
self.last_epoch,
EPOCH_TYPE_LENGTH as u64 * MEMORY_ACCESS_GAS_PER_BYTE,
)
}
/// Initialize the first epoch. The first epoch begins at genesis time.
pub fn init_genesis_epoch(
&mut self,
initial_height: BlockHeight,
genesis_time: DateTimeUtc,
parameters: &Parameters,
) -> Result<()> {
let EpochDuration {
min_num_of_blocks,
min_duration,
} = parameters.epoch_duration;
self.next_epoch_min_start_height = initial_height + min_num_of_blocks;
self.next_epoch_min_start_time = genesis_time + min_duration;
self.block.pred_epochs = Epochs {
first_block_heights: vec![initial_height],
};
self.update_epoch_in_merkle_tree()
}
/// Get the block header
pub fn get_block_header(
&self,
height: Option<BlockHeight>,
) -> Result<(Option<Header>, u64)> {
match height {
Some(h) if h == self.get_block_height().0 => {
let header = self.header.clone();
let gas = match header {
Some(ref header) => {
header.encoded_len() as u64 * MEMORY_ACCESS_GAS_PER_BYTE
}
None => MEMORY_ACCESS_GAS_PER_BYTE,
};
Ok((header, gas))
}
Some(h) => match self.db.read_block_header(h)? {
Some(header) => {
let gas = header.encoded_len() as u64
* STORAGE_ACCESS_GAS_PER_BYTE;
Ok((Some(header), gas))
}
None => Ok((None, STORAGE_ACCESS_GAS_PER_BYTE)),
},
None => Ok((self.header.clone(), STORAGE_ACCESS_GAS_PER_BYTE)),
}
}
/// Get the timestamp of the last committed block, or the current timestamp
/// if no blocks have been produced yet
pub fn get_last_block_timestamp(&self) -> Result<DateTimeUtc> {
let last_block_height = self.get_block_height().0;
Ok(self
.db
.read_block_header(last_block_height)?
.map_or_else(DateTimeUtc::now, |header| header.time))
}
/// Get the current conversions
pub fn get_conversion_state(&self) -> &ConversionState {
&self.conversion_state
}
/// Update the merkle tree with epoch data
fn update_epoch_in_merkle_tree(&mut self) -> Result<()> {
let key_prefix: Key =
Address::Internal(InternalAddress::PoS).to_db_key().into();
let key = key_prefix
.push(&"epoch_start_height".to_string())
.map_err(Error::KeyError)?;
self.block
.tree
.update(&key, encode(&self.next_epoch_min_start_height))?;
let key = key_prefix
.push(&"epoch_start_time".to_string())
.map_err(Error::KeyError)?;
self.block
.tree
.update(&key, encode(&self.next_epoch_min_start_time))?;
let key = key_prefix
.push(&"current_epoch".to_string())
.map_err(Error::KeyError)?;
self.block.tree.update(&key, encode(&self.block.epoch))?;
Ok(())
}
/// Start write batch.
pub fn batch() -> D::WriteBatch {
D::batch()
}
/// Execute write batch.
pub fn exec_batch(&mut self, batch: D::WriteBatch) -> Result<()> {
Ok(self.db.exec_batch(batch)?)
}
/// Batch write the value with the given height and account subspace key to
/// the DB. Returns the size difference from previous value, if any, or
/// the size of the value otherwise.
pub fn batch_write_subspace_val(
&mut self,
batch: &mut D::WriteBatch,
key: &Key,
value: impl AsRef<[u8]>,
) -> Result<i64> {
let value = value.as_ref();
let is_key_merklized = (self.merkle_tree_key_filter)(key);
if is_pending_transfer_key(key) {
// The tree of the bridge pool stores the current height for the
// pending transfer
let height = self.block.height.serialize_to_vec();
self.block.tree.update(key, height)?;
} else {
// Update the merkle tree
if is_key_merklized {
self.block.tree.update(key, value)?;
}
}
Ok(self.db.batch_write_subspace_val(
batch,
self.block.height,
key,
value,
is_key_merklized,
)?)
}
/// Batch delete the value with the given height and account subspace key
/// from the DB. Returns the size of the removed value, if any, 0 if no
/// previous value was found.
pub fn batch_delete_subspace_val(
&mut self,
batch: &mut D::WriteBatch,
key: &Key,
) -> Result<i64> {
let is_key_merklized = (self.merkle_tree_key_filter)(key);
// Update the merkle tree
if is_key_merklized {
self.block.tree.delete(key)?;
}
Ok(self.db.batch_delete_subspace_val(
batch,
self.block.height,
key,
is_key_merklized,
)?)
}
// Prune merkle tree stores. Use after updating self.block.height in the
// commit.
fn prune_merkle_tree_stores(
&mut self,
batch: &mut D::WriteBatch,
) -> Result<()> {
if self.block.epoch.0 == 0 {
return Ok(());
}
// Prune non-provable stores at the previous epoch
for st in StoreType::iter_non_provable() {
self.db.prune_merkle_tree_store(
batch,
st,
self.block.epoch.prev(),
)?;
}
// Prune provable stores
let oldest_epoch = self.get_oldest_epoch();
if oldest_epoch.0 > 0 {
// Remove stores at the previous epoch because the Merkle tree
// stores at the starting height of the epoch would be used to
// restore stores at a height (> oldest_height) in the epoch
for st in StoreType::iter_provable() {
self.db.prune_merkle_tree_store(
batch,
st,
oldest_epoch.prev(),
)?;
}
// Prune the BridgePool subtree stores with invalid nonce
let mut epoch = match self.get_oldest_epoch_with_valid_nonce()? {
Some(epoch) => epoch,
None => return Ok(()),
};
while oldest_epoch < epoch {
epoch = epoch.prev();
self.db.prune_merkle_tree_store(
batch,
&StoreType::BridgePool,
epoch,
)?;
}
}
Ok(())
}
/// Get the height of the last committed block or 0 if no block has been
/// committed yet. The first block is at height 1.