Skip to main content

tempo_precompiles/storage/
mod.rs

1//! EVM storage abstraction layer for Tempo precompile contracts.
2//!
3//! Provides traits and types for reading/writing contract state from EVM storage,
4//! including persistent (SLOAD/SSTORE) and transient (TLOAD/TSTORE) operations.
5
6pub mod evm;
7pub mod hashmap;
8
9pub mod thread_local;
10use alloy::primitives::keccak256;
11pub use thread_local::{CheckpointGuard, StorageCtx};
12
13mod types;
14pub use types::*;
15
16pub mod packing;
17pub use packing::FieldLocation;
18pub use types::mapping as slots;
19
20use alloy::primitives::{Address, B256, LogData, Signature, U256};
21use revm::{
22    context::journaled_state::JournalCheckpoint,
23    interpreter::gas::{KECCAK256, KECCAK256WORD},
24    state::{AccountInfo, Bytecode},
25};
26use tempo_chainspec::hardfork::TempoHardfork;
27
28use crate::error::{Result, TempoPrecompileError};
29
30/// Low-level storage provider for interacting with the EVM.
31///
32/// # Implementations
33///
34/// - `EvmPrecompileStorageProvider` - Production EVM storage
35/// - `HashMapStorageProvider` - Test storage
36///
37/// # Sync with `[StorageCtx]`
38///
39/// `StorageCtx` mirrors these methods with split mutability for read (staticcall) vs write (call).
40/// When adding new methods here, remember to add corresponding methods to `StorageCtx`.
41pub trait PrecompileStorageProvider {
42    /// Returns the chain ID.
43    fn chain_id(&self) -> u64;
44
45    /// Returns the current block timestamp.
46    fn timestamp(&self) -> U256;
47
48    /// Returns the current block beneficiary (coinbase).
49    fn beneficiary(&self) -> Address;
50
51    /// Returns the current block number.
52    fn block_number(&self) -> u64;
53
54    /// Sets the bytecode at the given address.
55    fn set_code(&mut self, address: Address, code: Bytecode) -> Result<()>;
56
57    /// Executes a closure with access to the account info for the given address.
58    fn with_account_info(
59        &mut self,
60        address: Address,
61        f: &mut dyn FnMut(&AccountInfo),
62    ) -> Result<()>;
63
64    /// Performs an SLOAD operation (persistent storage read).
65    fn sload(&mut self, address: Address, key: U256) -> Result<U256>;
66
67    /// Performs a TLOAD operation (transient storage read).
68    fn tload(&mut self, address: Address, key: U256) -> Result<U256>;
69
70    /// Performs an SSTORE operation (persistent storage write).
71    fn sstore(&mut self, address: Address, key: U256, value: U256) -> Result<()>;
72
73    /// Performs a TSTORE operation (transient storage write).
74    fn tstore(&mut self, address: Address, key: U256, value: U256) -> Result<()>;
75
76    /// Emits an event from the given contract address.
77    fn emit_event(&mut self, address: Address, event: LogData) -> Result<()>;
78
79    /// Deducts gas from the remaining gas and returns an error if insufficient.
80    fn deduct_gas(&mut self, gas: u64) -> Result<()>;
81
82    /// Add refund to the refund gas counter.
83    fn refund_gas(&mut self, gas: i64);
84
85    /// Returns the gas used so far.
86    fn gas_used(&self) -> u64;
87
88    /// Returns the gas refunded so far.
89    fn gas_refunded(&self) -> i64;
90
91    /// Returns the currently active hardfork.
92    fn spec(&self) -> TempoHardfork;
93
94    /// Returns whether the current call context is static.
95    fn is_static(&self) -> bool;
96
97    /// Creates a new journal checkpoint so that all subsequent state-changing
98    /// operations can be atomically committed ([`checkpoint_commit`](Self::checkpoint_commit))
99    /// or reverted ([`checkpoint_revert`](Self::checkpoint_revert)).
100    ///
101    /// Prefer [`StorageCtx::checkpoint`] which returns a [`CheckpointGuard`] that
102    /// auto-reverts on drop and is hardfork-aware (no-op pre-T1C).
103    fn checkpoint(&mut self) -> JournalCheckpoint;
104
105    /// Commits all state changes since the given checkpoint.
106    ///
107    /// Prefer [`CheckpointGuard::commit`].
108    fn checkpoint_commit(&mut self, checkpoint: JournalCheckpoint);
109
110    /// Reverts all state changes back to the given checkpoint.
111    ///
112    /// Prefer [`CheckpointGuard`] (auto-reverts on drop).
113    fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint);
114
115    /// Computes keccak256 and charges the appropriate gas.
116    ///
117    /// Implementations should use this over naked `keccak256` call to ensure gas is accounted for.
118    fn keccak256(&mut self, data: &[u8]) -> Result<B256> {
119        let num_words =
120            u64::try_from(data.len().div_ceil(32)).map_err(|_| TempoPrecompileError::OutOfGas)?;
121        let price = KECCAK256WORD
122            .checked_mul(num_words)
123            .and_then(|w| w.checked_add(KECCAK256))
124            .ok_or(TempoPrecompileError::OutOfGas)?;
125        self.deduct_gas(price)?;
126        Ok(keccak256(data))
127    }
128
129    /// Recovers the signer address from an ECDSA signature and charges ecrecover gas.
130    /// As per [TIP-1004], it only accepts `v` values of `27` or `28` (no `0`/`1` normalization).
131    ///
132    /// Returns `Ok(None)` on invalid signatures; callers map to domain-specific errors.
133    ///
134    /// [TIP-1004]: <https://github.com/tempoxyz/tempo/blob/main/tips/tip-1004.md#signature-validation>
135    fn recover_signer(&mut self, digest: B256, v: u8, r: B256, s: B256) -> Result<Option<Address>> {
136        self.deduct_gas(crate::ECRECOVER_GAS)?;
137
138        if v != 27 && v != 28 {
139            return Ok(None);
140        }
141
142        let parity = v == 28;
143        let sig = Signature::from_scalars_and_parity(r, s, parity);
144        let recovered = alloy::consensus::crypto::secp256k1::recover_signer(&sig, digest);
145
146        Ok(recovered.ok().filter(|addr| !addr.is_zero()))
147    }
148}
149
150/// Storage operations for a given (contract) address.
151///
152/// Abstracts over persistent storage (SLOAD/SSTORE) and transient storage (TLOAD/TSTORE).
153/// Implementors must route to the appropriate opcode.
154pub trait StorageOps {
155    /// Stores a value at the provided slot.
156    fn store(&mut self, slot: U256, value: U256) -> Result<()>;
157    /// Loads a value from the provided slot.
158    fn load(&self, slot: U256) -> Result<U256>;
159}
160
161/// Trait providing access to a contract's address.
162///
163/// Automatically implemented by the `#[contract]` macro.
164pub trait ContractStorage {
165    /// Contract address.
166    fn address(&self) -> Address;
167
168    /// Contract storage accessor.
169    fn storage(&self) -> &StorageCtx;
170
171    /// Contract storage mutable accessor.
172    fn storage_mut(&mut self) -> &mut StorageCtx;
173
174    /// Returns true if the contract has been initialized (has bytecode deployed).
175    fn is_initialized(&self) -> Result<bool> {
176        self.storage()
177            .with_account_info(self.address(), |info| Ok(!info.is_empty_code_hash()))
178    }
179}