Skip to main content

foundry_evm_fuzz/strategies/
state.rs

1use crate::{
2    BasicTxDetails,
3    invariant::{
4        FuzzRunIdentifiedContracts, TargetedContract, TargetedContractEvent, TargetedContracts,
5    },
6    strategies::literals::LiteralsDictionary,
7};
8use alloy_dyn_abi::{DynSolType, DynSolValue, EventExt, FunctionExt};
9use alloy_json_abi::Function;
10use alloy_primitives::{
11    Address, B256, Bytes, Log, U256, keccak256,
12    map::{AddressIndexSet, B256IndexSet, HashMap, HashSet, IndexMap, IndexSet},
13};
14use evm2::{
15    bytecode::Bytecode,
16    evm::{AccountChanges, AccountInfo, CacheDB},
17};
18use foundry_common::{
19    ignore_metadata_hash,
20    slot_identifier::{SlotIdentifier, SlotInfo},
21};
22use foundry_config::FuzzDictionaryConfig;
23use foundry_evm_core::{bytecode::InstIter, eip2935::is_history_storage_address};
24use std::{cell::RefCell, fmt, rc::Rc, sync::Arc};
25
26#[cfg(test)]
27use evm2::evm::InMemoryDB;
28
29/// The maximum number of bytes we will look at in bytecodes to find push bytes (24 KiB).
30///
31/// This is to limit the performance impact of fuzz tests that might deploy arbitrarily sized
32/// bytecode (as is the case with Solmate).
33const PUSH_BYTE_ANALYSIS_LIMIT: usize = 24 * 1024;
34
35/// The maximum length in bytes of a `bytes` or `string` value recorded whole on its own in the
36/// composite dictionary. Longer values are not recorded, since they have no word leaves; composites
37/// containing them are still recorded whole.
38const MAX_COMPOSITE_BYTES_LEN: usize = 1024;
39
40/// Immutable fuzz dictionary seed used by parallel stateless fuzz workers.
41#[derive(Clone, Debug)]
42pub struct EvmFuzzState {
43    inner: Arc<FuzzDictionary>,
44    /// Addresses of external libraries deployed in test setup, excluded from fuzz test inputs.
45    pub deployed_libs: Vec<Address>,
46}
47
48/// Worker-local fuzz state.
49///
50/// Stateless workers share the immutable campaign seed, while invariant workers own an isolated
51/// mutable dictionary. The latter deliberately uses `Rc<RefCell<_>>`: worker state is not shared
52/// across threads.
53#[derive(Clone, Debug)]
54pub struct FuzzState {
55    inner: FuzzStateInner,
56    /// Addresses of external libraries deployed in test setup, excluded from fuzz test inputs.
57    pub deployed_libs: Vec<Address>,
58}
59
60#[derive(Clone, Debug)]
61enum FuzzStateInner {
62    Stateless(Arc<FuzzDictionary>),
63    Invariant(Rc<RefCell<FuzzDictionary>>),
64}
65
66pub(crate) trait DictionaryRead: Clone + 'static {
67    fn deployed_libs(&self) -> &[Address];
68    fn with_dictionary<R>(&self, f: impl FnOnce(&FuzzDictionary) -> R) -> R;
69}
70
71impl EvmFuzzState {
72    #[cfg(test)]
73    pub(crate) fn test() -> Self {
74        Self::new(&[], &InMemoryDB::default(), FuzzDictionaryConfig::default(), None)
75    }
76
77    /// Creates the dictionary seed from the accounts, code and storage accepted into `db`, such as
78    /// the overlay of an EVM's state after `setUp`.
79    pub fn new<DB>(
80        deployed_libs: &[Address],
81        db: &CacheDB<DB>,
82        config: FuzzDictionaryConfig,
83        literals: Option<&LiteralsDictionary>,
84    ) -> Self {
85        // Create fuzz dictionary and insert values from db state. Literals go in first: the db
86        // values seed the typed samples, which merges the literals in at that point.
87        let mut dictionary = FuzzDictionary::new(config);
88        if let Some(literals) = literals {
89            dictionary.literal_values = literals.clone();
90        }
91        dictionary.insert_db_values(db);
92
93        Self { inner: Arc::new(dictionary), deployed_libs: deployed_libs.to_vec() }
94    }
95
96    pub fn stateless_worker(&self) -> FuzzState {
97        FuzzState {
98            inner: FuzzStateInner::Stateless(Arc::clone(&self.inner)),
99            deployed_libs: self.deployed_libs.clone(),
100        }
101    }
102
103    pub fn into_invariant(self) -> FuzzState {
104        FuzzState {
105            inner: FuzzStateInner::Invariant(Rc::new(RefCell::new((*self.inner).clone()))),
106            deployed_libs: self.deployed_libs,
107        }
108    }
109
110    pub fn fork(&self) -> Self {
111        Self { inner: Arc::clone(&self.inner), deployed_libs: self.deployed_libs.clone() }
112    }
113
114    #[cfg(test)]
115    pub(crate) fn collect_sample_values(
116        &mut self,
117        values: impl IntoIterator<Item = DynSolValue>,
118        limit: u32,
119    ) {
120        Arc::make_mut(&mut self.inner).insert_sample_values(values, limit);
121    }
122
123    pub fn collect_values(&mut self, values: impl IntoIterator<Item = B256>) {
124        let dict = Arc::make_mut(&mut self.inner);
125        for value in values {
126            dict.insert_value(value);
127        }
128    }
129
130    /// Logs stats about the current state.
131    pub fn log_stats(&self) {
132        self.inner.log_stats();
133    }
134
135    /// Test-only helper to seed the dictionary with literal values.
136    #[cfg(test)]
137    pub(crate) fn seed_literals(&mut self, map: super::LiteralMaps) {
138        Arc::make_mut(&mut self.inner).seed_literals(map);
139    }
140}
141
142impl FuzzState {
143    pub fn snapshot(&self) -> EvmFuzzState {
144        EvmFuzzState {
145            inner: Arc::new(self.with_dictionary(Clone::clone)),
146            deployed_libs: self.deployed_libs.clone(),
147        }
148    }
149
150    pub fn collect_values(&self, values: impl IntoIterator<Item = B256>) {
151        let FuzzStateInner::Invariant(inner) = &self.inner else { return };
152        let mut dict = inner.borrow_mut();
153        for value in values {
154            dict.insert_value(value);
155        }
156    }
157
158    /// Collects the accounts and storage a call loaded, its output and its logs into a worker
159    /// state according to the given [FuzzDictionaryConfig].
160    ///
161    /// `state_changes` are the call's [`AccountChanges`], as returned by
162    /// `ExecutedTx::account_changes` or `PendingState::account_changes`.
163    #[allow(clippy::too_many_arguments)]
164    pub fn collect_values_from_call<'a>(
165        &self,
166        fuzzed_contracts: &FuzzRunIdentifiedContracts,
167        tx: &BasicTxDetails,
168        result: &Bytes,
169        logs: &[Log],
170        state_changes: impl IntoIterator<Item = AccountChanges<'a>>,
171        run_depth: u32,
172    ) {
173        let mut state_changes = state_changes.into_iter().peekable();
174        if logs.is_empty() && result.is_empty() && state_changes.peek().is_none() {
175            return;
176        }
177
178        let FuzzStateInner::Invariant(inner) = &self.inner else { return };
179        let mut dict = inner.borrow_mut();
180        let targets = fuzzed_contracts.targets();
181        let (target_contract, target_function) = if logs.is_empty() && result.is_empty() {
182            (None, None)
183        } else {
184            targets.fuzzed_artifacts(tx)
185        };
186        if !logs.is_empty() {
187            dict.insert_logs_values(target_contract, &targets, logs, run_depth);
188        }
189        if !result.is_empty() {
190            dict.insert_result_values(target_function, result, run_depth);
191        }
192        dict.insert_new_state_values(state_changes, &targets);
193    }
194
195    /// Collects the decoded result of a view call into the fuzz dictionary.
196    pub fn collect_values_from_view(&self, function: &Function, result: &Bytes, run_depth: u32) {
197        let FuzzStateInner::Invariant(inner) = &self.inner else { return };
198        inner.borrow_mut().insert_result_values(Some(function), result, run_depth);
199    }
200
201    /// Collects typed trace-cmp operands from sancov-instrumented code.
202    /// Values are inserted into both persistent state values (survive reverts) and typed
203    /// sample buckets (for ABI-aware mutation).
204    pub fn collect_typed_cmp_values(&self, values: impl IntoIterator<Item = (u8, B256)>) {
205        let FuzzStateInner::Invariant(inner) = &self.inner else { return };
206        let mut dict = inner.borrow_mut();
207        for (width, value) in values {
208            dict.insert_persistent_value(value);
209            dict.insert_typed_cmp_value(width, value);
210        }
211    }
212
213    /// Removes all newly added entries from the dictionary.
214    ///
215    /// Should be called between fuzz/invariant runs to avoid accumulating data derived from fuzz
216    /// inputs.
217    pub fn revert(&self) {
218        if let FuzzStateInner::Invariant(inner) = &self.inner {
219            inner.borrow_mut().revert();
220        }
221    }
222
223    /// Logs stats about the current state.
224    pub fn log_stats(&self) {
225        self.with_dictionary(FuzzDictionary::log_stats);
226    }
227
228    pub fn deployed_libs(&self) -> &[Address] {
229        &self.deployed_libs
230    }
231
232    pub fn with_dictionary<R>(&self, f: impl FnOnce(&FuzzDictionary) -> R) -> R {
233        match &self.inner {
234            FuzzStateInner::Stateless(inner) => f(inner),
235            FuzzStateInner::Invariant(inner) => f(&inner.borrow()),
236        }
237    }
238}
239
240impl DictionaryRead for FuzzState {
241    fn deployed_libs(&self) -> &[Address] {
242        self.deployed_libs()
243    }
244
245    fn with_dictionary<R>(&self, f: impl FnOnce(&FuzzDictionary) -> R) -> R {
246        self.with_dictionary(f)
247    }
248}
249
250impl DictionaryRead for EvmFuzzState {
251    fn deployed_libs(&self) -> &[Address] {
252        &self.deployed_libs
253    }
254
255    fn with_dictionary<R>(&self, f: impl FnOnce(&FuzzDictionary) -> R) -> R {
256        f(&self.inner)
257    }
258}
259
260impl From<EvmFuzzState> for FuzzState {
261    fn from(state: EvmFuzzState) -> Self {
262        state.into_invariant()
263    }
264}
265
266// We're using `IndexSet` to have a stable element order when restoring persisted state, as well as
267// for performance when iterating over the sets.
268/// Maximum number of persistent values from sancov trace-cmp.
269const MAX_PERSISTENT_VALUES: usize = 2048;
270/// Maximum cached storage slot layout lookups per fuzz dictionary.
271const MAX_SLOT_INFO_CACHE_ENTRIES: usize = 4096;
272/// Maximum number of account addresses kept as typed `address` samples.
273const MAX_ADDRESS_SAMPLES: usize = 1024;
274
275#[derive(Clone)]
276pub struct FuzzDictionary {
277    /// Collected state values.
278    state_values: B256IndexSet,
279    /// Addresses that already had their PUSH bytes collected.
280    addresses: AddressIndexSet,
281    /// Code hashes that already had their PUSH bytes collected.
282    push_bytecode_hashes: B256IndexSet,
283    /// Configuration for the dictionary.
284    config: FuzzDictionaryConfig,
285    /// Number of state values initially collected from db.
286    /// Used to revert new collected values at the end of each run.
287    db_state_values: usize,
288    /// Number of address values initially collected from db.
289    /// Used to revert new collected addresses at the end of each run.
290    db_addresses: usize,
291    /// Number of bytecode hashes initially collected from db.
292    /// Used to revert new collected bytecode hashes at the end of each run.
293    db_push_bytecode_hashes: usize,
294    /// Typed runtime sample values persisted across invariant runs.
295    /// Initially seeded with literal values collected from the source code.
296    sample_values: HashMap<DynSolType, B256IndexSet>,
297    /// Number of runtime samples persisted per type, capped at the run depth separately from the
298    /// literal, storage, and trace-cmp values that share `sample_values`.
299    learned_samples: HashMap<DynSolType, usize>,
300    /// Lazily initialized dictionary of literal values collected from the source code.
301    literal_values: LiteralsDictionary,
302    /// Tracks whether literals from `literal_values` have been merged into `sample_values`.
303    ///
304    /// Set to `true` on first call to `seed_samples()`. Before seeding, `samples()` checks both
305    /// maps separately. After seeding, literals are merged in, so only `sample_values` is checked.
306    samples_seeded: bool,
307    /// Whole composite ABI values (structs, tuples, arrays, `bytes` and `string`) observed in call
308    /// results and logs, keyed by canonical ABI type and deduplicated by encoding hash.
309    ///
310    /// Reusing a value whole keeps related fields consistent: a struct returned by a getter or
311    /// emitted in an event can be passed back verbatim, which field-by-field generation almost
312    /// never reconstructs. Persisted across invariant runs and bounded per type like
313    /// `sample_values`, evicting the oldest entry when full. Values whose type depends on an empty
314    /// dynamic array, such as a struct with an empty array field, have no derivable type and are
315    /// not recorded whole; their leaves still are.
316    composite_values: HashMap<DynSolType, IndexMap<B256, DynSolValue>>,
317    /// Persistent values from sancov trace-cmp that survive `revert()` across runs.
318    persistent_values: B256IndexSet,
319    /// Parsed storage layout identifiers keyed by the layout allocation.
320    slot_identifiers: HashMap<usize, SlotIdentifier>,
321    /// Cached non-mapping storage slot identification keyed by layout allocation and slot.
322    slot_info_cache: HashMap<(usize, B256), Option<Arc<SlotInfo>>>,
323
324    misses: usize,
325    hits: usize,
326}
327
328impl fmt::Debug for FuzzDictionary {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        f.debug_struct("FuzzDictionary")
331            .field("state_values", &self.state_values.len())
332            .field("addresses", &self.addresses)
333            .field("persistent_values", &self.persistent_values.len())
334            .finish()
335    }
336}
337
338impl Default for FuzzDictionary {
339    fn default() -> Self {
340        Self::new(Default::default())
341    }
342}
343
344impl FuzzDictionary {
345    pub fn new(mut config: FuzzDictionaryConfig) -> Self {
346        config.max_fuzz_dictionary_values = config.max_fuzz_dictionary_values.max(1);
347        let mut dictionary = Self {
348            config,
349            samples_seeded: false,
350
351            state_values: Default::default(),
352            addresses: Default::default(),
353            push_bytecode_hashes: Default::default(),
354            db_state_values: Default::default(),
355            db_addresses: Default::default(),
356            db_push_bytecode_hashes: Default::default(),
357            sample_values: Default::default(),
358            learned_samples: Default::default(),
359            composite_values: Default::default(),
360            literal_values: Default::default(),
361            persistent_values: Default::default(),
362            slot_identifiers: Default::default(),
363            slot_info_cache: Default::default(),
364            misses: Default::default(),
365            hits: Default::default(),
366        };
367        // Zero is a useful default seed even before state or literals populate the dictionary.
368        dictionary.insert_value(B256::ZERO);
369        dictionary
370    }
371
372    /// Seeds `sample_values` with all words from the [`LiteralsDictionary`].
373    /// Should only be called once per dictionary lifetime.
374    #[cold]
375    fn seed_samples(&mut self) {
376        trace!("seeding `sample_values` from literal dictionary");
377        self.sample_values
378            .extend(self.literal_values.get().words.iter().map(|(k, v)| (k.clone(), v.clone())));
379        self.samples_seeded = true;
380    }
381
382    /// Insert values from initial db state into fuzz dictionary.
383    /// These values are persisted across invariant runs.
384    fn insert_db_values<DB>(&mut self, db: &CacheDB<DB>) {
385        let cache = &db.cache;
386        // Accounts whose storage changed without changing their info only have a storage entry.
387        // Sort addresses to ensure deterministic dictionary generation from the same setUp state.
388        let mut addresses =
389            cache.accounts.keys().chain(cache.storage.keys()).copied().collect::<Vec<_>>();
390        addresses.sort_unstable();
391        addresses.dedup();
392        for address in addresses {
393            if is_history_storage_address(&address) {
394                continue;
395            }
396
397            // Insert basic account information
398            self.insert_value(address.into_word());
399            self.insert_address_sample(address);
400            // Insert push bytes. The cache stores code separately, keyed by code hash.
401            if let Some(Some(info)) = cache.accounts.get(&address) {
402                let code = info.code.as_ref().or_else(|| cache.contracts.get(&info.code_hash));
403                self.insert_push_bytes_values(&address, info, code);
404            }
405            // Insert storage values.
406            if self.config.include_storage
407                && let Some(storage) = cache.storage.get(&address)
408            {
409                // Sort storage values before inserting to ensure deterministic dictionary.
410                let mut values = storage.slots.iter().collect::<Vec<_>>();
411                values.sort_unstable_by_key(|(slot, _)| **slot);
412                for (slot, value) in values {
413                    self.insert_storage_value(slot, value, None);
414                }
415            }
416        }
417
418        // We need at least some state data if DB is empty,
419        // otherwise we can't select random data for state fuzzing.
420        if self.values().is_empty() {
421            // Prefill with a random address.
422            self.insert_value(Address::random().into_word());
423        }
424
425        // Record number of values and addresses inserted from db to be used for reverting at the
426        // end of each run.
427        self.db_state_values = self.state_values.len();
428        self.db_addresses = self.addresses.len();
429        self.db_push_bytecode_hashes = self.push_bytecode_hashes.len();
430    }
431
432    /// Insert values collected from call result into fuzz dictionary.
433    fn insert_result_values(
434        &mut self,
435        function: Option<&Function>,
436        result: &Bytes,
437        run_depth: u32,
438    ) {
439        if let Some(function) = function
440            && !function.outputs.is_empty()
441        {
442            // Decode result and collect samples to be used in subsequent fuzz runs.
443            if let Ok(decoded_result) = function.abi_decode_output(result) {
444                self.insert_sample_values(decoded_result, run_depth);
445            }
446        }
447    }
448
449    /// Insert values from call log topics and data into fuzz dictionary.
450    ///
451    /// Each log is decoded with the ABI of the targeted contract that emitted it, then with the
452    /// called contract's, then with any other targeted contract's, so typed values (including
453    /// whole structs) from events emitted by nested calls are not lost to raw-word fallback.
454    fn insert_logs_values(
455        &mut self,
456        target_contract: Option<&TargetedContract>,
457        targets: &TargetedContracts,
458        logs: &[Log],
459        run_depth: u32,
460    ) {
461        let mut samples = Vec::new();
462        // Decode logs with known events and collect samples from indexed fields and event body.
463        for log in logs {
464            let emitter = targets.get(&log.address);
465            let log_decoded = emitter
466                .into_iter()
467                .chain(target_contract)
468                .chain(targets.values())
469                .any(|contract| Self::decode_log_with_contract(contract, log, &mut samples));
470
471            // If we weren't able to decode event then we insert raw data in fuzz dictionary.
472            if !log_decoded {
473                for &topic in log.topics() {
474                    self.insert_value(topic);
475                }
476                let (chunks, rem) = log.data.data.as_chunks::<32>();
477                for chunk in chunks {
478                    self.insert_value((*chunk).into());
479                }
480                if !rem.is_empty() {
481                    self.insert_value(B256::right_padding_from(rem));
482                }
483            }
484        }
485
486        // Insert samples collected from current call in fuzz dictionary.
487        if !samples.is_empty() {
488            self.insert_sample_values(samples, run_depth);
489        }
490    }
491
492    fn decode_log_with_contract(
493        contract: &TargetedContract,
494        log: &Log,
495        samples: &mut Vec<DynSolValue>,
496    ) -> bool {
497        let matched_events = log
498            .topics()
499            .first()
500            .and_then(|selector| {
501                contract.event_lookup.by_topic(selector, log.topics().len().saturating_sub(1))
502            })
503            .unwrap_or(&[]);
504        Self::decode_log_events(matched_events, contract.event_lookup.anonymous(), log, samples)
505    }
506
507    fn decode_log_events(
508        matched_events: &[TargetedContractEvent],
509        anonymous_events: &[TargetedContractEvent],
510        log: &Log,
511        samples: &mut Vec<DynSolValue>,
512    ) -> bool {
513        let mut matched = matched_events.iter().peekable();
514        let mut anonymous = anonymous_events.iter().peekable();
515        while matched.peek().is_some() || anonymous.peek().is_some() {
516            let event = match (matched.peek(), anonymous.peek()) {
517                (Some(matched_event), Some(anonymous_event)) => {
518                    if matched_event.order() < anonymous_event.order() {
519                        matched.next().unwrap()
520                    } else {
521                        anonymous.next().unwrap()
522                    }
523                }
524                (Some(_), None) => matched.next().unwrap(),
525                (None, Some(_)) => anonymous.next().unwrap(),
526                (None, None) => unreachable!(),
527            };
528            if let Ok(decoded_event) = event.event().decode_log(log) {
529                samples.extend(decoded_event.indexed);
530                samples.extend(decoded_event.body);
531                return true;
532            }
533        }
534        false
535    }
536
537    /// Insert values from the accounts and storage loaded by a call into fuzz dictionary.
538    /// These values are removed at the end of current run.
539    fn insert_new_state_values<'a>(
540        &mut self,
541        state_changes: impl IntoIterator<Item = AccountChanges<'a>>,
542        targets: &TargetedContracts,
543    ) {
544        // Sort accounts before inserting to ensure deterministic dictionary.
545        let mut accounts = state_changes.into_iter().collect::<Vec<_>>();
546        accounts.sort_unstable_by_key(|changes| changes.address);
547        for changes in accounts {
548            let address = &changes.address;
549            if is_history_storage_address(address) {
550                continue;
551            }
552
553            // Insert basic account information.
554            self.insert_value(address.into_word());
555            self.insert_address_sample(*address);
556            // Insert push bytes.
557            if let Some(info) = changes.current {
558                let code = changes.code.map(|(_, code)| code).or(info.code.as_ref());
559                self.insert_push_bytes_values(address, info, code);
560            }
561            // Insert storage values.
562            let storage = &changes.storage.slots;
563            if self.config.include_storage && !storage.is_empty() {
564                let slot_identifier_key = targets.get(address).and_then(|contract| {
565                    contract.storage_layout.as_ref().map(|layout| {
566                        let key = Arc::as_ptr(layout) as usize;
567                        self.slot_identifiers
568                            .entry(key)
569                            .or_insert_with(|| SlotIdentifier::new(Arc::clone(layout)));
570                        key
571                    })
572                });
573                // Sort storage values before inserting to ensure deterministic dictionary.
574                let mut storage = storage.iter().collect::<Vec<_>>();
575                storage.sort_unstable_by_key(|(slot, _)| **slot);
576                for (slot, value) in storage {
577                    let value = value.value.current;
578                    let slot_info = slot_identifier_key.and_then(|key| {
579                        let slot = B256::from(*slot);
580                        let value_word = B256::from(value);
581                        // A dynamic array's slot, also as an element of a fixed array, holds its
582                        // length, which no parameter samples by the array type, so keep it untyped.
583                        // So is a slot packing several array elements, which decodes as an array of
584                        // them and is no sample of one.
585                        self.identify_storage_slot(key, slot).filter(|slot_info| {
586                            let mut ty = &slot_info.slot_type.dyn_sol_type;
587                            while let DynSolType::FixedArray(inner, _) = ty {
588                                ty = inner;
589                            }
590                            !matches!(ty, DynSolType::Array(_))
591                                && slot_info.decode(value_word).is_some_and(|value| {
592                                    !matches!(value, DynSolValue::FixedArray(_))
593                                })
594                        })
595                    });
596                    self.insert_storage_value(slot, &value, slot_info.as_deref());
597                }
598            }
599        }
600    }
601
602    fn identify_storage_slot(&mut self, key: usize, slot: B256) -> Option<Arc<SlotInfo>> {
603        let cache_key = (key, slot);
604        if let Some(slot_info) = self.slot_info_cache.get(&cache_key) {
605            return slot_info.clone();
606        }
607
608        let slot_info = self
609            .slot_identifiers
610            .get(&key)
611            .and_then(|identifier| identifier.identify(&slot, None))
612            .map(Arc::new);
613        if self.slot_info_cache.len() < MAX_SLOT_INFO_CACHE_ENTRIES {
614            self.slot_info_cache.insert(cache_key, slot_info.clone());
615        }
616        slot_info
617    }
618
619    /// Insert values from push bytes into fuzz dictionary.
620    /// Values are collected only once for a given bytecode.
621    /// If values are newly collected then they are removed at the end of current run.
622    fn insert_push_bytes_values(
623        &mut self,
624        address: &Address,
625        account_info: &AccountInfo,
626        code: Option<&Bytecode>,
627    ) {
628        if !self.config.include_push_bytes {
629            return;
630        }
631
632        let Some(code) = code else {
633            return;
634        };
635        self.insert_address(*address);
636        if self.values_full() {
637            return;
638        }
639        if self.push_bytecode_hashes.insert(account_info.code_hash) {
640            self.collect_push_bytes(ignore_metadata_hash(code.original_byte_slice()));
641        }
642    }
643
644    fn collect_push_bytes(&mut self, code: &[u8]) {
645        let len = code.len().min(PUSH_BYTE_ANALYSIS_LIMIT);
646        let code = &code[..len];
647        let mut seen = HashSet::default();
648        for inst in InstIter::new(code) {
649            if self.values_full() {
650                break;
651            }
652            // Don't add 0 to the dictionary as it's already present.
653            if !inst.immediate.is_empty()
654                && let Some(push_value) = U256::try_from_be_slice(inst.immediate)
655                && !push_value.is_zero()
656            {
657                self.insert_push_value_u256(push_value, &mut seen);
658            }
659        }
660    }
661
662    /// Insert values from single storage slot and storage value into fuzz dictionary.
663    /// Uses [`SlotIdentifier`] to identify storage slots types.
664    fn insert_storage_value(&mut self, slot: &U256, value: &U256, slot_info: Option<&SlotInfo>) {
665        let slot = B256::from(*slot);
666        let value_word = B256::from(*value);
667
668        // Always insert the slot itself
669        self.insert_value(slot);
670
671        if let Some(slot_info) = slot_info {
672            trace!(?slot_info, "inserting typed storage value");
673            if !self.samples_seeded {
674                self.seed_samples();
675            }
676            self.sample_values
677                .entry(slot_info.slot_type.dyn_sol_type.clone())
678                .or_default()
679                .insert(value_word);
680        } else {
681            self.insert_value_u256(*value);
682        }
683    }
684
685    /// Insert address into fuzz dictionary.
686    /// If address is newly collected then it is removed by index at the end of current run.
687    fn insert_address(&mut self, address: Address) {
688        if self.addresses.len() < self.config.max_fuzz_dictionary_addresses {
689            self.addresses.insert(address);
690        }
691    }
692
693    /// Insert raw value into fuzz dictionary.
694    ///
695    /// If value is newly collected then it is removed by index at the end of current run.
696    ///
697    /// Returns true if the value was inserted.
698    fn insert_value(&mut self, value: B256) -> bool {
699        let insert = !self.values_full();
700        if insert {
701            let new_value = self.state_values.insert(value);
702            let counter = if new_value { &mut self.misses } else { &mut self.hits };
703            *counter += 1;
704        }
705        insert
706    }
707
708    /// Insert a persistent value that survives `revert()` across invariant runs.
709    /// Used for trace-cmp operands that should compound over time.
710    fn insert_persistent_value(&mut self, value: B256) {
711        if self.persistent_values.len() >= MAX_PERSISTENT_VALUES {
712            return;
713        }
714        if !self.persistent_values.insert(value) {
715            return;
716        }
717        // `revert()` truncates `state_values` down to the first `db_state_values` entries, so the
718        // value must be placed inside that prefix; a plain `insert` appends past it and would be
719        // truncated at the end of the run.
720        match self.state_values.get_index_of(&value) {
721            // Already inside the persisted prefix.
722            Some(index) if index < self.db_state_values => {}
723            // Collected as an ephemeral value earlier in this run: move it into the prefix.
724            Some(index) => {
725                self.state_values.move_index(index, self.db_state_values);
726                self.db_state_values += 1;
727            }
728            None => {
729                self.state_values.shift_insert(self.db_state_values, value);
730                self.db_state_values += 1;
731            }
732        }
733    }
734
735    /// Insert a typed trace-cmp value into the `sample_values` map.
736    /// Maps sancov width to `DynSolType` buckets and promotes to larger types.
737    fn insert_typed_cmp_value(&mut self, width: u8, value: B256) {
738        if !self.samples_seeded {
739            self.seed_samples();
740        }
741
742        const MAX_TYPED_CMP_PER_BUCKET: usize = 1024;
743
744        let native_type = match width {
745            8 => DynSolType::Uint(8),
746            16 => DynSolType::Uint(16),
747            32 => DynSolType::Uint(32),
748            64 => DynSolType::Uint(64),
749            _ => DynSolType::Uint(256),
750        };
751
752        let insert = |map: &mut HashMap<DynSolType, B256IndexSet>, ty: DynSolType, val: B256| {
753            let bucket = map.entry(ty).or_default();
754            if bucket.len() < MAX_TYPED_CMP_PER_BUCKET {
755                bucket.insert(val);
756            }
757        };
758
759        insert(&mut self.sample_values, native_type, value);
760
761        if width <= 64 {
762            insert(&mut self.sample_values, DynSolType::Uint(128), value);
763            insert(&mut self.sample_values, DynSolType::Uint(256), value);
764            insert(&mut self.sample_values, DynSolType::Int(256), value);
765        }
766    }
767
768    /// Insert the address of an account the campaign touched as a typed `address` sample.
769    ///
770    /// The address also lives in the untyped value pool, but `address` parameters only reach it
771    /// there in the share of picks that falls on the untyped pool. Samples are not reverted at the
772    /// end of a run, so addresses that a reverted call created stay available.
773    fn insert_address_sample(&mut self, address: Address) {
774        if !self.samples_seeded {
775            self.seed_samples();
776        }
777        let bucket = self.sample_values.entry(DynSolType::Address).or_default();
778        if bucket.len() < MAX_ADDRESS_SAMPLES {
779            bucket.insert(address.into_word());
780        }
781    }
782
783    fn insert_value_u256(&mut self, value: U256) -> bool {
784        // Also add the value below and above the push value to the dictionary.
785        let one = U256::ONE;
786        let mut inserted = self.insert_value(value.into());
787        if !self.values_full() {
788            inserted |= self.insert_value((value.wrapping_sub(one)).into());
789        }
790        if !self.values_full() {
791            inserted |= self.insert_value((value.wrapping_add(one)).into());
792        }
793        inserted
794    }
795
796    fn insert_push_value_u256(&mut self, value: U256, seen: &mut HashSet<B256>) -> bool {
797        // Also add the value below and above the push value to the dictionary.
798        let one = U256::ONE;
799        let mut inserted = false;
800        for value in [value, value.wrapping_sub(one), value.wrapping_add(one)] {
801            if self.values_full() {
802                break;
803            }
804            let value = value.into();
805            if seen.insert(value) {
806                inserted |= self.insert_value(value);
807            }
808        }
809        inserted
810    }
811
812    fn values_full(&self) -> bool {
813        self.state_values.len() >= self.config.max_fuzz_dictionary_values
814    }
815
816    /// Insert sample values that are reused across multiple runs.
817    /// The number of samples is limited to invariant run depth.
818    /// If collected samples limit is reached then values are inserted as regular values.
819    pub fn insert_sample_values(
820        &mut self,
821        sample_values: impl IntoIterator<Item = DynSolValue>,
822        limit: u32,
823    ) {
824        if !self.samples_seeded {
825            self.seed_samples();
826        }
827        for sample in sample_values {
828            self.insert_sample_value(&sample, limit);
829        }
830    }
831
832    /// Inserts one decoded value. Composite values are recorded whole under their canonical type
833    /// and their nested values are recorded recursively, so every leaf also feeds its own typed
834    /// bucket instead of being dropped.
835    fn insert_sample_value(&mut self, sample: &DynSolValue, limit: u32) {
836        match sample {
837            DynSolValue::Tuple(inner)
838            | DynSolValue::Array(inner)
839            | DynSolValue::FixedArray(inner)
840            | DynSolValue::CustomStruct { tuple: inner, .. } => {
841                for value in inner {
842                    self.insert_sample_value(value, limit);
843                }
844                self.insert_composite_value(sample, limit);
845            }
846            DynSolValue::Bytes(bytes) => {
847                if bytes.len() <= MAX_COMPOSITE_BYTES_LEN {
848                    self.insert_composite_value(sample, limit);
849                }
850            }
851            DynSolValue::String(string) => {
852                if string.len() <= MAX_COMPOSITE_BYTES_LEN {
853                    self.insert_composite_value(sample, limit);
854                }
855            }
856            _ => {
857                let (Some(sample_type), Some(sample_value)) = (sample.as_type(), sample.as_word())
858                else {
859                    return;
860                };
861                let learned = self.learned_samples.entry(sample_type.clone()).or_default();
862                if *learned < limit as usize {
863                    if self.sample_values.entry(sample_type).or_default().insert(sample_value) {
864                        *learned += 1;
865                    }
866                } else {
867                    // Insert as state value (will be removed at the end of the run).
868                    self.insert_value(sample_value);
869                }
870            }
871        }
872    }
873
874    /// Records a whole composite value under its canonical ABI type, evicting the oldest entry
875    /// of that type once `limit` entries are stored.
876    fn insert_composite_value(&mut self, value: &DynSolValue, limit: u32) {
877        // A value whose type depends on an empty dynamic array has no element type to key on.
878        let Some(ty) = value.as_type().map(canonical_type) else { return };
879        let key = keccak256(value.abi_encode());
880        let values = self.composite_values.entry(ty).or_default();
881        if values.contains_key(&key) {
882            return;
883        }
884        if values.len() >= (limit as usize).max(1) {
885            values.shift_remove_index(0);
886        }
887        values.insert(key, value.clone());
888    }
889
890    /// Returns whole composite values previously observed for the given type.
891    #[inline]
892    pub fn composite_samples(
893        &self,
894        param_type: &DynSolType,
895    ) -> Option<&IndexMap<B256, DynSolValue>> {
896        self.composite_values.get(param_type).filter(|values| !values.is_empty())
897    }
898
899    pub const fn values(&self) -> &B256IndexSet {
900        &self.state_values
901    }
902
903    pub fn len(&self) -> usize {
904        self.state_values.len()
905    }
906
907    pub fn is_empty(&self) -> bool {
908        self.state_values.is_empty()
909    }
910
911    /// Returns sample values for a given type, checking both runtime samples and literals.
912    ///
913    /// Before `seed_samples()` is called, checks both `literal_values` and `sample_values`
914    /// separately. After seeding, all literal values are merged into `sample_values`.
915    #[inline]
916    pub fn samples(&self, param_type: &DynSolType) -> Option<&B256IndexSet> {
917        // If not seeded yet, return literals
918        if !self.samples_seeded {
919            return self.literal_values.get().words.get(param_type);
920        }
921
922        self.sample_values.get(param_type)
923    }
924
925    /// Returns the collected literal strings, triggering initialization if needed.
926    #[inline]
927    pub fn ast_strings(&self) -> &IndexSet<String> {
928        &self.literal_values.get().strings
929    }
930
931    /// Returns the collected literal bytes (hex strings), triggering initialization if needed.
932    #[inline]
933    pub fn ast_bytes(&self) -> &IndexSet<Bytes> {
934        &self.literal_values.get().bytes
935    }
936
937    #[inline]
938    pub const fn addresses(&self) -> &AddressIndexSet {
939        &self.addresses
940    }
941
942    /// Revert values and addresses collected during the run by truncating to initial db len.
943    pub fn revert(&mut self) {
944        self.state_values.truncate(self.db_state_values);
945        self.addresses.truncate(self.db_addresses);
946        self.push_bytecode_hashes.truncate(self.db_push_bytecode_hashes);
947    }
948
949    pub fn log_stats(&self) {
950        trace!(
951            addresses.len = self.addresses.len(),
952            sample.len = self.sample_values.len(),
953            state.len = self.state_values.len(),
954            state.misses = self.misses,
955            state.hits = self.hits,
956            "FuzzDictionary stats",
957        );
958    }
959
960    #[cfg(test)]
961    /// Test-only helper to seed the dictionary with literal values.
962    pub(crate) fn seed_literals(&mut self, map: super::LiteralMaps) {
963        self.literal_values.set(map);
964    }
965}
966
967/// Returns the type with every struct replaced by its plain tuple, which is how ABI function
968/// parameters resolve, so values decoded with struct names still match parameter types.
969fn canonical_type(ty: DynSolType) -> DynSolType {
970    match ty {
971        DynSolType::CustomStruct { tuple, .. } | DynSolType::Tuple(tuple) => {
972            DynSolType::Tuple(tuple.into_iter().map(canonical_type).collect())
973        }
974        DynSolType::Array(inner) => DynSolType::Array(Box::new(canonical_type(*inner))),
975        DynSolType::FixedArray(inner, size) => {
976            DynSolType::FixedArray(Box::new(canonical_type(*inner)), size)
977        }
978        ty => ty,
979    }
980}
981
982#[cfg(test)]
983mod tests {
984
985    use super::*;
986    use crate::strategies::LiteralMaps;
987    use alloy_json_abi::{Event, JsonAbi};
988    use foundry_compilers::artifacts::{Storage, StorageLayout, StorageType};
989    use foundry_evm_core::eip2935::HISTORY_STORAGE_ADDRESS;
990
991    fn account_with_code(raw: &'static [u8]) -> AccountInfo {
992        AccountInfo::default().with_code(Bytecode::new_raw(Bytes::from_static(raw)))
993    }
994
995    #[test]
996    fn log_decoding_preserves_anonymous_event_priority() {
997        let mut abi = JsonAbi::new();
998        let anonymous_event =
999            Event::parse("event AEvent(bytes32 indexed topic, uint256 value) anonymous").unwrap();
1000        let matched_event = Event::parse("event ZEvent(uint256 value)").unwrap();
1001        let selector = matched_event.selector();
1002        abi.events.entry(anonymous_event.name.clone()).or_default().push(anonymous_event);
1003        abi.events.entry(matched_event.name.clone()).or_default().push(matched_event);
1004        let contract = TargetedContract::new("Target".to_string(), abi);
1005        let matched_events = contract.event_lookup.by_topic(&selector, 0).unwrap();
1006        let word: B256 = U256::from(42).into();
1007        let log = Log::new_unchecked(Address::ZERO, vec![selector], Bytes::from(word));
1008        let mut samples = Vec::new();
1009
1010        assert!(FuzzDictionary::decode_log_events(
1011            matched_events,
1012            contract.event_lookup.anonymous(),
1013            &log,
1014            &mut samples,
1015        ));
1016
1017        assert_eq!(samples.len(), 2);
1018        assert_eq!(samples[0], DynSolValue::FixedBytes(selector, 32));
1019        assert_eq!(samples[1], DynSolValue::Uint(U256::from(42), 256));
1020    }
1021
1022    #[test]
1023    fn push_byte_collection_stops_when_dictionary_is_full() {
1024        let mut dictionary = FuzzDictionary::new(FuzzDictionaryConfig {
1025            max_fuzz_dictionary_values: 3,
1026            ..Default::default()
1027        });
1028
1029        dictionary.collect_push_bytes(&[0x60, 0x01, 0x60, 0x03]);
1030
1031        assert_eq!(dictionary.len(), 3);
1032        assert!(dictionary.state_values.contains(&B256::ZERO));
1033        assert!(dictionary.state_values.contains(&B256::with_last_byte(1)));
1034        assert!(dictionary.state_values.contains(&B256::with_last_byte(2)));
1035        assert!(!dictionary.state_values.contains(&B256::with_last_byte(3)));
1036    }
1037
1038    #[test]
1039    fn zero_value_capacity_keeps_only_required_seed() {
1040        let mut dictionary = FuzzDictionary::new(FuzzDictionaryConfig {
1041            max_fuzz_dictionary_values: 0,
1042            ..Default::default()
1043        });
1044
1045        assert_eq!(dictionary.config.max_fuzz_dictionary_values, 1);
1046        assert_eq!(dictionary.state_values.as_slice(), &[B256::ZERO]);
1047        assert!(!dictionary.insert_value(B256::with_last_byte(1)));
1048        assert_eq!(dictionary.state_values.as_slice(), &[B256::ZERO]);
1049    }
1050
1051    #[test]
1052    fn duplicate_push_values_in_same_bytecode_are_collected_once() {
1053        let mut dictionary = FuzzDictionary::default();
1054
1055        dictionary.collect_push_bytes(&[0x60, 0x01, 0x60, 0x01]);
1056
1057        assert!(dictionary.state_values.contains(&B256::ZERO));
1058        assert!(dictionary.state_values.contains(&B256::with_last_byte(1)));
1059        assert!(dictionary.state_values.contains(&B256::with_last_byte(2)));
1060        assert_eq!(dictionary.hits, 1);
1061    }
1062
1063    #[test]
1064    fn duplicate_bytecode_push_bytes_are_collected_once() {
1065        let mut dictionary = FuzzDictionary::default();
1066        let account = account_with_code(&[0x60, 0x01]);
1067
1068        dictionary.insert_push_bytes_values(
1069            &Address::repeat_byte(0x11),
1070            &account,
1071            account.code.as_ref(),
1072        );
1073        let hits_after_first_scan = dictionary.hits;
1074
1075        dictionary.insert_push_bytes_values(
1076            &Address::repeat_byte(0x22),
1077            &account,
1078            account.code.as_ref(),
1079        );
1080
1081        assert_eq!(dictionary.push_bytecode_hashes.len(), 1);
1082        assert_eq!(dictionary.addresses.len(), 2);
1083        assert_eq!(dictionary.hits, hits_after_first_scan);
1084    }
1085
1086    #[test]
1087    fn same_address_with_new_bytecode_is_scanned_again() {
1088        let mut dictionary = FuzzDictionary::default();
1089        let address = Address::repeat_byte(0x22);
1090
1091        for account in [account_with_code(&[0x60, 0x01]), account_with_code(&[0x60, 0x04])] {
1092            dictionary.insert_push_bytes_values(&address, &account, account.code.as_ref());
1093        }
1094
1095        assert_eq!(dictionary.addresses.len(), 1);
1096        assert_eq!(dictionary.push_bytecode_hashes.len(), 2);
1097        assert!(dictionary.state_values.contains(&B256::with_last_byte(1)));
1098        assert!(dictionary.state_values.contains(&B256::with_last_byte(4)));
1099    }
1100
1101    #[test]
1102    fn no_code_account_does_not_block_later_push_byte_scan() {
1103        let mut dictionary = FuzzDictionary::default();
1104        let address = Address::repeat_byte(0x33);
1105        let account_without_code = AccountInfo { code: None, ..Default::default() };
1106
1107        dictionary.insert_push_bytes_values(&address, &account_without_code, None);
1108
1109        assert!(!dictionary.addresses.contains(&address));
1110        assert_eq!(dictionary.push_bytecode_hashes.len(), 0);
1111
1112        let account = account_with_code(&[0x60, 0x04]);
1113        dictionary.insert_push_bytes_values(&address, &account, account.code.as_ref());
1114
1115        assert!(dictionary.addresses.contains(&address));
1116        assert_eq!(dictionary.push_bytecode_hashes.len(), 1);
1117        assert!(dictionary.state_values.contains(&B256::with_last_byte(4)));
1118    }
1119
1120    #[test]
1121    fn revert_removes_runtime_bytecode_scan_cache() {
1122        let mut dictionary = FuzzDictionary::default();
1123        dictionary.db_state_values = dictionary.state_values.len();
1124        dictionary.db_addresses = dictionary.addresses.len();
1125        dictionary.db_push_bytecode_hashes = dictionary.push_bytecode_hashes.len();
1126
1127        let account = account_with_code(&[0x60, 0x01]);
1128        dictionary.insert_push_bytes_values(
1129            &Address::repeat_byte(0x11),
1130            &account,
1131            account.code.as_ref(),
1132        );
1133        assert_eq!(dictionary.push_bytecode_hashes.len(), 1);
1134
1135        dictionary.revert();
1136        assert_eq!(dictionary.push_bytecode_hashes.len(), 0);
1137
1138        dictionary.insert_push_bytes_values(
1139            &Address::repeat_byte(0x22),
1140            &account,
1141            account.code.as_ref(),
1142        );
1143        assert_eq!(dictionary.push_bytecode_hashes.len(), 1);
1144        assert!(dictionary.state_values.contains(&B256::with_last_byte(1)));
1145    }
1146
1147    #[test]
1148    fn persistent_value_survives_revert() {
1149        let mut dictionary = FuzzDictionary::default();
1150        dictionary.db_state_values = dictionary.state_values.len();
1151
1152        let ephemeral = B256::from(U256::from(0xbeef_u64));
1153        let persistent = B256::from(U256::from(0xcafe_u64));
1154        dictionary.insert_value(ephemeral);
1155        dictionary.insert_persistent_value(persistent);
1156
1157        dictionary.revert();
1158
1159        assert!(dictionary.state_values.contains(&persistent));
1160        assert!(!dictionary.state_values.contains(&ephemeral));
1161        assert!(dictionary.db_state_values <= dictionary.state_values.len());
1162
1163        // Values already inside the persisted prefix are left untouched.
1164        let watermark = dictionary.db_state_values;
1165        let len = dictionary.state_values.len();
1166        dictionary.insert_persistent_value(B256::ZERO);
1167        assert_eq!(dictionary.db_state_values, watermark);
1168        assert_eq!(dictionary.state_values.len(), len);
1169    }
1170
1171    #[test]
1172    fn persistent_value_promotes_existing_ephemeral() {
1173        let mut dictionary = FuzzDictionary::default();
1174        dictionary.db_state_values = dictionary.state_values.len();
1175
1176        let ephemeral = B256::from(U256::from(0xbeef_u64));
1177        let value = B256::from(U256::from(0xdead_u64));
1178        dictionary.insert_value(ephemeral);
1179        dictionary.insert_value(value);
1180        dictionary.insert_persistent_value(value);
1181
1182        dictionary.revert();
1183
1184        assert!(dictionary.state_values.contains(&value));
1185        assert!(!dictionary.state_values.contains(&ephemeral));
1186        assert!(dictionary.db_state_values <= dictionary.state_values.len());
1187    }
1188
1189    #[test]
1190    fn history_storage_account_is_excluded_from_initial_dictionary() {
1191        let mut db = InMemoryDB::default();
1192        let code = Bytecode::new_raw(Bytes::from_static(&[0x61, 0x01, 0x23, 0x00]));
1193        db.insert_account_info(&HISTORY_STORAGE_ADDRESS, AccountInfo::default().with_code(code));
1194        db.insert_account_storage(
1195            &HISTORY_STORAGE_ADDRESS,
1196            &U256::from(7),
1197            &U256::from(0xdead_u64),
1198        );
1199
1200        let state = EvmFuzzState::new(&[], &db, FuzzDictionaryConfig::default(), None);
1201
1202        state.with_dictionary(|dict| {
1203            assert!(!dict.values().contains(&HISTORY_STORAGE_ADDRESS.into_word()));
1204            assert!(!dict.values().contains(&B256::from(U256::from(0x123))));
1205            assert!(!dict.values().contains(&B256::with_last_byte(7)));
1206            assert!(!dict.values().contains(&B256::from(U256::from(0xdead_u64))));
1207        });
1208    }
1209
1210    #[test]
1211    fn db_seed_reads_cached_code_and_storage_only_accounts() {
1212        let (contract, storage_only) = (Address::repeat_byte(0x11), Address::repeat_byte(0x22));
1213        let mut db = InMemoryDB::default();
1214        // The cache moves the code into its contracts map.
1215        db.insert_account_info(&contract, account_with_code(&[0x61, 0x01, 0x23, 0x00]));
1216        db.insert_account_storage(&storage_only, &U256::from(7), &U256::from(0xdead_u64));
1217
1218        let state = EvmFuzzState::new(&[], &db, FuzzDictionaryConfig::default(), None);
1219
1220        state.with_dictionary(|dict| {
1221            for value in [
1222                contract.into_word(),
1223                B256::from(U256::from(0x123)),
1224                storage_only.into_word(),
1225                B256::with_last_byte(7),
1226                B256::from(U256::from(0xdead_u64)),
1227            ] {
1228                assert!(dict.values().contains(&value), "{value}");
1229            }
1230            assert_eq!(dict.addresses().iter().copied().collect::<Vec<_>>(), [contract]);
1231        });
1232    }
1233
1234    #[test]
1235    fn call_values_come_from_loaded_accounts_and_storage() {
1236        let address = Address::repeat_byte(0x11);
1237        let mut state = evm2::evm::PendingState::default();
1238        state.insert_account(address, None, Some(account_with_code(&[0x61, 0x01, 0x23, 0x00])));
1239        state.insert_storage(address, U256::from(7), U256::ZERO, U256::from(0xbeef_u64));
1240        let mut dictionary = FuzzDictionary::default();
1241
1242        dictionary.insert_new_state_values(state.account_changes(), &TargetedContracts::new());
1243
1244        for value in [
1245            address.into_word(),
1246            B256::from(U256::from(0x123)),
1247            B256::with_last_byte(7),
1248            B256::from(U256::from(0xbeef_u64)),
1249        ] {
1250            assert!(dictionary.values().contains(&value), "{value}");
1251        }
1252        assert!(dictionary.addresses().contains(&address));
1253    }
1254
1255    #[test]
1256    fn worker_modes_share_seed_but_isolate_feedback() {
1257        let seed = EvmFuzzState::test();
1258        let readonly = seed.stateless_worker();
1259        let first = seed.clone().into_invariant();
1260        let second = seed.into_invariant();
1261        let transient = B256::from(U256::from(0xdead_u64));
1262        let persistent = B256::from(U256::from(0xbeef_u64));
1263
1264        readonly.collect_values([transient]);
1265        assert!(!readonly.with_dictionary(|dict| dict.state_values.contains(&transient)));
1266
1267        first.collect_values([transient]);
1268        first.collect_typed_cmp_values([(8, persistent)]);
1269        assert!(first.with_dictionary(|dict| dict.state_values.contains(&transient)));
1270        assert!(!second.with_dictionary(|dict| dict.state_values.contains(&transient)));
1271
1272        first.revert();
1273        assert!(!first.with_dictionary(|dict| dict.state_values.contains(&transient)));
1274        first.with_dictionary(|dict| {
1275            assert!(dict.state_values.contains(&persistent));
1276            assert!(dict.persistent_values.contains(&persistent));
1277            assert!(dict.sample_values[&DynSolType::Uint(8)].contains(&persistent));
1278        });
1279    }
1280
1281    #[test]
1282    fn new_state_values_are_inserted_in_sorted_order() {
1283        // Account `i` holds slots `i * 0x100 + j` with values `i * 0x10000 + j * 0x10`, so no
1284        // address, slot, or value (+/- 1) collides with another.
1285        let entry =
1286            |i: u64, j: u64| (U256::from(i * 0x100 + j), U256::from(i * 0x10000 + j * 0x10));
1287        let address = |i: u64| Address::repeat_byte(i as u8 * 0x11);
1288
1289        let mut state = evm2::evm::PendingState::default();
1290        for i in [3, 1, 4, 2] {
1291            state.insert_account(address(i), None, Some(AccountInfo::default()));
1292            for j in [3, 1, 2] {
1293                let (slot, value) = entry(i, j);
1294                state.insert_storage(address(i), slot, U256::ZERO, value);
1295            }
1296        }
1297
1298        let mut dictionary = FuzzDictionary::default();
1299        dictionary.insert_new_state_values(state.account_changes(), &TargetedContracts::new());
1300
1301        let mut expected = vec![B256::ZERO];
1302        for i in 1..=4 {
1303            expected.push(address(i).into_word());
1304            for j in 1..=3 {
1305                let (slot, value) = entry(i, j);
1306                expected
1307                    .extend([slot, value, value - U256::ONE, value + U256::ONE].map(B256::from));
1308            }
1309        }
1310        assert_eq!(dictionary.state_values.as_slice(), expected.as_slice());
1311    }
1312
1313    #[test]
1314    fn touched_account_addresses_become_typed_address_samples() {
1315        let mut state = evm2::evm::PendingState::default();
1316        for i in 1..=3u8 {
1317            state.insert_account(Address::repeat_byte(i), None, Some(AccountInfo::default()));
1318        }
1319
1320        let mut dictionary = FuzzDictionary::default();
1321        dictionary.insert_new_state_values(state.account_changes(), &TargetedContracts::new());
1322
1323        let samples = dictionary.samples(&DynSolType::Address).unwrap();
1324        for i in 1..=3u8 {
1325            assert!(samples.contains(&Address::repeat_byte(i).into_word()));
1326        }
1327        assert!(dictionary.samples(&DynSolType::Uint(256)).is_none_or(|s| s.is_empty()));
1328    }
1329
1330    #[test]
1331    fn dynamic_array_lengths_stay_untyped_storage_values() {
1332        let storage = |label: &str, slot: &str, ty: &str| Storage {
1333            ast_id: 1,
1334            contract: "C".into(),
1335            label: label.into(),
1336            offset: 0,
1337            slot: slot.into(),
1338            storage_type: ty.into(),
1339        };
1340        let ty = |encoding: &str, label: &str, bytes: &str, base: Option<&str>| StorageType {
1341            encoding: encoding.into(),
1342            key: None,
1343            label: label.into(),
1344            number_of_bytes: bytes.into(),
1345            value: None,
1346            other: base.map(|base| ("base".to_string(), base.into())).into_iter().collect(),
1347        };
1348        let layout = StorageLayout {
1349            storage: vec![
1350                storage("nums", "0", "t_array(t_uint256)dyn_storage"),
1351                storage("x", "1", "t_uint256"),
1352                storage("pairs", "2", "t_array(t_array(t_uint256)dyn_storage)2_storage"),
1353                storage("grid", "4", "t_array(t_array(t_struct(Item))dyn_storage)dyn_storage"),
1354                storage("packed", "5", "t_array(t_uint128)dyn_storage"),
1355            ],
1356            types: [
1357                (
1358                    "t_array(t_uint256)dyn_storage".into(),
1359                    ty("dynamic_array", "uint256[]", "32", Some("t_uint256")),
1360                ),
1361                ("t_uint256".into(), ty("inplace", "uint256", "32", None)),
1362                (
1363                    "t_array(t_array(t_uint256)dyn_storage)2_storage".into(),
1364                    ty("inplace", "uint256[][2]", "64", Some("t_array(t_uint256)dyn_storage")),
1365                ),
1366                (
1367                    "t_array(t_array(t_struct(Item))dyn_storage)dyn_storage".into(),
1368                    ty(
1369                        "dynamic_array",
1370                        "struct C.Item[][]",
1371                        "32",
1372                        Some("t_array(t_struct(Item))dyn_storage"),
1373                    ),
1374                ),
1375                (
1376                    "t_array(t_struct(Item))dyn_storage".into(),
1377                    ty("dynamic_array", "struct C.Item[]", "32", Some("t_struct(Item)")),
1378                ),
1379                (
1380                    "t_array(t_uint128)dyn_storage".into(),
1381                    ty("dynamic_array", "uint128[]", "32", Some("t_uint128")),
1382                ),
1383                ("t_uint128".into(), ty("inplace", "uint128", "16", None)),
1384            ]
1385            .into(),
1386        };
1387        let address = Address::repeat_byte(0x42);
1388        let mut contract = TargetedContract::new("C".into(), JsonAbi::default());
1389        contract.storage_layout = Some(Arc::new(layout));
1390        let mut targets = TargetedContracts::new();
1391        targets.insert(address, contract);
1392
1393        // `nums`, `x`, `pairs[1]`, `grid`, `grid[0]` and `packed[0..1]`.
1394        let data_start = |slot: u64| Into::<U256>::into(keccak256(B256::from(U256::from(slot))));
1395        let packed = (U256::from(6) << 128) | U256::from(5);
1396        let mut state = evm2::evm::PendingState::default();
1397        state.insert_account(address, None, Some(AccountInfo::default()));
1398        for (slot, value) in [
1399            (U256::ZERO, U256::from(5)),
1400            (U256::ONE, U256::from(7)),
1401            (U256::from(3), U256::from(9)),
1402            (U256::from(4), U256::from(15)),
1403            (data_start(4), U256::from(12)),
1404            (data_start(5), packed),
1405        ] {
1406            state.insert_storage(address, slot, U256::ZERO, value);
1407        }
1408        let mut dictionary = FuzzDictionary::default();
1409        dictionary.insert_new_state_values(state.account_changes(), &targets);
1410
1411        // Lengths and their neighbours are sampled for any parameter, like other words.
1412        for length in [4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16] {
1413            assert!(dictionary.values().contains(&B256::from(U256::from(length))), "{length}");
1414        }
1415        // So is a slot of packed array elements, which is no sample of one element.
1416        assert!(dictionary.values().contains(&B256::from(packed)));
1417        assert!(dictionary.samples(&DynSolType::Uint(128)).is_none_or(|s| s.is_empty()));
1418        // The account itself is an address sample; storage adds only `x`.
1419        assert!(
1420            dictionary
1421                .sample_values
1422                .keys()
1423                .all(|ty| matches!(ty, DynSolType::Address | DynSolType::Uint(256)))
1424        );
1425        let uints = dictionary.samples(&DynSolType::Uint(256)).unwrap();
1426        assert_eq!(uints.iter().copied().collect::<Vec<_>>(), [B256::from(U256::from(7))]);
1427    }
1428
1429    #[test]
1430    fn literals_survive_db_seeding() {
1431        let word = B256::from(U256::from(154));
1432        let mut maps = LiteralMaps::default();
1433        maps.words.entry(DynSolType::Uint(256)).or_default().insert(word);
1434        let mut literals = LiteralsDictionary::default();
1435        literals.set(maps);
1436
1437        let mut db = InMemoryDB::default();
1438        let account = Address::repeat_byte(0x42);
1439        db.insert_account_info(&account, AccountInfo::default());
1440
1441        let state = EvmFuzzState::new(&[], &db, FuzzDictionaryConfig::default(), Some(&literals));
1442        state.with_dictionary(|dict| {
1443            assert!(dict.samples(&DynSolType::Uint(256)).unwrap().contains(&word));
1444            assert!(dict.samples(&DynSolType::Address).unwrap().contains(&account.into_word()));
1445        });
1446    }
1447
1448    fn withdrawal(staker: u8, nonce: u64) -> DynSolValue {
1449        DynSolValue::Tuple(vec![
1450            DynSolValue::Address(Address::repeat_byte(staker)),
1451            DynSolValue::Uint(U256::from(nonce), 256),
1452            DynSolValue::Tuple(vec![DynSolValue::Uint(U256::from(7), 32), DynSolValue::Bool(true)]),
1453        ])
1454    }
1455
1456    #[test]
1457    fn struct_samples_are_kept_whole_and_flattened() {
1458        let mut dictionary = FuzzDictionary::default();
1459        let value = withdrawal(0x11, 42);
1460        dictionary.insert_sample_values([value.clone()], 8);
1461
1462        let ty = value.as_type().unwrap();
1463        let whole = dictionary.composite_samples(&ty).expect("struct kept whole");
1464        assert_eq!(whole.values().collect::<Vec<_>>(), vec![&value]);
1465
1466        let inner_ty = DynSolType::Tuple(vec![DynSolType::Uint(32), DynSolType::Bool]);
1467        assert!(dictionary.composite_samples(&inner_ty).is_some());
1468
1469        let addresses = dictionary.samples(&DynSolType::Address).unwrap();
1470        assert!(addresses.contains(&Address::repeat_byte(0x11).into_word()));
1471        let uints = dictionary.samples(&DynSolType::Uint(256)).unwrap();
1472        assert!(uints.contains(&B256::from(U256::from(42))));
1473    }
1474
1475    #[test]
1476    fn named_struct_samples_match_tuple_parameters() {
1477        let mut dictionary = FuzzDictionary::default();
1478        let DynSolValue::Tuple(tuple) = withdrawal(0x22, 1) else { unreachable!() };
1479        let named = DynSolValue::CustomStruct {
1480            name: "Withdrawal".into(),
1481            prop_names: vec!["staker".into(), "nonce".into(), "meta".into()],
1482            tuple,
1483        };
1484        dictionary.insert_sample_values([named], 8);
1485
1486        assert!(dictionary.composite_samples(&withdrawal(0, 0).as_type().unwrap()).is_some());
1487    }
1488
1489    #[test]
1490    fn composite_samples_evict_oldest_when_full() {
1491        let mut dictionary = FuzzDictionary::default();
1492        dictionary.insert_sample_values([withdrawal(1, 1), withdrawal(2, 2)], 2);
1493        dictionary.insert_sample_values([withdrawal(2, 2), withdrawal(3, 3)], 2);
1494
1495        let ty = withdrawal(0, 0).as_type().unwrap();
1496        let values = dictionary.composite_samples(&ty).unwrap();
1497        assert_eq!(
1498            values.values().cloned().collect::<Vec<_>>(),
1499            vec![withdrawal(2, 2), withdrawal(3, 3)]
1500        );
1501    }
1502
1503    #[test]
1504    fn literals_do_not_fill_runtime_sample_cap() {
1505        let word = |value: u64| B256::from(U256::from(value));
1506        let mut literals = LiteralMaps::default();
1507        literals.words.entry(DynSolType::Uint(256)).or_default().extend([1, 2].map(word));
1508        let mut dictionary = FuzzDictionary::default();
1509        dictionary.seed_literals(literals);
1510
1511        dictionary.insert_sample_values(
1512            [42, 43, 44].map(|value| DynSolValue::Uint(U256::from(value), 256)),
1513            2,
1514        );
1515
1516        let uints = dictionary.samples(&DynSolType::Uint(256)).unwrap();
1517        assert_eq!(uints.iter().copied().collect::<Vec<_>>(), [1, 2, 42, 43].map(word));
1518        assert!(dictionary.values().contains(&word(44)));
1519    }
1520
1521    #[test]
1522    fn logs_from_other_targets_decode_with_emitter_abi() {
1523        let emitter_abi =
1524            JsonAbi::parse(["event Queued(bytes32 root, (address,uint256,(uint32,bool)) w)"])
1525                .unwrap();
1526        let event = emitter_abi.events().next().unwrap().clone();
1527        let emitter = Address::repeat_byte(0xe0);
1528        let called = Address::repeat_byte(0xca);
1529
1530        let mut targets = TargetedContracts::new();
1531        targets.insert(emitter, TargetedContract::new("Emitter".into(), emitter_abi));
1532        targets.insert(called, TargetedContract::new("Handler".into(), JsonAbi::default()));
1533
1534        let value = withdrawal(0x33, 9);
1535        let data = DynSolValue::Tuple(vec![
1536            DynSolValue::FixedBytes(B256::repeat_byte(0xaa), 32),
1537            value.clone(),
1538        ])
1539        .abi_encode_params();
1540        let log = Log::new_unchecked(emitter, vec![event.selector()], data.into());
1541
1542        let mut dictionary = FuzzDictionary::default();
1543        dictionary.insert_logs_values(targets.get(&called), &targets, &[log], 8);
1544
1545        let values = dictionary.composite_samples(&value.as_type().unwrap()).unwrap();
1546        assert!(values.values().any(|v| *v == value));
1547    }
1548}