Skip to main content

foundry_evm_symbolic/runtime/
precompiles.rs

1use super::*;
2use evm2::interpreter::gas::CALL_STIPEND;
3
4/// Order of the secp256k1 curve, the exclusive bound of a valid signature scalar.
5const SECP256K1_ORDER: U256 =
6    U256::from_be_bytes(hex!("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"));
7
8pub(crate) fn precompile_number(address: Address) -> Option<u8> {
9    let bytes = address.as_slice();
10    if bytes[..PRECOMPILE_ADDRESS_LEADING_ZEROS].iter().any(|byte| *byte != 0) {
11        return None;
12    }
13    match bytes[PRECOMPILE_ADDRESS_LEADING_ZEROS] {
14        1..=10 => Some(bytes[PRECOMPILE_ADDRESS_LEADING_ZEROS]),
15        _ => None,
16    }
17}
18
19pub(crate) fn precompile_number_for_spec(address: Address, spec_id: SpecId) -> Option<u8> {
20    match precompile_number(address)? {
21        5..=8 if spec_id < SpecId::BYZANTIUM => None,
22        9 if spec_id < SpecId::ISTANBUL => None,
23        10 if spec_id < SpecId::CANCUN => None,
24        number => Some(number),
25    }
26}
27
28/// Returns the canonical precompiles active under `spec_id`.
29pub(crate) fn active_precompiles(spec_id: SpecId) -> Precompiles {
30    Precompiles::base(spec_id)
31}
32
33/// Returns whether `address` is a canonical precompile active under `spec_id`.
34pub(crate) fn is_precompile_for_spec(address: Address, spec_id: SpecId) -> bool {
35    active_precompiles(spec_id).as_map().contains(&address)
36}
37
38/// Returns the most gas a `gasleft()` call gives a precompile in a transaction with `gas_limit`
39/// gas: 63/64 of the gas left (EIP-150), plus the value transfer stipend when it sends value.
40pub(crate) fn precompile_call_gas(gas_limit: u64, sends_value: bool) -> u64 {
41    let forwarded = gas_limit - gas_limit / 64;
42    if sends_value { forwarded.saturating_add(CALL_STIPEND.into()) } else { forwarded }
43}
44
45/// Executes a canonical precompile on concrete input with at most `gas` gas.
46///
47/// Returns `None` when the precompile fails, including when it runs out of gas.
48pub(crate) fn execute_precompile(
49    cx: &mut SymCx,
50    address: Address,
51    input: &[u8],
52    spec_id: SpecId,
53    gas: u64,
54) -> Result<Option<SymReturnData>, SymbolicError> {
55    if !is_precompile_for_spec(address, spec_id) {
56        return Err(SymbolicError::Unsupported("unsupported precompile"));
57    }
58    // evm2's precompile table runs these through an EVM; select the same input-only
59    // implementations the base table registers for `spec_id`.
60    let run = match u16::from_be_bytes([address[18], address[19]]) {
61        0x01 => secp256k1::run,
62        0x02 => hash::run_sha256,
63        0x03 => hash::run_ripemd160,
64        0x04 => identity::run,
65        0x05 if spec_id.enables(SpecId::OSAKA) => modexp::run_osaka,
66        0x05 if spec_id.enables(SpecId::BERLIN) => modexp::run_berlin,
67        0x05 => modexp::run_byzantium,
68        0x06 if spec_id.enables(SpecId::ISTANBUL) => bn254::add::run_istanbul,
69        0x06 => bn254::add::run_byzantium,
70        0x07 if spec_id.enables(SpecId::ISTANBUL) => bn254::mul::run_istanbul,
71        0x07 => bn254::mul::run_byzantium,
72        0x08 if spec_id.enables(SpecId::ISTANBUL) => bn254::pair::run_istanbul,
73        0x08 => bn254::pair::run_byzantium,
74        0x09 => blake2::run,
75        0x0a => kzg_point_evaluation::run,
76        0x0b => bls12_381::g1_add::run,
77        0x0c => bls12_381::g1_msm::run,
78        0x0d => bls12_381::g2_add::run,
79        0x0e => bls12_381::g2_msm::run,
80        0x0f => bls12_381::pairing::run,
81        0x10 => bls12_381::map_fp_to_g1::run,
82        0x11 => bls12_381::map_fp2_to_g2::run,
83        0x100 => secp256r1::run_osaka,
84        _ => return Err(SymbolicError::Unsupported("unsupported precompile")),
85    };
86
87    match run(input, &mut GasTracker::new(gas)) {
88        Ok(output) => Ok(Some(SymReturnData::from_concrete_bytes(cx, output.bytes().to_vec()))),
89        Err(_) => Ok(None),
90    }
91}
92
93pub(crate) fn execute_symbolic_precompile(
94    cx: &mut SymCx,
95    address: Address,
96    input: SymBytes,
97    input_len: SymExpr,
98    spec_id: SpecId,
99    gas: u64,
100) -> Result<Option<SymReturnData>, SymbolicError> {
101    match precompile_number_for_spec(address, spec_id) {
102        Some(1) => {
103            // ECRECOVER ignores trailing bytes and pads short input with zeros.
104            let input = SymBytes::sized(cx, input, input_len, 128);
105            if let Ok(input) = input.concrete_bytes(cx, "symbolic ecrecover input") {
106                return execute_precompile(cx, address, &input, spec_id, gas);
107            }
108            let valid_v = ecrecover_signature_well_formed(cx, &input);
109            if valid_v.as_const() == Some(false) {
110                return Ok(Some(SymReturnData::empty(cx)));
111            }
112
113            let input = input.materialize(cx);
114            let input_len = SymExpr::constant(cx, U256::from(128));
115            let word = symbolic_hash_word_with_len(cx, "ecrecover", input, input_len);
116            // Recovery may fail even with a valid v. Use an otherwise discarded byte of the
117            // opaque word so this choice is independent of the low 160-bit recovered address.
118            let recovered = byte_word(cx, U256::ZERO, word.clone()).nonzero_bool(cx);
119            let recovered = SymBoolExpr::and(cx, vec![valid_v, recovered]);
120            let full_len = SymExpr::constant(cx, U256::from(32));
121            let empty_len = SymExpr::zero(cx);
122            let len = SymExpr::ite(cx, recovered, full_len, empty_len);
123            let mut bytes = vec![SymExpr::zero(cx); 12];
124            bytes.extend((12..32).map(|idx| byte_word(cx, U256::from(idx), word.clone())));
125            let bytes = SymBytes::exprs(cx, bytes);
126            Ok(Some(SymReturnData { len_word: len, bytes }))
127        }
128        Some(2) => {
129            let input = input.materialize(cx);
130            let word = symbolic_hash_word_with_len(cx, "sha256", input, input_len);
131            let bytes = word.into_byte_exprs(cx);
132            Ok(Some(SymReturnData::from_byte_exprs(cx, bytes)))
133        }
134        Some(3) => {
135            let input = input.materialize(cx);
136            let word = symbolic_hash_word_with_len(cx, "ripemd160", input, input_len);
137            let mut bytes = vec![SymExpr::zero(cx); 12];
138            bytes.extend((12..32).map(|idx| byte_word(cx, U256::from(idx), word.clone())));
139            Ok(Some(SymReturnData::from_byte_exprs(cx, bytes)))
140        }
141        Some(4) => Ok(Some(SymReturnData { len_word: input_len, bytes: input })),
142        Some(5) => symbolic_modexp_precompile(cx, &input, input_len, spec_id, gas),
143        // Constant BN254 input runs the precompile before this; symbolic input may be an invalid
144        // point, which the model cannot tell.
145        Some(6 | 7) => {
146            Err(SymbolicError::Unsupported("symbolic bn254 precompile validity not modeled"))
147        }
148        Some(8) => {
149            let input_len = input_len.as_usize_or("symbolic precompile input")?;
150            if input_len % 192 != 0 {
151                return Ok(None);
152            }
153            Err(SymbolicError::Unsupported("symbolic bn254 precompile validity not modeled"))
154        }
155        Some(9) => {
156            let input_len = input_len.as_usize_or("symbolic precompile input")?;
157            if input_len != 213 {
158                return Ok(None);
159            }
160            if input_len > input.len() {
161                return Err(SymbolicError::Unsupported("out-of-bounds symbolic precompile input"));
162            }
163            // BLAKE2f costs one gas per round, from the first four input bytes.
164            let (min_rounds, max_rounds) = symbolic_input_word_range(cx, &input, input_len, 0, 4);
165            match precompile_gas_fits(gas, min_rounds.saturating_to(), max_rounds.saturating_to()) {
166                Some(true) => {}
167                Some(false) => return Ok(None),
168                None => {
169                    return Err(SymbolicError::Unsupported("symbolic blake2f precompile gas"));
170                }
171            }
172            let flag = input.byte(cx, 212);
173            match flag.as_const() {
174                Some(flag) if flag.is_zero() || flag == U256::ONE => {}
175                Some(_) => return Ok(None),
176                None => {
177                    return Err(SymbolicError::Unsupported(
178                        "symbolic blake2f precompile final flag not modeled",
179                    ));
180                }
181            }
182            Ok(Some(symbolic_fixed_len_precompile_output(cx, "blake2f", &input, input_len, 64)))
183        }
184        Some(10) => Err(SymbolicError::Unsupported("KZG handled by execute_kzg_precompile_call")),
185        _ => {
186            let input_len = input_len.as_usize_or("symbolic precompile input")?;
187            if input_len > input.len() {
188                return Err(SymbolicError::Unsupported("out-of-bounds symbolic precompile input"));
189            }
190            let input = input
191                .slice_concrete(cx, 0, input_len)
192                .concrete_bytes(cx, "symbolic precompile input")?;
193            execute_precompile(cx, address, &input, spec_id, gas)
194        }
195    }
196}
197
198/// Returns whether a 128-byte ECRECOVER input is a well-formed signature: `v` is 27 or 28 and `r`
199/// and `s` are in `[1, n)`. The precompile returns no data otherwise.
200pub(crate) fn ecrecover_signature_well_formed(cx: &mut SymCx, input: &SymBytes) -> SymBoolExpr {
201    let v = input.word_at(cx, 32);
202    let v27 = SymBoolExpr::eq_word_const(cx, &v, U256::from(27));
203    let v28 = SymBoolExpr::eq_word_const(cx, &v, U256::from(28));
204    let mut valid = vec![SymBoolExpr::or(cx, vec![v27, v28])];
205    for offset in [64, 96] {
206        let scalar = input.word_at(cx, offset);
207        valid.push(SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &scalar, SECP256K1_ORDER));
208        valid.push(scalar.nonzero_bool(cx));
209    }
210    SymBoolExpr::and(cx, valid)
211}
212
213pub(crate) fn symbolic_modexp_precompile(
214    cx: &mut SymCx,
215    input: &SymBytes,
216    input_len: SymExpr,
217    spec_id: SpecId,
218    gas: u64,
219) -> Result<Option<SymReturnData>, SymbolicError> {
220    let input_len = input_len.as_usize_or("symbolic precompile input")?;
221    if input_len > input.len() {
222        return Err(SymbolicError::Unsupported("out-of-bounds symbolic precompile input"));
223    }
224
225    // The cost depends on the lengths and the exponent's leading word, read as evm2 does. Each
226    // is bounded by the range of its bytes, and the cost grows with each of them.
227    let [(min_base_len, max_base_len), (min_exp_len, max_exp_len), (min_mod_len, max_mod_len)] =
228        [0, 32, 64].map(|offset| {
229            let (min, max) = symbolic_input_word_range(cx, input, input_len, offset, 32);
230            (min.saturating_to::<u64>(), max.saturating_to::<u64>())
231        });
232    if spec_id.enables(SpecId::OSAKA) {
233        // EIP-7823 rejects any length above 1024 bytes.
234        let limit = MODEXP_INPUT_SIZE_LIMIT as u64;
235        if min_base_len > limit || min_exp_len > limit || min_mod_len > limit {
236            return Ok(None);
237        }
238        if max_base_len > limit || max_exp_len > limit || max_mod_len > limit {
239            return Err(SymbolicError::Unsupported("symbolic modexp length header"));
240        }
241    }
242    let (min_exp_highp, max_exp_highp) = if min_base_len == max_base_len
243        && let Some(exp_offset) =
244            usize::try_from(min_base_len).ok().and_then(|base_len| base_len.checked_add(96))
245    {
246        let (min, _) = symbolic_input_word_range(
247            cx,
248            input,
249            input_len,
250            exp_offset,
251            min_exp_len.min(32) as usize,
252        );
253        let (_, max) = symbolic_input_word_range(
254            cx,
255            input,
256            input_len,
257            exp_offset,
258            max_exp_len.min(32) as usize,
259        );
260        (min, max)
261    } else {
262        // The exponent's offset is symbolic, so its leading word can be any value of its length.
263        (U256::ZERO, U256::MAX >> (256 - 8 * max_exp_len.min(32) as usize))
264    };
265    let min_gas = modexp_gas(spec_id, min_base_len, min_exp_len, min_mod_len, &min_exp_highp);
266    let max_gas = modexp_gas(spec_id, max_base_len, max_exp_len, max_mod_len, &max_exp_highp);
267    match precompile_gas_fits(gas, min_gas, max_gas) {
268        Some(true) => {}
269        Some(false) => return Ok(None),
270        None => return Err(SymbolicError::Unsupported("symbolic modexp precompile gas")),
271    }
272
273    if min_mod_len != max_mod_len {
274        return Err(SymbolicError::Unsupported("symbolic modexp output length"));
275    }
276    let modulus_len = usize::try_from(min_mod_len)
277        .ok()
278        .filter(|modulus_len| *modulus_len <= 4096)
279        .ok_or(SymbolicError::Unsupported("symbolic modexp output length"))?;
280    Ok(Some(symbolic_fixed_len_precompile_output(cx, "modexp", input, input_len, modulus_len)))
281}
282
283/// Returns the gas the modexp precompile for `spec_id` charges for these lengths and leading
284/// exponent word, as EIP-198, EIP-2565 (Berlin) and EIP-7883 (Osaka) define it.
285///
286/// This mirrors evm2's modexp gas calculation, which evm2 does not export.
287fn modexp_gas(spec_id: SpecId, base_len: u64, exp_len: u64, mod_len: u64, exp_highp: &U256) -> u64 {
288    let (min_price, multiplier, divisor) = if spec_id.enables(SpecId::OSAKA) {
289        (500u64, 16u64, 1u64)
290    } else if spec_id.enables(SpecId::BERLIN) {
291        (200, 8, 3)
292    } else {
293        (0, 8, 20)
294    };
295
296    let max_len = base_len.max(mod_len);
297    let words_squared = || {
298        let words = U256::from(max_len.div_ceil(8));
299        words * words
300    };
301    let multiplication_complexity = if spec_id.enables(SpecId::OSAKA) {
302        if max_len <= 32 { U256::from(16) } else { words_squared() * U256::from(2) }
303    } else if spec_id.enables(SpecId::BERLIN) {
304        words_squared()
305    } else {
306        let x = U256::from(max_len);
307        if max_len <= 64 {
308            x * x
309        } else if max_len <= 1_024 {
310            x * x / U256::from(4) + U256::from(96) * x - U256::from(3_072)
311        } else {
312            x * x / U256::from(16) + U256::from(480) * x - U256::from(199_680)
313        }
314    };
315
316    let exp_bits = exp_highp.bit_len() as u64;
317    let iteration_count = if exp_len <= 32 {
318        exp_bits.saturating_sub(1)
319    } else {
320        multiplier.saturating_mul(exp_len - 32).saturating_add(exp_bits.max(1) - 1)
321    };
322    let gas = multiplication_complexity * U256::from(iteration_count.max(1)) / U256::from(divisor);
323    gas.saturating_to::<u64>().max(min_price)
324}
325
326/// Returns whether a precompile whose cost lies between `min_cost` and `max_cost` fits in
327/// `gas`, or `None` when that depends on symbolic input.
328const fn precompile_gas_fits(gas: u64, min_cost: u64, max_cost: u64) -> Option<bool> {
329    if max_cost <= gas {
330        Some(true)
331    } else if min_cost > gas {
332        Some(false)
333    } else {
334        None
335    }
336}
337
338/// Returns the smallest and largest big-endian values of the `len` input bytes at `offset`,
339/// taking each symbolic byte as `0x00` and `0xff` and each byte past `input_len` as zero.
340fn symbolic_input_word_range(
341    cx: &mut SymCx,
342    input: &SymBytes,
343    input_len: usize,
344    offset: usize,
345    len: usize,
346) -> (U256, U256) {
347    let (mut min, mut max) = (U256::ZERO, U256::ZERO);
348    for idx in offset..offset.saturating_add(len) {
349        let byte = if idx < input_len { input.byte(cx, idx).as_const() } else { Some(U256::ZERO) };
350        min = (min << 8) | byte.unwrap_or_default();
351        max = (max << 8) | byte.unwrap_or(U256::from(0xff));
352    }
353    (min, max)
354}
355
356pub(crate) fn symbolic_fixed_len_precompile_output(
357    cx: &mut SymCx,
358    algorithm: &'static str,
359    input: &SymBytes,
360    input_len: usize,
361    output_len: usize,
362) -> SymReturnData {
363    let input_len_word = SymExpr::constant(cx, U256::from(input_len));
364    let input = input.materialize(cx);
365    let mut bytes = Vec::with_capacity(output_len);
366    for chunk in 0..output_len.div_ceil(32) {
367        let mut chunk_input = Vec::with_capacity(input.len() + 1);
368        chunk_input.push(SymExpr::constant(cx, U256::from(chunk)));
369        chunk_input.extend(input.iter().cloned());
370        bytes.extend(
371            symbolic_hash_word_with_len(cx, algorithm, chunk_input, input_len_word.clone())
372                .into_byte_exprs(cx),
373        );
374    }
375    bytes.truncate(output_len);
376    SymReturnData::from_byte_exprs(cx, bytes)
377}