revm_precompile/
secp256k1.rs1#[cfg(feature = "secp256k1")]
16pub mod bitcoin_secp256k1;
17pub mod k256;
18
19use crate::{
20 crypto, utilities::right_pad, Precompile, PrecompileError, PrecompileId, PrecompileOutput,
21 PrecompileResult,
22};
23use primitives::{alloy_primitives::B512, Bytes, B256};
24
25pub const ECRECOVER: Precompile = Precompile::new(
27 PrecompileId::EcRec,
28 crate::u64_to_address(1),
29 ec_recover_run,
30);
31
32pub fn ec_recover_run(input: &[u8], gas_limit: u64) -> PrecompileResult {
34 const ECRECOVER_BASE: u64 = 3_000;
35
36 if ECRECOVER_BASE > gas_limit {
37 return Err(PrecompileError::OutOfGas);
38 }
39
40 let input = right_pad::<128>(input);
41
42 if !(input[32..63].iter().all(|&b| b == 0) && matches!(input[63], 27 | 28)) {
44 return Ok(PrecompileOutput::new(ECRECOVER_BASE, Bytes::new()));
45 }
46
47 let msg = <&B256>::try_from(&input[0..32]).unwrap();
48 let recid = input[63] - 27;
49 let sig = <&B512>::try_from(&input[64..128]).unwrap();
50
51 let res = crypto().secp256k1_ecrecover(&sig.0, recid, &msg.0).ok();
52 let out = res.map(|o| o.to_vec().into()).unwrap_or_default();
53 Ok(PrecompileOutput::new(ECRECOVER_BASE, out))
54}
55
56pub(crate) fn ecrecover_bytes(sig: [u8; 64], recid: u8, msg: [u8; 32]) -> Option<[u8; 32]> {
57 let sig = B512::from_slice(&sig);
58 let msg = B256::from_slice(&msg);
59
60 match ecrecover(&sig, recid, &msg) {
61 Ok(address) => Some(address.0),
62 Err(_) => None,
63 }
64}
65
66cfg_if::cfg_if! {
68 if #[cfg(feature = "secp256k1")] {
69 pub use bitcoin_secp256k1::ecrecover;
70 } else {
71 pub use k256::ecrecover;
72 }
73}