aurora-evm 2.2.1

Aurora Ethereum Virtual Machine implementation written in pure Rust
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
563
564
565
566
567
568
569
570
571
572
573
use super::Control;
use crate::core::utils::{U256_ZERO, U64_MAX, USIZE_MAX};
use crate::prelude::*;
use crate::{
    CallScheme, Capture, Context, CreateScheme, ExitError, ExitSucceed, Handler, Runtime, Transfer,
};
use core::cmp::max;
use primitive_types::{H256, U256};
use sha3::{Digest, Keccak256};

pub fn sha3<H: Handler>(runtime: &mut Runtime) -> Control<H> {
    pop_u256!(runtime, from, len);

    // Cast to `usize` after length checking to avoid overflow
    let from = if len == U256_ZERO {
        usize::MAX
    } else {
        as_usize_or_fail!(from)
    };
    let len = as_usize_or_fail!(len);

    try_or_fail!(runtime.machine.memory_mut().resize_offset(from, len));
    let data = if len == 0 {
        Vec::new()
    } else {
        runtime.machine.memory_mut().get(from, len)
    };

    let ret = Keccak256::digest(data.as_slice());
    push_h256!(runtime, H256::from_slice(<[u8; 32]>::from(ret).as_slice()));

    Control::Continue
}

pub fn chainid<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.chain_id());

    Control::Continue
}

pub fn address<H: Handler>(runtime: &mut Runtime) -> Control<H> {
    let ret = H256::from(runtime.context.address);
    push_h256!(runtime, ret);

    Control::Continue
}

pub fn balance<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    pop_h256!(runtime, address);
    push_u256!(runtime, handler.balance(address.into()));

    Control::Continue
}

pub fn selfbalance<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.balance(runtime.context.address));

    Control::Continue
}

pub fn origin<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    let ret = H256::from(handler.origin());
    push_h256!(runtime, ret);

    Control::Continue
}

pub fn caller<H: Handler>(runtime: &mut Runtime) -> Control<H> {
    let ret = H256::from(runtime.context.caller);
    push_h256!(runtime, ret);

    Control::Continue
}

pub fn callvalue<H: Handler>(runtime: &mut Runtime) -> Control<H> {
    let ret = H256(runtime.context.apparent_value.to_big_endian());
    push_h256!(runtime, ret);

    Control::Continue
}

pub fn gasprice<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    let ret = H256(handler.gas_price().to_big_endian());
    push_h256!(runtime, ret);

    Control::Continue
}

pub fn base_fee<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.block_base_fee_per_gas());
    Control::Continue
}

/// CANCUN hard fork
/// EIP-7516: BLOBBASEFEE opcode
pub fn blob_base_fee<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    let blob_base_fee = U256::from(handler.blob_base_fee().unwrap_or_default());
    push_u256!(runtime, blob_base_fee);
    Control::Continue
}

/// CANCUN hard fork
/// EIP-4844: Shard Blob Transactions
/// Logic related to operating with BLOBHASH opcode described:
/// - <https://eips.ethereum.org/EIPS/eip-4844#opcode-to-get-versioned-hashes>
pub fn blob_hash<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    // Peek index from the top of the stack
    let raw_index = match runtime.machine.stack().peek(0) {
        Ok(value) => value,
        Err(e) => return Control::Exit(e.into()),
    };
    // Safely cast to usize
    let index = if raw_index > USIZE_MAX {
        usize::MAX
    } else {
        raw_index.as_usize()
    };
    // Get blob_hash from `tx.blob_versioned_hashes[index]`
    // as described:
    // - https://eips.ethereum.org/EIPS/eip-4844#opcode-to-get-versioned-hashes
    let blob_hash = handler.get_blob_hash(index).unwrap_or(U256_ZERO);
    // Set top stack index with `blob_hash` value
    if let Err(e) = runtime.machine.stack_mut().set(0, blob_hash) {
        return Control::Exit(e.into());
    }
    Control::Continue
}

/// NOTE: For EIP-7702 should return 2 (size of `0xEF01`)
pub fn extcodesize<H: Handler>(runtime: &mut Runtime, handler: &mut H) -> Control<H> {
    pop_h256!(runtime, address);
    push_u256!(runtime, handler.code_size(address.into()));

    Control::Continue
}

/// NOTE: For EIP-7702 should return  `keccak(0xEF01)`
pub fn extcodehash<H: Handler>(runtime: &mut Runtime, handler: &mut H) -> Control<H> {
    pop_h256!(runtime, address);
    push_h256!(runtime, handler.code_hash(address.into()));

    Control::Continue
}

/// NOTE: For EIP-7702 should not copy from designated address
pub fn extcodecopy<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    pop_h256!(runtime, address);
    pop_u256!(runtime, memory_offset, code_offset, len);

    if len == U256_ZERO {
        return Control::Continue;
    }
    let len = as_usize_or_fail!(len);

    // Cast to `usize` after length checking to avoid overflow
    let memory_offset = as_usize_or_fail!(memory_offset);

    try_or_fail!(runtime
        .machine
        .memory_mut()
        .resize_offset(memory_offset, len));
    match runtime.machine.memory_mut().copy_data(
        memory_offset,
        code_offset,
        len,
        &handler.code(address.into()),
    ) {
        Ok(()) => (),
        Err(e) => return Control::Exit(e.into()),
    }

    Control::Continue
}

pub fn returndatasize<H: Handler>(runtime: &mut Runtime) -> Control<H> {
    let size = U256::from(runtime.return_data_buffer.len());
    push_u256!(runtime, size);

    Control::Continue
}

pub fn returndatacopy<H: Handler>(runtime: &mut Runtime) -> Control<H> {
    pop_u256!(runtime, memory_offset, data_offset, len);

    // If `len` is zero then nothing happens to the memory, regardless
    // of the value of `memory_offset`. In particular, the value taken
    // from the stack might be larger than `usize::MAX`, hence why the
    // `as_usize` cast is not always safe. But because the value does
    // not matter when `len == 0` we can safely set it equal to zero instead.
    let memory_offset = if len == U256_ZERO {
        0
    } else {
        // SAFETY: this cast is safe because if `len > 0` then gas cost of memory
        // would have already been taken into account at this point. It is impossible
        // to have a memory offset greater than `usize::MAX` for any gas limit less
        // than `u64::MAX` (and gas limits higher than this are disallowed in general).
        as_usize_or_fail!(memory_offset)
    };
    let len = as_usize_or_fail!(len);

    try_or_fail!(runtime
        .machine
        .memory_mut()
        .resize_offset(memory_offset, len));
    if data_offset
        .checked_add(len.into())
        .is_none_or(|l| l > U256::from(runtime.return_data_buffer.len()))
    {
        return Control::Exit(ExitError::OutOfOffset.into());
    }

    match runtime.machine.memory_mut().copy_data(
        memory_offset,
        data_offset,
        len,
        &runtime.return_data_buffer,
    ) {
        Ok(()) => Control::Continue,
        Err(e) => Control::Exit(e.into()),
    }
}

pub fn blockhash<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    pop_u256!(runtime, number);
    push_h256!(runtime, handler.block_hash(number));

    Control::Continue
}

pub fn coinbase<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_h256!(runtime, handler.block_coinbase());
    Control::Continue
}

pub fn timestamp<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.block_timestamp());
    Control::Continue
}

pub fn number<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.block_number());
    Control::Continue
}

pub fn difficulty<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.block_difficulty());
    Control::Continue
}

pub fn prevrandao<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    if let Some(rand) = handler.block_randomness() {
        push_h256!(runtime, rand);
        Control::Continue
    } else {
        difficulty(runtime, handler)
    }
}

pub fn gaslimit<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.block_gas_limit());
    Control::Continue
}

pub fn sload<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    pop_h256!(runtime, index);
    let value = handler.storage(runtime.context.address, index);
    push_h256!(runtime, value);

    event!(SLoad {
        address: runtime.context.address,
        index,
        value
    });

    Control::Continue
}

pub fn sstore<H: Handler>(runtime: &mut Runtime, handler: &mut H) -> Control<H> {
    pop_h256!(runtime, index, value);

    event!(SStore {
        address: runtime.context.address,
        index,
        value
    });

    match handler.set_storage(runtime.context.address, index, value) {
        Ok(()) => Control::Continue,
        Err(e) => Control::Exit(e.into()),
    }
}

/// EIP-1153: Transient storage opcodes
/// Load value from transient storage
pub fn tload<H: Handler>(runtime: &mut Runtime, handler: &mut H) -> Control<H> {
    // Peek index from the top of the stack
    let index = match runtime.machine.stack().peek(0) {
        Ok(value) => H256(value.to_big_endian()),
        Err(e) => return Control::Exit(e.into()),
    };
    // Load value from transient storage
    let value = match handler.tload(runtime.context.address, index) {
        Ok(value) => value,
        Err(e) => return Control::Exit(e.into()),
    };
    // Set top stack index with `transient` value result
    match runtime.machine.stack_mut().set(0, value) {
        Ok(()) => (),
        Err(e) => return Control::Exit(e.into()),
    }

    Control::Continue
}

/// EIP-1153: Transient storage
/// Store value to transient storage
pub fn tstore<H: Handler>(runtime: &mut Runtime, handler: &mut H) -> Control<H> {
    pop_h256!(runtime, index);
    pop_u256!(runtime, value);
    match handler.tstore(runtime.context.address, index, value) {
        Ok(()) => Control::Continue,
        Err(e) => Control::Exit(e.into()),
    }
}

/// CANCUN hard fork
/// EIP-5656: MCOPY - Memory copying instruction
pub fn mcopy<H: Handler>(runtime: &mut Runtime, _handler: &mut H) -> Control<H> {
    pop_u256!(runtime, dst, src, len);
    if len == U256_ZERO {
        return Control::Continue;
    }
    let len = as_usize_or_fail!(len, ExitError::OutOfGas);
    let dst = as_usize_or_fail!(dst, ExitError::OutOfGas);
    let src = as_usize_or_fail!(src, ExitError::OutOfGas);

    try_or_fail!(runtime
        .machine
        .memory_mut()
        .resize_offset(max(src, dst), len));

    // copy memory
    match runtime.machine.memory_mut().copy(src, dst, len) {
        Ok(()) => (),
        Err(e) => return Control::Exit(e.into()),
    }

    Control::Continue
}

pub fn gas<H: Handler>(runtime: &mut Runtime, handler: &H) -> Control<H> {
    push_u256!(runtime, handler.gas_left());

    Control::Continue
}

pub fn log<H: Handler>(runtime: &mut Runtime, n: u8, handler: &mut H) -> Control<H> {
    pop_u256!(runtime, offset, len);

    // Cast to `usize` after length checking to avoid overflow
    let offset = if len == U256_ZERO {
        usize::MAX
    } else {
        as_usize_or_fail!(offset)
    };
    let len = as_usize_or_fail!(len);

    try_or_fail!(runtime.machine.memory_mut().resize_offset(offset, len));
    let data = if len == 0 {
        Vec::new()
    } else {
        runtime.machine.memory().get(offset, len)
    };

    let mut topics = Vec::new();
    for _ in 0..n {
        match runtime.machine.stack_mut().pop_h256() {
            Ok(value) => {
                topics.push(value);
            }
            Err(e) => return Control::Exit(e.into()),
        }
    }

    match handler.log(runtime.context.address, topics, data) {
        Ok(()) => Control::Continue,
        Err(e) => Control::Exit(e.into()),
    }
}

/// Performances SELFDESTRUCT action.
/// Transfers balance from address to target. Check if target `exist/is_cold`
///
/// Note: balance will be lost if address and target are the same BUT when
/// current spec enables Cancun, this happens only when the account associated to address
/// is created in the same tx
///
/// references:
///  * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/vm/instructions.go#L832-L833>
///  * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/state/statedb.go#L449>
///  * <https://eips.ethereum.org/EIPS/eip-6780>
pub fn selfdestruct<H: Handler>(runtime: &mut Runtime, handler: &mut H) -> Control<H> {
    pop_h256!(runtime, target);

    match handler.mark_delete(runtime.context.address, target.into()) {
        Ok(()) => (),
        Err(e) => return Control::Exit(e.into()),
    }

    Control::Exit(ExitSucceed::Suicided.into())
}

pub fn create<H: Handler>(runtime: &mut Runtime, is_create2: bool, handler: &mut H) -> Control<H> {
    runtime.return_data_buffer = Vec::new();

    pop_u256!(runtime, value, code_offset, len);

    // Cast to `usize` after length checking to avoid overflow
    let code_offset = if len == U256_ZERO {
        usize::MAX
    } else {
        as_usize_or_fail!(code_offset)
    };
    let len = as_usize_or_fail!(len);

    try_or_fail!(runtime.machine.memory_mut().resize_offset(code_offset, len));
    let code = if len == 0 {
        Vec::new()
    } else {
        runtime.machine.memory().get(code_offset, len)
    };

    let scheme = if is_create2 {
        pop_h256!(runtime, salt);
        let code_hash = H256::from_slice(<[u8; 32]>::from(Keccak256::digest(&code)).as_slice());
        CreateScheme::Create2 {
            caller: runtime.context.address,
            salt,
            code_hash,
        }
    } else {
        CreateScheme::Legacy {
            caller: runtime.context.address,
        }
    };

    match handler.create(runtime.context.address, scheme, value, code, None) {
        Capture::Exit((reason, return_data)) => {
            // The `Capture::Exit` case used to always have `address: None` because it was only returned when
            // the call to `create_inner` encountered an error and therefore no contract was created. The happy
            // path is returning `Capture::Trap` and `finish_create` ends up being called later
            // with the created address as part of the EVM call stack handling logic.
            // And it means that the `Capture::Exit` case only happens if there was an error - `ExitError`.
            debug_assert!(
                reason.is_error(),
                "ExitReason for finish_create should be only ExitError"
            );
            match super::finish_create(runtime, reason, None, return_data) {
                Ok(()) => Control::Continue,
                Err(e) => Control::Exit(e),
            }
        }
        Capture::Trap(interrupt) => Control::CreateInterrupt(interrupt),
    }
}

pub fn call<H: Handler>(runtime: &mut Runtime, scheme: CallScheme, handler: &mut H) -> Control<H> {
    runtime.return_data_buffer = Vec::new();

    pop_u256!(runtime, gas);
    pop_h256!(runtime, to);
    let gas = if gas > U64_MAX {
        None
    } else {
        Some(gas.as_u64())
    };

    let value = match scheme {
        CallScheme::Call | CallScheme::CallCode => {
            pop_u256!(runtime, value);
            value
        }
        CallScheme::DelegateCall | CallScheme::StaticCall => U256_ZERO,
    };

    pop_u256!(runtime, in_offset, in_len);
    pop_u256!(runtime, out_offset, out_len);

    // Cast to `usize` after length checking to avoid overflow
    let in_offset = if in_len == U256_ZERO {
        usize::MAX
    } else {
        as_usize_or_fail!(in_offset)
    };
    let in_len = as_usize_or_fail!(in_len);
    // Cast to `usize` after length checking to avoid overflow
    let out_offset = if out_len == U256_ZERO {
        usize::MAX
    } else {
        as_usize_or_fail!(out_offset)
    };
    let out_len = as_usize_or_fail!(out_len);

    try_or_fail!(runtime
        .machine
        .memory_mut()
        .resize_offset(in_offset, in_len));
    try_or_fail!(runtime
        .machine
        .memory_mut()
        .resize_offset(out_offset, out_len));

    let input = if in_len == 0 {
        Vec::new()
    } else {
        runtime.machine.memory().get(in_offset, in_len)
    };

    let context = match scheme {
        CallScheme::Call | CallScheme::StaticCall => Context {
            address: to.into(),
            caller: runtime.context.address,
            apparent_value: value,
        },
        CallScheme::CallCode => Context {
            address: runtime.context.address,
            caller: runtime.context.address,
            apparent_value: value,
        },
        CallScheme::DelegateCall => Context {
            address: runtime.context.address,
            caller: runtime.context.caller,
            apparent_value: runtime.context.apparent_value,
        },
    };

    let transfer = if scheme == CallScheme::Call {
        Some(Transfer {
            source: runtime.context.address,
            target: to.into(),
            value,
        })
    } else if scheme == CallScheme::CallCode {
        Some(Transfer {
            source: runtime.context.address,
            target: runtime.context.address,
            value,
        })
    } else {
        None
    };

    match handler.call(
        to.into(),
        transfer,
        input,
        gas,
        scheme == CallScheme::StaticCall,
        context,
    ) {
        Capture::Exit((reason, return_data)) => {
            match super::finish_call(runtime, out_len, out_offset, reason, return_data) {
                Ok(()) => Control::Continue,
                Err(e) => Control::Exit(e),
            }
        }
        Capture::Trap(interrupt) => {
            runtime.return_data_len = out_len;
            runtime.return_data_offset = out_offset;
            Control::CallInterrupt(interrupt)
        }
    }
}