Skip to main content

revm_precompile/
secp256k1.rs

1//! `ecrecover` precompile.
2//!
3//! Depending on enabled features, it will use different implementations of `ecrecover`.
4//! * [`k256`](https://crates.io/crates/k256) - uses maintained pure rust lib `k256`, it is perfect use for no_std environments.
5//! * [`secp256k1`](https://crates.io/crates/secp256k1) - uses `bitcoin_secp256k1` lib, it is a C implementation of secp256k1 used in bitcoin core.
6//!   It is faster than k256 and enabled by default and in std environment.
7
8//!   Order of preference is `secp256k1` -> `k256`. Where if no features are enabled, it will use `k256`.
9//!
10//! Input format:
11//! [32 bytes for message][64 bytes for signature][1 byte for recovery id]
12//!
13//! Output format:
14//! [32 bytes for recovered address]
15#[cfg(feature = "secp256k1")]
16pub mod bitcoin_secp256k1;
17pub mod k256;
18
19use crate::{
20    crypto, eth_precompile_fn, utilities::right_pad, EthPrecompileOutput, EthPrecompileResult,
21    Precompile, PrecompileHalt, PrecompileId,
22};
23use primitives::{alloy_primitives::B512, Bytes, B256};
24
25eth_precompile_fn!(ecrecover_precompile, ec_recover_run);
26
27/// `ecrecover` precompile, containing address and function to run.
28pub const ECRECOVER: Precompile = Precompile::new(
29    PrecompileId::EcRec,
30    crate::u64_to_address(1),
31    ecrecover_precompile,
32);
33
34/// `ecrecover` precompile function. Read more about input and output format in [this module docs](self).
35pub fn ec_recover_run(input: &[u8], gas_limit: u64) -> EthPrecompileResult {
36    const ECRECOVER_BASE: u64 = 3_000;
37
38    if ECRECOVER_BASE > gas_limit {
39        return Err(PrecompileHalt::OutOfGas);
40    }
41
42    let input = right_pad::<128>(input);
43
44    // `v` must be a 32-byte big-endian integer equal to 27 or 28.
45    if !(input[32..63].iter().all(|&b| b == 0) && matches!(input[63], 27 | 28)) {
46        return Ok(EthPrecompileOutput::new(ECRECOVER_BASE, Bytes::new()));
47    }
48
49    let msg = <&B256>::try_from(&input[0..32]).unwrap();
50    let recid = input[63] - 27;
51    let sig = <&B512>::try_from(&input[64..128]).unwrap();
52
53    let res = crypto().secp256k1_ecrecover(&sig.0, recid, &msg.0).ok();
54    let out = res.map(|o| o.to_vec().into()).unwrap_or_default();
55    Ok(EthPrecompileOutput::new(ECRECOVER_BASE, out))
56}
57
58pub(crate) fn ecrecover_bytes(sig: &[u8; 64], recid: u8, msg: &[u8; 32]) -> Option<[u8; 32]> {
59    match ecrecover(sig.into(), recid, msg.into()) {
60        Ok(address) => Some(address.0),
61        Err(_) => None,
62    }
63}
64
65// Select the correct implementation based on the enabled features.
66cfg_if::cfg_if! {
67    if #[cfg(feature = "secp256k1")] {
68        pub use bitcoin_secp256k1::ecrecover;
69    } else {
70        pub use k256::ecrecover;
71    }
72}