EVM Puzzle 2 - Codesize

EVM Puzzle 2 - Codesize

Introduction

EVM puzzles push our understanding of Ethereum's low-level execution. This installment presents a seemingly simple challenge that hides a subtle error in jump logic. Let's analyze the puzzle and understand why this contract unexpectedly fails.

Puzzle #2 Bytecode

00      34      CALLVALUE
01      38      CODESIZE
02      03      SUB
03      56      JUMP
04      FD      REVERT
05      FD      REVERT
06      5B      JUMPDEST
07      00      STOP
08      FD      REVERT
09      FD      REVERT
        

Analysis

Let's break down the instructions:

  • CALLVALUE (0x34): Retrieves the amount of Ether sent in the transaction and pushes it onto the stack.
  • CODESIZE (0x38): Pushes the size of the contract's own code onto the stack.
  • SUB (0x03): Subtracts the top two values (CODESIZE - CALLVALUE) and leaves the result on the stack.
  • JUMP (0x56): Attempts to jump to the location specified by the value on top of the stack.
  • REVERT (0xFD): Multiple revert instructions indicating a potential failure condition.
  • JUMPDEST (0x5B) and STOP (0x00): Denote a potential jump target and contract termination.

The Issue

The intended logic of the puzzle seems to be a comparison between CALLVALUE and CODESIZE. However, there's a crucial error in the JUMP instruction:

  • CALLVALUE: Unless Ether is explicitly sent with the transaction, CALLVALUE will always be 0.
  • CODESIZE: The contract's code size will be a positive value.
  • SUB: Subtracting CALLVALUE from CODESIZE will always result in a negative number.
  • JUMP: The JUMP opcode expects a non-negative offset. This negative offset leads to an out-of-bounds jump, causing the contract to revert unexpectedly.

Solving the Puzzle

This puzzle cannot be solved in its current form. The intended logic is flawed due to the unconditional negative jump offset. To create a working puzzle, you would need to adjust the opcodes or introduce additional instructions to ensure a valid jump.

Key Takeaways

  • Jumps depend on valid offsets. Attempting to access invalid memory regions will cause execution to fail.
  • Stack manipulation is a powerful tool, but it's crucial to track the values on the stack to ensure logical code flow.
  • Even seemingly simple EVM code can contain subtle errors that require careful analysis.

Looking Ahead

Future EVM puzzles will present more complex stack manipulations, dynamic jump calculations, and perhaps interactions with external data. Let's sharpen our skills even further!

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics