revm-context-interface 18.0.0

Revm context interface crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Gas constants and functions for gas calculation.

use crate::{cfg::GasParams, transaction::AccessListItemTr as _, Transaction, TransactionType};
use primitives::hardfork::SpecId;

/// Tracker for gas during execution.
///
/// This is used to track the gas during execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GasTracker {
    /// Gas Limit,
    gas_limit: u64,
    /// Regular gas remaining (`gas_left`). Reservoir is tracked separately.
    remaining: u64,
    /// State gas reservoir (gas exceeding TX_MAX_GAS_LIMIT). Starts as `execution_gas - min(execution_gas, regular_gas_budget)`.
    /// When 0, all remaining gas is regular gas with hard cap at `TX_MAX_GAS_LIMIT`.
    reservoir: u64,
    /// Net state gas spent so far.
    ///
    /// Can be negative within a call frame when 0→x→0 storage restoration refills
    /// more state gas than the frame itself has charged (the parent previously
    /// charged the 0→x portion). The net is reconciled on frame return.
    state_gas_spent: i64,
    /// Cumulative reservoir refill amount from 0→x→0 storage restorations
    /// performed by this frame (EIP-8037 issue #2). Tracked so that on
    /// revert/halt the parent can subtract this inflation when propagating
    /// the child's reservoir, without confusing it with legitimate reservoir
    /// growth from grandchild halt/revert refunds.
    refill_amount: u64,
    /// Refunded gas. Used to refund the gas to the caller at the end of execution.
    refunded: i64,
}

impl GasTracker {
    /// Creates a new `GasTracker` with the given remaining gas and reservoir.
    #[inline]
    pub const fn new(gas_limit: u64, remaining: u64, reservoir: u64) -> Self {
        Self {
            gas_limit,
            remaining,
            reservoir,
            state_gas_spent: 0,
            refill_amount: 0,
            refunded: 0,
        }
    }

    /// Creates a new `GasTracker` with the given used gas and reservoir.
    #[inline]
    pub const fn new_used_gas(gas_limit: u64, used_gas: u64, reservoir: u64) -> Self {
        Self::new(gas_limit, gas_limit - used_gas, reservoir)
    }

    /// Returns the gas limit.
    #[inline]
    pub const fn limit(&self) -> u64 {
        self.gas_limit
    }

    /// Sets the gas limit.
    #[inline]
    pub const fn set_limit(&mut self, val: u64) {
        self.gas_limit = val;
    }

    /// Returns the remaining gas.
    #[inline]
    pub const fn remaining(&self) -> u64 {
        self.remaining
    }

    /// Sets the remaining gas.
    #[inline]
    pub const fn set_remaining(&mut self, val: u64) {
        self.remaining = val;
    }

    /// Returns the reservoir gas.
    #[inline]
    pub const fn reservoir(&self) -> u64 {
        self.reservoir
    }

    /// Sets the reservoir gas.
    #[inline]
    pub const fn set_reservoir(&mut self, val: u64) {
        self.reservoir = val;
    }

    /// Returns the state gas spent.
    #[inline]
    pub const fn state_gas_spent(&self) -> i64 {
        self.state_gas_spent
    }

    /// Sets the state gas spent.
    #[inline]
    pub const fn set_state_gas_spent(&mut self, val: i64) {
        self.state_gas_spent = val;
    }

    /// Returns the refunded gas.
    #[inline]
    pub const fn refunded(&self) -> i64 {
        self.refunded
    }

    /// Sets the refunded gas.
    #[inline]
    pub const fn set_refunded(&mut self, val: i64) {
        self.refunded = val;
    }

    /// Records a regular gas cost.
    ///
    /// Deducts from `remaining`. Returns `false` if insufficient gas.
    #[inline]
    #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
    pub const fn record_regular_cost(&mut self, cost: u64) -> bool {
        if let Some(new_remaining) = self.remaining.checked_sub(cost) {
            self.remaining = new_remaining;
            return true;
        }
        false
    }

    /// Records a state gas cost (EIP-8037 reservoir model).
    ///
    /// State gas charges deduct from the reservoir first. If the reservoir is exhausted,
    /// remaining charges spill into `remaining` (requiring `remaining >= cost`).
    /// Tracks state gas spent.
    ///
    /// Returns `false` if total remaining gas is insufficient.
    #[inline]
    #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
    pub const fn record_state_cost(&mut self, cost: u64) -> bool {
        if self.reservoir >= cost {
            self.state_gas_spent = self.state_gas_spent.saturating_add(cost as i64);
            self.reservoir -= cost;
            return true;
        }

        let spill = cost - self.reservoir;

        let success = self.record_regular_cost(spill);
        if success {
            self.state_gas_spent = self.state_gas_spent.saturating_add(cost as i64);
            self.reservoir = 0;
        }
        success
    }

    /// Refills the reservoir with state gas that is returned by 0→x→0 storage
    /// restoration (EIP-8037 issue #2).
    ///
    /// Per the spec, when a storage slot is restored to its original zero value
    /// within the same transaction, the state gas charged for the initial 0→x
    /// transition is directly restored to the reservoir rather than routed
    /// through the capped refund counter.
    ///
    /// `state_gas_spent` is decremented by the same amount and may become
    /// negative if the matching 0→x charge was made by a parent frame. The
    /// parent's total is reconciled on frame return.
    #[inline]
    pub const fn refill_reservoir(&mut self, amount: u64) {
        self.reservoir = self.reservoir.saturating_add(amount);
        self.state_gas_spent = self.state_gas_spent.saturating_sub(amount as i64);
        self.refill_amount = self.refill_amount.saturating_add(amount);
    }

    /// Returns cumulative reservoir refill amount from 0→x→0 restorations
    /// performed in this frame.
    #[inline]
    pub const fn refill_amount(&self) -> u64 {
        self.refill_amount
    }

    /// Sets the refill amount.
    #[inline]
    pub const fn set_refill_amount(&mut self, val: u64) {
        self.refill_amount = val;
    }

    /// Records a refund value.
    #[inline]
    pub const fn record_refund(&mut self, refund: i64) {
        self.refunded += refund;
    }

    /// Erases a gas cost from remaining (returns gas from child frame).
    #[inline]
    pub const fn erase_cost(&mut self, returned: u64) {
        self.remaining += returned;
    }

    /// Spends all remaining gas excluding the reservoir.
    #[inline]
    pub const fn spend_all(&mut self) {
        self.remaining = 0;
    }
}

/// Gas cost for operations that consume zero gas.
pub const ZERO: u64 = 0;
/// Base gas cost for basic operations.
pub const BASE: u64 = 2;

/// Gas cost for very low-cost operations.
pub const VERYLOW: u64 = 3;
/// Gas cost for DATALOADN instruction.
pub const DATA_LOADN_GAS: u64 = 3;

/// Gas cost for conditional jump instructions.
pub const CONDITION_JUMP_GAS: u64 = 4;
/// Gas cost for RETF instruction.
pub const RETF_GAS: u64 = 3;
/// Gas cost for DATALOAD instruction.
pub const DATA_LOAD_GAS: u64 = 4;

/// Gas cost for low-cost operations.
pub const LOW: u64 = 5;
/// Gas cost for medium-cost operations.
pub const MID: u64 = 8;
/// Gas cost for high-cost operations.
pub const HIGH: u64 = 10;
/// Gas cost for JUMPDEST instruction.
pub const JUMPDEST: u64 = 1;
/// Gas cost for REFUND SELFDESTRUCT instruction.
pub const SELFDESTRUCT_REFUND: i64 = 24000;
/// Gas cost for CREATE instruction.
pub const CREATE: u64 = 32000;
/// Additional gas cost when a call transfers value.
pub const CALLVALUE: u64 = 9000;
/// Gas cost for creating a new account.
pub const NEWACCOUNT: u64 = 25000;
/// Base gas cost for EXP instruction.
pub const EXP: u64 = 10;
/// Gas cost per word for memory operations.
pub const MEMORY: u64 = 3;
/// Base gas cost for LOG instructions.
pub const LOG: u64 = 375;
/// Gas cost per byte of data in LOG instructions.
pub const LOGDATA: u64 = 8;
/// Gas cost per topic in LOG instructions.
pub const LOGTOPIC: u64 = 375;
/// Base gas cost for KECCAK256 instruction.
pub const KECCAK256: u64 = 30;
/// Gas cost per word for KECCAK256 instruction.
pub const KECCAK256WORD: u64 = 6;
/// Gas cost per word for copy operations.
pub const COPY: u64 = 3;
/// Gas cost for BLOCKHASH instruction.
pub const BLOCKHASH: u64 = 20;
/// Gas cost per byte for code deposit during contract creation.
pub const CODEDEPOSIT: u64 = 200;

/// EIP-1884: Repricing for trie-size-dependent opcodes
pub const ISTANBUL_SLOAD_GAS: u64 = 800;
/// Gas cost for SSTORE when setting a storage slot from zero to non-zero.
pub const SSTORE_SET: u64 = 20000;
/// Gas cost for SSTORE when modifying an existing non-zero storage slot.
pub const SSTORE_RESET: u64 = 5000;
/// Gas refund for SSTORE when clearing a storage slot (setting to zero).
pub const REFUND_SSTORE_CLEARS: i64 = 15000;

/// The standard cost of calldata token.
pub const STANDARD_TOKEN_COST: u64 = 4;
/// The cost of a non-zero byte in calldata.
pub const NON_ZERO_BYTE_DATA_COST: u64 = 68;
/// The multiplier for a non zero byte in calldata.
pub const NON_ZERO_BYTE_MULTIPLIER: u64 = NON_ZERO_BYTE_DATA_COST / STANDARD_TOKEN_COST;
/// The cost of a non-zero byte in calldata adjusted by [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028).
pub const NON_ZERO_BYTE_DATA_COST_ISTANBUL: u64 = 16;
/// The multiplier for a non zero byte in calldata adjusted by [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028).
pub const NON_ZERO_BYTE_MULTIPLIER_ISTANBUL: u64 =
    NON_ZERO_BYTE_DATA_COST_ISTANBUL / STANDARD_TOKEN_COST;
/// The cost floor per token as defined by [EIP-7623](https://eips.ethereum.org/EIPS/eip-7623).
pub const TOTAL_COST_FLOOR_PER_TOKEN: u64 = 10;

/// Gas cost for EOF CREATE instruction.
pub const EOF_CREATE_GAS: u64 = 32000;

// Berlin EIP-2929/EIP-2930 constants
/// Gas cost for accessing an address in the access list (EIP-2930).
pub const ACCESS_LIST_ADDRESS: u64 = 2400;
/// Gas cost for accessing a storage key in the access list (EIP-2930).
pub const ACCESS_LIST_STORAGE_KEY: u64 = 1900;

/// Gas cost for SLOAD when accessing a cold storage slot (EIP-2929).
pub const COLD_SLOAD_COST: u64 = 2100;
/// Gas cost for accessing a cold account (EIP-2929).
pub const COLD_ACCOUNT_ACCESS_COST: u64 = 2600;
/// Additional gas cost for accessing a cold account.
pub const COLD_ACCOUNT_ACCESS_COST_ADDITIONAL: u64 =
    COLD_ACCOUNT_ACCESS_COST - WARM_STORAGE_READ_COST;
/// Gas cost for reading from a warm storage slot (EIP-2929).
pub const WARM_STORAGE_READ_COST: u64 = 100;
/// Gas cost for SSTORE reset operation on a warm storage slot.
pub const WARM_SSTORE_RESET: u64 = SSTORE_RESET - COLD_SLOAD_COST;

/// EIP-3860 : Limit and meter initcode
pub const INITCODE_WORD_COST: u64 = 2;

/// Gas stipend provided to the recipient of a CALL with value transfer.
pub const CALL_STIPEND: u64 = 2300;

/// Init and floor gas from transaction
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InitialAndFloorGas {
    /// Regular (non-state) portion of the initial intrinsic gas.
    ///
    /// Under EIP-8037, this is the part constrained by `TX_MAX_GAS_LIMIT`;
    /// state gas uses its own reservoir and is not subject to that cap.
    pub initial_regular_gas: u64,
    /// State gas component of the initial intrinsic gas.
    /// Under EIP-8037, this includes:
    /// - EIP-7702 auth list state gas (per-auth account creation + metadata costs)
    /// - For CREATE transactions: `create_state_gas` (account creation + contract metadata)
    /// - For CALL transactions: 0 (state gas is unpredictable at validation time)
    pub initial_state_gas: u64,
    /// EIP-7702 refund for existing authorities.
    /// This is the refund given when an authorization is applied to an already existing account.
    pub state_refund: u64,
    /// If transaction is a Call and Prague is enabled
    /// floor_gas is at least amount of gas that is going to be spent.
    pub floor_gas: u64,
}

impl InitialAndFloorGas {
    /***** Constructors *****/

    /// Create a new InitialAndFloorGas instance.
    #[inline]
    pub const fn new(initial_regular_gas: u64, floor_gas: u64) -> Self {
        Self {
            initial_regular_gas,
            initial_state_gas: 0,
            state_refund: 0,
            floor_gas,
        }
    }

    /// Create a new InitialAndFloorGas instance with state gas tracking.
    #[inline]
    pub const fn new_with_state_gas(
        initial_regular_gas: u64,
        initial_state_gas: u64,
        floor_gas: u64,
    ) -> Self {
        Self {
            initial_regular_gas,
            initial_state_gas,
            state_refund: 0,
            floor_gas,
        }
    }

    /***** Simple getters *****/

    /// Regular (non-state) portion of the initial intrinsic gas.
    ///
    /// Under EIP-8037, this is the part constrained by `TX_MAX_GAS_LIMIT`;
    /// state gas uses its own reservoir and is not subject to that cap.
    #[inline]
    pub const fn initial_regular_gas(&self) -> u64 {
        self.initial_regular_gas
    }

    /// State gas component of the initial intrinsic gas.
    /// This is the state gas component of the initial intrinsic gas minus the EIP-7702 refund.
    #[inline]
    pub const fn initial_state_gas_final(&self) -> u64 {
        self.initial_state_gas - self.state_refund
    }

    /// EIP-7623 floor gas.
    #[inline]
    pub const fn floor_gas(&self) -> u64 {
        self.floor_gas
    }

    /// Total initial intrinsic gas: `initial_regular_gas + initial_state_gas`.
    #[inline]
    pub const fn initial_total_gas(&self) -> u64 {
        self.initial_regular_gas + self.initial_state_gas_final()
    }

    /***** Simple setters *****/

    /// Sets the `initial_regular_gas` field by mutable reference.
    #[inline]
    pub const fn set_initial_regular_gas(&mut self, initial_regular_gas: u64) {
        self.initial_regular_gas = initial_regular_gas;
    }

    /// Sets the `initial_state_gas` field by mutable reference.
    #[inline]
    pub const fn set_initial_state_gas(&mut self, initial_state_gas: u64) {
        self.initial_state_gas = initial_state_gas;
    }

    /// Sets the `floor_gas` field by mutable reference.
    #[inline]
    pub const fn set_floor_gas(&mut self, floor_gas: u64) {
        self.floor_gas = floor_gas;
    }

    /***** Builder with_* methods *****/

    /// Sets the `initial_regular_gas` field.
    #[inline]
    pub const fn with_initial_regular_gas(mut self, initial_regular_gas: u64) -> Self {
        self.initial_regular_gas = initial_regular_gas;
        self
    }

    /// Sets the `initial_state_gas` field.
    #[inline]
    pub const fn with_initial_state_gas(mut self, initial_state_gas: u64) -> Self {
        self.initial_state_gas = initial_state_gas;
        self
    }

    /// Sets the `floor_gas` field.
    #[inline]
    pub const fn with_floor_gas(mut self, floor_gas: u64) -> Self {
        self.floor_gas = floor_gas;
        self
    }

    /// Computes the regular gas budget and reservoir for the initial call frame.
    ///
    /// EIP-8037 reservoir model:
    ///   execution_gas = tx.gas_limit - intrinsic_gas  (= gas_limit parameter)
    ///   regular_gas_budget = min(execution_gas, TX_MAX_GAS_LIMIT - intrinsic_gas)
    ///   reservoir = execution_gas - regular_gas_budget
    ///
    /// Initial state gas is then deducted from the reservoir (spilling into the
    /// regular budget when the reservoir is insufficient), and the EIP-7702
    /// refund for existing authorities is added back to the reservoir.
    ///
    /// On mainnet (state gas disabled), reservoir = 0 and gas_limit is unchanged.
    ///
    /// Returns `(gas_limit, reservoir)`.
    pub fn initial_gas_and_reservoir(
        &self,
        tx_gas_limit: u64,
        tx_gas_limit_cap: u64,
    ) -> (u64, u64) {
        let execution_gas = tx_gas_limit - self.initial_regular_gas();

        // System calls pass InitialAndFloorGas with all zeros and should not be
        // subject to the TX_MAX_GAS_LIMIT cap.
        let tx_gas_limit_cap = if self.initial_total_gas() == 0 {
            u64::MAX
        } else {
            tx_gas_limit_cap
        };

        let mut regular_gas_limit = core::cmp::min(tx_gas_limit, tx_gas_limit_cap)
            .saturating_sub(self.initial_regular_gas());
        let mut reservoir = execution_gas - regular_gas_limit;

        // Deduct initial state gas from the reservoir. When the reservoir is
        // insufficient, the deficit is charged from the regular gas budget.
        if reservoir >= self.initial_state_gas {
            reservoir -= self.initial_state_gas;
        } else {
            regular_gas_limit -= self.initial_state_gas - reservoir;
            reservoir = 0;
        }

        // EIP-7702 state gas refund for existing authorities goes directly to
        // the reservoir. In the Python spec, set_delegation adds this refund to
        // state_gas_reservoir so it stays as state gas (not regular gas).
        reservoir += self.state_refund;

        (regular_gas_limit, reservoir)
    }
}

/// Initial gas that is deducted for transaction to be included.
/// Initial gas contains initial stipend gas, gas for access list and input data.
///
/// # Returns
///
/// - Intrinsic gas
/// - Number of tokens in calldata
pub fn calculate_initial_tx_gas(
    spec_id: SpecId,
    input: &[u8],
    is_create: bool,
    access_list_accounts: u64,
    access_list_storages: u64,
    authorization_list_num: u64,
    cpsb: u64,
) -> InitialAndFloorGas {
    GasParams::new_spec(spec_id).initial_tx_gas(
        input,
        is_create,
        access_list_accounts,
        access_list_storages,
        authorization_list_num,
        cpsb,
    )
}

/// Initial gas that is deducted for transaction to be included.
/// Initial gas contains initial stipend gas, gas for access list and input data.
///
/// # Returns
///
/// - Intrinsic gas
/// - Number of tokens in calldata
pub fn calculate_initial_tx_gas_for_tx(
    tx: impl Transaction,
    spec: SpecId,
    cpsb: u64,
) -> InitialAndFloorGas {
    let mut accounts = 0;
    let mut storages = 0;
    // legacy is only tx type that does not have access list.
    if tx.tx_type() != TransactionType::Legacy {
        (accounts, storages) = tx
            .access_list()
            .map(|al| {
                al.fold((0, 0), |(mut num_accounts, mut num_storage_slots), item| {
                    num_accounts += 1;
                    num_storage_slots += item.storage_slots().count();

                    (num_accounts, num_storage_slots)
                })
            })
            .unwrap_or_default();
    }

    calculate_initial_tx_gas(
        spec,
        tx.input(),
        tx.kind().is_create(),
        accounts as u64,
        storages as u64,
        tx.authorization_list_len() as u64,
        cpsb,
    )
}

/// Retrieve the total number of tokens in calldata.
#[inline]
pub fn get_tokens_in_calldata_istanbul(input: &[u8]) -> u64 {
    get_tokens_in_calldata(input, NON_ZERO_BYTE_MULTIPLIER_ISTANBUL)
}

/// Retrieve the total number of tokens in calldata.
#[inline]
pub fn get_tokens_in_calldata(input: &[u8], non_zero_data_multiplier: u64) -> u64 {
    let zero_data_len = input.iter().filter(|v| **v == 0).count() as u64;
    let non_zero_data_len = input.len() as u64 - zero_data_len;
    zero_data_len + non_zero_data_len * non_zero_data_multiplier
}