1use crate::{
2 account::LevmAccount,
3 constants::STACK_LIMIT,
4 errors::{ExceptionalHalt, InternalError, VMError},
5 memory::{CallData, Memory},
6 utils::restore_cache_state,
7 vm::VM,
8};
9use bytes::Bytes;
10use ethrex_common::seeded_hash::SeededHashMap;
11use ethrex_common::types::block_access_list::BlockAccessListCheckpoint;
12use ethrex_common::{Address, H256, U256, types::Code};
13use std::{
14 fmt,
15 hash::{Hash, Hasher},
16 hint::assert_unchecked,
17};
18
19const U64_PER_U256: usize = U256::MAX.0.len();
21
22#[derive(Clone, PartialEq, Eq)]
23pub struct Stack {
34 pub values: Box<[U256; STACK_LIMIT]>,
35 pub offset: usize,
36}
37
38impl Stack {
39 #[inline]
40 pub fn pop<const N: usize>(&mut self) -> Result<&[U256; N], ExceptionalHalt> {
41 const {
43 assert!(N <= STACK_LIMIT);
44 }
45
46 let next_offset = self.offset.wrapping_add(N);
49
50 #[expect(unsafe_code)]
54 let values = unsafe {
55 self.values
56 .get_unchecked(self.offset..)
57 .first_chunk::<N>()
58 .ok_or(ExceptionalHalt::StackUnderflow)?
59 };
60 self.offset = next_offset;
62
63 Ok(values)
64 }
65
66 #[inline]
67 pub fn pop1(&mut self) -> Result<U256, ExceptionalHalt> {
68 let value = *self
69 .values
70 .get(self.offset)
71 .ok_or(ExceptionalHalt::StackUnderflow)?;
72 self.offset = self.offset.wrapping_add(1);
75
76 Ok(value)
77 }
78
79 #[inline]
84 pub fn top_mut(&mut self) -> Result<&mut U256, ExceptionalHalt> {
85 self.values
86 .get_mut(self.offset)
87 .ok_or(ExceptionalHalt::StackUnderflow)
88 }
89
90 #[expect(unsafe_code, reason = "top validated by caller; depth unchanged")]
97 #[inline]
98 pub unsafe fn set_top_unchecked(&mut self, value: U256) {
99 unsafe {
100 *self.values.get_unchecked_mut(self.offset) = value;
101 }
102 }
103
104 #[inline]
113 pub fn pop1_and_top_mut(&mut self) -> Result<(&U256, &mut U256), ExceptionalHalt> {
114 let new_top = self.offset.wrapping_add(1);
115 if new_top >= self.values.len() {
116 return Err(ExceptionalHalt::StackUnderflow);
117 }
118 self.offset = new_top;
119 let (popped, rest) = self.values.split_at_mut(new_top);
120 match (popped.last(), rest.first_mut()) {
121 (Some(a), Some(b)) => Ok((a, b)),
122 _ => Err(ExceptionalHalt::StackUnderflow),
124 }
125 }
126
127 #[inline]
129 pub fn push(&mut self, value: U256) -> Result<(), ExceptionalHalt> {
130 let next_offset = self
133 .offset
134 .checked_sub(1)
135 .ok_or(ExceptionalHalt::StackOverflow)?;
136
137 #[expect(unsafe_code, reason = "next_offset == self.offset - 1 >= 0")]
144 unsafe {
145 let slot = self.values.get_unchecked_mut(next_offset);
146 slot.0[0] = value.0[0];
147 slot.0[1] = value.0[1];
148 slot.0[2] = value.0[2];
149 slot.0[3] = value.0[3];
150 }
151 self.offset = next_offset;
152
153 Ok(())
154 }
155
156 #[inline]
157 pub fn push_zero(&mut self) -> Result<(), ExceptionalHalt> {
158 let next_offset = self
161 .offset
162 .checked_sub(1)
163 .ok_or(ExceptionalHalt::StackOverflow)?;
164
165 #[expect(unsafe_code, reason = "next_offset == self.offset - 1 >= 0")]
168 unsafe {
169 *self
170 .values
171 .get_unchecked_mut(next_offset)
172 .0
173 .as_mut_ptr()
174 .cast() = [0u64; U64_PER_U256];
175 }
176 self.offset = next_offset;
177
178 Ok(())
179 }
180
181 pub fn len(&self) -> usize {
182 #[expect(clippy::arithmetic_side_effects)]
185 {
186 self.values.len() - self.offset
187 }
188 }
189
190 pub fn is_empty(&self) -> bool {
191 self.offset == self.values.len()
192 }
193
194 #[inline(always)]
195 pub fn swap<const N: usize>(&mut self) -> Result<(), ExceptionalHalt> {
196 const {
199 assert!(STACK_LIMIT.checked_add(N).is_some());
200 }
201 #[expect(clippy::arithmetic_side_effects)]
202 let index = self.offset + N;
203
204 if index >= self.values.len() {
205 return Err(ExceptionalHalt::StackUnderflow);
206 }
207
208 #[expect(unsafe_code, reason = "self.offset always < STACK_LIMIT")]
209 unsafe {
210 assert_unchecked(self.offset < STACK_LIMIT)
211 };
212
213 self.values.swap(self.offset, index);
214 Ok(())
215 }
216
217 pub fn clear(&mut self) {
218 self.offset = STACK_LIMIT;
219 }
220
221 #[inline]
223 pub fn dup<const N: usize>(&mut self) -> Result<(), ExceptionalHalt> {
224 const {
227 assert!(STACK_LIMIT.checked_add(N).is_some());
228 }
229 #[expect(clippy::arithmetic_side_effects)]
230 let index = self.offset + N;
231 if index >= self.values.len() {
232 return Err(ExceptionalHalt::StackUnderflow);
233 }
234
235 self.offset = self
236 .offset
237 .checked_sub(1)
238 .ok_or(ExceptionalHalt::StackOverflow)?;
239
240 #[expect(unsafe_code, reason = "index < size, offset-1 >= 0")]
241 unsafe {
242 std::ptr::copy_nonoverlapping(
243 self.values.get_unchecked_mut(index).0.as_mut_ptr(),
244 self.values.get_unchecked_mut(self.offset).0.as_mut_ptr(),
245 U64_PER_U256,
246 );
247 }
248 Ok(())
249 }
250}
251
252impl Default for Stack {
253 fn default() -> Self {
254 Self {
255 values: Box::new([U256::zero(); STACK_LIMIT]),
256 offset: STACK_LIMIT,
257 }
258 }
259}
260
261impl fmt::Debug for Stack {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 struct StackValues<'a>(&'a [U256]);
264
265 impl fmt::Debug for StackValues<'_> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 f.debug_list().entries(self.0.iter().rev()).finish()
268 }
269 }
270
271 #[expect(clippy::indexing_slicing)]
272 f.debug_tuple("Stack")
273 .field(&StackValues(&self.values[self.offset..]))
274 .finish()
275 }
276}
277
278impl Hash for Stack {
279 #[expect(
280 clippy::indexing_slicing,
281 reason = "offset is always within bounds of values"
282 )]
283 fn hash<H: Hasher>(&self, state: &mut H) {
284 self.values[self.offset..].hash(state);
285 }
286}
287
288#[derive(Debug)]
289pub struct CallFrame {
294 pub gas_limit: u64,
296 pub gas_remaining: i64,
302 pub pc: usize,
304 pub msg_sender: Address,
306 pub to: Address,
308 pub code_address: Address,
310 pub bytecode: Code,
314 pub msg_value: U256,
316 pub stack: Stack,
317 pub memory: Memory,
318 pub calldata: CallData,
320 pub output: Bytes,
322 pub sub_return_data: Bytes,
324 pub is_static: bool,
326 pub depth: usize,
328 pub is_create: bool,
330 pub call_frame_backup: CallFrameBackup,
332 pub ret_offset: usize,
334 pub ret_size: usize,
336 pub should_transfer_value: bool,
338 pub state_gas_used_at_entry: i64,
341 pub frame_state_gas_spilled: u64,
344 pub target_alive: bool,
349 pub new_account_state_gas_charged: bool,
353}
354
355#[derive(Debug, Clone, Eq, PartialEq, Default)]
356pub struct CallFrameBackup {
357 pub original_accounts_info: SeededHashMap<Address, LevmAccount>,
360 pub original_account_storage_slots: SeededHashMap<Address, SeededHashMap<H256, U256>>,
361 pub bal_checkpoint: Option<BlockAccessListCheckpoint>,
364 pub inserted_code_hashes: Vec<H256>,
370}
371
372impl CallFrameBackup {
373 pub fn backup_account_info(
374 &mut self,
375 address: Address,
376 account: &LevmAccount,
377 ) -> Result<(), InternalError> {
378 self.original_accounts_info
379 .entry(address)
380 .or_insert_with(|| LevmAccount {
381 info: account.info.clone(),
382 storage: Default::default(),
383 status: account.status.clone(),
384 has_storage: account.has_storage,
385 exists: account.exists,
386 });
387
388 Ok(())
389 }
390
391 pub fn clear(&mut self) {
392 self.original_accounts_info.clear();
393 self.original_account_storage_slots.clear();
394 self.bal_checkpoint = None;
395 self.inserted_code_hashes.clear();
396 }
397
398 pub fn extend(&mut self, other: CallFrameBackup) {
403 for (address, other_storage) in other.original_account_storage_slots {
406 self.original_account_storage_slots
407 .entry(address)
408 .or_default()
409 .extend(other_storage);
410 }
411 self.original_accounts_info
412 .extend(other.original_accounts_info);
413 self.inserted_code_hashes.extend(other.inserted_code_hashes);
414 }
416
417 pub fn absorb(&mut self, other: &CallFrameBackup) {
426 for (address, account) in other.original_accounts_info.iter() {
427 self.original_accounts_info
428 .entry(*address)
429 .or_insert_with(|| account.clone());
430 }
431 for (address, storage) in other.original_account_storage_slots.iter() {
432 let slot = self
433 .original_account_storage_slots
434 .entry(*address)
435 .or_default();
436 for (key, value) in storage.iter() {
437 slot.entry(*key).or_insert(*value);
438 }
439 }
440 }
441}
442
443impl CallFrame {
444 #[expect(
445 clippy::too_many_arguments,
446 reason = "inlined constructor, many args needed for performance"
447 )]
448 #[inline(always)]
451 pub fn new(
452 msg_sender: Address,
453 to: Address,
454 code_address: Address,
455 bytecode: Code,
456 msg_value: U256,
457 calldata: CallData,
458 is_static: bool,
459 gas_limit: u64,
460 depth: usize,
461 should_transfer_value: bool,
462 is_create: bool,
463 ret_offset: usize,
464 ret_size: usize,
465 stack: Stack,
466 memory: Memory,
467 ) -> Self {
468 #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
471 Self {
472 gas_limit,
473 gas_remaining: gas_limit as i64,
474 msg_sender,
475 to,
476 code_address,
477 bytecode,
478 msg_value,
479 calldata,
480 is_static,
481 depth,
482 should_transfer_value,
483 is_create,
484 ret_offset,
485 ret_size,
486 stack,
487 memory,
488 call_frame_backup: CallFrameBackup::default(),
489 output: Bytes::default(),
490 pc: 0,
491 sub_return_data: Bytes::default(),
492 state_gas_used_at_entry: 0,
493 frame_state_gas_spilled: 0,
494 target_alive: false,
495 new_account_state_gas_charged: false,
496 }
497 }
498
499 #[inline(always)]
500 pub fn next_opcode(&self) -> u8 {
501 #[expect(unsafe_code, reason = "pc bounded by padded bytecode len")]
506 unsafe {
507 *self.bytecode.dispatch_buf().get_unchecked(self.pc)
508 }
509 }
510
511 pub fn pc(&self) -> usize {
512 self.pc
513 }
514
515 #[inline(always)]
517 #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
518 #[expect(clippy::arithmetic_side_effects, reason = "arithmethic checked")]
519 pub fn increase_consumed_gas(&mut self, gas: u64) -> Result<(), ExceptionalHalt> {
520 self.gas_remaining -= gas as i64;
521
522 if self.gas_remaining < 0 {
523 return Err(ExceptionalHalt::OutOfGas);
524 }
525
526 Ok(())
527 }
528
529 #[inline(always)]
531 #[expect(clippy::as_conversions, reason = "remaining gas conversion")]
532 pub fn check_gas(&self, gas: u64) -> Result<(), ExceptionalHalt> {
533 if self.gas_remaining < 0 || (self.gas_remaining as u64) < gas {
534 return Err(ExceptionalHalt::OutOfGas);
535 }
536 Ok(())
537 }
538
539 pub fn set_code(&mut self, code: Code) -> Result<(), VMError> {
540 self.bytecode = code;
541 Ok(())
542 }
543}
544
545impl<'a> VM<'a> {
546 #[inline(always)]
548 pub fn add_callframe(&mut self, new_call_frame: CallFrame) {
549 if self.call_frames.is_empty() {
553 self.call_frames.reserve(8);
554 }
555 self.call_frames.push(new_call_frame);
556 #[allow(unsafe_code, reason = "just pushed, so the vec is not empty")]
557 unsafe {
558 std::mem::swap(
559 &mut self.current_call_frame,
560 self.call_frames.last_mut().unwrap_unchecked(),
561 );
562 }
563 }
564
565 #[inline(always)]
566 pub fn pop_call_frame(&mut self) -> Result<CallFrame, InternalError> {
567 let mut new = self.call_frames.pop().ok_or(InternalError::CallFrame)?;
568
569 std::mem::swap(&mut new, &mut self.current_call_frame);
570
571 Ok(new)
572 }
573
574 pub fn is_initial_call_frame(&self) -> bool {
575 self.call_frames.is_empty()
576 }
577
578 pub fn restore_cache_state(&mut self) -> Result<(), VMError> {
580 let callframe_backup = self.current_call_frame.call_frame_backup.clone();
581 restore_cache_state(self.db, callframe_backup)
582 }
583
584 pub fn restore_cache_state_consuming(&mut self) -> Result<(), VMError> {
593 let callframe_backup = std::mem::take(&mut self.current_call_frame.call_frame_backup);
594 restore_cache_state(self.db, callframe_backup)
595 }
596
597 pub fn merge_call_frame_backup_with_parent(
602 &mut self,
603 child_call_frame_backup: &CallFrameBackup,
604 ) -> Result<(), VMError> {
605 let parent_backup_accounts = &mut self
606 .current_call_frame
607 .call_frame_backup
608 .original_accounts_info;
609 for (address, account) in child_call_frame_backup.original_accounts_info.iter() {
610 if parent_backup_accounts.get(address).is_none() {
611 parent_backup_accounts.insert(*address, account.clone());
612 }
613 }
614
615 let parent_backup_storage = &mut self
616 .current_call_frame
617 .call_frame_backup
618 .original_account_storage_slots;
619 for (address, storage) in child_call_frame_backup
620 .original_account_storage_slots
621 .iter()
622 {
623 let parent_storage = parent_backup_storage.entry(*address).or_default();
624 for (key, value) in storage {
625 if parent_storage.get(key).is_none() {
626 parent_storage.insert(*key, *value);
627 }
628 }
629 }
630
631 self.current_call_frame
634 .call_frame_backup
635 .inserted_code_hashes
636 .extend(child_call_frame_backup.inserted_code_hashes.iter().copied());
637
638 Ok(())
639 }
640
641 #[inline(always)]
642 #[expect(
643 clippy::arithmetic_side_effects,
644 reason = "pc bounded by padded bytecode len"
645 )]
646 pub fn advance_pc(&mut self) {
647 self.current_call_frame.pc += 1;
648 }
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654 use ethrex_common::types::AccountInfo;
655
656 #[test]
657 fn absorb_keeps_earliest_original_value() {
658 let addr = Address::from_low_u64_be(1);
659 let mut acc = CallFrameBackup::default();
660
661 let mut first = CallFrameBackup::default();
662 first
663 .original_account_storage_slots
664 .entry(addr)
665 .or_default()
666 .insert(H256::zero(), U256::from(10));
667
668 let mut second = CallFrameBackup::default();
669 second
670 .original_account_storage_slots
671 .entry(addr)
672 .or_default()
673 .insert(H256::zero(), U256::from(20));
674
675 acc.absorb(&first);
676 acc.absorb(&second);
677
678 let value = acc
680 .original_account_storage_slots
681 .get(&addr)
682 .and_then(|slots| slots.get(&H256::zero()))
683 .copied();
684 assert_eq!(value, Some(U256::from(10)));
685 }
686
687 #[test]
688 fn absorb_keeps_earliest_account_info() {
689 let addr = Address::from_low_u64_be(2);
690 let mut acc = CallFrameBackup::default();
691
692 let first_acc = LevmAccount {
693 info: AccountInfo {
694 nonce: 1,
695 ..Default::default()
696 },
697 ..Default::default()
698 };
699 let mut first = CallFrameBackup::default();
700 first.original_accounts_info.insert(addr, first_acc);
701
702 let second_acc = LevmAccount {
703 info: AccountInfo {
704 nonce: 2,
705 ..Default::default()
706 },
707 ..Default::default()
708 };
709 let mut second = CallFrameBackup::default();
710 second.original_accounts_info.insert(addr, second_acc);
711
712 acc.absorb(&first);
713 acc.absorb(&second);
714
715 let nonce = acc.original_accounts_info.get(&addr).map(|a| a.info.nonce);
716 assert_eq!(nonce, Some(1));
717 }
718}