|
| 1 | +from typing import ( |
| 2 | + List, |
| 3 | + Tuple, |
| 4 | + Union, |
| 5 | +) |
| 6 | + |
| 7 | +from eth.exceptions import ( |
| 8 | + InsufficientStack, |
| 9 | + FullStack, |
| 10 | +) |
| 11 | + |
| 12 | +from eth.validation import ( |
| 13 | + validate_stack_int, |
| 14 | +) |
| 15 | + |
| 16 | +from eth_utils import ( |
| 17 | + big_endian_to_int, |
| 18 | + ValidationError, |
| 19 | +) |
| 20 | + |
| 21 | +""" |
| 22 | +This module simply implements for the return stack the exact same design used for the data stack. |
| 23 | +As this stack must simply push_int or pop1_int any time a subroutine is accessed or left, only |
| 24 | +those two functions are provided. |
| 25 | +For the same reason, the class RStack doesn't inherit from the abc StackAPI, as it would require |
| 26 | +to implement all the abstract methods defined. |
| 27 | +""" |
| 28 | + |
| 29 | + |
| 30 | +class RStack: |
| 31 | + """ |
| 32 | + VM Return Stack |
| 33 | + """ |
| 34 | + |
| 35 | + __slots__ = ['values', '_append', '_pop_typed', '__len__'] |
| 36 | + |
| 37 | + def __init__(self) -> None: |
| 38 | + values: List[Tuple[type, Union[int, bytes]]] = [] |
| 39 | + self.values = values |
| 40 | + self._append = values.append |
| 41 | + self._pop_typed = values.pop |
| 42 | + self.__len__ = values.__len__ |
| 43 | + |
| 44 | + def push_int(self, value: int) -> None: |
| 45 | + if len(self.values) > 1023: |
| 46 | + raise FullStack('Stack limit reached') |
| 47 | + |
| 48 | + validate_stack_int(value) |
| 49 | + |
| 50 | + self._append((int, value)) |
| 51 | + |
| 52 | + def pop1_int(self) -> int: |
| 53 | + # |
| 54 | + # Note: This function is optimized for speed over readability. |
| 55 | + # |
| 56 | + if not self.values: |
| 57 | + raise InsufficientStack("Wanted 1 stack item as int, had none") |
| 58 | + else: |
| 59 | + item_type, popped = self._pop_typed() |
| 60 | + if item_type is int: |
| 61 | + return popped # type: ignore |
| 62 | + elif item_type is bytes: |
| 63 | + return big_endian_to_int(popped) # type: ignore |
| 64 | + else: |
| 65 | + raise ValidationError( |
| 66 | + "Stack must always be bytes or int, " |
| 67 | + f"got {item_type!r} type" |
| 68 | + ) |
0 commit comments