Skip to main content

revm_interpreter/
gas.rs

1//! EVM gas calculation utilities.
2
3pub use context_interface::cfg::gas::*;
4
5/// Represents the state of gas during execution.
6///
7/// Implements the EIP-8037 reservoir model for dual-limit gas accounting:
8/// - `remaining`: regular gas left (`gas_left`). Does NOT include `reservoir`.
9/// - `reservoir`: state gas pool (separate from `remaining`). Starts as `execution_gas - gas_left`.
10/// - `state_gas_spent`: tracks total state gas spent
11///
12/// **Regular gas charges** (`record_cost`): deduct from `remaining`, checked against `remaining`.
13/// **State gas charges** (`record_state_cost`): deduct from `reservoir` first; when exhausted, spill into `remaining`.
14/// Total gas available = `remaining` + `reservoir`.
15///
16/// On mainnet (no state gas), `reservoir = 0` so all gas is regular gas and behavior is unchanged.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub struct Gas {
20    /// Tracker for gas during execution.
21    tracker: GasTracker,
22    /// Memoisation of values for memory expansion cost.
23    memory: MemoryGas,
24}
25
26impl Gas {
27    /// Creates a new `Gas` struct with the given gas limit.
28    ///
29    /// Sets `reservoir = 0` so all gas is regular gas (standard mainnet behavior).
30    #[inline]
31    pub const fn new(limit: u64) -> Self {
32        Self {
33            tracker: GasTracker::new(limit, limit, 0),
34            memory: MemoryGas::new(),
35        }
36    }
37
38    /// Returns the tracker for gas during execution.
39    #[inline]
40    pub const fn tracker(&self) -> &GasTracker {
41        &self.tracker
42    }
43
44    /// Returns the mutable tracker for gas during execution.
45    #[inline]
46    pub const fn tracker_mut(&mut self) -> &mut GasTracker {
47        &mut self.tracker
48    }
49
50    /// Creates a new `Gas` struct with a regular gas budget and reservoir (EIP-8037 reservoir model).
51    ///
52    /// Following the EIP-8037 spec:
53    /// - `remaining = limit` (regular gas available, i.e. `gas_left`)
54    /// - `reservoir` = state gas pool (separate from `remaining`)
55    /// - Total gas available = `remaining + reservoir = limit + reservoir`
56    ///
57    /// # Arguments
58    /// * `limit`: regular gas budget (capped execution gas, i.e. `gas_left`)
59    /// * `reservoir`: state gas pool (execution gas exceeding the regular gas cap)
60    #[inline]
61    pub const fn new_with_regular_gas_and_reservoir(limit: u64, reservoir: u64) -> Self {
62        Self {
63            tracker: GasTracker::new(limit, limit, reservoir),
64            memory: MemoryGas::new(),
65        }
66    }
67
68    /// Creates a new `Gas` struct with the given gas limit, but without any gas remaining.
69    #[inline]
70    pub const fn new_spent_with_reservoir(limit: u64, reservoir: u64) -> Self {
71        Self {
72            tracker: GasTracker::new(limit, 0, reservoir),
73            memory: MemoryGas::new(),
74        }
75    }
76
77    /// Returns the gas limit.
78    #[inline]
79    pub const fn limit(&self) -> u64 {
80        self.tracker.limit()
81    }
82
83    /// Returns the memory gas.
84    #[inline]
85    pub fn memory(&self) -> &MemoryGas {
86        &self.memory
87    }
88
89    /// Returns the memory gas.
90    #[inline]
91    pub fn memory_mut(&mut self) -> &mut MemoryGas {
92        &mut self.memory
93    }
94
95    /// Returns the total amount of gas that was refunded.
96    #[inline]
97    pub const fn refunded(&self) -> i64 {
98        self.tracker.refunded()
99    }
100
101    /// Returns the total amount of gas spent.
102    #[inline]
103    #[deprecated(
104        since = "32.0.0",
105        note = "After EIP-8037 gas is split on
106    regular and state gas, this method is no longer valid.
107    Use [`Gas::total_gas_spent`] instead"
108    )]
109    pub const fn spent(&self) -> u64 {
110        self.tracker
111            .limit()
112            .saturating_sub(self.tracker.remaining())
113    }
114
115    /// Returns the regular gas spent.
116    #[inline]
117    pub const fn total_gas_spent(&self) -> u64 {
118        self.tracker
119            .limit()
120            .saturating_sub(self.tracker.remaining())
121    }
122
123    /// Returns the final amount of gas used by subtracting the refund from spent gas.
124    #[inline]
125    pub const fn used(&self) -> u64 {
126        self.total_gas_spent()
127            .saturating_sub(self.refunded() as u64)
128    }
129
130    /// Returns the total amount of gas spent, minus the refunded gas.
131    #[inline]
132    pub const fn spent_sub_refunded(&self) -> u64 {
133        self.total_gas_spent()
134            .saturating_sub(self.tracker.refunded() as u64)
135    }
136
137    /// Returns the amount of gas remaining.
138    #[inline]
139    pub const fn remaining(&self) -> u64 {
140        self.tracker.remaining()
141    }
142
143    /// Returns the state gas reservoir.
144    #[inline]
145    pub const fn reservoir(&self) -> u64 {
146        self.tracker.reservoir()
147    }
148
149    /// Sets the state gas reservoir (used when propagating from child frame).
150    #[inline]
151    pub fn set_reservoir(&mut self, val: u64) {
152        self.tracker.set_reservoir(val);
153    }
154
155    /// Returns total state gas spent so far.
156    #[inline]
157    pub const fn state_gas_spent(&self) -> u64 {
158        self.tracker.state_gas_spent()
159    }
160
161    /// Sets the total state gas spent (used when propagating from child frame).
162    #[inline]
163    pub fn set_state_gas_spent(&mut self, val: u64) {
164        self.tracker.set_state_gas_spent(val);
165    }
166
167    /// Erases a gas cost from remaining (returns gas from child frame).
168    #[inline]
169    pub fn erase_cost(&mut self, returned: u64) {
170        self.tracker.erase_cost(returned);
171    }
172
173    /// Spends all remaining gas excluding the reservoir.
174    ///
175    /// On exceptional halt, the remaining gas must be zeroed
176    /// to prevent state operations from succeeding via remaining gas.
177    ///
178    /// Note that this does not affect the reservoir.
179    #[inline]
180    pub fn spend_all(&mut self) {
181        self.tracker.spend_all();
182    }
183
184    /// Records a refund value.
185    ///
186    /// `refund` can be negative but `self.refunded` should always be positive
187    /// at the end of transact.
188    #[inline]
189    pub fn record_refund(&mut self, refund: i64) {
190        self.tracker.record_refund(refund);
191    }
192
193    /// Set a refund value for final refund.
194    ///
195    /// Max refund value is limited to Nth part (depending of fork) of gas spend.
196    ///
197    /// Related to EIP-3529: Reduction in refunds
198    #[inline]
199    pub fn set_final_refund(&mut self, is_london: bool) {
200        let max_refund_quotient = if is_london { 5 } else { 2 };
201        // EIP-8037: gas_used = total_gas_spent - reservoir (reservoir is unused state gas)
202        let gas_used = self.total_gas_spent().saturating_sub(self.reservoir());
203        self.tracker
204            .set_refunded((self.refunded() as u64).min(gas_used / max_refund_quotient) as i64);
205    }
206
207    /// Set a refund value. This overrides the current refund value.
208    #[inline]
209    pub fn set_refund(&mut self, refund: i64) {
210        self.tracker.set_refunded(refund);
211    }
212
213    /// Set a remaining value. This overrides the current remaining value.
214    #[inline]
215    pub fn set_remaining(&mut self, remaining: u64) {
216        self.tracker.set_remaining(remaining);
217    }
218
219    /// Set a spent value. This overrides the current spent value.
220    #[inline]
221    pub fn set_spent(&mut self, spent: u64) {
222        self.tracker
223            .set_remaining(self.tracker.limit().saturating_sub(spent));
224    }
225
226    /// Records a regular gas cost (EIP-8037 reservoir model).
227    ///
228    /// Deducts from `remaining` and checks against implicit `gas_left` budget.
229    /// Regular gas charges cannot draw from the reservoir.
230    ///
231    /// Returns `false` if the regular gas limit is exceeded.
232    /// On failure, values contain wrapped (invalid) state — callers must not read after OOG.
233    #[inline]
234    #[must_use = "prefer using `gas!` instead to return an out-of-gas error on failure"]
235    #[deprecated(since = "32.0.0", note = "use record_regular_cost instead")]
236    pub fn record_cost(&mut self, cost: u64) -> bool {
237        self.record_regular_cost(cost)
238    }
239
240    /// Records an explicit cost without bounds checking (unsafe path).
241    ///
242    /// Returns `true` if the gas limit is exceeded. Values wrap on underflow.
243    /// Only the regular gas check is meaningful here; total remaining can underflow
244    /// without consequence if the caller handles it.
245    #[inline(always)]
246    #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
247    pub fn record_cost_unsafe(&mut self, cost: u64) -> bool {
248        let remaining = self.tracker.remaining();
249        let oog = remaining < cost;
250        self.tracker.set_remaining(remaining.wrapping_sub(cost));
251        oog
252    }
253
254    /// Records a state gas cost (EIP-8037 reservoir model).
255    ///
256    /// State gas charges deduct from the reservoir first. If the reservoir is exhausted,
257    /// remaining charges spill into `gas_left` (requiring total `remaining >= cost`).
258    /// Tracks state gas spent.
259    ///
260    /// Returns `false` if total remaining gas is insufficient.
261    #[inline]
262    #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
263    pub fn record_state_cost(&mut self, cost: u64) -> bool {
264        self.tracker.record_state_cost(cost)
265    }
266
267    /// Deducts from `remaining` only (used for child frame gas forwarding).
268    /// Does not affect reservoir or regular gas budget.
269    /// Used for forwarding gas to child frames.
270    #[inline]
271    #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
272    pub fn record_regular_cost(&mut self, cost: u64) -> bool {
273        self.tracker.record_regular_cost(cost)
274    }
275}
276
277/// Result of attempting to extend memory during execution.
278#[derive(Debug)]
279pub enum MemoryExtensionResult {
280    /// Memory was extended.
281    Extended,
282    /// Memory size stayed the same.
283    Same,
284    /// Not enough gas to extend memory.
285    OutOfGas,
286}
287
288/// Utility struct that speeds up calculation of memory expansion
289/// It contains the current memory length and its memory expansion cost.
290///
291/// It allows us to split gas accounting from memory structure.
292#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
293#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
294pub struct MemoryGas {
295    /// Current memory length
296    pub words_num: usize,
297    /// Current memory expansion cost
298    pub expansion_cost: u64,
299}
300
301impl MemoryGas {
302    /// Creates a new `MemoryGas` instance with zero memory allocation.
303    #[inline]
304    pub const fn new() -> Self {
305        Self {
306            words_num: 0,
307            expansion_cost: 0,
308        }
309    }
310
311    /// Sets the number of words and the expansion cost.
312    ///
313    /// Returns the difference between the new and old expansion cost.
314    #[inline]
315    pub fn set_words_num(&mut self, words_num: usize, mut expansion_cost: u64) -> Option<u64> {
316        self.words_num = words_num;
317        core::mem::swap(&mut self.expansion_cost, &mut expansion_cost);
318        self.expansion_cost.checked_sub(expansion_cost)
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn test_record_state_cost() {
328        // Test 1: Cost from reservoir only
329        let mut gas = Gas::new_with_regular_gas_and_reservoir(1000, 500);
330        assert!(gas.record_state_cost(200));
331        assert_eq!(
332            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
333            (300, 1000, 200)
334        );
335
336        // Test 2: Exhaust reservoir exactly
337        let mut gas = Gas::new_with_regular_gas_and_reservoir(1000, 500);
338        assert!(gas.record_state_cost(500));
339        assert_eq!(
340            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
341            (0, 1000, 500)
342        );
343
344        // Test 3: Spill to remaining (reservoir < cost)
345        let mut gas = Gas::new_with_regular_gas_and_reservoir(1000, 300);
346        assert!(gas.record_state_cost(500));
347        assert_eq!(
348            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
349            (0, 800, 500)
350        );
351
352        // Test 4: No reservoir (mainnet standard)
353        let mut gas = Gas::new(1000);
354        assert!(gas.record_state_cost(200));
355        assert_eq!(
356            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
357            (0, 800, 200)
358        );
359
360        // Test 5: Zero cost
361        let mut gas = Gas::new_with_regular_gas_and_reservoir(100, 50);
362        assert!(gas.record_state_cost(0));
363        assert_eq!(
364            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
365            (50, 100, 0)
366        );
367
368        // Test 6: Out of gas (cost > remaining + reservoir)
369        let mut gas = Gas::new_with_regular_gas_and_reservoir(100, 50);
370        assert!(!gas.record_state_cost(200));
371
372        // Test 7: Multiple operations accumulate state_gas_spent
373        let mut gas = Gas::new_with_regular_gas_and_reservoir(2000, 1000);
374        assert!(gas.record_state_cost(100));
375        assert!(gas.record_state_cost(200));
376        assert!(gas.record_state_cost(150));
377        assert_eq!(gas.state_gas_spent(), 450);
378
379        // Test 8: Complex scenario exhausting reservoir then remaining
380        let mut gas = Gas::new_with_regular_gas_and_reservoir(500, 300);
381        assert!(gas.record_state_cost(150)); // 150 from reservoir
382        assert_eq!((gas.reservoir(), gas.remaining()), (150, 500));
383        assert!(gas.record_state_cost(200)); // 150 from reservoir, 50 from remaining
384        assert_eq!((gas.reservoir(), gas.remaining()), (0, 450));
385        assert!(gas.record_state_cost(100)); // 100 from remaining
386        assert_eq!(
387            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
388            (0, 350, 450)
389        );
390    }
391
392    /// A.1: Verify state_gas_spent is incremented even after failed record_state_cost.
393    /// On OOG, state_gas_spent is NOT incremented and reservoir is unchanged.
394    #[test]
395    fn test_record_state_cost_oog_inflates_state_gas_spent() {
396        // remaining=30, reservoir=0, cost=100 → OOG
397        let mut gas = Gas::new(30);
398        assert!(!gas.record_state_cost(100));
399        // On OOG, state_gas_spent is NOT incremented (operation failed)
400        assert_eq!(gas.state_gas_spent(), 0);
401
402        // With reservoir partially covering: reservoir=20, remaining=30, cost=100
403        // spill = 100 - 20 = 80, remaining(30) < 80 → OOG
404        let mut gas = Gas::new_with_regular_gas_and_reservoir(30, 20);
405        assert!(!gas.record_state_cost(100));
406        // On OOG, state_gas_spent is NOT incremented and reservoir is unchanged
407        assert_eq!(gas.state_gas_spent(), 0);
408        assert_eq!(gas.reservoir(), 20);
409    }
410
411    /// A.3: State gas with zero regular remaining but non-zero reservoir.
412    #[test]
413    fn test_record_state_cost_zero_remaining_with_reservoir() {
414        // remaining=0, reservoir=500: state gas draws entirely from reservoir
415        let mut gas = Gas::new_with_regular_gas_and_reservoir(0, 500);
416        assert!(gas.record_state_cost(200));
417        assert_eq!(
418            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
419            (300, 0, 200)
420        );
421
422        // Exhaust reservoir exactly
423        assert!(gas.record_state_cost(300));
424        assert_eq!(
425            (gas.reservoir(), gas.remaining(), gas.state_gas_spent()),
426            (0, 0, 500)
427        );
428
429        // Now any cost → OOG (both remaining and reservoir are 0)
430        assert!(!gas.record_state_cost(1));
431    }
432}