revm-context-interface 17.0.1

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
//! Journaled state trait [`JournalTr`] and related types.

pub mod account;
pub mod entry;

use crate::{
    context::{SStoreResult, SelfDestructResult},
    host::LoadError,
    journaled_state::account::JournaledAccountTr,
    ErasedError,
};
use core::ops::{Deref, DerefMut};
use database_interface::Database;
use primitives::{
    hardfork::SpecId, Address, AddressMap, AddressSet, Bytes, HashSet, Log, StorageKey,
    StorageValue, B256, U256,
};
use state::{Account, AccountInfo, Bytecode};
use std::{borrow::Cow, vec::Vec};
/// Trait that contains database and journal of all changes that were made to the state.
pub trait JournalTr {
    /// Database type that is used in the journal.
    type Database: Database;
    /// State type that is returned by the journal after finalization.
    type State;
    /// Journal account allows modification of account with all needed changes.
    type JournaledAccount<'a>: JournaledAccountTr
    where
        Self: 'a;

    /// Creates new Journaled state.
    ///
    /// Dont forget to set spec_id.
    fn new(database: Self::Database) -> Self;

    /// Returns a mutable reference to the database.
    fn db_mut(&mut self) -> &mut Self::Database;

    /// Returns an immutable reference to the database.
    fn db(&self) -> &Self::Database;

    /// Returns the storage value from Journal state.
    ///
    /// Loads the storage from database if not found in Journal state.
    fn sload(
        &mut self,
        address: Address,
        key: StorageKey,
    ) -> Result<StateLoad<StorageValue>, <Self::Database as Database>::Error> {
        // unwrapping is safe as we only can get DBError
        self.sload_skip_cold_load(address, key, false)
            .map_err(JournalLoadError::unwrap_db_error)
    }

    /// Loads the storage value from Journal state.
    fn sload_skip_cold_load(
        &mut self,
        _address: Address,
        _key: StorageKey,
        _skip_cold_load: bool,
    ) -> Result<StateLoad<StorageValue>, JournalLoadError<<Self::Database as Database>::Error>>;

    /// Stores the storage value in Journal state.
    fn sstore(
        &mut self,
        address: Address,
        key: StorageKey,
        value: StorageValue,
    ) -> Result<StateLoad<SStoreResult>, <Self::Database as Database>::Error> {
        // unwrapping is safe as we only can get DBError
        self.sstore_skip_cold_load(address, key, value, false)
            .map_err(JournalLoadError::unwrap_db_error)
    }

    /// Stores the storage value in Journal state.
    fn sstore_skip_cold_load(
        &mut self,
        _address: Address,
        _key: StorageKey,
        _value: StorageValue,
        _skip_cold_load: bool,
    ) -> Result<StateLoad<SStoreResult>, JournalLoadError<<Self::Database as Database>::Error>>;

    /// Loads transient storage value.
    fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue;

    /// Stores transient storage value.
    fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue);

    /// Logs the log in Journal state.
    fn log(&mut self, log: Log);

    /// Take logs from journal.
    fn take_logs(&mut self) -> Vec<Log>;

    /// Returns the logs from journal.
    fn logs(&self) -> &[Log];

    /// Marks the account for selfdestruction and transfers all the balance to the target.
    fn selfdestruct(
        &mut self,
        address: Address,
        target: Address,
        skip_cold_load: bool,
    ) -> Result<StateLoad<SelfDestructResult>, JournalLoadError<<Self::Database as Database>::Error>>;

    /// Sets access list inside journal.
    fn warm_access_list(&mut self, access_list: AddressMap<HashSet<StorageKey>>);

    /// Warms the coinbase account.
    fn warm_coinbase_account(&mut self, address: Address);

    /// Warms the precompiles.
    fn warm_precompiles(&mut self, addresses: AddressSet);

    /// Returns the addresses of the precompiles.
    fn precompile_addresses(&self) -> &AddressSet;

    /// Sets the spec id.
    fn set_spec_id(&mut self, spec_id: SpecId);

    /// Sets EIP-7708 configuration flags.
    ///
    /// - `disabled`: Whether EIP-7708 (ETH transfers emit logs) is completely disabled.
    /// - `delayed_burn_disabled`: Whether delayed burn logging is disabled. When enabled,
    ///   revm tracks all self-destructed addresses and emits logs for accounts that still
    ///   have remaining balance at the end of the transaction. This can be disabled for
    ///   performance reasons as it requires storing and iterating over all self-destructed
    ///   accounts. When disabled, the logging can be done outside of revm when applying
    ///   accounts to database state.
    fn set_eip7708_config(&mut self, disabled: bool, delayed_burn_disabled: bool);

    /// Touches the account.
    fn touch_account(&mut self, address: Address);

    /// Transfers the balance from one account to another.
    fn transfer(
        &mut self,
        from: Address,
        to: Address,
        balance: U256,
    ) -> Result<Option<TransferError>, <Self::Database as Database>::Error>;

    /// Transfers the balance from one account to another. Assume form and to are loaded.
    fn transfer_loaded(
        &mut self,
        from: Address,
        to: Address,
        balance: U256,
    ) -> Option<TransferError>;

    /// Increments the balance of the account.
    #[deprecated]
    fn caller_accounting_journal_entry(
        &mut self,
        address: Address,
        old_balance: U256,
        bump_nonce: bool,
    );

    /// Increments the balance of the account.
    fn balance_incr(
        &mut self,
        address: Address,
        balance: U256,
    ) -> Result<(), <Self::Database as Database>::Error>;

    /// Increments the nonce of the account.
    #[deprecated]
    fn nonce_bump_journal_entry(&mut self, address: Address);

    /// Loads the account.
    fn load_account(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<&Account>, <Self::Database as Database>::Error>;

    /// Loads the account code, use `load_account_with_code` instead.
    #[inline]
    #[deprecated(note = "Use `load_account_with_code` instead")]
    fn load_account_code(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<&Account>, <Self::Database as Database>::Error> {
        self.load_account_with_code(address)
    }

    /// Loads the account with code.
    fn load_account_with_code(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<&Account>, <Self::Database as Database>::Error>;

    /// Loads the account delegated.
    fn load_account_delegated(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<AccountLoad>, <Self::Database as Database>::Error>;

    /// Loads the journaled account.
    #[inline]
    fn load_account_mut(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<Self::JournaledAccount<'_>>, <Self::Database as Database>::Error> {
        self.load_account_mut_skip_cold_load(address, false)
            .map_err(JournalLoadError::unwrap_db_error)
    }

    /// Loads the journaled account.
    fn load_account_mut_skip_cold_load(
        &mut self,
        address: Address,
        skip_cold_load: bool,
    ) -> Result<
        StateLoad<Self::JournaledAccount<'_>>,
        JournalLoadError<<Self::Database as Database>::Error>,
    >;

    /// Loads the journaled account.
    #[inline]
    fn load_account_with_code_mut(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<Self::JournaledAccount<'_>>, <Self::Database as Database>::Error> {
        self.load_account_mut_optional_code(address, true)
    }

    /// Loads the journaled account.
    fn load_account_mut_optional_code(
        &mut self,
        address: Address,
        load_code: bool,
    ) -> Result<StateLoad<Self::JournaledAccount<'_>>, <Self::Database as Database>::Error>;

    /// Sets bytecode with hash. Assume that account is warm.
    fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256);

    /// Sets bytecode and calculates hash.
    ///
    /// Assume account is warm.
    #[inline]
    fn set_code(&mut self, address: Address, code: Bytecode) {
        let hash = code.hash_slow();
        self.set_code_with_hash(address, code, hash);
    }

    /// Returns account code bytes and if address is cold loaded.
    #[inline]
    fn code(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<Bytes>, <Self::Database as Database>::Error> {
        let a = self.load_account_with_code(address)?;
        // SAFETY: Safe to unwrap as load_code will insert code if it is empty.
        let code = a.info.code.as_ref().unwrap().original_bytes();

        Ok(StateLoad::new(code, a.is_cold))
    }

    /// Gets code hash of account.
    fn code_hash(
        &mut self,
        address: Address,
    ) -> Result<StateLoad<B256>, <Self::Database as Database>::Error> {
        let acc = self.load_account_with_code(address)?;
        if acc.is_empty() {
            return Ok(StateLoad::new(B256::ZERO, acc.is_cold));
        }
        let hash = acc.info.code_hash;
        Ok(StateLoad::new(hash, acc.is_cold))
    }

    /// Called at the end of the transaction to clean all residue data from journal.
    fn clear(&mut self) {
        let _ = self.finalize();
    }

    /// Creates a checkpoint of the current state. State can be revert to this point
    /// if needed.
    fn checkpoint(&mut self) -> JournalCheckpoint;

    /// Commits the changes made since the last checkpoint.
    fn checkpoint_commit(&mut self);

    /// Reverts the changes made since the last checkpoint.
    fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint);

    /// Creates a checkpoint of the account creation.
    fn create_account_checkpoint(
        &mut self,
        caller: Address,
        address: Address,
        balance: U256,
        spec_id: SpecId,
    ) -> Result<JournalCheckpoint, TransferError>;

    /// Returns the depth of the journal.
    fn depth(&self) -> usize;

    /// Commit current transaction journal and returns transaction logs.
    fn commit_tx(&mut self);

    /// Discard current transaction journal by removing journal entries and logs and incrementing the transaction id.
    ///
    /// This function is useful to discard intermediate state that is interrupted by error and it will not revert
    /// any already committed changes and it is safe to call it multiple times.
    fn discard_tx(&mut self);

    /// Clear current journal resetting it to initial state and return changes state.
    fn finalize(&mut self) -> Self::State;

    /// Loads the account info from Journal state.
    fn load_account_info_skip_cold_load(
        &mut self,
        _address: Address,
        _load_code: bool,
        _skip_cold_load: bool,
    ) -> Result<AccountInfoLoad<'_>, JournalLoadError<<Self::Database as Database>::Error>>;
}

/// Error that can happen when loading account info.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum JournalLoadError<E> {
    /// Database error.
    DBError(E),
    /// Cold load skipped.
    ColdLoadSkipped,
}

/// Journal error on loading of storage or account with Boxed Database error.
pub type JournalLoadErasedError = JournalLoadError<ErasedError>;

impl<E> JournalLoadError<E> {
    /// Returns true if the error is a database error.
    #[inline]
    pub fn is_db_error(&self) -> bool {
        matches!(self, JournalLoadError::DBError(_))
    }

    /// Returns true if the error is a cold load skipped.
    #[inline]
    pub fn is_cold_load_skipped(&self) -> bool {
        matches!(self, JournalLoadError::ColdLoadSkipped)
    }

    /// Takes the error if it is a database error.
    #[inline]
    pub fn take_db_error(self) -> Option<E> {
        if let JournalLoadError::DBError(e) = self {
            Some(e)
        } else {
            None
        }
    }

    /// Unwraps the error if it is a database error.
    #[inline]
    pub fn unwrap_db_error(self) -> E {
        if let JournalLoadError::DBError(e) = self {
            e
        } else {
            panic!("Expected DBError");
        }
    }

    /// Converts the error to a load error.
    #[inline]
    pub fn into_parts(self) -> (LoadError, Option<E>) {
        match self {
            JournalLoadError::DBError(e) => (LoadError::DBError, Some(e)),
            JournalLoadError::ColdLoadSkipped => (LoadError::ColdLoadSkipped, None),
        }
    }

    /// Maps the database error to a new error.
    #[inline]
    pub fn map<B, F>(self, f: F) -> JournalLoadError<B>
    where
        F: FnOnce(E) -> B,
    {
        match self {
            JournalLoadError::DBError(e) => JournalLoadError::DBError(f(e)),
            JournalLoadError::ColdLoadSkipped => JournalLoadError::ColdLoadSkipped,
        }
    }
}

impl<E> From<E> for JournalLoadError<E> {
    fn from(e: E) -> Self {
        JournalLoadError::DBError(e)
    }
}

impl<E> From<JournalLoadError<E>> for LoadError {
    fn from(e: JournalLoadError<E>) -> Self {
        match e {
            JournalLoadError::DBError(_) => LoadError::DBError,
            JournalLoadError::ColdLoadSkipped => LoadError::ColdLoadSkipped,
        }
    }
}

/// Transfer and creation result
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TransferError {
    /// Caller does not have enough funds
    OutOfFunds,
    /// Overflow in target account
    OverflowPayment,
    /// Create collision.
    CreateCollision,
}

/// SubRoutine checkpoint that will help us to go back from this
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct JournalCheckpoint {
    /// Checkpoint to where on revert we will go back to.
    pub log_i: usize,
    /// Checkpoint to where on revert we will go back to and revert other journal entries.
    pub journal_i: usize,
    /// Checkpoint for self-destructed addresses tracking (EIP-7708).
    pub selfdestructed_i: usize,
}

/// State load information that contains the data and if the account or storage is cold loaded
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StateLoad<T> {
    /// Returned data
    pub data: T,
    /// Is account is cold loaded
    pub is_cold: bool,
}

impl<T> Deref for StateLoad<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<T> DerefMut for StateLoad<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

impl<T> StateLoad<T> {
    /// Returns a new [`StateLoad`] with the given data and cold load status.
    #[inline]
    pub fn new(data: T, is_cold: bool) -> Self {
        Self { data, is_cold }
    }

    /// Maps the data of the [`StateLoad`] to a new value.
    ///
    /// Useful for transforming the data of the [`StateLoad`] without changing the cold load status.
    #[inline]
    pub fn map<B, F>(self, f: F) -> StateLoad<B>
    where
        F: FnOnce(T) -> B,
    {
        StateLoad::new(f(self.data), self.is_cold)
    }
}

/// Result of the account load from Journal state
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountLoad {
    /// Does account have delegate code and delegated account is cold loaded
    pub is_delegate_account_cold: Option<bool>,
    /// Is account empty, if `true` account is not created
    pub is_empty: bool,
}

/// Result of the account load from Journal state
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountInfoLoad<'a> {
    /// Account info
    pub account: Cow<'a, AccountInfo>,
    /// Is account cold loaded
    pub is_cold: bool,
    /// Is account empty, if `true` account is not created
    pub is_empty: bool,
}

impl<'a> AccountInfoLoad<'a> {
    /// Creates new [`AccountInfoLoad`] with the given account info, cold load status and empty status.
    #[inline]
    pub fn new(account: &'a AccountInfo, is_cold: bool, is_empty: bool) -> Self {
        Self {
            account: Cow::Borrowed(account),
            is_cold,
            is_empty,
        }
    }

    /// Maps the account info of the [`AccountInfoLoad`] to a new [`StateLoad`].
    ///
    /// Useful for transforming the account info of the [`AccountInfoLoad`] and preserving the cold load status.
    #[inline]
    pub fn into_state_load<F, O>(self, f: F) -> StateLoad<O>
    where
        F: FnOnce(Cow<'a, AccountInfo>) -> O,
    {
        StateLoad::new(f(self.account), self.is_cold)
    }
}

impl<'a> Deref for AccountInfoLoad<'a> {
    type Target = AccountInfo;

    fn deref(&self) -> &Self::Target {
        &self.account
    }
}