forked from bluealloy/revm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundle_state.rs
More file actions
1304 lines (1169 loc) · 44.2 KB
/
bundle_state.rs
File metadata and controls
1304 lines (1169 loc) · 44.2 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 super::{
changes::{PlainStorageChangeset, StateChangeset},
reverts::{AccountInfoRevert, Reverts},
AccountRevert, AccountStatus, BundleAccount, PlainStateReverts, RevertToSlot, StorageSlot,
TransitionState,
};
use core::{mem, ops::RangeInclusive};
use revm_interpreter::primitives::{
hash_map::{self, Entry},
AccountInfo, Address, Bytecode, HashMap, HashSet, B256, KECCAK_EMPTY, U256,
};
use std::{
collections::{BTreeMap, BTreeSet},
vec::Vec,
};
/// This builder is used to help to facilitate the initialization of `BundleState` struct
#[derive(Debug)]
pub struct BundleBuilder {
states: HashSet<Address>,
state_original: HashMap<Address, AccountInfo>,
state_present: HashMap<Address, AccountInfo>,
state_storage: HashMap<Address, HashMap<U256, (U256, U256)>>,
reverts: BTreeSet<(u64, Address)>,
revert_range: RangeInclusive<u64>,
revert_account: HashMap<(u64, Address), Option<Option<AccountInfo>>>,
revert_storage: HashMap<(u64, Address), Vec<(U256, U256)>>,
contracts: HashMap<B256, Bytecode>,
}
/// Option for [`BundleState`] when converting it to the plain state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OriginalValuesKnown {
/// Check changed with original values that [BundleState] has.
///
/// If we don't expect parent blocks to be committed or unwinded from database, this option
/// should be used.
Yes,
/// Don't check original values, see the implementation of [BundleState::into_plain_state] for
/// more info.
///
/// If the Bundle can be split or extended, we would not be sure about original values, in that
/// case this option should be used.
No,
}
impl OriginalValuesKnown {
/// Original value is not known for sure.
pub fn is_not_known(&self) -> bool {
matches!(self, Self::No)
}
}
impl Default for BundleBuilder {
fn default() -> Self {
BundleBuilder {
states: HashSet::new(),
state_original: HashMap::new(),
state_present: HashMap::new(),
state_storage: HashMap::new(),
reverts: BTreeSet::new(),
revert_range: 0..=0,
revert_account: HashMap::new(),
revert_storage: HashMap::new(),
contracts: HashMap::new(),
}
}
}
impl BundleBuilder {
/// Create builder instance
///
/// `revert_range` indicates the size of BundleState `reverts` field
pub fn new(revert_range: RangeInclusive<u64>) -> Self {
BundleBuilder {
revert_range,
..Default::default()
}
}
/// Apply a transformation to the builder.
pub fn apply<F>(self, f: F) -> Self
where
F: FnOnce(Self) -> Self,
{
f(self)
}
/// Apply a mutable transformation to the builder.
pub fn apply_mut<F>(&mut self, f: F) -> &mut Self
where
F: FnOnce(&mut Self),
{
f(self);
self
}
/// Collect address info of BundleState state
pub fn state_address(mut self, address: Address) -> Self {
self.set_state_address(address);
self
}
/// Collect account info of BundleState state
pub fn state_original_account_info(mut self, address: Address, original: AccountInfo) -> Self {
self.set_state_original_account_info(address, original);
self
}
/// Collect account info of BundleState state
pub fn state_present_account_info(mut self, address: Address, present: AccountInfo) -> Self {
self.set_state_present_account_info(address, present);
self
}
/// Collect storage info of BundleState state
pub fn state_storage(mut self, address: Address, storage: HashMap<U256, (U256, U256)>) -> Self {
self.set_state_storage(address, storage);
self
}
/// Collect address info of BundleState reverts
///
/// `block_number` must respect `revert_range`, or the input
/// will be ignored during the final build process
pub fn revert_address(mut self, block_number: u64, address: Address) -> Self {
self.set_revert_address(block_number, address);
self
}
/// Collect account info of BundleState reverts
///
/// `block_number` must respect `revert_range`, or the input
/// will be ignored during the final build process
pub fn revert_account_info(
mut self,
block_number: u64,
address: Address,
account: Option<Option<AccountInfo>>,
) -> Self {
self.set_revert_account_info(block_number, address, account);
self
}
/// Collect storage info of BundleState reverts
///
/// `block_number` must respect `revert_range`, or the input
/// will be ignored during the final build process
pub fn revert_storage(
mut self,
block_number: u64,
address: Address,
storage: Vec<(U256, U256)>,
) -> Self {
self.set_revert_storage(block_number, address, storage);
self
}
/// Collect contracts info
pub fn contract(mut self, address: B256, bytecode: Bytecode) -> Self {
self.set_contract(address, bytecode);
self
}
/// Set address info of BundleState state.
pub fn set_state_address(&mut self, address: Address) -> &mut Self {
self.states.insert(address);
self
}
/// Set original account info of BundleState state.
pub fn set_state_original_account_info(
&mut self,
address: Address,
original: AccountInfo,
) -> &mut Self {
self.states.insert(address);
self.state_original.insert(address, original);
self
}
/// Set present account info of BundleState state.
pub fn set_state_present_account_info(
&mut self,
address: Address,
present: AccountInfo,
) -> &mut Self {
self.states.insert(address);
self.state_present.insert(address, present);
self
}
/// Set storage info of BundleState state.
pub fn set_state_storage(
&mut self,
address: Address,
storage: HashMap<U256, (U256, U256)>,
) -> &mut Self {
self.states.insert(address);
self.state_storage.insert(address, storage);
self
}
/// Set address info of BundleState reverts.
pub fn set_revert_address(&mut self, block_number: u64, address: Address) -> &mut Self {
self.reverts.insert((block_number, address));
self
}
/// Set account info of BundleState reverts.
pub fn set_revert_account_info(
&mut self,
block_number: u64,
address: Address,
account: Option<Option<AccountInfo>>,
) -> &mut Self {
self.reverts.insert((block_number, address));
self.revert_account.insert((block_number, address), account);
self
}
/// Set storage info of BundleState reverts.
pub fn set_revert_storage(
&mut self,
block_number: u64,
address: Address,
storage: Vec<(U256, U256)>,
) -> &mut Self {
self.reverts.insert((block_number, address));
self.revert_storage.insert((block_number, address), storage);
self
}
/// Set contracts info.
pub fn set_contract(&mut self, address: B256, bytecode: Bytecode) -> &mut Self {
self.contracts.insert(address, bytecode);
self
}
/// Create `BundleState` instance based on collected information
pub fn build(mut self) -> BundleState {
let mut state_size = 0;
let state = self
.states
.into_iter()
.map(|address| {
let storage = self
.state_storage
.remove(&address)
.map(|s| {
s.into_iter()
.map(|(k, (o_val, p_val))| (k, StorageSlot::new_changed(o_val, p_val)))
.collect()
})
.unwrap_or_default();
let bundle_account = BundleAccount::new(
self.state_original.remove(&address),
self.state_present.remove(&address),
storage,
AccountStatus::Changed,
);
state_size += bundle_account.size_hint();
(address, bundle_account)
})
.collect();
let mut reverts_size = 0;
let mut reverts_map = BTreeMap::new();
for block_number in self.revert_range {
reverts_map.insert(block_number, Vec::new());
}
self.reverts
.into_iter()
.for_each(|(block_number, address)| {
let account = match self
.revert_account
.remove(&(block_number, address))
.unwrap_or_default()
{
Some(Some(account)) => AccountInfoRevert::RevertTo(account),
Some(None) => AccountInfoRevert::DeleteIt,
None => AccountInfoRevert::DoNothing,
};
let storage = self
.revert_storage
.remove(&(block_number, address))
.map(|s| {
s.into_iter()
.map(|(k, v)| (k, RevertToSlot::Some(v)))
.collect()
})
.unwrap_or_default();
let account_revert = AccountRevert {
account,
storage,
previous_status: AccountStatus::Changed,
wipe_storage: false,
};
if reverts_map.contains_key(&block_number) {
reverts_size += account_revert.size_hint();
reverts_map
.entry(block_number)
.or_insert(Vec::new())
.push((address, account_revert));
}
});
BundleState {
state,
contracts: self.contracts,
reverts: Reverts::new(reverts_map.into_values().collect()),
state_size,
reverts_size,
}
}
/// Getter for `states` field
pub fn get_states(&self) -> &HashSet<Address> {
&self.states
}
/// Mutable getter for `states` field
pub fn get_states_mut(&mut self) -> &mut HashSet<Address> {
&mut self.states
}
/// Mutable getter for `state_original` field
pub fn get_state_original_mut(&mut self) -> &mut HashMap<Address, AccountInfo> {
&mut self.state_original
}
/// Mutable getter for `state_present` field
pub fn get_state_present_mut(&mut self) -> &mut HashMap<Address, AccountInfo> {
&mut self.state_present
}
/// Mutable getter for `state_storage` field
pub fn get_state_storage_mut(&mut self) -> &mut HashMap<Address, HashMap<U256, (U256, U256)>> {
&mut self.state_storage
}
/// Mutable getter for `reverts` field
pub fn get_reverts_mut(&mut self) -> &mut BTreeSet<(u64, Address)> {
&mut self.reverts
}
/// Mutable getter for `revert_range` field
pub fn get_revert_range_mut(&mut self) -> &mut RangeInclusive<u64> {
&mut self.revert_range
}
/// Mutable getter for `revert_account` field
pub fn get_revert_account_mut(
&mut self,
) -> &mut HashMap<(u64, Address), Option<Option<AccountInfo>>> {
&mut self.revert_account
}
/// Mutable getter for `revert_storage` field
pub fn get_revert_storage_mut(&mut self) -> &mut HashMap<(u64, Address), Vec<(U256, U256)>> {
&mut self.revert_storage
}
/// Mutable getter for `contracts` field
pub fn get_contracts_mut(&mut self) -> &mut HashMap<B256, Bytecode> {
&mut self.contracts
}
}
/// Bundle retention policy for applying substate to the bundle.
#[derive(Debug)]
pub enum BundleRetention {
/// Only plain state is updated.
PlainState,
/// Both, plain state and reverts, are retained
Reverts,
}
impl BundleRetention {
/// Returns `true` if reverts should be retained.
pub fn includes_reverts(&self) -> bool {
matches!(self, Self::Reverts)
}
}
/// Bundle state contain only values that got changed
///
/// For every account it contains both original and present state.
/// This is needed to decide if there were any changes to the account.
///
/// Reverts and created when TransitionState is applied to BundleState.
/// And can be used to revert BundleState to the state before transition.
#[derive(Default, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BundleState {
/// Account state.
pub state: HashMap<Address, BundleAccount>,
/// All created contracts in this block.
pub contracts: HashMap<B256, Bytecode>,
/// Changes to revert.
///
/// Note: Inside vector is *not* sorted by address.
/// But it is unique by address.
pub reverts: Reverts,
/// The size of the plain state in the bundle state.
pub state_size: usize,
/// The size of reverts in the bundle state.
pub reverts_size: usize,
}
impl BundleState {
/// Return builder instance for further manipulation
pub fn builder(revert_range: RangeInclusive<u64>) -> BundleBuilder {
BundleBuilder::new(revert_range)
}
/// Create it with new and old values of both Storage and AccountInfo.
pub fn new(
state: impl IntoIterator<
Item = (
Address,
Option<AccountInfo>,
Option<AccountInfo>,
HashMap<U256, (U256, U256)>,
),
>,
reverts: impl IntoIterator<
Item = impl IntoIterator<
Item = (
Address,
Option<Option<AccountInfo>>,
impl IntoIterator<Item = (U256, U256)>,
),
>,
>,
contracts: impl IntoIterator<Item = (B256, Bytecode)>,
) -> Self {
// Create state from iterator.
let mut state_size = 0;
let state = state
.into_iter()
.map(|(address, original, present, storage)| {
let account = BundleAccount::new(
original,
present,
storage
.into_iter()
.map(|(k, (o_val, p_val))| (k, StorageSlot::new_changed(o_val, p_val)))
.collect(),
AccountStatus::Changed,
);
state_size += account.size_hint();
(address, account)
})
.collect();
// Create reverts from iterator.
let mut reverts_size = 0;
let reverts = reverts
.into_iter()
.map(|block_reverts| {
block_reverts
.into_iter()
.map(|(address, account, storage)| {
let account = match account {
Some(Some(account)) => AccountInfoRevert::RevertTo(account),
Some(None) => AccountInfoRevert::DeleteIt,
None => AccountInfoRevert::DoNothing,
};
let revert = AccountRevert {
account,
storage: storage
.into_iter()
.map(|(k, v)| (k, RevertToSlot::Some(v)))
.collect(),
previous_status: AccountStatus::Changed,
wipe_storage: false,
};
reverts_size += revert.size_hint();
(address, revert)
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
Self {
state,
contracts: contracts.into_iter().collect(),
reverts: Reverts::new(reverts),
state_size,
reverts_size,
}
}
/// Returns the approximate size of changes in the bundle state.
/// The estimation is not precise, because the information about the number of
/// destroyed entries that need to be removed is not accessible to the bundle state.
pub fn size_hint(&self) -> usize {
self.state_size + self.reverts_size + self.contracts.len()
}
/// Return reference to the state.
pub fn state(&self) -> &HashMap<Address, BundleAccount> {
&self.state
}
/// Is bundle state empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Return number of changed accounts.
pub fn len(&self) -> usize {
self.state.len()
}
/// Get account from state
pub fn account(&self, address: &Address) -> Option<&BundleAccount> {
self.state.get(address)
}
/// Get bytecode from state
pub fn bytecode(&self, hash: &B256) -> Option<Bytecode> {
self.contracts.get(hash).cloned()
}
/// Consume `TransitionState` by applying the changes and creating the reverts
///
/// If [BundleRetention::includes_reverts] is `true`, then the reverts will be retained.
pub fn apply_transitions_and_create_reverts(
&mut self,
transitions: TransitionState,
retention: BundleRetention,
) {
let include_reverts = retention.includes_reverts();
// pessimistically pre-allocate assuming _all_ accounts changed.
let reverts_capacity = if include_reverts {
transitions.transitions.len()
} else {
0
};
let mut reverts = Vec::with_capacity(reverts_capacity);
for (address, transition) in transitions.transitions.into_iter() {
// add new contract if it was created/changed.
if let Some((hash, new_bytecode)) = transition.has_new_contract() {
self.contracts.insert(hash, new_bytecode.clone());
}
// update state and create revert.
let revert = match self.state.entry(address) {
hash_map::Entry::Occupied(mut entry) => {
let entry = entry.get_mut();
self.state_size -= entry.size_hint();
// update and create revert if it is present
let revert = entry.update_and_create_revert(transition);
// update the state size
self.state_size += entry.size_hint();
revert
}
hash_map::Entry::Vacant(entry) => {
// make revert from transition account
let present_bundle = transition.present_bundle_account();
let revert = transition.create_revert();
if revert.is_some() {
self.state_size += present_bundle.size_hint();
entry.insert(present_bundle);
}
revert
}
};
// append revert if present.
if let Some(revert) = revert.filter(|_| include_reverts) {
self.reverts_size += revert.size_hint();
reverts.push((address, revert));
}
}
self.reverts.push(reverts);
}
/// Consume the bundle state and return plain state.
pub fn into_plain_state(self, is_value_known: OriginalValuesKnown) -> StateChangeset {
// pessimistically pre-allocate assuming _all_ accounts changed.
let state_len = self.state.len();
let mut accounts = Vec::with_capacity(state_len);
let mut storage = Vec::with_capacity(state_len);
for (address, account) in self.state {
// append account info if it is changed.
let was_destroyed = account.was_destroyed();
if is_value_known.is_not_known() || account.is_info_changed() {
let info = account.info.map(AccountInfo::without_code);
accounts.push((address, info));
}
// append storage changes
// NOTE: Assumption is that revert is going to remove whole plain storage from
// database so we can check if plain state was wiped or not.
let mut account_storage_changed = Vec::with_capacity(account.storage.len());
for (key, slot) in account.storage {
// If storage was destroyed that means that storage was wiped.
// In that case we need to check if present storage value is different then ZERO.
let destroyed_and_not_zero = was_destroyed && !slot.present_value.is_zero();
// If account is not destroyed check if original values was changed,
// so we can update it.
let not_destroyed_and_changed = !was_destroyed && slot.is_changed();
if is_value_known.is_not_known()
|| destroyed_and_not_zero
|| not_destroyed_and_changed
{
account_storage_changed.push((key, slot.present_value));
}
}
if !account_storage_changed.is_empty() || was_destroyed {
// append storage changes to account.
storage.push(PlainStorageChangeset {
address,
wipe_storage: was_destroyed,
storage: account_storage_changed,
});
}
}
let contracts = self
.contracts
.into_iter()
// remove empty bytecodes
.filter(|(b, _)| *b != KECCAK_EMPTY)
.collect::<Vec<_>>();
StateChangeset {
accounts,
storage,
contracts,
}
}
/// Consume the bundle state and split it into reverts and plain state.
pub fn into_plain_state_and_reverts(
mut self,
is_value_known: OriginalValuesKnown,
) -> (StateChangeset, PlainStateReverts) {
let reverts = self.take_all_reverts();
let plain_state = self.into_plain_state(is_value_known);
(plain_state, reverts.into_plain_state_reverts())
}
/// Extend the bundle with other state
///
/// Update the `other` state only if `other` is not flagged as destroyed.
pub fn extend_state(&mut self, other_state: HashMap<Address, BundleAccount>) {
for (address, other_account) in other_state {
match self.state.entry(address) {
hash_map::Entry::Occupied(mut entry) => {
let this = entry.get_mut();
self.state_size -= this.size_hint();
// if other was destroyed. replace `this` storage with
// the `other one.
if other_account.was_destroyed() {
this.storage = other_account.storage;
} else {
// otherwise extend this storage with other
for (key, storage_slot) in other_account.storage {
// update present value or insert storage slot.
this.storage
.entry(key)
.or_insert(storage_slot)
.present_value = storage_slot.present_value;
}
}
this.info = other_account.info;
this.status.transition(other_account.status);
// Update the state size
self.state_size += this.size_hint();
}
hash_map::Entry::Vacant(entry) => {
// just insert if empty
self.state_size += other_account.size_hint();
entry.insert(other_account);
}
}
}
}
/// Extend the state with state that is build on top of it.
///
/// If storage was wiped in `other` state, copy `this` plain state
/// and put it inside `other` revert (if there is no duplicates of course).
///
/// If `this` and `other` accounts were both destroyed invalidate second
/// wipe flag (from `other`). As wiping from database should be done only once
/// and we already transferred all potentially missing storages to the `other` revert.
pub fn extend(&mut self, mut other: Self) {
// iterate over reverts and if its storage is wiped try to add previous bundle
// state as there is potential missing slots.
for (address, revert) in other.reverts.iter_mut().flatten() {
if revert.wipe_storage {
// If there is wipe storage in `other` revert
// we need to move storage from present state.
if let Some(this_account) = self.state.get_mut(address) {
// As this account was destroyed inside `other` bundle.
// we are fine to wipe/drain this storage and put it inside revert.
for (key, value) in this_account.storage.drain() {
revert
.storage
.entry(key)
.or_insert(RevertToSlot::Some(value.present_value));
}
// nullify `other` wipe as primary database wipe is done in `this`.
if this_account.was_destroyed() {
revert.wipe_storage = false;
}
}
}
// Increment reverts size for each of the updated reverts.
self.reverts_size += revert.size_hint();
}
// Extension of state
self.extend_state(other.state);
// Contract can be just extended, when counter is introduced we will take into account that.
self.contracts.extend(other.contracts);
// Reverts can be just extended
self.reverts.extend(other.reverts);
}
/// Take first N raw reverts from the [BundleState].
pub fn take_n_reverts(&mut self, reverts_to_take: usize) -> Reverts {
// split is done as [0, num) and [num, len].
if reverts_to_take > self.reverts.len() {
return self.take_all_reverts();
}
let (detach, this) = self.reverts.split_at(reverts_to_take);
let detached_reverts = Reverts::new(detach.to_vec());
self.reverts_size = this
.iter()
.flatten()
.fold(0, |acc, (_, revert)| acc + revert.size_hint());
self.reverts = Reverts::new(this.to_vec());
detached_reverts
}
/// Return and clear all reverts from [BundleState]
pub fn take_all_reverts(&mut self) -> Reverts {
self.reverts_size = 0;
core::mem::take(&mut self.reverts)
}
/// Reverts the state changes of the latest transition
///
/// Note: This is the same as `BundleState::revert(1)`
///
/// Returns true if the state was reverted.
pub fn revert_latest(&mut self) -> bool {
// revert the latest recorded state
if let Some(reverts) = self.reverts.pop() {
for (address, revert_account) in reverts.into_iter() {
self.reverts_size -= revert_account.size_hint();
match self.state.entry(address) {
Entry::Occupied(mut entry) => {
let account = entry.get_mut();
self.state_size -= account.size_hint();
if account.revert(revert_account) {
entry.remove();
} else {
self.state_size += account.size_hint();
}
}
Entry::Vacant(entry) => {
// create empty account that we will revert on.
// Only place where this account is not existing is if revert is DeleteIt.
let mut account = BundleAccount::new(
None,
None,
HashMap::new(),
AccountStatus::LoadedNotExisting,
);
if !account.revert(revert_account) {
self.state_size += account.size_hint();
entry.insert(account);
}
}
}
}
return true;
}
false
}
/// Reverts the state changes by N transitions back.
///
/// See also [Self::revert_latest]
pub fn revert(&mut self, mut num_transitions: usize) {
if num_transitions == 0 {
return;
}
while self.revert_latest() {
num_transitions -= 1;
if num_transitions == 0 {
// break the loop.
break;
}
}
}
/// Prepends present the state with the given BundleState.
/// It adds changes from the given state but does not override any existing changes.
///
/// Reverts are not updated.
pub fn prepend_state(&mut self, mut other: BundleState) {
// take this bundle
let this_bundle = mem::take(self);
// extend other bundle state with this
other.extend_state(this_bundle.state);
// extend other contracts
other.contracts.extend(this_bundle.contracts);
// swap bundles
mem::swap(self, &mut other)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{db::StorageWithOriginalValues, TransitionAccount};
#[test]
fn transition_states() {
// dummy data
let address = Address::new([0x01; 20]);
let acc1 = AccountInfo {
balance: U256::from(10),
nonce: 1,
code_hash: KECCAK_EMPTY,
code: None,
};
let mut bundle_state = BundleState::default();
// have transition from loaded to all other states
let transition = TransitionAccount {
info: Some(acc1),
status: AccountStatus::InMemoryChange,
previous_info: None,
previous_status: AccountStatus::LoadedNotExisting,
storage: StorageWithOriginalValues::default(),
storage_was_destroyed: false,
};
// apply first transition
bundle_state.apply_transitions_and_create_reverts(
TransitionState::single(address, transition.clone()),
BundleRetention::Reverts,
);
}
const fn account1() -> Address {
Address::new([0x60; 20])
}
const fn account2() -> Address {
Address::new([0x61; 20])
}
fn slot1() -> U256 {
U256::from(5)
}
fn slot2() -> U256 {
U256::from(7)
}
/// Test bundle one
fn test_bundle1() -> BundleState {
// block changes
BundleState::new(
vec![
(
account1(),
None,
Some(AccountInfo {
nonce: 1,
balance: U256::from(10),
code_hash: KECCAK_EMPTY,
code: None,
}),
HashMap::from([
(slot1(), (U256::from(0), U256::from(10))),
(slot2(), (U256::from(0), U256::from(15))),
]),
),
(
account2(),
None,
Some(AccountInfo {
nonce: 1,
balance: U256::from(10),
code_hash: KECCAK_EMPTY,
code: None,
}),
HashMap::from([]),
),
],
vec![vec![
(
account1(),
Some(None),
vec![(slot1(), U256::from(0)), (slot2(), U256::from(0))],
),
(account2(), Some(None), vec![]),
]],
vec![],
)
}
/// Test bundle two
fn test_bundle2() -> BundleState {
// block changes
BundleState::new(
vec![(
account1(),
None,
Some(AccountInfo {
nonce: 3,
balance: U256::from(20),
code_hash: KECCAK_EMPTY,
code: None,
}),
HashMap::from([(slot1(), (U256::from(0), U256::from(15)))]),
)],
vec![vec![(
account1(),
Some(Some(AccountInfo {
nonce: 1,
balance: U256::from(10),
code_hash: KECCAK_EMPTY,
code: None,
})),
vec![(slot1(), U256::from(10))],
)]],
vec![],
)
}
/// Test bundle three
fn test_bundle3() -> BundleState {
BundleState::builder(0..=0)
.state_present_account_info(
account1(),
AccountInfo {
nonce: 1,
balance: U256::from(10),
code_hash: KECCAK_EMPTY,
code: None,
},
)
.state_storage(
account1(),
HashMap::from([(slot1(), (U256::from(0), U256::from(10)))]),
)
.state_address(account2())
.state_present_account_info(
account2(),
AccountInfo {
nonce: 1,
balance: U256::from(10),
code_hash: KECCAK_EMPTY,
code: None,
},
)
.revert_address(0, account1())
.revert_account_info(0, account1(), Some(None))
.revert_storage(0, account1(), vec![(slot1(), U256::from(0))])
.revert_account_info(0, account2(), Some(None))
.build()
}
/// Test bundle four
fn test_bundle4() -> BundleState {
BundleState::builder(0..=0)
.state_present_account_info(
account1(),
AccountInfo {
nonce: 3,
balance: U256::from(20),
code_hash: KECCAK_EMPTY,
code: None,
},
)