-
Notifications
You must be signed in to change notification settings - Fork 891
/
mod.rs
2076 lines (1890 loc) · 77.7 KB
/
mod.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
//! Output of execution.
use reth_db::{
cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO, DbDupCursorRW},
models::{AccountBeforeTx, BlockNumberAddress},
tables,
transaction::{DbTx, DbTxMut},
DatabaseError as DbError,
};
use reth_interfaces::Error;
use reth_primitives::{
bloom::logs_bloom, keccak256, proofs::calculate_receipt_root_ref, Account, Address,
BlockNumber, Bloom, Bytecode, Log, PruneMode, PruneModes, Receipt, StorageEntry, H256,
MINIMUM_PRUNING_DISTANCE, U256,
};
use reth_trie::{
hashed_cursor::{HashedPostState, HashedPostStateCursorFactory, HashedStorage},
StateRoot, StateRootError,
};
use std::collections::{BTreeMap, BTreeSet};
mod account;
pub use account::AccountChanges;
mod storage;
pub use storage::{Storage, StorageChanges, StorageChangeset, StorageTransition, StorageWipe};
// todo: rewrite all the docs for this
/// The state of accounts after execution of one or more transactions, including receipts and new
/// bytecode.
///
/// The latest state can be found in `accounts`, `storage`, and `bytecode`. The receipts for the
/// transactions that lead to these changes can be found in `receipts`, and each change leading to
/// this state can be found in `changes`.
///
/// # Wiped Storage
///
/// The [Storage] type has a field, `wiped` which denotes whether the pre-existing storage in the
/// database should be cleared or not.
///
/// If `wiped` is true, then the account was selfdestructed at some point, and the values contained
/// in `storage` should be the only values written to the database.
///
/// # Transitions
///
/// The block level transition includes:
///
/// - Block rewards
/// - Ommer rewards
/// - Withdrawals
/// - The irregular state change for the DAO hardfork
///
/// For multi-block [PostState]s it is not possible to figure out what transition ID maps on to a
/// transaction or a block.
///
/// # Shaving Allocations
///
/// Since most [PostState]s in reth are for multiple blocks it is better to pre-allocate capacity
/// for receipts and changes, which [PostState::new] does, and thus it (or
/// [PostState::with_tx_capacity]) should be preferred to using the [Default] implementation.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub struct PostState {
/// The state of all modified accounts after execution.
///
/// If the value contained is `None`, then the account should be deleted.
accounts: BTreeMap<Address, Option<Account>>,
/// The state of all modified storage after execution
///
/// If the contained [Storage] is marked as wiped, then all storage values should be cleared
/// from the database.
storage: BTreeMap<Address, Storage>,
/// The state of accounts before they were changed in the given block.
///
/// If the value is `None`, then the account is new, otherwise it is a change.
account_changes: AccountChanges,
/// The state of account storage before it was changed in the given block.
///
/// This map only contains old values for storage slots.
storage_changes: StorageChanges,
/// New code created during the execution
bytecode: BTreeMap<H256, Bytecode>,
/// The receipt(s) of the executed transaction(s).
receipts: BTreeMap<BlockNumber, Vec<Receipt>>,
/// Pruning configuration.
prune_modes: PruneModes,
}
impl PostState {
/// Create an empty [PostState].
pub fn new() -> Self {
Self::default()
}
/// Create an empty [PostState] with pre-allocated space for a certain amount of transactions.
pub fn with_tx_capacity(block: BlockNumber, txs: usize) -> Self {
Self { receipts: BTreeMap::from([(block, Vec::with_capacity(txs))]), ..Default::default() }
}
/// Add a pruning configuration.
pub fn add_prune_modes(&mut self, prune_modes: PruneModes) {
self.prune_modes = prune_modes;
}
/// Return the current size of the poststate.
///
/// Size is the sum of individual changes to accounts, storage, bytecode and receipts.
pub fn size_hint(&self) -> usize {
// The amount of plain state account entries to update.
self.accounts.len()
// The approximate amount of plain state storage entries to update.
// NOTE: This can be improved by manually keeping track of the storage size for each account.
+ self.storage.len()
// The amount of bytecodes to insert.
+ self.bytecode.len()
// The approximate amount of receipts.
// NOTE: This can be improved by manually keeping track of the receipt size for each block number.
+ self.receipts.len()
// The approximate amount of changsets to update.
+ self.changeset_size_hint()
}
/// Return the current size of history changes in the poststate.
pub fn changeset_size_hint(&self) -> usize {
// The amount of account changesets to insert.
self.account_changes.size
// The approximate amount of storage changes to insert.
// NOTE: This does not include the entries for primary storage wipes,
// which need to be read from plain state.
+ self.storage_changes.size
}
/// Get the latest state of all changed accounts.
pub fn accounts(&self) -> &BTreeMap<Address, Option<Account>> {
&self.accounts
}
/// Get a reference to all the account changes
pub fn account_changes(&self) -> &AccountChanges {
&self.account_changes
}
/// Get a reference to all the storage changes
pub fn storage_changes(&self) -> &StorageChanges {
&self.storage_changes
}
/// Get the latest state for a specific account.
///
/// # Returns
///
/// - `None` if the account does not exist
/// - `Some(&None)` if the account existed, but has since been deleted.
/// - `Some(..)` if the account currently exists
pub fn account(&self, address: &Address) -> Option<&Option<Account>> {
self.accounts.get(address)
}
/// Get the latest state of storage.
pub fn storage(&self) -> &BTreeMap<Address, Storage> {
&self.storage
}
/// Get the storage for an account.
pub fn account_storage(&self, address: &Address) -> Option<&Storage> {
self.storage.get(address)
}
/// Get the newly created bytecodes
pub fn bytecodes(&self) -> &BTreeMap<H256, Bytecode> {
&self.bytecode
}
/// Get a bytecode in the post-state.
pub fn bytecode(&self, code_hash: &H256) -> Option<&Bytecode> {
self.bytecode.get(code_hash)
}
/// Get the receipts for the transactions executed to form this [PostState].
pub fn receipts(&self, block: BlockNumber) -> &[Receipt] {
self.receipts.get(&block).map(Vec::as_slice).unwrap_or(&[])
}
/// Returns an iterator over all logs in this [PostState].
pub fn logs(&self, block: BlockNumber) -> impl Iterator<Item = &Log> {
self.receipts(block).iter().flat_map(|r| r.logs.iter())
}
/// Returns the logs bloom for all recorded logs.
pub fn logs_bloom(&self, block: BlockNumber) -> Bloom {
logs_bloom(self.logs(block))
}
/// Returns the receipt root for all recorded receipts.
/// TODO: This function hides an expensive operation (bloom). We should probably make it more
/// explicit.
pub fn receipts_root(&self, block: BlockNumber) -> H256 {
calculate_receipt_root_ref(self.receipts(block))
}
/// Hash all changed accounts and storage entries that are currently stored in the post state.
///
/// # Returns
///
/// The hashed post state.
pub fn hash_state_slow(&self) -> HashedPostState {
let mut hashed_post_state = HashedPostState::default();
// Insert accounts with hashed keys from account changes.
for (address, account) in self.accounts() {
let hashed_address = keccak256(address);
if let Some(account) = account {
hashed_post_state.insert_account(hashed_address, *account);
} else {
hashed_post_state.insert_cleared_account(hashed_address);
}
}
// Insert accounts and storages with hashed keys from storage changes.
for (address, storage) in self.storage() {
let mut hashed_storage = HashedStorage::new(storage.wiped());
for (slot, value) in &storage.storage {
let hashed_slot = keccak256(H256(slot.to_be_bytes()));
if *value == U256::ZERO {
hashed_storage.insert_zero_valued_slot(hashed_slot);
} else {
hashed_storage.insert_non_zero_valued_storage(hashed_slot, *value);
}
}
hashed_post_state.insert_hashed_storage(keccak256(address), hashed_storage);
}
hashed_post_state
}
/// Calculate the state root for this [PostState].
/// Internally, function calls [Self::hash_state_slow] to obtain the [HashedPostState].
/// Afterwards, it retrieves the [PrefixSets](reth_trie::prefix_set::PrefixSet) of changed keys
/// from the [HashedPostState] and uses them to calculate the incremental state root.
///
/// # Example
///
/// ```
/// use reth_primitives::{Address, Account};
/// use reth_provider::PostState;
/// use reth_db::{test_utils::create_test_rw_db, database::Database};
///
/// // Initialize the database
/// let db = create_test_rw_db();
///
/// // Initialize the post state
/// let mut post_state = PostState::new();
///
/// // Create an account
/// let block_number = 1;
/// let address = Address::random();
/// post_state.create_account(1, address, Account { nonce: 1, ..Default::default() });
///
/// // Calculate the state root
/// let tx = db.tx().expect("failed to create transaction");
/// let state_root = post_state.state_root_slow(&tx);
/// ```
///
/// # Returns
///
/// The state root for this [PostState].
pub fn state_root_slow<'a, 'tx, TX: DbTx<'tx>>(
&self,
tx: &'a TX,
) -> Result<H256, StateRootError> {
let hashed_post_state = self.hash_state_slow().sorted();
let (account_prefix_set, storage_prefix_set) = hashed_post_state.construct_prefix_sets();
let hashed_cursor_factory = HashedPostStateCursorFactory::new(tx, &hashed_post_state);
StateRoot::new(tx)
.with_hashed_cursor_factory(&hashed_cursor_factory)
.with_changed_account_prefixes(account_prefix_set)
.with_changed_storage_prefixes(storage_prefix_set)
.root()
}
// todo: note overwrite behavior, i.e. changes in `other` take precedent
/// Extend this [PostState] with the changes in another [PostState].
pub fn extend(&mut self, mut other: PostState) {
// Insert storage change sets
for (block_number, storage_changes) in std::mem::take(&mut other.storage_changes).inner {
for (address, their_storage_transition) in storage_changes {
let our_storage = self.storage.entry(address).or_default();
let (wipe, storage) = if their_storage_transition.wipe.is_wiped() {
// Check existing storage change.
match self.storage_changes.get(&block_number).and_then(|ch| ch.get(&address)) {
Some(change) if change.wipe.is_wiped() => (), // already counted
_ => {
our_storage.times_wiped += 1;
}
};
// Check if this is the first wipe.
let wipe = if our_storage.times_wiped == 1 {
StorageWipe::Primary
} else {
// Even if the wipe in other poststate was primary before, demote it to
// secondary.
StorageWipe::Secondary
};
let mut wiped_storage = std::mem::take(&mut our_storage.storage);
wiped_storage.extend(their_storage_transition.storage);
(wipe, wiped_storage)
} else {
(StorageWipe::None, their_storage_transition.storage)
};
self.storage_changes.insert_for_block_and_address(
block_number,
address,
wipe,
storage.into_iter(),
);
}
}
// Insert account change sets
for (block_number, account_changes) in std::mem::take(&mut other.account_changes).inner {
self.account_changes.insert_for_block(block_number, account_changes);
}
// Update plain state
self.accounts.extend(other.accounts);
for (address, their_storage) in other.storage {
let our_storage = self.storage.entry(address).or_default();
our_storage.storage.extend(their_storage.storage);
}
self.receipts.extend(other.receipts);
self.bytecode.extend(other.bytecode);
}
/// Reverts each change up to the `target_block_number` (excluding).
///
/// The reverted changes are removed from this post-state, and their effects are reverted.
pub fn revert_to(&mut self, target_block_number: BlockNumber) {
// Revert account state & changes
let removed_account_changes = self.account_changes.drain_above(target_block_number);
let changed_accounts = self
.account_changes
.iter()
.flat_map(|(_, account_changes)| account_changes.iter().map(|(address, _)| *address))
.collect::<BTreeSet<_>>();
let mut account_state: BTreeMap<Address, Option<Account>> = BTreeMap::default();
for address in changed_accounts {
let info = removed_account_changes
.iter()
.find_map(|(_, changes)| {
changes.iter().find_map(|ch| (ch.0 == &address).then_some(*ch.1))
})
.unwrap_or(*self.accounts.get(&address).expect("exists"));
account_state.insert(address, info);
}
self.accounts = account_state;
// Revert changes and recreate the storage state
let removed_storage_changes = self.storage_changes.drain_above(target_block_number);
let mut storage_state: BTreeMap<Address, Storage> = BTreeMap::default();
for (_, storage_changes) in self.storage_changes.iter() {
for (address, storage_change) in storage_changes {
let entry = storage_state.entry(*address).or_default();
if storage_change.wipe.is_wiped() {
entry.times_wiped += 1;
}
for (slot, _) in storage_change.storage.iter() {
let value = removed_storage_changes
.iter()
.find_map(|(_, changes)| {
changes.iter().find_map(|ch| {
if ch.0 == address {
match ch.1.storage.iter().find_map(|(changed_slot, value)| {
(slot == changed_slot).then_some(*value)
}) {
value @ Some(_) => Some(value),
None if ch.1.wipe.is_wiped() => Some(None),
None => None,
}
} else {
None
}
})
})
.unwrap_or_else(|| {
self.storage.get(address).and_then(|s| s.storage.get(slot).copied())
});
if let Some(value) = value {
entry.storage.insert(*slot, value);
}
}
}
}
self.storage = storage_state;
// Revert receipts
self.receipts.retain(|block_number, _| *block_number <= target_block_number);
}
/// Reverts each change up to and including any change that is part of `transition_id`.
///
/// The reverted changes are removed from this post-state, and their effects are reverted.
///
/// A new post-state containing the pre-revert state, as well as the reverted changes *only* is
/// returned.
///
/// This effectively splits the post state in two:
///
/// 1. This post-state has the changes reverted
/// 2. The returned post-state does *not* have the changes reverted, but only contains the
/// descriptions of the changes that were reverted in the first post-state.
pub fn split_at(&mut self, revert_to_block: BlockNumber) -> Self {
// Clone ourselves
let mut non_reverted_state = self.clone();
// Revert the desired changes
self.revert_to(revert_to_block);
// Remove all changes in the returned post-state that were not reverted
non_reverted_state.account_changes.retain_above(revert_to_block);
let updated_times_wiped = non_reverted_state.storage_changes.retain_above(revert_to_block);
// Update or reset the number of times the account was wiped.
for (address, storage) in non_reverted_state.storage.iter_mut() {
storage.times_wiped = updated_times_wiped.get(address).cloned().unwrap_or_default();
}
// Remove receipts
non_reverted_state.receipts.retain(|block_number, _| *block_number > revert_to_block);
non_reverted_state
}
/// Add a newly created account to the post-state.
pub fn create_account(
&mut self,
block_number: BlockNumber,
address: Address,
account: Account,
) {
self.accounts.insert(address, Some(account));
self.account_changes.insert(block_number, address, None, Some(account));
}
/// Add a changed account to the post-state.
///
/// If the account also has changed storage values, [PostState::change_storage] should also be
/// called.
pub fn change_account(
&mut self,
block_number: BlockNumber,
address: Address,
old: Account,
new: Account,
) {
self.accounts.insert(address, Some(new));
self.account_changes.insert(block_number, address, Some(old), Some(new));
}
/// Mark an account as destroyed.
pub fn destroy_account(
&mut self,
block_number: BlockNumber,
address: Address,
account: Account,
) {
self.accounts.insert(address, None);
self.account_changes.insert(block_number, address, Some(account), None);
let storage = self.storage.entry(address).or_default();
storage.times_wiped += 1;
let wipe =
if storage.times_wiped == 1 { StorageWipe::Primary } else { StorageWipe::Secondary };
let wiped_storage = std::mem::take(&mut storage.storage);
self.storage_changes.insert_for_block_and_address(
block_number,
address,
wipe,
wiped_storage.into_iter(),
);
}
/// Add changed storage values to the post-state.
pub fn change_storage(
&mut self,
block_number: BlockNumber,
address: Address,
changeset: StorageChangeset,
) {
self.storage
.entry(address)
.or_default()
.storage
.extend(changeset.iter().map(|(slot, (_, new))| (*slot, *new)));
self.storage_changes.insert_for_block_and_address(
block_number,
address,
StorageWipe::None,
changeset.into_iter().map(|(slot, (old, _))| (slot, old)),
);
}
/// Add new bytecode to the post-state.
pub fn add_bytecode(&mut self, code_hash: H256, bytecode: Bytecode) {
// Assumption: `insert` will override the value if present, but since the code hash for a
// given bytecode will always be the same, we are overriding with the same value.
//
// In other words: if this entry already exists, replacing the bytecode will replace with
// the same value, which is wasteful.
self.bytecode.entry(code_hash).or_insert(bytecode);
}
/// Add a transaction receipt to the post-state.
///
/// Transactions should always include their receipts in the post-state.
pub fn add_receipt(&mut self, block: BlockNumber, receipt: Receipt) {
self.receipts.entry(block).or_default().push(receipt);
}
/// Write changeset history to the database.
pub fn write_history_to_db<'a, TX: DbTxMut<'a> + DbTx<'a>>(
&mut self,
tx: &TX,
tip: BlockNumber,
) -> Result<(), DbError> {
// Write storage changes
tracing::trace!(target: "provider::post_state", "Writing storage changes");
let mut storages_cursor = tx.cursor_dup_write::<tables::PlainStorageState>()?;
let mut storage_changeset_cursor = tx.cursor_dup_write::<tables::StorageChangeSet>()?;
for (block_number, storage_changes) in
std::mem::take(&mut self.storage_changes).inner.into_iter()
{
for (address, mut storage) in storage_changes.into_iter() {
if self.prune_modes.should_prune_storage_history(block_number, tip) {
continue
}
let storage_id = BlockNumberAddress((block_number, address));
// If the account was created and wiped at the same block, skip all storage changes
if storage.wipe.is_wiped() &&
self.account_changes
.get(&block_number)
.and_then(|changes| changes.get(&address).map(|info| info.is_none()))
// No account info available, fallback to `false`
.unwrap_or_default()
{
continue
}
// If we are writing the primary storage wipe transition, the pre-existing plain
// storage state has to be taken from the database and written to storage history.
// See [StorageWipe::Primary] for more details.
if storage.wipe.is_primary() {
if let Some((_, entry)) = storages_cursor.seek_exact(address)? {
tracing::trace!(target: "provider::post_state", ?storage_id, key = ?entry.key, "Storage wiped");
let key = U256::from_be_bytes(entry.key.to_fixed_bytes());
if !storage.storage.contains_key(&key) {
storage.storage.insert(entry.key.into(), entry.value);
}
while let Some(entry) = storages_cursor.next_dup_val()? {
let key = U256::from_be_bytes(entry.key.to_fixed_bytes());
if !storage.storage.contains_key(&key) {
storage.storage.insert(entry.key.into(), entry.value);
}
}
}
}
for (slot, old_value) in storage.storage {
tracing::trace!(target: "provider::post_state", ?storage_id, ?slot, ?old_value, "Storage changed");
storage_changeset_cursor.append_dup(
storage_id,
StorageEntry { key: H256(slot.to_be_bytes()), value: old_value },
)?;
}
}
}
// Write account changes
tracing::trace!(target: "provider::post_state", "Writing account changes");
let mut account_changeset_cursor = tx.cursor_dup_write::<tables::AccountChangeSet>()?;
for (block_number, account_changes) in
std::mem::take(&mut self.account_changes).inner.into_iter()
{
if self.prune_modes.should_prune_account_history(block_number, tip) {
continue
}
for (address, info) in account_changes.into_iter() {
tracing::trace!(target: "provider::post_state", block_number, ?address, old = ?info, "Account changed");
account_changeset_cursor
.append_dup(block_number, AccountBeforeTx { address, info })?;
}
}
Ok(())
}
/// Write the post state to the database.
pub fn write_to_db<'a, TX: DbTxMut<'a> + DbTx<'a>>(
mut self,
tx: &TX,
tip: BlockNumber,
) -> Result<(), Error> {
self.write_history_to_db(tx, tip)?;
// Write new storage state
tracing::trace!(target: "provider::post_state", len = self.storage.len(), "Writing new storage state");
let mut storages_cursor = tx.cursor_dup_write::<tables::PlainStorageState>()?;
for (address, storage) in self.storage.into_iter() {
// If the storage was wiped at least once, remove all previous entries from the
// database.
if storage.wiped() {
tracing::trace!(target: "provider::post_state", ?address, "Wiping storage from plain state");
if storages_cursor.seek_exact(address)?.is_some() {
storages_cursor.delete_current_duplicates()?;
}
}
for (key, value) in storage.storage {
tracing::trace!(target: "provider::post_state", ?address, ?key, "Updating plain state storage");
let key: H256 = key.into();
if let Some(entry) = storages_cursor.seek_by_key_subkey(address, key)? {
if entry.key == key {
storages_cursor.delete_current()?;
}
}
if value != U256::ZERO {
storages_cursor.upsert(address, StorageEntry { key, value })?;
}
}
}
// Write new account state
tracing::trace!(target: "provider::post_state", len = self.accounts.len(), "Writing new account state");
let mut accounts_cursor = tx.cursor_write::<tables::PlainAccountState>()?;
for (address, account) in self.accounts.into_iter() {
if let Some(account) = account {
tracing::trace!(target: "provider::post_state", ?address, "Updating plain state account");
accounts_cursor.upsert(address, account)?;
} else if accounts_cursor.seek_exact(address)?.is_some() {
tracing::trace!(target: "provider::post_state", ?address, "Deleting plain state account");
accounts_cursor.delete_current()?;
}
}
// Write bytecode
tracing::trace!(target: "provider::post_state", len = self.bytecode.len(), "Writing bytecodes");
let mut bytecodes_cursor = tx.cursor_write::<tables::Bytecodes>()?;
for (hash, bytecode) in self.bytecode.into_iter() {
bytecodes_cursor.upsert(hash, bytecode)?;
}
// Write the receipts of the transactions if not pruned
tracing::trace!(target: "provider::post_state", len = self.receipts.len(), "Writing receipts");
if !self.receipts.is_empty() && self.prune_modes.receipts != Some(PruneMode::Full) {
let mut bodies_cursor = tx.cursor_read::<tables::BlockBodyIndices>()?;
let mut receipts_cursor = tx.cursor_write::<tables::Receipts>()?;
let contract_log_pruner = self
.prune_modes
.receipts_log_filter
.group_by_block(tip, None)
.map_err(|e| Error::Custom(e.to_string()))?;
// Empty implies that there is going to be
// addresses to include in the filter in a future block. None means there isn't any kind
// of configuration.
let mut address_filter: Option<(u64, Vec<&Address>)> = None;
for (block, receipts) in self.receipts {
// [`PrunePart::Receipts`] takes priority over [`PrunePart::ContractLogs`]
if receipts.is_empty() || self.prune_modes.should_prune_receipts(block, tip) {
continue
}
// All receipts from the last 128 blocks are required for blockchain tree, even with
// [`PrunePart::ContractLogs`].
let prunable_receipts =
PruneMode::Distance(MINIMUM_PRUNING_DISTANCE).should_prune(block, tip);
if prunable_receipts && !contract_log_pruner.is_empty() {
if address_filter.is_none() {
address_filter = Some((0, vec![]));
}
// Get all addresses higher than the previous checked block up to the current
// one
if let Some((prev_block, filter)) = &mut address_filter {
for (_, addresses) in contract_log_pruner.range(*prev_block..=block) {
filter.extend_from_slice(addresses.as_slice())
}
*prev_block = block;
}
}
let (_, body_indices) =
bodies_cursor.seek_exact(block)?.expect("body indices exist");
let tx_range = body_indices.tx_num_range();
assert_eq!(receipts.len(), tx_range.clone().count(), "Receipt length mismatch");
for (tx_num, receipt) in tx_range.zip(receipts) {
if prunable_receipts {
// If there is an address_filter, and it does not contain any of the
// contract addresses, then skip writing this
// receipt.
if let Some((_, filter)) = &address_filter {
if !receipt.logs.iter().any(|log| filter.contains(&&log.address)) {
continue
}
}
}
receipts_cursor.append(tx_num, receipt)?;
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{AccountReader, ProviderFactory};
use reth_db::{
database::Database, test_utils::create_test_rw_db, transaction::DbTx, DatabaseEnv,
};
use reth_primitives::{proofs::EMPTY_ROOT, MAINNET};
use reth_trie::test_utils::state_root;
use std::sync::Arc;
// Ensure that the transition id is not incremented if postate is extended by another empty
// poststate.
#[test]
fn extend_empty() {
let mut a = PostState::new();
// Extend empty poststate with another empty poststate
a.extend(PostState::new());
// Add single transition and extend with empty poststate
a.create_account(1, Address::zero(), Account::default());
a.extend(PostState::new());
assert_eq!(a.account_changes.iter().fold(0, |len, (_, changes)| len + changes.len()), 1);
}
#[test]
fn extend() {
let mut a = PostState::new();
a.create_account(1, Address::zero(), Account::default());
a.destroy_account(1, Address::zero(), Account::default());
assert_eq!(a.account_changes.iter().fold(0, |len, (_, changes)| len + changes.len()), 0);
let mut b = PostState::new();
b.create_account(2, Address::repeat_byte(0xff), Account::default());
assert_eq!(b.account_changes.iter().fold(0, |len, (_, changes)| len + changes.len()), 1);
let mut c = a.clone();
c.extend(b.clone());
assert_eq!(c.account_changes.iter().fold(0, |len, (_, changes)| len + changes.len()), 1);
let mut d = PostState::new();
d.create_account(3, Address::zero(), Account::default());
d.destroy_account(3, Address::zero(), Account::default());
c.extend(d);
assert_eq!(c.account_storage(&Address::zero()).unwrap().times_wiped, 2);
// Primary wipe occurred at block #1.
assert_eq!(
c.storage_changes.get(&1).unwrap().get(&Address::zero()).unwrap().wipe,
StorageWipe::Primary
);
// Primary wipe occurred at block #3.
assert_eq!(
c.storage_changes.get(&3).unwrap().get(&Address::zero()).unwrap().wipe,
StorageWipe::Secondary
);
}
#[test]
fn revert_to() {
let mut state = PostState::new();
let address1 = Address::repeat_byte(0);
let account1 = Account { nonce: 1, balance: U256::from(1), bytecode_hash: None };
state.create_account(1, address1, account1);
state.create_account(
2,
Address::repeat_byte(0xff),
Account { nonce: 2, balance: U256::from(2), bytecode_hash: None },
);
assert_eq!(
state.account_changes.iter().fold(0, |len, (_, changes)| len + changes.len()),
2
);
let revert_to = 1;
state.revert_to(revert_to);
assert_eq!(state.accounts, BTreeMap::from([(address1, Some(account1))]));
assert_eq!(
state.account_changes.iter().fold(0, |len, (_, changes)| len + changes.len()),
1
);
}
#[test]
fn wiped_revert() {
let address = Address::random();
let init_block_number = 0;
let init_account = Account { balance: U256::from(3), ..Default::default() };
let init_slot = U256::from(1);
// Create init state for demonstration purposes
// Block 0
// Account: exists
// Storage: 0x01: 1
let mut init_state = PostState::new();
init_state.create_account(init_block_number, address, init_account);
init_state.change_storage(
init_block_number,
address,
BTreeMap::from([(init_slot, (U256::ZERO, U256::from(1)))]),
);
assert_eq!(
init_state.storage.get(&address),
Some(&Storage {
storage: BTreeMap::from([(init_slot, U256::from(1))]),
times_wiped: 0
})
);
let mut post_state = PostState::new();
// Block 1
// <nothing>
// Block 2
// Account: destroyed
// Storage: wiped
post_state.destroy_account(2, address, init_account);
assert!(post_state.storage.get(&address).unwrap().wiped());
// Block 3
// Account: recreated
// Storage: wiped, then 0x01: 2
let recreated_account = Account { balance: U256::from(4), ..Default::default() };
post_state.create_account(3, address, recreated_account);
post_state.change_storage(
3,
address,
BTreeMap::from([(init_slot, (U256::ZERO, U256::from(2)))]),
);
assert!(post_state.storage.get(&address).unwrap().wiped());
// Revert to block 2
post_state.revert_to(2);
assert!(post_state.storage.get(&address).unwrap().wiped());
assert_eq!(
post_state.storage.get(&address).unwrap(),
&Storage { times_wiped: 1, storage: BTreeMap::default() }
);
// Revert to block 1
post_state.revert_to(1);
assert_eq!(post_state.storage.get(&address), None);
}
#[test]
fn split_at() {
let address1 = Address::random();
let address2 = Address::random();
let slot1 = U256::from(1);
let slot2 = U256::from(2);
let mut state = PostState::new();
// Block #1
// Create account 1 and change its storage
// Assume account 2 already exists in the database and change storage for it
state.create_account(1, address1, Account::default());
state.change_storage(1, address1, BTreeMap::from([(slot1, (U256::ZERO, U256::from(1)))]));
state.change_storage(1, address1, BTreeMap::from([(slot2, (U256::ZERO, U256::from(1)))]));
state.change_storage(1, address2, BTreeMap::from([(slot2, (U256::ZERO, U256::from(2)))]));
let block1_account_changes = (1, BTreeMap::from([(address1, None)]));
let block1_storage_changes = (
1,
BTreeMap::from([
(
address1,
StorageTransition {
storage: BTreeMap::from([(slot1, U256::ZERO), (slot2, U256::ZERO)]),
wipe: StorageWipe::None,
},
),
(
address2,
StorageTransition {
storage: BTreeMap::from([(slot2, U256::ZERO)]),
wipe: StorageWipe::None,
},
),
]),
);
assert_eq!(
state.account_changes,
AccountChanges { inner: BTreeMap::from([block1_account_changes.clone()]), size: 1 }
);
assert_eq!(
state.storage_changes,
StorageChanges { inner: BTreeMap::from([block1_storage_changes.clone()]), size: 3 }
);
// Block #2
// Destroy account 1
// Change storage for account 2
state.destroy_account(2, address1, Account::default());
state.change_storage(
2,
address2,
BTreeMap::from([(slot2, (U256::from(2), U256::from(4)))]),
);
let account_state_after_block_2 = state.accounts.clone();
let storage_state_after_block_2 = state.storage.clone();
let block2_account_changes = (2, BTreeMap::from([(address1, Some(Account::default()))]));
let block2_storage_changes = (
2,
BTreeMap::from([
(
address1,
StorageTransition {
storage: BTreeMap::from([(slot1, U256::from(1)), (slot2, U256::from(1))]),
wipe: StorageWipe::Primary,
},
),
(
address2,
StorageTransition {
storage: BTreeMap::from([(slot2, U256::from(2))]),
wipe: StorageWipe::None,
},
),
]),
);
assert_eq!(
state.account_changes,
AccountChanges {
inner: BTreeMap::from([
block1_account_changes.clone(),
block2_account_changes.clone()
]),
size: 2
}
);
assert_eq!(
state.storage_changes,
StorageChanges {
inner: BTreeMap::from([
block1_storage_changes.clone(),
block2_storage_changes.clone()
]),
size: 6,
}
);
// Block #3
// Recreate account 1
// Destroy account 2
state.create_account(3, address1, Account::default());
state.change_storage(
3,
address2,
BTreeMap::from([(slot2, (U256::from(4), U256::from(1)))]),
);
state.destroy_account(3, address2, Account::default());
let block3_account_changes =
(3, BTreeMap::from([(address1, None), (address2, Some(Account::default()))]));
let block3_storage_changes = (
3,
BTreeMap::from([(
address2,
StorageTransition {
storage: BTreeMap::from([(slot2, U256::from(4))]),
wipe: StorageWipe::Primary,
},
)]),
);
assert_eq!(
state.account_changes,
AccountChanges {
inner: BTreeMap::from([
block1_account_changes.clone(),
block2_account_changes.clone(),
block3_account_changes.clone()
]),
size: 4
}
);