EIP-2666 · Stagnant · Core · 2020-05-22
EIP-2666: Repricing of precompiles and Keccak256 function
Proposed new, benchmark-based gas formulas for the SHA256 and RIPEMD-160 precompiles and the KECCAK256 opcode, charging per internal hash block instead of per 32-byte word.
What problem does it solve?
The gas costs of Ethereum's built-in hash functions were set early on and charge per 32-byte word of input. But hash functions don't work in 32-byte words. SHA-256 and RIPEMD-160 process 64-byte blocks, and Keccak-256 absorbs 136 bytes per round. The old prices therefore did not match the real CPU work, and RIPEMD in particular was very expensive.
ERC-2666 asked client teams to benchmark these functions and proposed formulas that follow the internal block structure. It also anticipated EIP-2046, which would make STATICCALL to precompiles cheap, removing a large fixed overhead some precompile prices might have been compensating for.
How it works
After a fork block, the costs would become (integer division throughout):
| Function | Current | Proposed |
|---|---|---|
SHA256 precompile 0x02 |
60 + 12 per word | 10 + ((len + 8) / 64 + 1) * 9 |
RIPEMD-160 precompile 0x03 |
600 + 120 per word | 6 + ((len + 8) / 64 + 1) * 12 |
KECCAK256 opcode 0x20 |
30 + 6 per word | 13 + (len / 136 + 1) * 15 |
The + 1 terms are kept separate on purpose: hashing even an empty input still runs one full round.
The coefficients were chosen from benchmarks supplied by Geth, OpenEthereum, Besu and Nethermind, combined with knowledge of each hash function's block size.
Sample code
Comparing old and new Keccak-256 cost, using the spec's own test cases:
const oldKeccak = (len: number) => 30 + 6 * Math.ceil(len / 32);
const newKeccak = (len: number) => 13 + 15 * (Math.floor(len / 136) + 1);
for (const len of [0, 64, 160]) {
console.log(len, oldKeccak(len), newKeccak(len));
}
// 0 30 28
// 64 42 28
// 160 60 43
The same idea for SHA256:
const newSha256 = (len: number) => 10 + 9 * (Math.floor((len + 8) / 64) + 1);
console.log(newSha256(32)); // 19 (old price: 72)
Things to know
- Status is Stagnant. None of these formulas have been adopted; the hash costs on mainnet are still the per-word ones.
- It depends on EIP-2046 (cheaper precompile calls) and ideally on the ModExp repricing in EIP-2565, which did ship in Berlin. Berlin also introduced EIP-2929, which changed how calls to precompiles are charged.
- Lowering costs can break contracts that rely on fixed gas amounts for safety, such as re-entrancy guards based on the 2300 gas stipend. The spec argues such designs were never sound.