-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassertion_store.rs
More file actions
1151 lines (1000 loc) · 38.4 KB
/
assertion_store.rs
File metadata and controls
1151 lines (1000 loc) · 38.4 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::{
inspectors::{
CallTracer,
TriggerRecorder,
TriggerType,
},
primitives::{
Address,
AssertionContract,
Bytes,
FixedBytes,
B256,
U256,
},
store::{
assertion_contract_extractor::{
extract_assertion_contract,
FnSelectorExtractorError,
},
PendingModification,
},
ExecutorConfig,
};
use std::sync::{
Arc,
Mutex,
};
use bincode::{
deserialize as de,
serialize as ser,
};
use serde::{
Deserialize,
Serialize,
};
use tracing::{
debug,
error,
};
use std::collections::HashSet;
#[derive(thiserror::Error, Debug)]
pub enum AssertionStoreError {
#[error("Sled error")]
SledError(#[from] std::io::Error),
#[error("Bincode error")]
BincodeError(#[from] bincode::Error),
#[error("Block number exceeds u64")]
BlockNumberExceedsU64,
}
/// Struct representing an assertion contract, matched fn selectors, and the adopter.
/// This is necessary context when running assertions.
#[derive(Debug, Clone)]
pub struct AssertionsForExecution {
pub assertion_contract: AssertionContract,
pub selectors: Vec<FixedBytes<4>>,
pub adopter: Address,
}
/// Used to represent important tracing information
#[derive(Debug)]
struct AssertionsForExecutionMetadata<'a> {
#[allow(dead_code)]
assertion_id: &'a B256,
#[allow(dead_code)]
selectors: &'a Vec<FixedBytes<4>>,
#[allow(dead_code)]
adopter: &'a Address,
}
/// Struct representing a pending assertion modification that has not passed the timelock.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct AssertionState {
pub active_at_block: u64,
pub inactive_at_block: Option<u64>,
pub assertion_contract: AssertionContract,
pub trigger_recorder: TriggerRecorder,
}
/// Used to represent important tracing information.
#[derive(Debug)]
struct AssertionStateMetadata<'a> {
#[allow(dead_code)]
active_at_block: u64,
#[allow(dead_code)]
inactive_at_block: Option<u64>,
#[allow(dead_code)]
assertion_id: &'a B256,
#[allow(dead_code)]
recorded_triggers: &'a std::collections::HashMap<TriggerType, HashSet<FixedBytes<4>>>,
}
impl AssertionState {
/// Creates a new active assertion state.
/// WIll be active across all blocks.
#[allow(clippy::result_large_err)]
pub fn new_active(
bytecode: Bytes,
executor_config: &ExecutorConfig,
) -> Result<Self, FnSelectorExtractorError> {
let (contract, trigger_recorder) =
extract_assertion_contract(bytecode.clone(), executor_config)?;
Ok(Self {
active_at_block: 0,
inactive_at_block: None,
assertion_contract: contract,
trigger_recorder,
})
}
#[cfg(any(test, feature = "test"))]
pub fn new_test(bytecode: Bytes) -> Self {
Self::new_active(bytecode, &ExecutorConfig::default()).unwrap()
}
/// Getter for the assertion_contract_id
pub fn assertion_contract_id(&self) -> B256 {
self.assertion_contract.id
}
}
#[derive(Debug, Clone)]
pub struct AssertionStore {
db: Arc<Mutex<sled::Db>>,
}
impl AssertionStore {
/// Create a new assertion store
pub fn new(active_assertions_tree: sled::Db) -> Self {
Self {
db: Arc::new(Mutex::new(active_assertions_tree)),
}
}
/// Creates a new assertion store without persistence.
pub fn new_ephemeral() -> Result<Self, AssertionStoreError> {
let db = sled::Config::tmp()?.open()?;
Ok(Self::new(db))
}
/// Inserts the given assertion into the store.
/// If an assertion with the same assertion_contract_id already exists, it is replaced.
/// Returns the previous assertion if it existed.
pub fn insert(
&self,
assertion_adopter: Address,
assertion: AssertionState,
) -> Result<Option<AssertionState>, AssertionStoreError> {
debug!(
target: "assertion-executor::assertion_store",
assertion_adopter=?assertion_adopter,
active_at_block=?assertion.active_at_block,
triggers=?assertion.trigger_recorder.triggers,
"Inserting assertion into store"
);
let db_lock = self.db.lock().unwrap_or_else(|e| e.into_inner());
let mut assertions: Vec<AssertionState> = db_lock
.get(assertion_adopter)?
.map(|a| de(&a))
.transpose()?
.unwrap_or_default();
let position = assertions
.iter()
.position(|a| a.assertion_contract_id() == assertion.assertion_contract_id());
let previous = if let Some(pos) = position {
Some(std::mem::replace(&mut assertions[pos], assertion))
} else {
assertions.push(assertion);
None
};
db_lock.insert(assertion_adopter, ser(&assertions)?)?;
Ok(previous)
}
/// Applies the given modifications to the store.
pub fn apply_pending_modifications(
&self,
pending_modifications: Vec<PendingModification>,
) -> Result<(), AssertionStoreError> {
let mut map = std::collections::HashMap::<Address, Vec<PendingModification>>::new();
for modification in pending_modifications {
map.entry(modification.assertion_adopter())
.or_default()
.push(modification);
}
for (aa, mods) in map {
self.apply_pending_modification(aa, mods)?;
}
Ok(())
}
/// Reads the assertions for the given block from the store, given the traces.
#[tracing::instrument(skip_all, name = "read_assertions_from_store", target = "assertion_store::read", fields(triggers=?traces.triggers(), block_num=?block_num), level="DEBUG")]
pub fn read(
&self,
traces: &CallTracer,
block_num: U256,
) -> Result<Vec<AssertionsForExecution>, AssertionStoreError> {
let block_num = block_num
.try_into()
.map_err(|_| AssertionStoreError::BlockNumberExceedsU64)?;
let mut assertions = Vec::new();
for (contract_address, triggers) in traces.triggers() {
let contract_assertions = self.read_adopter(contract_address, triggers, block_num)?;
let assertions_for_execution: Vec<AssertionsForExecution> = contract_assertions
.into_iter()
.map(|(assertion_contract, selectors)| {
AssertionsForExecution {
assertion_contract,
selectors,
adopter: contract_address,
}
})
.collect();
assertions.extend(assertions_for_execution);
}
if assertions.is_empty() {
debug!(
target: "assertion-executor::assertion_store",
triggers=?traces.triggers(),
"No assertions found based on triggers",
);
} else {
debug!(
target: "assertion-executor::assertion_store",
assertions = ?assertions.iter().map(|assertion| format!("{:?}", AssertionsForExecutionMetadata {
assertion_id: &assertion.assertion_contract.id,
selectors: &assertion.selectors,
adopter: &assertion.adopter
})).collect::<Vec<_>>(),
triggers=?traces.triggers(),
"Assertions found based on triggers",
);
}
Ok(assertions)
}
/// Reads the assertions for the given assertion adopter at the given block.
/// Returns the assertions that are active at the given block.
/// An assertion is considered active at a block if the active_at_block is less than or equal
/// to the given block, and the inactive_at_block is greater than the given block.
/// `assertion_adopter` is the address of the contract leveraging assertions.
#[tracing::instrument(skip_all, name = "read_adopter_from_db", target = "assertion_store::read_adopter", fields(assertion_adopter=?assertion_adopter, triggers=?triggers, block=?block), level="trace")]
fn read_adopter(
&self,
assertion_adopter: Address,
triggers: HashSet<TriggerType>,
block: u64,
) -> Result<Vec<(AssertionContract, Vec<FixedBytes<4>>)>, AssertionStoreError> {
let assertion_states = tracing::trace_span!(
"read_adopter_from_db",
?assertion_adopter,
?triggers,
?block
)
.in_scope(|| {
self.db
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(assertion_adopter)?
.map(|a| de::<Vec<AssertionState>>(&a))
.transpose()
})?
.unwrap_or_default();
debug!(
target: "assertion_store::read_adopter",
?assertion_adopter,
assertion_states = ?assertion_states.iter().map(|a|
format!("{:?}",
AssertionStateMetadata {
assertion_id: &a.assertion_contract.id,
active_at_block : a.active_at_block,
inactive_at_block : a.inactive_at_block,
recorded_triggers : &a.trigger_recorder.triggers
})).collect::<Vec<_>>(),
"Assertion states in store for adopter.",
);
let active_assertion_contracts = assertion_states
.into_iter()
.filter(|a| {
let inactive_block = match a.inactive_at_block {
Some(inactive_block) => {
// If the inactive block is less than the active block, the end bound is
// ignored.
if inactive_block < a.active_at_block {
u64::MAX
} else {
inactive_block
}
}
None => u64::MAX,
};
let in_bound_start = a.active_at_block <= block;
let in_bound_end = block < inactive_block;
in_bound_start && in_bound_end
})
.map(|a| {
// Get all function selectors from matching triggers
let mut all_selectors = HashSet::new();
let mut has_call_trigger = false;
let mut has_storage_trigger = false;
// Process specific triggers and detect trigger types
for trigger in &triggers {
if let Some(selectors) = a.trigger_recorder.triggers.get(trigger) {
all_selectors.extend(selectors.iter().cloned());
}
// Check trigger type while we're iterating
match trigger {
TriggerType::Call { .. } => has_call_trigger = true,
TriggerType::StorageChange { .. } => has_storage_trigger = true,
_ => {}
}
}
// Add AllCalls selectors if needed
if has_call_trigger {
if let Some(selectors) = a.trigger_recorder.triggers.get(&TriggerType::AllCalls)
{
all_selectors.extend(selectors.iter().cloned());
}
}
// Add AllStorageChanges selectors if needed
if has_storage_trigger {
if let Some(selectors) = a
.trigger_recorder
.triggers
.get(&TriggerType::AllStorageChanges)
{
all_selectors.extend(selectors.iter().cloned());
}
}
// Convert HashSet to Vec to match the expected return type
(a.assertion_contract, all_selectors.into_iter().collect())
})
.collect();
Ok(active_assertion_contracts)
}
/// Applies the given assertion adopter modifications to the store.
fn apply_pending_modification(
&self,
assertion_adopter: Address,
modifications: Vec<PendingModification>,
) -> Result<(), AssertionStoreError> {
loop {
let assertions_serialized = self
.db
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(assertion_adopter)?;
let mut assertions: Vec<AssertionState> = assertions_serialized
.clone()
.map(|a| de(&a))
.transpose()?
.unwrap_or_default();
debug!(
target: "assertion-executor::assertion_store",
pending_modifations_len = assertions.len(),
"Applying pending modifications"
);
for modification in modifications.clone().into_iter() {
match modification {
PendingModification::Add {
assertion_contract,
trigger_recorder,
active_at_block,
..
} => {
debug!(
target: "assertion-executor::assertion_store",
?assertion_contract,
?trigger_recorder,
active_at_block,
"Applying pending assertion addition"
);
let existing_state = assertions
.iter_mut()
.find(|a| a.assertion_contract_id() == assertion_contract.id);
match existing_state {
Some(state) => {
state.active_at_block = active_at_block;
}
None => {
assertions.push(AssertionState {
active_at_block,
inactive_at_block: None,
assertion_contract,
trigger_recorder,
});
}
}
}
PendingModification::Remove {
assertion_contract_id,
inactive_at_block,
..
} => {
debug!(
target: "assertion-executor::assertion_store",
?assertion_contract_id,
inactive_at_block,
"Applying pending assertion removal"
);
let existing_state = assertions
.iter_mut()
.find(|a| a.assertion_contract_id() == assertion_contract_id);
match existing_state {
Some(state) => {
state.inactive_at_block = Some(inactive_at_block);
}
None => {
// The assertion was not found, so we add it with the inactive_at_block set.
error!(
target: "assertion-executor::assertion_store",
?assertion_contract_id,
"Apply pending modifications error: Assertion not found for removal",
);
}
}
}
}
}
let result = self
.db
.lock()
.unwrap_or_else(|e| e.into_inner())
.compare_and_swap(
assertion_adopter,
assertions_serialized,
Some(ser(&assertions)?),
);
if let Ok(Ok(_)) = result {
break;
} else {
tracing::debug!(
target: "assertion-executor::assertion_store",
?result,
"Assertion store Compare and Swap failed, retrying"
);
}
}
Ok(())
}
#[cfg(any(test, feature = "test"))]
pub fn assertion_contract_count(&self, assertion_adopter: Address) -> usize {
let assertions = self.get_assertions_for_contract(assertion_adopter);
assertions.len()
}
#[cfg(any(test, feature = "test"))]
pub fn get_assertions_for_contract(&self, assertion_adopter: Address) -> Vec<AssertionState> {
let assertions_serialized = self
.db
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(assertion_adopter)
.unwrap_or(None);
if let Some(assertions_serialized) = assertions_serialized {
let assertions: Vec<AssertionState> = de(&assertions_serialized).unwrap_or_default();
assertions
} else {
vec![]
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::primitives::{
Address,
JournalEntry,
JournaledState,
SpecId,
};
use revm::primitives::HashSet as RevmHashSet;
use std::collections::HashSet;
fn create_test_assertion(
active_at_block: u64,
inactive_at_block: Option<u64>,
) -> AssertionState {
AssertionState {
active_at_block,
inactive_at_block,
assertion_contract: AssertionContract {
id: B256::random(),
..Default::default()
},
trigger_recorder: TriggerRecorder::default(),
}
}
fn create_test_modification(
active_at: u64,
aa: Address,
log_index: u64,
) -> PendingModification {
create_test_modification_with_id(active_at, aa, log_index, B256::random())
}
fn create_test_modification_with_id(
active_at: u64,
aa: Address,
log_index: u64,
id: B256,
) -> PendingModification {
PendingModification::Add {
assertion_adopter: aa,
assertion_contract: AssertionContract {
id,
..Default::default()
},
trigger_recorder: TriggerRecorder::default(),
active_at_block: active_at,
log_index,
}
}
fn create_test_modification_remove(
inactive_at: u64,
aa: Address,
log_index: u64,
id: B256,
) -> PendingModification {
PendingModification::Remove {
log_index,
assertion_adopter: aa,
assertion_contract_id: id,
inactive_at_block: inactive_at,
}
}
#[test]
fn test_insert_and_read() -> Result<(), AssertionStoreError> {
let store = AssertionStore::new_ephemeral()?;
let aa = Address::random();
// Create a test assertion
let assertion = create_test_assertion(100, None);
let assertion_contract_id = assertion.assertion_contract_id();
// Insert the assertion
store.insert(aa, assertion.clone())?;
// Create a call tracer that includes our AA
let mut tracer = CallTracer::default();
tracer.insert_trace(aa);
// Read at block 150 (should be active)
let assertions = store.read(&tracer, U256::from(150))?;
assert_eq!(assertions.len(), 1);
assert_eq!(assertions[0].assertion_contract.id, assertion_contract_id);
// Read at block 50 (should be inactive)
let assertions = store.read(&tracer, U256::from(50))?;
assert_eq!(assertions.len(), 0);
Ok(())
}
#[test]
fn test_apply_pending_modifications() -> Result<(), AssertionStoreError> {
let store = AssertionStore::new_ephemeral()?;
let aa = Address::random();
// Create two modifications
let mod1 = create_test_modification(100, aa, 0);
let mod2 = create_test_modification(200, aa, 0);
// Apply modifications
store.apply_pending_modifications(vec![mod1.clone(), mod2])?;
// Create a call tracer that includes our AA
let mut tracer = CallTracer::default();
tracer.insert_trace(aa);
// Read at block 150 (should see first assertion only)
let assertions = store.read(&tracer, U256::from(150))?;
assert_eq!(assertions.len(), 1);
assert_eq!(
assertions[0].assertion_contract.id,
mod1.assertion_contract_id()
);
// Read at block 250 (should see both assertions)
let assertions = store.read(&tracer, U256::from(250))?;
assert_eq!(assertions.len(), 2);
Ok(())
}
#[test]
fn test_removal_modification() -> Result<(), AssertionStoreError> {
let store = AssertionStore::new_ephemeral()?;
let aa = Address::random();
// Add an assertion
let add_mod = create_test_modification(100, aa, 0);
store.apply_pending_modifications(vec![add_mod.clone()])?;
// Remove the assertion at block 200
let remove_mod = PendingModification::Remove {
log_index: 1,
assertion_adopter: aa,
assertion_contract_id: add_mod.assertion_contract_id(),
inactive_at_block: 200,
};
store.apply_pending_modifications(vec![remove_mod])?;
// Create a call tracer
let mut tracer = CallTracer::default();
tracer.insert_trace(aa);
// Check at different blocks
let assertions = store.read(&tracer, U256::from(150))?;
assert_eq!(assertions.len(), 1); // Active
let assertions = store.read(&tracer, U256::from(250))?;
assert_eq!(assertions.len(), 0); // Inactive
Ok(())
}
#[test]
fn test_multiple_assertion_adopters() -> Result<(), AssertionStoreError> {
let store = AssertionStore::new_ephemeral()?;
let aa1 = Address::random();
let aa2 = Address::random();
// Create modifications for different AAs
let mod1 = create_test_modification(100, aa1, 0);
let mod2 = create_test_modification(100, aa2, 1);
// Apply modifications
store.apply_pending_modifications(vec![mod1.clone(), mod2])?;
// Create a call tracer that includes both AAs
let mut tracer = CallTracer::default();
tracer.insert_trace(aa1);
tracer.insert_trace(aa2);
// Read at block 150 (should see both assertions)
let assertions = store.read(&tracer, U256::from(150))?;
assert_eq!(assertions.len(), 2);
// Create a tracer with only aa1
let mut tracer = CallTracer::default();
tracer.insert_trace(aa1);
// Should only see one assertion
let assertions = store.read(&tracer, U256::from(150))?;
assert_eq!(assertions.len(), 1);
assert_eq!(
assertions[0].assertion_contract.id,
mod1.assertion_contract_id()
);
Ok(())
}
#[test]
fn test_update_same_assertion() -> Result<(), AssertionStoreError> {
let store = AssertionStore::new_ephemeral()?;
let aa = Address::random();
let a_state = create_test_assertion(100, None);
let id = a_state.assertion_contract_id();
let _ = store.insert(aa, a_state);
let mod1 = create_test_modification_remove(200, aa, 0, id);
let mod2 = create_test_modification_with_id(300, aa, 1, id);
// Apply modifications
store.apply_pending_modifications(vec![mod1, mod2])?;
// Create a call tracer that includes both AAs
let mut tracer = CallTracer::default();
tracer.insert_trace(aa);
assert_eq!(store.db.lock().unwrap().len(), 1);
let assertions: Vec<AssertionState> =
de(&store.db.lock().unwrap().get(aa)?.unwrap()).unwrap();
assert_eq!(assertions.len(), 1);
// Read at block 250 (should see no assertion)
let assertions = store.read(&tracer, U256::from(250))?;
assert_eq!(assertions.len(), 0);
let assertions = store.read(&tracer, U256::from(350))?;
assert_eq!(assertions.len(), 1);
Ok(())
}
#[test]
fn test_block_number_exceeds_u64() {
let store = AssertionStore::new_ephemeral().unwrap();
let mut tracer = CallTracer::default();
tracer.insert_trace(Address::random());
let result = store.read(&tracer, U256::MAX);
assert!(matches!(
result,
Err(AssertionStoreError::BlockNumberExceedsU64)
));
}
fn setup_and_match(
recorded_triggers: Vec<(TriggerType, HashSet<FixedBytes<4>>)>,
journal_entries: Vec<JournalEntry>,
assertion_adopter: Address,
) -> Result<Vec<AssertionsForExecution>, AssertionStoreError> {
let store = AssertionStore::new_ephemeral()?;
let mut trigger_recorder = TriggerRecorder::default();
recorded_triggers.iter().for_each(|(trigger, selectors)| {
trigger_recorder
.triggers
.insert(trigger.clone(), selectors.clone());
});
let mut assertion = create_test_assertion(100, None);
assertion.trigger_recorder = trigger_recorder;
store.insert(assertion_adopter, assertion)?;
let mut tracer = CallTracer::default();
// insert_trace inserts (address, 0x00000000) in call_inputs to pretend a call
tracer.insert_trace(assertion_adopter);
tracer.journaled_state = Some(JournaledState::new(
SpecId::LONDON,
RevmHashSet::<Address>::default(),
));
tracer
.journaled_state
.as_mut()
.unwrap()
.journal
.push(journal_entries);
store.read(&tracer, U256::from(100))
}
#[test]
fn test_read_adopter_with_all_triggers() -> Result<(), AssertionStoreError> {
let aa = Address::random();
let assertion_selector_call = FixedBytes::<4>::random();
let assertion_selector_storage = FixedBytes::<4>::random();
let assertion_selector_both = FixedBytes::<4>::random();
let mut expected_selectors = vec![
assertion_selector_call,
assertion_selector_storage,
assertion_selector_both,
];
expected_selectors.sort();
// Create recorded triggers for all calls and storage changes
let recorded_triggers = vec![
(
TriggerType::AllCalls,
vec![assertion_selector_call, assertion_selector_both]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::AllStorageChanges,
vec![assertion_selector_storage, assertion_selector_both]
.into_iter()
.collect::<HashSet<_>>(),
),
];
let journal_entries = vec![JournalEntry::StorageChanged {
address: aa,
key: U256::from(1),
had_value: U256::from(0),
}];
let assertions = setup_and_match(recorded_triggers, journal_entries, aa)?;
assert_eq!(assertions.len(), 1);
let mut matched_selectors = assertions[0].selectors.clone();
matched_selectors.sort();
assert_eq!(matched_selectors, expected_selectors);
Ok(())
}
#[test]
fn test_read_adopter_with_specific_triggers() -> Result<(), AssertionStoreError> {
let aa = Address::random();
let assertion_selector_call = FixedBytes::<4>::random();
let assertion_selector_storage = FixedBytes::<4>::random();
let assertion_selector_balance = FixedBytes::<4>::random();
let mut expected_selectors = vec![
assertion_selector_call,
assertion_selector_storage,
assertion_selector_balance,
];
expected_selectors.sort();
let trigger_selector = FixedBytes::<4>::default();
let recorded_triggers = vec![
(
TriggerType::Call { trigger_selector },
vec![assertion_selector_call]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::StorageChange {
trigger_slot: U256::from(1).into(),
},
vec![assertion_selector_storage]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::BalanceChange,
vec![assertion_selector_balance]
.into_iter()
.collect::<HashSet<_>>(),
),
];
let journal_entries = vec![
JournalEntry::StorageChanged {
address: aa,
key: U256::from(1),
had_value: U256::from(0),
},
JournalEntry::BalanceTransfer {
from: aa,
to: Address::random(),
balance: U256::from(1),
},
];
let assertions = setup_and_match(recorded_triggers, journal_entries, aa)?;
assert_eq!(assertions.len(), 1);
let mut matched_selectors = assertions[0].selectors.clone();
matched_selectors.sort();
assert_eq!(matched_selectors, expected_selectors);
Ok(())
}
#[test]
fn test_read_adopter_only_match_call_trigger() -> Result<(), AssertionStoreError> {
let aa = Address::random();
let assertion_selector_call = FixedBytes::<4>::random();
let assertion_selector_all_storage = FixedBytes::<4>::random();
let assertion_selector_balance = FixedBytes::<4>::random();
let mut expected_selectors = vec![assertion_selector_call];
expected_selectors.sort();
let trigger_selector_call = FixedBytes::<4>::default();
let recorded_triggers = vec![
(
TriggerType::Call {
trigger_selector: trigger_selector_call,
},
vec![assertion_selector_call]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::AllStorageChanges,
vec![assertion_selector_all_storage]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::BalanceChange,
vec![assertion_selector_balance]
.into_iter()
.collect::<HashSet<_>>(),
),
];
let assertions = setup_and_match(recorded_triggers, vec![], aa)?;
assert_eq!(assertions.len(), 1);
let mut matched_selectors = assertions[0].selectors.clone();
matched_selectors.sort();
assert_eq!(matched_selectors, expected_selectors);
Ok(())
}
#[test]
fn test_all_trigger_types_comprehensive() -> Result<(), AssertionStoreError> {
let aa = Address::random();
// Create unique selectors for each trigger type
let selector_specific_call = FixedBytes::<4>::random();
let selector_all_calls = FixedBytes::<4>::random();
let selector_specific_storage = FixedBytes::<4>::random();
let selector_all_storage = FixedBytes::<4>::random();
let selector_balance = FixedBytes::<4>::random();
let trigger_selector = FixedBytes::<4>::from([0x12, 0x34, 0x56, 0x78]);
let trigger_slot = U256::from(42);
// Create recorded triggers for ALL trigger types
let recorded_triggers = vec![
(
TriggerType::Call { trigger_selector },
vec![selector_specific_call]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::AllCalls,
vec![selector_all_calls].into_iter().collect::<HashSet<_>>(),
),
(
TriggerType::StorageChange {
trigger_slot: trigger_slot.into(),
},
vec![selector_specific_storage]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::AllStorageChanges,
vec![selector_all_storage]
.into_iter()
.collect::<HashSet<_>>(),
),
(
TriggerType::BalanceChange,
vec![selector_balance].into_iter().collect::<HashSet<_>>(),
),
];
// Create journal entries that trigger specific call, storage change, and balance change
let journal_entries = vec![
JournalEntry::StorageChanged {
address: aa,
key: trigger_slot,
had_value: U256::from(0),
},
JournalEntry::StorageChanged {
address: aa,
key: U256::from(99), // Different slot to trigger AllStorageChanges
had_value: U256::from(1),
},
JournalEntry::BalanceTransfer {
from: aa,
to: Address::random(),
balance: U256::from(100),
},
];
let store = AssertionStore::new_ephemeral()?;
let mut trigger_recorder = TriggerRecorder::default();
recorded_triggers.iter().for_each(|(trigger, selectors)| {
trigger_recorder
.triggers