Skip to main content

foundry_evm_symbolic/
abi.rs

1use super::{runtime::*, *};
2
3#[derive(Clone, Debug)]
4pub(super) struct SymbolicCalldata {
5    bytes: SymBytes,
6    inputs: Vec<SymbolicInput>,
7    constraints: Vec<SymBoolExpr>,
8    /// Symbolic length of the calldata, at most `bytes.len()`, when it is not fixed.
9    size: Option<SymExpr>,
10}
11
12impl SymbolicCalldata {
13    pub(super) fn variants(
14        function: &Function,
15        config: &SymbolicConfig,
16        cx: &mut SymCx,
17    ) -> Result<Vec<Self>, SymbolicError> {
18        Self::variants_with_prefix(function, config, cx, "calldata")
19    }
20
21    pub(super) fn selector_only(
22        cx: &mut SymCx,
23        function: &Function,
24    ) -> Result<Self, SymbolicError> {
25        if !function.inputs.is_empty() {
26            return Err(SymbolicError::UnsupportedAbi(format!(
27                "symbolic invariant `{}` must take no parameters",
28                function.name
29            )));
30        }
31        Ok(Self {
32            bytes: SymBytes::concrete(cx, function.selector().to_vec()),
33            inputs: Vec::new(),
34            constraints: Vec::new(),
35            size: None,
36        })
37    }
38
39    /// Builds `len` bytes of unconstrained raw calldata that is not tied to any ABI.
40    pub(super) fn raw(cx: &mut SymCx, len: usize, prefix: &str) -> Self {
41        let words = (0..len.div_ceil(32))
42            .map(|idx| {
43                let word = SymExpr::var(cx, &format!("{prefix}_raw{len}_{idx}"));
44                SymBytes::word(cx, word)
45            })
46            .collect::<Vec<_>>();
47        let bytes = SymBytes::concat(cx, words);
48        let bytes = bytes.slice_concrete(cx, 0, len);
49        Self { bytes, inputs: Vec::new(), constraints: Vec::new(), size: None }
50    }
51
52    /// Builds unconstrained raw calldata of a symbolic length of at most `max` bytes, whose
53    /// bytes past its end read as zero.
54    pub(super) fn symbolic_size(cx: &mut SymCx, max: usize, prefix: &str) -> Self {
55        let Self { bytes, .. } = Self::raw(cx, max, prefix);
56        let size = SymExpr::var(cx, &format!("{prefix}_size"));
57        let fits = SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ule, &size, U256::from(max));
58        let bytes = SymBytes::sized(cx, bytes, size.clone(), max);
59        Self { bytes, inputs: Vec::new(), constraints: vec![fits], size: Some(size) }
60    }
61
62    pub(super) fn variants_with_prefix(
63        function: &Function,
64        config: &SymbolicConfig,
65        cx: &mut SymCx,
66        prefix: &str,
67    ) -> Result<Vec<Self>, SymbolicError> {
68        let variant_limit = calldata_variant_limit(config);
69        let mut builder = SymbolicAbiBuilder { config, cx };
70        let mut variants = vec![(SymbolicAbiState::default(), Vec::new())];
71        for (idx, input) in function.inputs.iter().enumerate() {
72            let ty = input.selector_type();
73            let mut next_variants = Vec::new();
74            for (state, inputs) in variants {
75                for (state, input) in SymbolicInput::variants(
76                    &mut builder,
77                    state,
78                    prefix,
79                    idx,
80                    Some(input.name.as_str()),
81                    ty.as_ref(),
82                )? {
83                    let mut inputs = inputs.clone();
84                    inputs.push(input);
85                    push_variant(&mut next_variants, (state, inputs), variant_limit)?;
86                }
87            }
88            variants = next_variants;
89        }
90
91        validate_positional_dynamic_lengths(
92            config,
93            variants.iter().map(|(state, _)| state.positional_dynamic_index).max().unwrap_or(0),
94        )?;
95
96        // Explore equal-address cases as variants sharing a representative account.
97        let mut partitioned = Vec::new();
98        for (state, inputs) in variants {
99            let address_indices = inputs
100                .iter()
101                .enumerate()
102                .filter_map(|(idx, input)| match input.value {
103                    SymbolicAbiValue::Address { .. } => Some(idx),
104                    _ => None,
105                })
106                .collect::<Vec<_>>();
107            for partition in set_partitions(address_indices.len(), variant_limit)? {
108                let mut state = state.clone();
109                let mut inputs = inputs.clone();
110                let mut representatives = Vec::with_capacity(partition.len());
111                for block in partition {
112                    let representative = match &inputs[address_indices[block[0]]].value {
113                        SymbolicAbiValue::Address { word } => word.clone(),
114                        _ => unreachable!("address index must refer to an address input"),
115                    };
116                    for member in block {
117                        let replaced = match &mut inputs[address_indices[member]].value {
118                            SymbolicAbiValue::Address { word } => {
119                                let replaced = word.clone();
120                                *word = representative.clone();
121                                replaced
122                            }
123                            _ => unreachable!("address index must refer to an address input"),
124                        };
125                        if replaced != representative {
126                            for constraint in &mut state.constraints {
127                                *constraint = constraint.fold_exprs(builder.cx, &mut |_, expr| {
128                                    if expr == replaced { representative.clone() } else { expr }
129                                });
130                            }
131                        }
132                    }
133                    representatives.push(representative);
134                }
135                for (idx, representative) in representatives.iter().enumerate() {
136                    for other in &representatives[idx + 1..] {
137                        let eq = SymBoolExpr::eq(builder.cx, representative.clone(), other.clone());
138                        state.constraints.push(eq.not(builder.cx));
139                    }
140                }
141                push_variant(&mut partitioned, (state, inputs), variant_limit)?;
142            }
143        }
144
145        let mut out = Vec::with_capacity(partitioned.len());
146        for (state, inputs) in partitioned {
147            let selector = SymBytes::concrete(builder.cx, function.selector().to_vec());
148            let encoded = builder.encode_sequence(inputs.iter().map(|input| &input.value));
149            let bytes = SymBytes::concat(builder.cx, [selector, encoded]);
150            if bytes.len() > config.max_calldata_bytes as usize {
151                return Err(SymbolicError::Unsupported(
152                    "symbolic calldata size exceeds configured max",
153                ));
154            }
155
156            out.push(Self { bytes, inputs, constraints: state.constraints, size: None });
157        }
158        Ok(out)
159    }
160
161    /// Builds the calldata shapes of a contract ABI, as Halmos `createCalldata` does: empty
162    /// calldata for `receive` and `fallback`, a selector outside the ABI with arbitrary bytes for
163    /// `fallback`, and each function with symbolic arguments. View and pure functions are left
164    /// out unless `include_view` is set.
165    pub(super) fn contract_variants(
166        abi: &JsonAbi,
167        include_view: bool,
168        config: &SymbolicConfig,
169        cx: &mut SymCx,
170        prefix: &str,
171    ) -> Result<Vec<Self>, SymbolicError> {
172        let max_len = config.max_calldata_bytes as usize;
173        if max_len < 4 {
174            return Err(SymbolicError::Unsupported(
175                "symbolic calldata size exceeds configured max",
176            ));
177        }
178        let empty = Self {
179            bytes: SymBytes::empty(cx),
180            inputs: Vec::new(),
181            constraints: Vec::new(),
182            size: None,
183        };
184
185        let mut builder = SymbolicAbiBuilder { config, cx };
186        let mut state = SymbolicAbiState::default();
187        let bytes = (0..CREATE_CALLDATA_FALLBACK_LEN.min(max_len))
188            .map(|idx| builder.fresh_byte(&mut state, &format!("{prefix}_fallback_{idx}"), false))
189            .collect();
190        let bytes = SymBytes::exprs(cx, bytes);
191        let selector = bytes.right_aligned_word(cx, 0, 4);
192        for function in abi.functions() {
193            let selector = SymBoolExpr::eq_word_const(
194                cx,
195                &selector,
196                U256::from_be_slice(function.selector().as_slice()),
197            );
198            state.constraints.push(selector.not(cx));
199        }
200        let fallback =
201            Self { bytes, inputs: Vec::new(), constraints: state.constraints, size: None };
202
203        let mut variants = vec![empty, fallback];
204        for (idx, function) in abi.functions().enumerate() {
205            if include_view
206                || !matches!(
207                    function.state_mutability,
208                    StateMutability::Pure | StateMutability::View
209                )
210            {
211                variants.extend(Self::variants_with_prefix(
212                    function,
213                    config,
214                    cx,
215                    &format!("{prefix}_{idx}"),
216                )?);
217            }
218        }
219        Ok(variants)
220    }
221
222    pub(super) fn call_data(&self, cx: &mut SymCx) -> SymCalldata {
223        match &self.size {
224            Some(size) => SymCalldata::with_size_word(self.bytes.clone(), size.clone()),
225            None => SymCalldata::from_bytes(cx, self.bytes.clone()),
226        }
227    }
228
229    /// Returns this calldata ABI-encoded as a single `bytes` value.
230    pub(super) fn abi_encoded_bytes(&self, cx: &mut SymCx) -> SymBytes {
231        let value = SymbolicAbiValue::Bytes {
232            len: SymExpr::constant(cx, U256::from(self.bytes.len())),
233            bytes: self.bytes.clone(),
234        };
235        encode_sequence(cx, [&value])
236    }
237
238    /// Returns symbolic calldata constraints.
239    pub(super) fn constraints(&self) -> &[SymBoolExpr] {
240        &self.constraints
241    }
242
243    /// Consumes this symbolic calldata into its constraints.
244    pub(super) fn into_constraints(self) -> Vec<SymBoolExpr> {
245        self.constraints
246    }
247
248    pub(super) fn model_to_args(
249        &self,
250        cx: &mut SymCx,
251        model: &(impl SymbolicModelLookup + ?Sized),
252    ) -> Result<Vec<DynSolValue>, SymbolicError> {
253        self.inputs.iter().map(|input| input.value.model_value(cx, model)).collect()
254    }
255
256    /// Evaluates the full calldata bytes under a solver model.
257    pub(super) fn model_to_bytes(
258        &self,
259        cx: &mut SymCx,
260        model: &(impl SymbolicModelLookup + ?Sized),
261    ) -> Result<Vec<u8>, SymbolicError> {
262        let mut bytes = self.bytes.eval_model(cx, model)?;
263        if let Some(size) = &self.size {
264            let size = size.eval_model(model)?;
265            bytes.truncate(usize::try_from(size).unwrap_or(usize::MAX));
266        }
267        Ok(bytes)
268    }
269
270    pub(super) fn seed_model(
271        &self,
272        cx: &mut SymCx,
273        seed: &SymbolicConcreteInput,
274    ) -> Option<SymbolicModel> {
275        if seed.args.len() != self.inputs.len() {
276            return None;
277        }
278
279        let mut model = SymbolicModel::default();
280        for (input, arg) in self.inputs.iter().zip(&seed.args) {
281            if !input.value.seed_model_value(cx, &mut model, arg) {
282                return None;
283            }
284        }
285
286        for constraint in &self.constraints {
287            if constraint.eval_model_if_complete(&model).ok().flatten() != Some(true) {
288                return None;
289            }
290        }
291
292        let calldata = self.bytes.eval_model(cx, &model).ok()?;
293        (calldata.as_slice() == seed.calldata.as_ref()).then_some(model)
294    }
295}
296
297#[derive(Clone, Debug)]
298pub(super) struct SymbolicInput {
299    value: SymbolicAbiValue,
300}
301
302impl SymbolicInput {
303    pub(super) fn variants<'a, 'cx>(
304        builder: &mut SymbolicAbiBuilder<'a, 'cx>,
305        state: SymbolicAbiState,
306        prefix: &str,
307        idx: usize,
308        abi_name: Option<&str>,
309        ty: &str,
310    ) -> Result<Vec<(SymbolicAbiState, Self)>, SymbolicError> {
311        let ty =
312            DynSolType::parse(ty).map_err(|_| SymbolicError::UnsupportedAbi(ty.to_string()))?;
313        let name = format!("{prefix}_{idx}");
314        let aliases =
315            abi_name.filter(|name| !name.is_empty()).map(str::to_string).into_iter().collect();
316        builder.value_variants(state, name, aliases, &ty).map(|variants| {
317            variants.into_iter().map(|(state, value)| (state, Self { value })).collect()
318        })
319    }
320}
321
322#[derive(Clone, Debug, Default)]
323pub(super) struct SymbolicAbiState {
324    constraints: Vec<SymBoolExpr>,
325    positional_dynamic_index: usize,
326}
327
328#[derive(Debug)]
329pub(super) struct SymbolicAbiBuilder<'a, 'cx> {
330    config: &'a SymbolicConfig,
331    cx: &'cx mut SymCx,
332}
333
334impl<'a, 'cx> SymbolicAbiBuilder<'a, 'cx> {
335    pub(super) fn value(
336        &mut self,
337        state: &mut SymbolicAbiState,
338        name: String,
339        ty: &DynSolType,
340    ) -> Result<SymbolicAbiValue, SymbolicError> {
341        Ok(match ty {
342            DynSolType::Bool => {
343                let word = self.fresh_word(&name);
344                state.constraints.push(SymBoolExpr::cmp_word_const(
345                    self.cx,
346                    SymCmpOp::Ult,
347                    &word,
348                    U256::from(2),
349                ));
350                SymbolicAbiValue::Bool { word }
351            }
352            DynSolType::Uint(bits) => {
353                let word = self.fresh_word(&name);
354                self.constrain_uint(state, &word, *bits);
355                SymbolicAbiValue::Uint { bits: *bits, word }
356            }
357            DynSolType::Int(bits) => {
358                let word = self.fresh_word(&name);
359                self.constrain_int(state, &word, *bits);
360                SymbolicAbiValue::Int { bits: *bits, word }
361            }
362            DynSolType::FixedBytes(size) => {
363                let bytes = (0..*size)
364                    .map(|idx| self.fresh_byte(state, &format!("{name}_{idx}"), false))
365                    .collect();
366                SymbolicAbiValue::FixedBytes { bytes: SymBytes::exprs(self.cx, bytes), size: *size }
367            }
368            DynSolType::Address => {
369                let word = self.fresh_word(&name);
370                self.constrain_uint(state, &word, 160);
371                SymbolicAbiValue::Address { word }
372            }
373            _ => return Err(SymbolicError::UnsupportedAbi(ty.to_string())),
374        })
375    }
376
377    pub(super) fn value_variants(
378        &mut self,
379        state: SymbolicAbiState,
380        name: String,
381        aliases: Vec<String>,
382        ty: &DynSolType,
383    ) -> Result<Vec<(SymbolicAbiState, SymbolicAbiValue)>, SymbolicError> {
384        Ok(match ty {
385            DynSolType::Bytes => {
386                let mut state = state;
387                let lengths = self.next_dynamic_length_options(
388                    &mut state,
389                    &name,
390                    &aliases,
391                    DynamicKind::Bytes,
392                )?;
393                let limit = calldata_variant_limit(self.config);
394                let mut variants = Vec::new();
395                for len in lengths {
396                    let mut state = state.clone();
397                    let bytes = (0..len as usize)
398                        .map(|idx| self.fresh_byte(&mut state, &format!("{name}_{idx}"), false))
399                        .collect();
400                    let value = SymbolicAbiValue::Bytes {
401                        len: SymExpr::constant(self.cx, U256::from(len)),
402                        bytes: SymBytes::exprs(self.cx, bytes),
403                    };
404                    push_variant(&mut variants, (state, value), limit)?;
405                }
406                variants
407            }
408            DynSolType::String => {
409                let mut state = state;
410                let lengths = self.next_dynamic_length_options(
411                    &mut state,
412                    &name,
413                    &aliases,
414                    DynamicKind::String,
415                )?;
416                let limit = calldata_variant_limit(self.config);
417                let mut variants = Vec::new();
418                for len in lengths {
419                    let mut state = state.clone();
420                    let bytes = (0..len as usize)
421                        .map(|idx| self.fresh_byte(&mut state, &format!("{name}_{idx}"), true))
422                        .collect();
423                    let value = SymbolicAbiValue::String { bytes: SymBytes::exprs(self.cx, bytes) };
424                    push_variant(&mut variants, (state, value), limit)?;
425                }
426                variants
427            }
428            DynSolType::Array(inner) => {
429                let mut state = state;
430                let lengths = self.next_dynamic_length_options(
431                    &mut state,
432                    &name,
433                    &aliases,
434                    DynamicKind::Array,
435                )?;
436                let limit = calldata_variant_limit(self.config);
437                let mut variants = Vec::new();
438                for len in lengths {
439                    for (state, elements) in self.array_elements_variants(
440                        state.clone(),
441                        &name,
442                        &aliases,
443                        inner,
444                        len as usize,
445                    )? {
446                        push_variant(
447                            &mut variants,
448                            (state, SymbolicAbiValue::Array { elements }),
449                            limit,
450                        )?;
451                    }
452                }
453                variants
454            }
455            DynSolType::FixedArray(inner, len) => self
456                .array_elements_variants(state, &name, &aliases, inner, *len)
457                .map(|variants| {
458                    variants
459                        .into_iter()
460                        .map(|(state, elements)| (state, SymbolicAbiValue::FixedArray { elements }))
461                        .collect()
462                })?,
463            DynSolType::Tuple(types) => self
464                .tuple_elements_variants(state, &name, &aliases, types)?
465                .into_iter()
466                .map(|(state, elements)| (state, SymbolicAbiValue::Tuple { elements }))
467                .collect(),
468            DynSolType::CustomStruct { tuple, .. } => self
469                .tuple_elements_variants(state, &name, &aliases, tuple)?
470                .into_iter()
471                .map(|(state, elements)| (state, SymbolicAbiValue::Tuple { elements }))
472                .collect(),
473            _ => {
474                let mut state = state;
475                let value = self.value(&mut state, name, ty)?;
476                vec![(state, value)]
477            }
478        })
479    }
480
481    pub(super) fn array_elements_variants(
482        &mut self,
483        state: SymbolicAbiState,
484        name: &str,
485        aliases: &[String],
486        inner: &DynSolType,
487        len: usize,
488    ) -> Result<Vec<(SymbolicAbiState, Vec<SymbolicAbiValue>)>, SymbolicError> {
489        let limit = calldata_variant_limit(self.config);
490        let mut variants = vec![(state, Vec::with_capacity(len))];
491        for idx in 0..len {
492            let mut next_variants = Vec::new();
493            for (state, elements) in variants {
494                for (state, value) in self.value_variants(
495                    state,
496                    format!("{name}_{idx}"),
497                    child_aliases(aliases, idx),
498                    inner,
499                )? {
500                    let mut elements = elements.clone();
501                    elements.push(value);
502                    push_variant(&mut next_variants, (state, elements), limit)?;
503                }
504            }
505            variants = next_variants;
506        }
507        Ok(variants)
508    }
509
510    pub(super) fn tuple_elements_variants(
511        &mut self,
512        state: SymbolicAbiState,
513        name: &str,
514        aliases: &[String],
515        types: &[DynSolType],
516    ) -> Result<Vec<(SymbolicAbiState, Vec<SymbolicAbiValue>)>, SymbolicError> {
517        let limit = calldata_variant_limit(self.config);
518        let mut variants = vec![(state, Vec::with_capacity(types.len()))];
519        for (idx, ty) in types.iter().enumerate() {
520            let mut next_variants = Vec::new();
521            for (state, elements) in variants {
522                for (state, value) in self.value_variants(
523                    state,
524                    format!("{name}_{idx}"),
525                    child_aliases(aliases, idx),
526                    ty,
527                )? {
528                    let mut elements = elements.clone();
529                    elements.push(value);
530                    push_variant(&mut next_variants, (state, elements), limit)?;
531                }
532            }
533            variants = next_variants;
534        }
535        Ok(variants)
536    }
537
538    pub(super) fn fresh_word(&mut self, name: &str) -> SymExpr {
539        let symbol = self.cx.intern(name);
540        self.cx.mark_replayable_input(symbol);
541        SymExpr::get_var(self.cx, symbol)
542    }
543
544    pub(super) fn fresh_byte(
545        &mut self,
546        state: &mut SymbolicAbiState,
547        name: &str,
548        printable: bool,
549    ) -> SymExpr {
550        let word = self.fresh_word(name);
551        state.constraints.push(SymBoolExpr::cmp_word_const(
552            self.cx,
553            SymCmpOp::Ult,
554            &word,
555            U256::from(256),
556        ));
557        if printable {
558            state.constraints.push(SymBoolExpr::cmp_word_const(
559                self.cx,
560                SymCmpOp::Uge,
561                &word,
562                U256::from(0x20),
563            ));
564            state.constraints.push(SymBoolExpr::cmp_word_const(
565                self.cx,
566                SymCmpOp::Ule,
567                &word,
568                U256::from(0x7e),
569            ));
570        }
571        word
572    }
573
574    pub(super) fn next_dynamic_length_options(
575        &self,
576        state: &mut SymbolicAbiState,
577        name: &str,
578        aliases: &[String],
579        kind: DynamicKind,
580    ) -> Result<Vec<u32>, SymbolicError> {
581        let named_lengths = std::iter::once(name)
582            .chain(aliases.iter().map(String::as_str))
583            .find_map(|name| self.config.dynamic_lengths.get(name));
584
585        let lengths = if let Some(lengths) = named_lengths {
586            lengths.clone()
587        } else if let Some(lengths) = kind.default_lengths(self.config) {
588            lengths.to_vec()
589        } else if let Some(len) =
590            self.config.array_lengths.get(state.positional_dynamic_index).copied()
591        {
592            state.positional_dynamic_index += 1;
593            vec![len]
594        } else {
595            vec![self.config.default_dynamic_length]
596        };
597
598        if lengths.is_empty() {
599            return Err(SymbolicError::UnsupportedAbi(
600                "symbolic dynamic length set must not be empty".to_string(),
601            ));
602        }
603        for len in &lengths {
604            if *len > self.config.max_dynamic_length {
605                return Err(SymbolicError::UnsupportedAbi(format!(
606                    "symbolic {} length {len} exceeds max_dynamic_length {}",
607                    kind.name(),
608                    self.config.max_dynamic_length
609                )));
610            }
611        }
612        Ok(lengths)
613    }
614
615    pub(super) fn constrain_uint(
616        &mut self,
617        state: &mut SymbolicAbiState,
618        word: &SymExpr,
619        bits: usize,
620    ) {
621        if bits < 256 {
622            state.constraints.push(SymBoolExpr::cmp_word_const(
623                self.cx,
624                SymCmpOp::Ult,
625                word,
626                U256::ONE << bits,
627            ));
628        }
629    }
630
631    pub(super) fn constrain_int(
632        &mut self,
633        state: &mut SymbolicAbiState,
634        word: &SymExpr,
635        bits: usize,
636    ) {
637        if bits < 256 {
638            let byte_index = U256::from(bits / 8 - 1);
639            let signextended = signextend_word(self.cx, byte_index, word.clone());
640            state.constraints.push(SymBoolExpr::eq(self.cx, word.clone(), signextended));
641        }
642    }
643
644    pub(super) fn encode_sequence<'v>(
645        &mut self,
646        values: impl IntoIterator<Item = &'v SymbolicAbiValue>,
647    ) -> SymBytes {
648        encode_sequence(self.cx, values)
649    }
650}
651
652/// Validates that positional ABI length config can be consumed by at least one expanded variant.
653fn validate_positional_dynamic_lengths(
654    config: &SymbolicConfig,
655    max_positional_dynamic_index: usize,
656) -> Result<(), SymbolicError> {
657    if config.array_lengths.len() > max_positional_dynamic_index {
658        return Err(SymbolicError::UnsupportedAbi(format!(
659            "symbolic.array_lengths has {} entries but ABI used at most {} positional dynamic leaves",
660            config.array_lengths.len(),
661            max_positional_dynamic_index
662        )));
663    }
664    Ok(())
665}
666
667/// Enumerates address partitions within the variant budget, all-distinct first.
668fn set_partitions(len: usize, limit: usize) -> Result<Vec<Vec<Vec<usize>>>, SymbolicError> {
669    let mut out = Vec::new();
670    let mut blocks = Vec::<Vec<usize>>::new();
671    fn go(
672        idx: usize,
673        len: usize,
674        blocks: &mut Vec<Vec<usize>>,
675        out: &mut Vec<Vec<Vec<usize>>>,
676        limit: usize,
677    ) -> Result<(), SymbolicError> {
678        if idx == len {
679            return push_variant(out, blocks.clone(), limit);
680        }
681        blocks.push(vec![idx]);
682        go(idx + 1, len, blocks, out, limit)?;
683        blocks.pop();
684        for block in 0..blocks.len() {
685            blocks[block].push(idx);
686            go(idx + 1, len, blocks, out, limit)?;
687            blocks[block].pop();
688        }
689        Ok(())
690    }
691    go(0, len, &mut blocks, &mut out, limit)?;
692    Ok(out)
693}
694
695/// Returns the maximum number of calldata variants allowed during ABI expansion.
696fn calldata_variant_limit(config: &SymbolicConfig) -> usize {
697    config.path_width().max(1) as usize
698}
699
700/// Adds one expansion variant while enforcing the configured symbolic path-width budget.
701fn push_variant<T>(variants: &mut Vec<T>, variant: T, limit: usize) -> Result<(), SymbolicError> {
702    if variants.len() >= limit {
703        return Err(SymbolicError::CalldataVariantLimit(limit));
704    }
705    variants.push(variant);
706    Ok(())
707}
708
709#[derive(Clone, Copy)]
710pub(super) enum DynamicKind {
711    Array,
712    Bytes,
713    String,
714}
715
716impl DynamicKind {
717    pub(super) const fn name(self) -> &'static str {
718        match self {
719            Self::Array => "array",
720            Self::Bytes => "bytes",
721            Self::String => "string",
722        }
723    }
724
725    pub(super) fn default_lengths(self, config: &SymbolicConfig) -> Option<&[u32]> {
726        match self {
727            Self::Array if !config.default_array_lengths.is_empty() => {
728                Some(&config.default_array_lengths)
729            }
730            Self::Bytes | Self::String if !config.default_bytes_lengths.is_empty() => {
731                Some(&config.default_bytes_lengths)
732            }
733            _ => None,
734        }
735    }
736}
737
738pub(super) fn child_aliases(aliases: &[String], idx: usize) -> Vec<String> {
739    aliases.iter().map(|alias| format!("{alias}_{idx}")).collect()
740}
741
742#[derive(Clone, Debug)]
743pub(super) enum SymbolicAbiValue {
744    Bool { word: SymExpr },
745    Uint { bits: usize, word: SymExpr },
746    Int { bits: usize, word: SymExpr },
747    FixedBytes { bytes: SymBytes, size: usize },
748    Address { word: SymExpr },
749    Bytes { len: SymExpr, bytes: SymBytes },
750    String { bytes: SymBytes },
751    Array { elements: Vec<Self> },
752    FixedArray { elements: Vec<Self> },
753    Tuple { elements: Vec<Self> },
754}
755
756impl SymbolicAbiValue {
757    /// Returns whether `is_dynamic` holds.
758    pub(super) fn is_dynamic(&self) -> bool {
759        match self {
760            Self::Bool { .. }
761            | Self::Uint { .. }
762            | Self::Int { .. }
763            | Self::FixedBytes { .. }
764            | Self::Address { .. } => false,
765            Self::Bytes { .. } | Self::String { .. } | Self::Array { .. } => true,
766            Self::FixedArray { elements } | Self::Tuple { elements } => {
767                elements.iter().any(Self::is_dynamic)
768            }
769        }
770    }
771
772    pub(super) fn head_size(&self) -> usize {
773        if self.is_dynamic() {
774            32
775        } else {
776            match self {
777                Self::Bool { .. }
778                | Self::Uint { .. }
779                | Self::Int { .. }
780                | Self::FixedBytes { .. }
781                | Self::Address { .. } => 32,
782                Self::FixedArray { elements } | Self::Tuple { elements } => {
783                    elements.iter().map(Self::head_size).sum()
784                }
785                Self::Bytes { .. } | Self::String { .. } | Self::Array { .. } => 32,
786            }
787        }
788    }
789
790    pub(super) fn model_value(
791        &self,
792        cx: &mut SymCx,
793        model: &(impl SymbolicModelLookup + ?Sized),
794    ) -> Result<DynSolValue, SymbolicError> {
795        Ok(match self {
796            Self::Bool { word } => DynSolValue::Bool(!word.eval_model(model)?.is_zero()),
797            Self::Uint { bits, word } => {
798                DynSolValue::Uint(mask_bits(word.eval_model(model)?, *bits), *bits)
799            }
800            Self::Int { bits, word } => {
801                DynSolValue::Int(I256::from_raw(word.eval_model(model)?), *bits)
802            }
803            Self::FixedBytes { bytes, size } => {
804                let mut word = [0u8; 32];
805                for (idx, out) in word.iter_mut().enumerate().take(bytes.len()) {
806                    *out = bytes.byte(cx, idx).eval_model(model)?.to::<u8>();
807                }
808                DynSolValue::FixedBytes(B256::from(word), *size)
809            }
810            Self::Address { word } => {
811                DynSolValue::Address(word_to_address(word.eval_model(model)?))
812            }
813            Self::Bytes { len, bytes } => {
814                let len = len.eval_model(model)?;
815                let len = usize::try_from(len)
816                    .ok()
817                    .filter(|len| *len <= bytes.len())
818                    .ok_or_else(|| SymbolicError::Solver("invalid symbolic bytes length".into()))?;
819                let mut bytes = bytes.eval_model(cx, model)?;
820                bytes.truncate(len);
821                DynSolValue::Bytes(bytes)
822            }
823            Self::String { bytes } => {
824                let bytes = bytes.eval_model(cx, model)?;
825                let value = String::from_utf8(bytes).map_err(|err| {
826                    SymbolicError::Solver(format!("invalid symbolic string model: {err}"))
827                })?;
828                DynSolValue::String(value)
829            }
830            Self::Array { elements } => DynSolValue::Array(
831                elements
832                    .iter()
833                    .map(|value| value.model_value(cx, model))
834                    .collect::<Result<Vec<_>, _>>()?,
835            ),
836            Self::FixedArray { elements } => DynSolValue::FixedArray(
837                elements
838                    .iter()
839                    .map(|value| value.model_value(cx, model))
840                    .collect::<Result<Vec<_>, _>>()?,
841            ),
842            Self::Tuple { elements } => DynSolValue::Tuple(
843                elements
844                    .iter()
845                    .map(|value| value.model_value(cx, model))
846                    .collect::<Result<Vec<_>, _>>()?,
847            ),
848        })
849    }
850
851    pub(super) fn seed_model_value(
852        &self,
853        cx: &mut SymCx,
854        model: &mut SymbolicModel,
855        value: &DynSolValue,
856    ) -> bool {
857        match (self, value) {
858            (Self::Bool { word }, DynSolValue::Bool(value)) => {
859                word.assign_model_value(model, U256::from(*value as u8))
860            }
861            (Self::Uint { bits, word }, DynSolValue::Uint(value, value_bits))
862                if bits == value_bits =>
863            {
864                word.assign_model_value(model, *value)
865            }
866            (Self::Int { bits, word }, DynSolValue::Int(value, value_bits))
867                if bits == value_bits =>
868            {
869                word.assign_model_value(model, value.into_raw())
870            }
871            (Self::FixedBytes { bytes, size }, DynSolValue::FixedBytes(value, value_size))
872                if size == value_size =>
873            {
874                seed_model_bytes(cx, model, bytes, &value.as_slice()[..*size])
875            }
876            (Self::Address { word }, DynSolValue::Address(value)) => {
877                word.assign_model_value(model, address_word(*value))
878            }
879            (Self::Bytes { len, bytes }, DynSolValue::Bytes(value)) => {
880                len.assign_model_value(model, U256::from(value.len()))
881                    && seed_model_bytes(cx, model, bytes, value)
882            }
883            (Self::String { bytes }, DynSolValue::String(value)) => {
884                seed_model_bytes(cx, model, bytes, value.as_bytes())
885            }
886            (Self::Array { elements }, DynSolValue::Array(values))
887            | (Self::FixedArray { elements }, DynSolValue::FixedArray(values))
888            | (Self::Tuple { elements }, DynSolValue::Tuple(values)) => {
889                seed_model_elements(cx, model, elements, values)
890            }
891            (Self::Tuple { elements }, DynSolValue::CustomStruct { tuple, .. }) => {
892                seed_model_elements(cx, model, elements, tuple)
893            }
894            _ => false,
895        }
896    }
897}
898
899fn seed_model_elements(
900    cx: &mut SymCx,
901    model: &mut SymbolicModel,
902    elements: &[SymbolicAbiValue],
903    values: &[DynSolValue],
904) -> bool {
905    elements.len() == values.len()
906        && elements
907            .iter()
908            .zip(values)
909            .all(|(element, value)| element.seed_model_value(cx, model, value))
910}
911
912fn seed_model_bytes(
913    cx: &mut SymCx,
914    model: &mut SymbolicModel,
915    bytes: &SymBytes,
916    value: &[u8],
917) -> bool {
918    bytes.len() == value.len()
919        && value
920            .iter()
921            .enumerate()
922            .all(|(idx, byte)| bytes.byte(cx, idx).assign_model_value(model, U256::from(*byte)))
923}
924
925pub(super) fn encode_sequence<'a>(
926    cx: &mut SymCx,
927    values: impl IntoIterator<Item = &'a SymbolicAbiValue>,
928) -> SymBytes {
929    let values = values.into_iter().collect::<Vec<_>>();
930    let head_size = values.iter().map(|value| value.head_size()).sum::<usize>();
931    let mut head = Vec::with_capacity(values.len());
932    let mut tail = Vec::new();
933    let mut tail_len = 0usize;
934
935    for value in values {
936        if value.is_dynamic() {
937            let offset = SymExpr::constant(cx, U256::from(head_size + tail_len));
938            head.push(offset.into_bytes(cx));
939            let body = encode_dynamic_body(cx, value);
940            tail_len += body.len();
941            tail.push(body);
942        } else {
943            head.push(encode_static(cx, value));
944        }
945    }
946
947    SymBytes::concat(cx, head.into_iter().chain(tail))
948}
949
950fn encode_static(cx: &mut SymCx, value: &SymbolicAbiValue) -> SymBytes {
951    match value {
952        SymbolicAbiValue::Bool { word }
953        | SymbolicAbiValue::Uint { word, .. }
954        | SymbolicAbiValue::Int { word, .. }
955        | SymbolicAbiValue::Address { word } => word.clone().into_bytes(cx),
956        SymbolicAbiValue::FixedBytes { bytes, .. } => {
957            let padding = SymBytes::concrete(cx, vec![0; 32usize.saturating_sub(bytes.len())]);
958            SymBytes::concat(cx, [bytes.clone(), padding])
959        }
960        SymbolicAbiValue::FixedArray { elements } | SymbolicAbiValue::Tuple { elements } => {
961            encode_sequence(cx, elements.iter())
962        }
963        SymbolicAbiValue::Bytes { .. }
964        | SymbolicAbiValue::String { .. }
965        | SymbolicAbiValue::Array { .. } => unreachable!("dynamic ABI value encoded as static"),
966    }
967}
968
969fn encode_dynamic_body(cx: &mut SymCx, value: &SymbolicAbiValue) -> SymBytes {
970    match value {
971        SymbolicAbiValue::Bytes { len, bytes } => {
972            encode_packed_bytes_with_len(cx, len.clone(), bytes)
973        }
974        SymbolicAbiValue::String { bytes } => {
975            let len = SymExpr::constant(cx, U256::from(bytes.len()));
976            encode_packed_bytes_with_len(cx, len, bytes)
977        }
978        SymbolicAbiValue::Array { elements } => {
979            let len = SymExpr::constant(cx, U256::from(elements.len()));
980            let len = len.into_bytes(cx);
981            let elements = encode_sequence(cx, elements.iter());
982            SymBytes::concat(cx, [len, elements])
983        }
984        SymbolicAbiValue::FixedArray { elements } | SymbolicAbiValue::Tuple { elements } => {
985            encode_sequence(cx, elements.iter())
986        }
987        SymbolicAbiValue::Bool { .. }
988        | SymbolicAbiValue::Uint { .. }
989        | SymbolicAbiValue::Int { .. }
990        | SymbolicAbiValue::FixedBytes { .. }
991        | SymbolicAbiValue::Address { .. } => unreachable!("static ABI value encoded as dynamic"),
992    }
993}
994
995pub(super) fn encode_packed_bytes_with_len(
996    cx: &mut SymCx,
997    len: SymExpr,
998    bytes: &SymBytes,
999) -> SymBytes {
1000    let padded_len = bytes.len().next_multiple_of(32);
1001    let len = len.into_bytes(cx);
1002    let padding = SymBytes::concrete(cx, vec![0; padded_len - bytes.len()]);
1003    SymBytes::concat(cx, [len, bytes.clone(), padding])
1004}