custom_precompile_journal/
precompile_provider.rs

1//! Custom precompile provider implementation.
2
3use revm::{
4    context::Cfg,
5    context_interface::{ContextTr, JournalTr, LocalContextTr, Transaction},
6    handler::{EthPrecompiles, PrecompileProvider},
7    interpreter::{Gas, InputsImpl, InstructionResult, InterpreterResult},
8    precompile::{PrecompileError, PrecompileOutput, PrecompileResult},
9    primitives::{address, hardfork::SpecId, Address, Bytes, U256},
10};
11use std::boxed::Box;
12use std::string::String;
13
14// Define our custom precompile address
15pub const CUSTOM_PRECOMPILE_ADDRESS: Address = address!("0000000000000000000000000000000000000100");
16
17// Custom storage key for our example
18const STORAGE_KEY: U256 = U256::ZERO;
19
20/// Custom precompile provider that includes journal access functionality
21#[derive(Debug, Clone)]
22pub struct CustomPrecompileProvider {
23    inner: EthPrecompiles,
24    spec: SpecId,
25}
26
27impl CustomPrecompileProvider {
28    pub fn new_with_spec(spec: SpecId) -> Self {
29        Self {
30            inner: EthPrecompiles::default(),
31            spec,
32        }
33    }
34}
35
36impl<CTX> PrecompileProvider<CTX> for CustomPrecompileProvider
37where
38    CTX: ContextTr<Cfg: Cfg<Spec = SpecId>>,
39{
40    type Output = InterpreterResult;
41
42    fn set_spec(&mut self, spec: <CTX::Cfg as Cfg>::Spec) -> bool {
43        if spec == self.spec {
44            return false;
45        }
46        self.spec = spec;
47        // Create a new inner provider with the new spec
48        self.inner = EthPrecompiles::default();
49        true
50    }
51
52    fn run(
53        &mut self,
54        context: &mut CTX,
55        address: &Address,
56        inputs: &InputsImpl,
57        is_static: bool,
58        gas_limit: u64,
59    ) -> Result<Option<Self::Output>, String> {
60        // Check if this is our custom precompile
61        if *address == CUSTOM_PRECOMPILE_ADDRESS {
62            return Ok(Some(run_custom_precompile(
63                context, inputs, is_static, gas_limit,
64            )?));
65        }
66
67        // Otherwise, delegate to standard Ethereum precompiles
68        self.inner
69            .run(context, address, inputs, is_static, gas_limit)
70    }
71
72    fn warm_addresses(&self) -> Box<impl Iterator<Item = Address>> {
73        // Include our custom precompile address along with standard ones
74        let mut addresses = vec![CUSTOM_PRECOMPILE_ADDRESS];
75        addresses.extend(self.inner.warm_addresses());
76        Box::new(addresses.into_iter())
77    }
78
79    fn contains(&self, address: &Address) -> bool {
80        *address == CUSTOM_PRECOMPILE_ADDRESS || self.inner.contains(address)
81    }
82}
83
84/// Runs our custom precompile
85fn run_custom_precompile<CTX: ContextTr>(
86    context: &mut CTX,
87    inputs: &InputsImpl,
88    is_static: bool,
89    gas_limit: u64,
90) -> Result<InterpreterResult, String> {
91    let input_bytes = match &inputs.input {
92        revm::interpreter::CallInput::SharedBuffer(range) => {
93            if let Some(slice) = context.local().shared_memory_buffer_slice(range.clone()) {
94                slice.to_vec()
95            } else {
96                vec![]
97            }
98        }
99        revm::interpreter::CallInput::Bytes(bytes) => bytes.0.to_vec(),
100    };
101
102    // For this example, we'll implement a simple precompile that:
103    // - If called with empty data: reads a storage value
104    // - If called with 32 bytes: writes that value to storage and transfers 1 wei to the caller
105
106    let result = if input_bytes.is_empty() {
107        // Read storage operation
108        handle_read_storage(context, gas_limit)
109    } else if input_bytes.len() == 32 {
110        if is_static {
111            return Err("Cannot modify state in static context".to_string());
112        }
113        // Write storage operation
114        handle_write_storage(context, &input_bytes, gas_limit)
115    } else {
116        Err(PrecompileError::Other("Invalid input length".to_string()))
117    };
118
119    match result {
120        Ok(output) => {
121            let mut interpreter_result = InterpreterResult {
122                result: InstructionResult::Return,
123                gas: Gas::new(gas_limit),
124                output: output.bytes,
125            };
126            let underflow = interpreter_result.gas.record_cost(output.gas_used);
127            if !underflow {
128                interpreter_result.result = InstructionResult::PrecompileOOG;
129            }
130            Ok(interpreter_result)
131        }
132        Err(e) => Ok(InterpreterResult {
133            result: if e.is_oog() {
134                InstructionResult::PrecompileOOG
135            } else {
136                InstructionResult::PrecompileError
137            },
138            gas: Gas::new(gas_limit),
139            output: Bytes::new(),
140        }),
141    }
142}
143
144/// Handles reading from storage
145fn handle_read_storage<CTX: ContextTr>(context: &mut CTX, gas_limit: u64) -> PrecompileResult {
146    // Base gas cost for reading storage
147    const BASE_GAS: u64 = 2_100;
148
149    if gas_limit < BASE_GAS {
150        return Err(PrecompileError::OutOfGas);
151    }
152
153    // Read from storage using the journal
154    let value = context
155        .journal_mut()
156        .sload(CUSTOM_PRECOMPILE_ADDRESS, STORAGE_KEY)
157        .map_err(|e| PrecompileError::Other(format!("Storage read failed: {e:?}")))?
158        .data;
159
160    // Return the value as output
161    Ok(PrecompileOutput::new(
162        BASE_GAS,
163        value.to_be_bytes_vec().into(),
164    ))
165}
166
167/// Handles writing to storage and transferring balance
168fn handle_write_storage<CTX: ContextTr>(
169    context: &mut CTX,
170    input: &[u8],
171    gas_limit: u64,
172) -> PrecompileResult {
173    // Base gas cost for the operation
174    const BASE_GAS: u64 = 21_000;
175    const SSTORE_GAS: u64 = 20_000;
176
177    if gas_limit < BASE_GAS + SSTORE_GAS {
178        return Err(PrecompileError::OutOfGas);
179    }
180
181    // Parse the input as a U256 value
182    let value = U256::from_be_slice(input);
183
184    // Store the value in the precompile's storage
185    context
186        .journal_mut()
187        .sstore(CUSTOM_PRECOMPILE_ADDRESS, STORAGE_KEY, value)
188        .map_err(|e| PrecompileError::Other(format!("Storage write failed: {e:?}")))?;
189
190    // Get the caller address
191    let caller = context.tx().caller();
192
193    // Transfer 1 wei from the precompile to the caller as a reward
194    // First, ensure the precompile has balance
195    context
196        .journal_mut()
197        .balance_incr(CUSTOM_PRECOMPILE_ADDRESS, U256::from(1))
198        .map_err(|e| PrecompileError::Other(format!("Balance increment failed: {e:?}")))?;
199
200    // Then transfer to caller
201    let transfer_result = context
202        .journal_mut()
203        .transfer(CUSTOM_PRECOMPILE_ADDRESS, caller, U256::from(1))
204        .map_err(|e| PrecompileError::Other(format!("Transfer failed: {e:?}")))?;
205
206    if let Some(error) = transfer_result {
207        return Err(PrecompileError::Other(format!("Transfer error: {error:?}")));
208    }
209
210    // Return success with empty output
211    Ok(PrecompileOutput::new(BASE_GAS + SSTORE_GAS, Bytes::new()))
212}