revm_interpreter/
gas.rs

1//! EVM gas calculation utilities.
2
3mod calc;
4mod constants;
5
6pub use calc::*;
7pub use constants::*;
8
9/// Represents the state of gas during execution.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct Gas {
13    /// The initial gas limit. This is constant throughout execution.
14    limit: u64,
15    /// The remaining gas.
16    remaining: u64,
17    /// Refunded gas. This is used only at the end of execution.
18    refunded: i64,
19    /// Memoisation of values for memory expansion cost.
20    memory: MemoryGas,
21}
22
23impl Gas {
24    /// Creates a new `Gas` struct with the given gas limit.
25    #[inline]
26    pub const fn new(limit: u64) -> Self {
27        Self {
28            limit,
29            remaining: limit,
30            refunded: 0,
31            memory: MemoryGas::new(),
32        }
33    }
34
35    /// Creates a new `Gas` struct with the given gas limit, but without any gas remaining.
36    #[inline]
37    pub const fn new_spent(limit: u64) -> Self {
38        Self {
39            limit,
40            remaining: 0,
41            refunded: 0,
42            memory: MemoryGas::new(),
43        }
44    }
45
46    /// Returns the gas limit.
47    #[inline]
48    pub const fn limit(&self) -> u64 {
49        self.limit
50    }
51
52    /// Returns the memory gas.
53    #[inline]
54    pub fn memory(&self) -> &MemoryGas {
55        &self.memory
56    }
57
58    /// Returns the memory gas.
59    #[inline]
60    pub fn memory_mut(&mut self) -> &mut MemoryGas {
61        &mut self.memory
62    }
63
64    /// Returns the total amount of gas that was refunded.
65    #[inline]
66    pub const fn refunded(&self) -> i64 {
67        self.refunded
68    }
69
70    /// Returns the total amount of gas spent.
71    #[inline]
72    pub const fn spent(&self) -> u64 {
73        self.limit - self.remaining
74    }
75
76    /// Returns the final amount of gas used by subtracting the refund from spent gas.
77    #[inline]
78    pub const fn used(&self) -> u64 {
79        self.spent().saturating_sub(self.refunded() as u64)
80    }
81
82    /// Returns the total amount of gas spent, minus the refunded gas.
83    #[inline]
84    pub const fn spent_sub_refunded(&self) -> u64 {
85        self.spent().saturating_sub(self.refunded as u64)
86    }
87
88    /// Returns the amount of gas remaining.
89    #[inline]
90    pub const fn remaining(&self) -> u64 {
91        self.remaining
92    }
93
94    /// Return remaining gas after subtracting 63/64 parts.
95    pub const fn remaining_63_of_64_parts(&self) -> u64 {
96        self.remaining - self.remaining / 64
97    }
98
99    /// Erases a gas cost from the totals.
100    #[inline]
101    pub fn erase_cost(&mut self, returned: u64) {
102        self.remaining += returned;
103    }
104
105    /// Spends all remaining gas.
106    #[inline]
107    pub fn spend_all(&mut self) {
108        self.remaining = 0;
109    }
110
111    /// Records a refund value.
112    ///
113    /// `refund` can be negative but `self.refunded` should always be positive
114    /// at the end of transact.
115    #[inline]
116    pub fn record_refund(&mut self, refund: i64) {
117        self.refunded += refund;
118    }
119
120    /// Set a refund value for final refund.
121    ///
122    /// Max refund value is limited to Nth part (depending of fork) of gas spend.
123    ///
124    /// Related to EIP-3529: Reduction in refunds
125    #[inline]
126    pub fn set_final_refund(&mut self, is_london: bool) {
127        let max_refund_quotient = if is_london { 5 } else { 2 };
128        self.refunded = (self.refunded() as u64).min(self.spent() / max_refund_quotient) as i64;
129    }
130
131    /// Set a refund value. This overrides the current refund value.
132    #[inline]
133    pub fn set_refund(&mut self, refund: i64) {
134        self.refunded = refund;
135    }
136
137    /// Set a spent value. This overrides the current spent value.
138    #[inline]
139    pub fn set_spent(&mut self, spent: u64) {
140        self.remaining = self.limit.saturating_sub(spent);
141    }
142
143    /// Records an explicit cost.
144    ///
145    /// Returns `false` if the gas limit is exceeded.
146    #[inline]
147    #[must_use = "prefer using `gas!` instead to return an out-of-gas error on failure"]
148    pub fn record_cost(&mut self, cost: u64) -> bool {
149        if let Some(new_remaining) = self.remaining.checked_sub(cost) {
150            self.remaining = new_remaining;
151            return true;
152        }
153        false
154    }
155
156    /// Record memory expansion
157    #[inline]
158    #[must_use = "internally uses record_cost that flags out of gas error"]
159    pub fn record_memory_expansion(&mut self, new_len: usize) -> MemoryExtensionResult {
160        let Some(additional_cost) = self.memory.record_new_len(new_len) else {
161            return MemoryExtensionResult::Same;
162        };
163
164        if !self.record_cost(additional_cost) {
165            return MemoryExtensionResult::OutOfGas;
166        }
167
168        MemoryExtensionResult::Extended
169    }
170}
171
172/// Result of attempting to extend memory during execution.
173#[derive(Debug)]
174pub enum MemoryExtensionResult {
175    /// Memory was extended.
176    Extended,
177    /// Memory size stayed the same.
178    Same,
179    /// Not enough gas to extend memory.
180    OutOfGas,
181}
182
183/// Utility struct that speeds up calculation of memory expansion
184/// It contains the current memory length and its memory expansion cost.
185///
186/// It allows us to split gas accounting from memory structure.
187#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
188#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
189pub struct MemoryGas {
190    /// Current memory length
191    pub words_num: usize,
192    /// Current memory expansion cost
193    pub expansion_cost: u64,
194}
195
196impl MemoryGas {
197    /// Creates a new `MemoryGas` instance with zero memory allocation.
198    #[inline]
199    pub const fn new() -> Self {
200        Self {
201            words_num: 0,
202            expansion_cost: 0,
203        }
204    }
205
206    /// Records a new memory length and calculates additional cost if memory is expanded.
207    /// Returns the additional gas cost required, or None if no expansion is needed.
208    #[inline]
209    pub fn record_new_len(&mut self, new_num: usize) -> Option<u64> {
210        if new_num <= self.words_num {
211            return None;
212        }
213        self.words_num = new_num;
214        let mut cost = crate::gas::calc::memory_gas(new_num);
215        core::mem::swap(&mut self.expansion_cost, &mut cost);
216        // Safe to subtract because we know that new_len > length
217        // Notice the swap above.
218        Some(self.expansion_cost - cost)
219    }
220}