Puzzle 7

gas cost

Puzzle

############
# Puzzle 7 #
############

00      5A        GAS
01      34        CALLVALUE
02      5B        JUMPDEST
03      6001      PUSH1 01
05      90        SWAP1
06      03        SUB
07      80        DUP1
08      6000      PUSH1 00
0A      14        EQ
0B      6011      PUSH1 11
0D      57        JUMPI
0E      6002      PUSH1 02
10      56        JUMP
11      5B        JUMPDEST
12      5A        GAS
13      90        SWAP1
14      91        SWAP2
15      03        SUB
16      60A6      PUSH1 A6
18      14        EQ
19      601D      PUSH1 1D
1B      57        JUMPI
1C      FD        REVERT
1D      5B        JUMPDEST
1E      00        STOP

? Enter the value to send: (0) 

Solution

This is a loop.

Pseudocode:

while (msg.value > 0) {
    msg.value -= 1;
}

if (beginning_gas - ending_gas == 0xA6) {
    jump(0x1D);
}

The while loop costs gas and we want to spend 0xA6 = 166 gas up until address 0x12.

Let's deduce the gas cost step by step:

beginning_gas = total_gas - 2 since GAS costs 2gas itself

before while loop:

(GAS does not count)
CALLVALUE - 2

Total: 2gas

while loop, except the very last loop (msg.value - 1 loops):

JUMPDEST - 1
PUSH1 01 - 3
SWAP1    - 3
SUB      - 3
DUP1     - 3
PUSH1 00 - 3
EQ       - 3
PUSH1 11 - 3
JUMPI    - 10
PUSH1 02 - 3
JUMP     - 8

Total: 43gas

the very last loop and after the loop (at 0x12): 

JUMPDEST - 1
PUSH1 01 - 3
SWAP1    - 3
SUB      - 3
DUP1     - 3
PUSH1 00 - 3
EQ       - 3
PUSH1 11 - 3
JUMPI    - 10
...
JUMPDEST - 1
GAS      - 2

Total: 35gas

ending_gas = beginning_gas - 2 - 43 * #loops - 35 = beginning_gas - 37 - 43 * #loops

We want beginning_gas - ending_gas = 166 => 37 + 43 * #loops = 166 => #loops = 3

Since #loops = msg.value - 1 => msg.value = 4

The tricky part is that the first GAS instruction costs 2gas itself and you have to take that into account.

Last updated