Skip to main content

revm_handler/
precompile_provider.rs

1use auto_impl::auto_impl;
2use context::{Cfg, LocalContextTr};
3use context_interface::{ContextTr, JournalTr};
4use interpreter::{CallInput, CallInputs, Gas, InstructionResult, InterpreterResult};
5use precompile::{PrecompileError, PrecompileSpecId, Precompiles};
6use primitives::{hardfork::SpecId, Address, Bytes};
7use std::{
8    boxed::Box,
9    string::{String, ToString},
10};
11
12/// Provider for precompiled contracts in the EVM.
13#[auto_impl(&mut, Box)]
14pub trait PrecompileProvider<CTX: ContextTr> {
15    /// The output type returned by precompile execution.
16    type Output;
17
18    /// Sets the spec id and returns true if the spec id was changed. Initial call to set_spec will always return true.
19    ///
20    /// Returns `true` if precompile addresses should be injected into the journal.
21    fn set_spec(&mut self, spec: <CTX::Cfg as Cfg>::Spec) -> bool;
22
23    /// Run the precompile.
24    fn run(
25        &mut self,
26        context: &mut CTX,
27        inputs: &CallInputs,
28    ) -> Result<Option<Self::Output>, String>;
29
30    /// Get the warm addresses.
31    fn warm_addresses(&self) -> Box<impl Iterator<Item = Address>>;
32
33    /// Check if the address is a precompile.
34    fn contains(&self, address: &Address) -> bool;
35}
36
37/// The [`PrecompileProvider`] for ethereum precompiles.
38#[derive(Debug)]
39pub struct EthPrecompiles {
40    /// Contains precompiles for the current spec.
41    pub precompiles: &'static Precompiles,
42    /// Current spec. None means that spec was not set yet.
43    pub spec: SpecId,
44}
45
46impl EthPrecompiles {
47    /// Create a new precompile provider with the given spec.
48    pub fn new(spec: SpecId) -> Self {
49        Self {
50            precompiles: Precompiles::new(PrecompileSpecId::from_spec_id(spec)),
51            spec,
52        }
53    }
54
55    /// Returns addresses of the precompiles.
56    pub fn warm_addresses(&self) -> Box<impl Iterator<Item = Address>> {
57        Box::new(self.precompiles.addresses().cloned())
58    }
59
60    /// Returns whether the address is a precompile.
61    pub fn contains(&self, address: &Address) -> bool {
62        self.precompiles.contains(address)
63    }
64}
65
66impl Clone for EthPrecompiles {
67    fn clone(&self) -> Self {
68        Self {
69            precompiles: self.precompiles,
70            spec: self.spec,
71        }
72    }
73}
74
75impl<CTX: ContextTr> PrecompileProvider<CTX> for EthPrecompiles {
76    type Output = InterpreterResult;
77
78    fn set_spec(&mut self, spec: <CTX::Cfg as Cfg>::Spec) -> bool {
79        let spec = spec.into();
80        // generate new precompiles only on new spec
81        if spec == self.spec {
82            return false;
83        }
84        self.precompiles = Precompiles::new(PrecompileSpecId::from_spec_id(spec));
85        self.spec = spec;
86        true
87    }
88
89    fn run(
90        &mut self,
91        context: &mut CTX,
92        inputs: &CallInputs,
93    ) -> Result<Option<InterpreterResult>, String> {
94        let Some(precompile) = self.precompiles.get(&inputs.bytecode_address) else {
95            return Ok(None);
96        };
97
98        let mut result = InterpreterResult {
99            result: InstructionResult::Return,
100            gas: Gas::new(inputs.gas_limit),
101            output: Bytes::new(),
102        };
103
104        let exec_result = {
105            let r;
106            let input_bytes = match &inputs.input {
107                CallInput::SharedBuffer(range) => {
108                    if let Some(slice) = context.local().shared_memory_buffer_slice(range.clone()) {
109                        r = slice;
110                        r.as_ref()
111                    } else {
112                        &[]
113                    }
114                }
115                CallInput::Bytes(bytes) => bytes.0.iter().as_slice(),
116            };
117            precompile.execute(input_bytes, inputs.gas_limit)
118        };
119
120        match exec_result {
121            Ok(output) => {
122                result.gas.record_refund(output.gas_refunded);
123                let success = result.gas.record_cost(output.gas_used);
124                assert!(success, "Gas underflow is not possible");
125                result.result = if output.reverted {
126                    InstructionResult::Revert
127                } else {
128                    InstructionResult::Return
129                };
130                result.output = output.bytes;
131            }
132            Err(PrecompileError::Fatal(e)) => return Err(e),
133            Err(e) => {
134                result.result = if e.is_oog() {
135                    InstructionResult::PrecompileOOG
136                } else {
137                    InstructionResult::PrecompileError
138                };
139                // If this is a top-level precompile call (depth == 1), persist the error message
140                // into the local context so it can be returned as output in the final result.
141                // Only do this for non-OOG errors (OOG is a distinct halt reason without output).
142                if !e.is_oog() && context.journal().depth() == 1 {
143                    context
144                        .local_mut()
145                        .set_precompile_error_context(e.to_string());
146                }
147            }
148        }
149        Ok(Some(result))
150    }
151
152    fn warm_addresses(&self) -> Box<impl Iterator<Item = Address>> {
153        Self::warm_addresses(self)
154    }
155
156    fn contains(&self, address: &Address) -> bool {
157        Self::contains(self, address)
158    }
159}