-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathstore.rs
More file actions
1807 lines (1633 loc) · 64.6 KB
/
Copy pathstore.rs
File metadata and controls
1807 lines (1633 loc) · 64.6 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
use crate::error::StoreError;
use crate::store_db::in_memory::Store as InMemoryStore;
#[cfg(feature = "rocksdb")]
use crate::store_db::rocksdb::Store as RocksDBStore;
use crate::{api::StoreEngine, apply_prefix};
use bytes::Bytes;
use ethereum_types::{Address, H256, U256};
use ethrex_common::{
constants::EMPTY_TRIE_HASH,
types::{
AccountInfo, AccountState, AccountUpdate, Block, BlockBody, BlockHash, BlockHeader,
BlockNumber, ChainConfig, ForkId, Genesis, GenesisAccount, Index, Receipt, Transaction,
code_hash,
},
};
use ethrex_rlp::decode::RLPDecode;
use ethrex_rlp::encode::RLPEncode;
use ethrex_trie::{Nibbles, NodeRLP, Trie, TrieLogger, TrieNode, TrieWitness};
use sha3::{Digest as _, Keccak256};
use std::sync::Arc;
use std::{
collections::{BTreeMap, HashMap},
sync::RwLock,
};
use std::{fmt::Debug, path::Path};
use tracing::{debug, error, info, instrument};
/// Number of state trie segments to fetch concurrently during state sync
pub const STATE_TRIE_SEGMENTS: usize = 2;
/// Maximum amount of reads from the snapshot in a single transaction to avoid performance hits due to long-living reads
/// This will always be the amount yielded by snapshot reads unless there are less elements left
pub const MAX_SNAPSHOT_READS: usize = 100;
#[derive(Debug, Clone)]
pub struct Store {
pub engine: Arc<dyn StoreEngine>,
pub chain_config: Arc<RwLock<ChainConfig>>,
pub latest_block_header: Arc<RwLock<BlockHeader>>,
}
pub type StorageTrieNodes = Vec<(H256, Vec<(Nibbles, Vec<u8>)>)>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EngineType {
InMemory,
#[cfg(feature = "rocksdb")]
RocksDB,
}
pub struct UpdateBatch {
/// Nodes to be added to the state trie
pub account_updates: Vec<TrieNode>,
/// Storage tries updated and their new nodes
pub storage_updates: Vec<(H256, Vec<TrieNode>)>,
/// Blocks to be added
pub blocks: Vec<Block>,
/// Receipts added per block
pub receipts: Vec<(H256, Vec<Receipt>)>,
/// Code updates
pub code_updates: Vec<(H256, Bytes)>,
}
type StorageUpdates = Vec<(H256, Vec<(Nibbles, Vec<u8>)>)>;
pub struct AccountUpdatesList {
pub state_trie_hash: H256,
pub state_updates: Vec<(Nibbles, Vec<u8>)>,
pub storage_updates: StorageUpdates,
pub code_updates: Vec<(H256, Bytes)>,
}
impl Store {
pub async fn store_block_updates(&self, update_batch: UpdateBatch) -> Result<(), StoreError> {
self.engine.apply_updates(update_batch).await
}
pub fn new(path: impl AsRef<Path>, engine_type: EngineType) -> Result<Self, StoreError> {
let path = path.as_ref();
info!(engine = ?engine_type, ?path, "Opening storage engine");
let store = match engine_type {
#[cfg(feature = "rocksdb")]
EngineType::RocksDB => Self {
engine: Arc::new(RocksDBStore::new(path)?),
chain_config: Default::default(),
latest_block_header: Arc::new(RwLock::new(BlockHeader::default())),
},
EngineType::InMemory => Self {
engine: Arc::new(InMemoryStore::new()),
chain_config: Default::default(),
latest_block_header: Arc::new(RwLock::new(BlockHeader::default())),
},
};
Ok(store)
}
pub async fn new_from_genesis(
store_path: &Path,
engine_type: EngineType,
genesis_path: &str,
) -> Result<Self, StoreError> {
let file = std::fs::File::open(genesis_path)
.map_err(|error| StoreError::Custom(format!("Failed to open genesis file: {error}")))?;
let reader = std::io::BufReader::new(file);
let genesis: Genesis =
serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
let store = Self::new(store_path, engine_type)?;
store.add_initial_state(genesis).await?;
Ok(store)
}
pub async fn get_account_info(
&self,
block_number: BlockNumber,
address: Address,
) -> Result<Option<AccountInfo>, StoreError> {
match self.get_canonical_block_hash(block_number).await? {
Some(block_hash) => self.get_account_info_by_hash(block_hash, address),
None => Ok(None),
}
}
pub fn get_account_info_by_hash(
&self,
block_hash: BlockHash,
address: Address,
) -> Result<Option<AccountInfo>, StoreError> {
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
let hashed_address = hash_address(&address);
let Some(encoded_state) = state_trie.get(&hashed_address)? else {
return Ok(None);
};
let account_state = AccountState::decode(&encoded_state)?;
Ok(Some(AccountInfo {
code_hash: account_state.code_hash,
balance: account_state.balance,
nonce: account_state.nonce,
}))
}
pub fn get_account_state_by_acc_hash(
&self,
block_hash: BlockHash,
account_hash: H256,
) -> Result<Option<AccountState>, StoreError> {
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
let Some(encoded_state) = state_trie.get(&account_hash.to_fixed_bytes().to_vec())? else {
return Ok(None);
};
let account_state = AccountState::decode(&encoded_state)?;
Ok(Some(account_state))
}
pub async fn add_block_header(
&self,
block_hash: BlockHash,
block_header: BlockHeader,
) -> Result<(), StoreError> {
self.engine.add_block_header(block_hash, block_header).await
}
pub async fn add_block_headers(
&self,
block_headers: Vec<BlockHeader>,
) -> Result<(), StoreError> {
self.engine.add_block_headers(block_headers).await
}
pub fn get_block_header(
&self,
block_number: BlockNumber,
) -> Result<Option<BlockHeader>, StoreError> {
let latest = self
.latest_block_header
.read()
.map_err(|_| StoreError::LockError)?
.clone();
if block_number == latest.number {
return Ok(Some(latest));
}
self.engine.get_block_header(block_number)
}
pub fn get_block_header_by_hash(
&self,
block_hash: BlockHash,
) -> Result<Option<BlockHeader>, StoreError> {
{
let latest = self
.latest_block_header
.read()
.map_err(|_| StoreError::LockError)?;
if block_hash == latest.hash() {
return Ok(Some(latest.clone()));
}
}
self.engine.get_block_header_by_hash(block_hash)
}
pub async fn get_block_body_by_hash(
&self,
block_hash: BlockHash,
) -> Result<Option<BlockBody>, StoreError> {
self.engine.get_block_body_by_hash(block_hash).await
}
pub async fn add_block_body(
&self,
block_hash: BlockHash,
block_body: BlockBody,
) -> Result<(), StoreError> {
self.engine.add_block_body(block_hash, block_body).await
}
pub async fn get_block_body(
&self,
block_number: BlockNumber,
) -> Result<Option<BlockBody>, StoreError> {
// FIXME (#4353)
let latest = self
.latest_block_header
.read()
.map_err(|_| StoreError::LockError)?
.clone();
if block_number == latest.number {
// The latest may not be marked as canonical yet
return self.engine.get_block_body_by_hash(latest.hash()).await;
}
self.engine.get_block_body(block_number).await
}
pub async fn remove_block(&self, block_number: BlockNumber) -> Result<(), StoreError> {
self.engine.remove_block(block_number).await
}
pub async fn get_block_bodies(
&self,
from: BlockNumber,
to: BlockNumber,
) -> Result<Vec<BlockBody>, StoreError> {
self.engine.get_block_bodies(from, to).await
}
pub async fn get_block_bodies_by_hash(
&self,
hashes: Vec<BlockHash>,
) -> Result<Vec<BlockBody>, StoreError> {
self.engine.get_block_bodies_by_hash(hashes).await
}
pub async fn add_pending_block(&self, block: Block) -> Result<(), StoreError> {
info!("Adding block to pending: {}", block.hash());
self.engine.add_pending_block(block).await
}
pub async fn get_pending_block(
&self,
block_hash: BlockHash,
) -> Result<Option<Block>, StoreError> {
info!("get pending: {}", block_hash);
self.engine.get_pending_block(block_hash).await
}
pub async fn add_block_number(
&self,
block_hash: BlockHash,
block_number: BlockNumber,
) -> Result<(), StoreError> {
self.engine
.clone()
.add_block_number(block_hash, block_number)
.await
}
pub async fn get_block_number(
&self,
block_hash: BlockHash,
) -> Result<Option<BlockNumber>, StoreError> {
self.engine.get_block_number(block_hash).await
}
pub async fn get_fork_id(&self) -> Result<ForkId, StoreError> {
let chain_config = self.get_chain_config()?;
let genesis_header = self
.engine
.get_block_header(0)?
.ok_or(StoreError::MissingEarliestBlockNumber)?;
let block_number = self.get_latest_block_number().await?;
let block_header = self
.get_block_header(block_number)?
.ok_or(StoreError::MissingLatestBlockNumber)?;
Ok(ForkId::new(
chain_config,
genesis_header,
block_header.timestamp,
block_number,
))
}
pub async fn get_transaction_location(
&self,
transaction_hash: H256,
) -> Result<Option<(BlockNumber, BlockHash, Index)>, StoreError> {
self.engine.get_transaction_location(transaction_hash).await
}
pub async fn add_account_code(&self, code_hash: H256, code: Bytes) -> Result<(), StoreError> {
self.engine.add_account_code(code_hash, code).await
}
pub fn get_account_code(&self, code_hash: H256) -> Result<Option<Bytes>, StoreError> {
self.engine.get_account_code(code_hash)
}
pub async fn get_code_by_account_address(
&self,
block_number: BlockNumber,
address: Address,
) -> Result<Option<Bytes>, StoreError> {
let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
return Ok(None);
};
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
let hashed_address = hash_address(&address);
let Some(encoded_state) = state_trie.get(&hashed_address)? else {
return Ok(None);
};
let account_state = AccountState::decode(&encoded_state)?;
self.get_account_code(account_state.code_hash)
}
pub async fn get_nonce_by_account_address(
&self,
block_number: BlockNumber,
address: Address,
) -> Result<Option<u64>, StoreError> {
let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
return Ok(None);
};
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
let hashed_address = hash_address(&address);
let Some(encoded_state) = state_trie.get(&hashed_address)? else {
return Ok(None);
};
let account_state = AccountState::decode(&encoded_state)?;
Ok(Some(account_state.nonce))
}
/// Applies account updates based on the block's latest storage state
/// and returns the new state root after the updates have been applied.
#[instrument(level = "trace", name = "Trie update", skip_all)]
pub async fn apply_account_updates_batch(
&self,
block_hash: BlockHash,
account_updates: &[AccountUpdate],
) -> Result<Option<AccountUpdatesList>, StoreError> {
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
Ok(Some(
self.apply_account_updates_from_trie_batch(state_trie, account_updates)
.await?,
))
}
pub async fn apply_account_updates_from_trie_batch(
&self,
mut state_trie: Trie,
account_updates: impl IntoIterator<Item = &AccountUpdate>,
) -> Result<AccountUpdatesList, StoreError> {
let mut ret_storage_updates = Vec::new();
let mut code_updates = Vec::new();
let state_root = state_trie.hash_no_commit();
for update in account_updates {
let hashed_address = hash_address(&update.address);
if update.removed {
// Remove account from trie
state_trie.remove(&hashed_address)?;
continue;
}
// Add or update AccountState in the trie
// Fetch current state or create a new state to be inserted
let mut account_state = match state_trie.get(&hashed_address)? {
Some(encoded_state) => AccountState::decode(&encoded_state)?,
None => AccountState::default(),
};
if let Some(info) = &update.info {
account_state.nonce = info.nonce;
account_state.balance = info.balance;
account_state.code_hash = info.code_hash;
// Store updated code in DB
if let Some(code) = &update.code {
code_updates.push((info.code_hash, code.clone()));
}
}
// Store the added storage in the account's storage trie and compute its new root
if !update.added_storage.is_empty() {
let mut storage_trie = self.engine.open_storage_trie(
H256::from_slice(&hashed_address),
account_state.storage_root,
state_root,
)?;
for (storage_key, storage_value) in &update.added_storage {
let hashed_key = hash_key(storage_key);
if storage_value.is_zero() {
storage_trie.remove(&hashed_key)?;
} else {
storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
}
}
let (storage_hash, storage_updates) =
storage_trie.collect_changes_since_last_hash();
account_state.storage_root = storage_hash;
ret_storage_updates.push((H256::from_slice(&hashed_address), storage_updates));
}
state_trie.insert(hashed_address, account_state.encode_to_vec())?;
}
let (state_trie_hash, state_updates) = state_trie.collect_changes_since_last_hash();
Ok(AccountUpdatesList {
state_trie_hash,
state_updates,
storage_updates: ret_storage_updates,
code_updates,
})
}
/// Performs the same actions as apply_account_updates_from_trie
/// but also returns the used storage tries with witness recorded
pub async fn apply_account_updates_from_trie_with_witness(
&self,
mut state_trie: Trie,
account_updates: &[AccountUpdate],
mut storage_tries: HashMap<Address, (TrieWitness, Trie)>,
) -> Result<(Trie, HashMap<Address, (TrieWitness, Trie)>), StoreError> {
let state_root = state_trie.hash_no_commit();
for update in account_updates.iter() {
let hashed_address = hash_address(&update.address);
if update.removed {
// Remove account from trie
state_trie.remove(&hashed_address)?;
} else {
// Add or update AccountState in the trie
// Fetch current state or create a new state to be inserted
let mut account_state = match state_trie.get(&hashed_address)? {
Some(encoded_state) => AccountState::decode(&encoded_state)?,
None => AccountState::default(),
};
if let Some(info) = &update.info {
account_state.nonce = info.nonce;
account_state.balance = info.balance;
account_state.code_hash = info.code_hash;
// Store updated code in DB
if let Some(code) = &update.code {
self.add_account_code(info.code_hash, code.clone()).await?;
}
}
// Store the added storage in the account's storage trie and compute its new root
if !update.added_storage.is_empty() {
let (_witness, storage_trie) = match storage_tries.entry(update.address) {
std::collections::hash_map::Entry::Occupied(value) => value.into_mut(),
std::collections::hash_map::Entry::Vacant(vacant) => {
let trie = self.engine.open_storage_trie(
H256::from_slice(&hashed_address),
account_state.storage_root,
state_root,
)?;
vacant.insert(TrieLogger::open_trie(trie))
}
};
for (storage_key, storage_value) in &update.added_storage {
let hashed_key = hash_key(storage_key);
if storage_value.is_zero() {
storage_trie.remove(&hashed_key)?;
} else {
storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
}
}
account_state.storage_root = storage_trie.hash_no_commit();
}
state_trie.insert(hashed_address, account_state.encode_to_vec())?;
}
}
Ok((state_trie, storage_tries))
}
/// Adds all genesis accounts and returns the genesis block's state_root
pub async fn setup_genesis_state_trie(
&self,
genesis_accounts: BTreeMap<Address, GenesisAccount>,
) -> Result<H256, StoreError> {
let mut nodes = HashMap::new();
let mut genesis_state_trie = self.engine.open_direct_state_trie(*EMPTY_TRIE_HASH)?;
for (address, account) in genesis_accounts {
let hashed_address = hash_address(&address);
// Store account code (as this won't be stored in the trie)
let code_hash = code_hash(&account.code);
self.add_account_code(code_hash, account.code).await?;
// Store the account's storage in a clean storage trie and compute its root
let mut storage_trie = self
.engine
.open_direct_storage_trie(H256::from_slice(&hashed_address), *EMPTY_TRIE_HASH)?;
for (storage_key, storage_value) in account.storage {
if !storage_value.is_zero() {
let hashed_key = hash_key(&H256(storage_key.to_big_endian()));
storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
}
}
let (storage_root, new_nodes) = storage_trie.collect_changes_since_last_hash();
nodes.insert(H256::from_slice(&hashed_address), new_nodes);
// Add account to trie
let account_state = AccountState {
nonce: account.nonce,
balance: account.balance,
storage_root,
code_hash,
};
genesis_state_trie.insert(hashed_address, account_state.encode_to_vec())?;
}
let (state_root, state_nodes) = genesis_state_trie.collect_changes_since_last_hash();
// TODO: replace this with a Store method
genesis_state_trie.db().put_batch(
nodes
.into_iter()
.flat_map(|(account_hash, nodes)| {
nodes
.into_iter()
.map(move |(path, node)| (apply_prefix(Some(account_hash), path), node))
})
.chain(state_nodes)
.collect(),
)?;
Ok(state_root)
}
pub async fn add_receipt(
&self,
block_hash: BlockHash,
index: Index,
receipt: Receipt,
) -> Result<(), StoreError> {
self.engine.add_receipt(block_hash, index, receipt).await
}
pub async fn add_receipts(
&self,
block_hash: BlockHash,
receipts: Vec<Receipt>,
) -> Result<(), StoreError> {
self.engine.add_receipts(block_hash, receipts).await
}
/// Obtain receipt for a canonical block represented by the block number.
pub async fn get_receipt(
&self,
block_number: BlockNumber,
index: Index,
) -> Result<Option<Receipt>, StoreError> {
// FIXME (#4353)
let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
return Ok(None);
};
self.engine.get_receipt(block_hash, index).await
}
pub async fn add_block(&self, block: Block) -> Result<(), StoreError> {
self.add_blocks(vec![block]).await
}
pub async fn add_blocks(&self, blocks: Vec<Block>) -> Result<(), StoreError> {
self.engine.add_blocks(blocks).await
}
pub async fn add_initial_state(&self, genesis: Genesis) -> Result<(), StoreError> {
debug!("Storing initial state from genesis");
// Obtain genesis block
let genesis_block = genesis.get_block();
let genesis_block_number = genesis_block.header.number;
let genesis_hash = genesis_block.hash();
// Set chain config
self.set_chain_config(&genesis.config).await?;
if let Some(number) = self.engine.get_latest_block_number().await? {
*self
.latest_block_header
.write()
.map_err(|_| StoreError::LockError)? = self
.engine
.get_block_header(number)?
.ok_or_else(|| StoreError::MissingLatestBlockNumber)?;
}
match self.engine.get_block_header(genesis_block_number)? {
Some(header) if header.hash() == genesis_hash => {
info!("Received genesis file matching a previously stored one, nothing to do");
return Ok(());
}
Some(_) => {
error!(
"The chain configuration stored in the database is incompatible with the provided configuration. If you intended to switch networks, choose another datadir or clear the database (e.g., run `ethrex removedb`) and try again."
);
return Err(StoreError::IncompatibleChainConfig);
}
None => {
self.engine
.add_block_header(genesis_hash, genesis_block.header.clone())
.await?
}
}
// Store genesis accounts
// TODO: Should we use this root instead of computing it before the block hash check?
let genesis_state_root = self.setup_genesis_state_trie(genesis.alloc).await?;
debug_assert_eq!(genesis_state_root, genesis_block.header.state_root);
// Store genesis block
info!(hash = %genesis_hash, "Storing genesis block");
self.add_block(genesis_block).await?;
self.update_earliest_block_number(genesis_block_number)
.await?;
self.forkchoice_update(None, genesis_block_number, genesis_hash, None, None)
.await?;
Ok(())
}
pub async fn load_initial_state(&self) -> Result<(), StoreError> {
info!("Loading initial state from DB");
let Some(number) = self.engine.get_latest_block_number().await? else {
return Err(StoreError::MissingLatestBlockNumber);
};
let latest_block_header = self
.engine
.get_block_header(number)?
.ok_or_else(|| StoreError::Custom("latest block header is missing".to_string()))?;
*self
.latest_block_header
.write()
.map_err(|_| StoreError::LockError)? = latest_block_header;
Ok(())
}
pub async fn get_transaction_by_hash(
&self,
transaction_hash: H256,
) -> Result<Option<Transaction>, StoreError> {
self.engine.get_transaction_by_hash(transaction_hash).await
}
pub async fn get_transaction_by_location(
&self,
block_hash: BlockHash,
index: Index,
) -> Result<Option<Transaction>, StoreError> {
self.engine
.get_transaction_by_location(block_hash, index)
.await
}
pub async fn get_block_by_hash(&self, block_hash: H256) -> Result<Option<Block>, StoreError> {
self.engine.get_block_by_hash(block_hash).await
}
pub async fn get_block_by_number(
&self,
block_number: BlockNumber,
) -> Result<Option<Block>, StoreError> {
self.engine.get_block_by_number(block_number).await
}
pub async fn get_storage_at(
&self,
block_number: BlockNumber,
address: Address,
storage_key: H256,
) -> Result<Option<U256>, StoreError> {
match self.get_canonical_block_hash(block_number).await? {
Some(block_hash) => self.get_storage_at_hash(block_hash, address, storage_key),
None => Ok(None),
}
}
pub fn get_storage_at_hash(
&self,
block_hash: BlockHash,
address: Address,
storage_key: H256,
) -> Result<Option<U256>, StoreError> {
let Some(storage_trie) = self.storage_trie(block_hash, address)? else {
return Ok(None);
};
let hashed_key = hash_key(&storage_key);
storage_trie
.get(&hashed_key)?
.map(|rlp| U256::decode(&rlp).map_err(StoreError::RLPDecode))
.transpose()
}
pub async fn set_chain_config(&self, chain_config: &ChainConfig) -> Result<(), StoreError> {
*self
.chain_config
.write()
.map_err(|_| StoreError::LockError)? = *chain_config;
self.engine.set_chain_config(chain_config).await
}
pub fn get_chain_config(&self) -> Result<ChainConfig, StoreError> {
Ok(*self
.chain_config
.read()
.map_err(|_| StoreError::LockError)?)
}
pub async fn update_earliest_block_number(
&self,
block_number: BlockNumber,
) -> Result<(), StoreError> {
self.engine.update_earliest_block_number(block_number).await
}
pub async fn get_earliest_block_number(&self) -> Result<BlockNumber, StoreError> {
self.engine
.get_earliest_block_number()
.await?
.ok_or(StoreError::MissingEarliestBlockNumber)
}
pub async fn get_finalized_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
self.engine.get_finalized_block_number().await
}
pub async fn get_safe_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
self.engine.get_safe_block_number().await
}
pub async fn get_latest_block_number(&self) -> Result<BlockNumber, StoreError> {
Ok(self
.latest_block_header
.read()
.map_err(|_| StoreError::LockError)?
.number)
}
pub async fn update_pending_block_number(
&self,
block_number: BlockNumber,
) -> Result<(), StoreError> {
self.engine.update_pending_block_number(block_number).await
}
pub async fn get_pending_block_number(&self) -> Result<Option<BlockNumber>, StoreError> {
self.engine.get_pending_block_number().await
}
pub async fn get_canonical_block_hash(
&self,
block_number: BlockNumber,
) -> Result<Option<BlockHash>, StoreError> {
{
let last = self
.latest_block_header
.read()
.map_err(|_| StoreError::LockError)?;
if last.number == block_number {
return Ok(Some(last.hash()));
}
}
self.engine.get_canonical_block_hash(block_number).await
}
pub async fn get_latest_canonical_block_hash(&self) -> Result<Option<BlockHash>, StoreError> {
Ok(Some(
self.latest_block_header
.read()
.map_err(|_| StoreError::LockError)?
.hash(),
))
}
/// Updates the canonical chain.
/// Inserts new canonical blocks, removes blocks beyond the new head,
/// and updates the head, safe, and finalized block pointers.
/// All operations are performed in a single database transaction.
pub async fn forkchoice_update(
&self,
new_canonical_blocks: Option<Vec<(BlockNumber, BlockHash)>>,
head_number: BlockNumber,
head_hash: BlockHash,
safe: Option<BlockNumber>,
finalized: Option<BlockNumber>,
) -> Result<(), StoreError> {
// Updates first the latest_block_header
// to avoid nonce inconsistencies #3927.
*self
.latest_block_header
.write()
.map_err(|_| StoreError::LockError)? = self
.engine
.get_block_header_by_hash(head_hash)?
.ok_or_else(|| StoreError::MissingLatestBlockNumber)?;
self.engine
.forkchoice_update(
new_canonical_blocks,
head_number,
head_hash,
safe,
finalized,
)
.await?;
Ok(())
}
/// Obtain the storage trie for the given block
pub fn state_trie(&self, block_hash: BlockHash) -> Result<Option<Trie>, StoreError> {
let Some(header) = self.get_block_header_by_hash(block_hash)? else {
return Ok(None);
};
Ok(Some(self.engine.open_state_trie(header.state_root)?))
}
/// Obtain the storage trie for the given account on the given block
pub fn storage_trie(
&self,
block_hash: BlockHash,
address: Address,
) -> Result<Option<Trie>, StoreError> {
let Some(header) = self.get_block_header_by_hash(block_hash)? else {
return Ok(None);
};
// Fetch Account from state_trie
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
let hashed_address = hash_address(&address);
let Some(encoded_account) = state_trie.get(&hashed_address)? else {
return Ok(None);
};
let account = AccountState::decode(&encoded_account)?;
// Open storage_trie
let storage_root = account.storage_root;
Ok(Some(self.engine.open_storage_trie(
H256::from_slice(&hashed_address),
storage_root,
header.state_root,
)?))
}
pub async fn get_account_state(
&self,
block_number: BlockNumber,
address: Address,
) -> Result<Option<AccountState>, StoreError> {
let Some(block_hash) = self.get_canonical_block_hash(block_number).await? else {
return Ok(None);
};
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
get_account_state_from_trie(&state_trie, address)
}
pub fn get_account_state_by_hash(
&self,
block_hash: BlockHash,
address: Address,
) -> Result<Option<AccountState>, StoreError> {
let Some(state_trie) = self.state_trie(block_hash)? else {
return Ok(None);
};
self.get_account_state_from_trie(&state_trie, address)
}
pub fn get_account_state_from_trie(
&self,
state_trie: &Trie,
address: Address,
) -> Result<Option<AccountState>, StoreError> {
let hashed_address = hash_address(&address);
let Some(encoded_state) = state_trie.get(&hashed_address)? else {
return Ok(None);
};
Ok(Some(AccountState::decode(&encoded_state)?))
}
/// Constructs a merkle proof for the given account address against a given state.
/// If storage_keys are provided, also constructs the storage proofs for those keys.
///
/// Returns `None` if the state trie is missing, otherwise returns the proof.
pub async fn get_account_proof(
&self,
state_root: H256,
address: Address,
storage_keys: &[H256],
) -> Result<Option<AccountProof>, StoreError> {
// TODO: check state root
// let Some(state_trie) = self.open_state_trie(state_trie)? else {
// return Ok(None);
// };
let state_trie = self.open_state_trie(state_root)?;
let hashed_address = hash_address_fixed(&address);
let address_path = hashed_address.0.to_vec();
let proof = state_trie.get_proof(&address_path)?;
let account_opt = state_trie
.get(&address_path)?
.map(|encoded_state| AccountState::decode(&encoded_state))
.transpose()?;
let mut storage_proof = Vec::with_capacity(storage_keys.len());
if let Some(account) = &account_opt {
let storage_trie = self.engine.open_storage_trie(
hashed_address,
account.storage_root,
state_trie.hash_no_commit(),
)?;
for key in storage_keys {
let hashed_key = hash_key(key);
let proof = storage_trie.get_proof(&hashed_key)?;
let value = storage_trie
.get(&hashed_key)?
.map(|rlp| U256::decode(&rlp).map_err(StoreError::RLPDecode))
.transpose()?
.unwrap_or_default();
let slot_proof = StorageSlotProof {
proof,
key: *key,
value,
};
storage_proof.push(slot_proof);
}
} else {
storage_proof.extend(storage_keys.iter().map(|key| StorageSlotProof {
proof: Vec::new(),
key: *key,
value: U256::zero(),
}));
}
let account = account_opt.unwrap_or_default();
let account_proof = AccountProof {
proof,
account,
storage_proof,
};
Ok(Some(account_proof))
}
// Returns an iterator across all accounts in the state trie given by the state_root
// Does not check that the state_root is valid
pub fn iter_accounts_from(
&self,
state_root: H256,
starting_address: H256,
) -> Result<impl Iterator<Item = (H256, AccountState)>, StoreError> {
let mut iter = self.engine.open_locked_state_trie(state_root)?.into_iter();
iter.advance(starting_address.0.to_vec())?;
Ok(iter.content().map_while(|(path, value)| {
Some((H256::from_slice(&path), AccountState::decode(&value).ok()?))
}))
}
// Returns an iterator across all accounts in the state trie given by the state_root
// Does not check that the state_root is valid
pub fn iter_accounts(
&self,
state_root: H256,
) -> Result<impl Iterator<Item = (H256, AccountState)>, StoreError> {
self.iter_accounts_from(state_root, H256::zero())
}
// Returns an iterator across all accounts in the state trie given by the state_root
// Does not check that the state_root is valid
pub fn iter_storage_from(
&self,
state_root: H256,
hashed_address: H256,
starting_slot: H256,
) -> Result<Option<impl Iterator<Item = (H256, U256)>>, StoreError> {
let state_trie = self.engine.open_locked_state_trie(state_root)?;
let Some(account_rlp) = state_trie.get(&hashed_address.as_bytes().to_vec())? else {