EIP-160 · Final · Core · 2016-10-20
EIP-160: EXP cost increase
Raised the gas cost of the EXP opcode from 10 to 50 gas per exponent byte in the Spurious Dragon fork, because benchmarks showed it was underpriced.
What problem does it solve?
Every EVM opcode has a fixed gas price that should roughly match how much work it costs a node to run. If an opcode is too cheap, an attacker can fill blocks with it and slow every node down while paying little. This kind of denial-of-service attack hit Ethereum in 2016.
EXP (0x0a, a ** b modulo 2^256) was one of the underpriced opcodes. The spec reports that benchmarks showed it was underpriced by a factor of about 4 to 8.
How it works
The cost of EXP depends on how many bytes the exponent needs. EIP-160 changes only the per-byte part:
| Static | Per byte of exponent | |
|---|---|---|
| Before | 10 | 10 |
| After EIP-160 | 10 | 50 |
"Bytes in the exponent" means the minimum number of bytes needed to represent b. An exponent of 0 costs only the static 10 gas. An exponent up to 255 costs 10 + 50 = 60. A full 256-bit exponent costs 10 + 50 × 32 = 1,610.
The change went live in the Spurious Dragon hard fork at block 2,675,000 on mainnet (chain ID 1).
Sample code
Gas calculation in pseudocode:
def exp_gas(exponent: int) -> int:
G_EXP = 10
G_EXPBYTE = 50 # was 10 before EIP-160
byte_len = (exponent.bit_length() + 7) // 8
return G_EXP + G_EXPBYTE * byte_len
exp_gas(0) # 10
exp_gas(255) # 60
exp_gas(256) # 110
exp_gas(2**256 - 1) # 1610
Solidity's ** operator compiles to EXP. For powers of two, a shift is cheaper:
uint256 a = 2 ** n; // EXP: 10 + 50 * bytes(n)
uint256 b = 1 << n; // SHL: 3 gas (opcode from EIP-145)
Things to know
- This is a pure repricing. The result of
EXPdoes not change. Only contracts that relied on an exact gas amount could notice it. - The fixed per-byte price makes
EXPcheap for small exponents and five times more expensive than before for large ones. That is fine for typical uses such as10 ** decimals, which has a one-byte exponent. - When the exponent is a constant, the compiler often folds
**away. The cost matters most when the exponent is a runtime value. - EIP-160 is one of several anti-DoS changes from 2016. See EIP-150 (IO-heavy opcodes repricing) and the Spurious Dragon meta EIP EIP-607, which also includes EIP-155, EIP-161 and EIP-170.