This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.
Overview
Opcode: 0x20
Introduced: Frontier (EVM genesis)
SHA3/KECCAK256 computes the Keccak-256 cryptographic hash of a memory region. Despite its name referencing SHA3, this opcode implements the original Keccak-256 algorithm, not the NIST-standardized SHA3.
This operation is essential for:
- Computing function selectors (first 4 bytes of
keccak256(signature))
- Hashing event data and topics
- Generating storage keys
- Implementing authentication schemes
Specification
Stack Input:
Stack Output:
Gas Cost:
Operation:
Behavior
SHA3 reads a variable-length byte sequence from memory, computes its Keccak-256 hash, and pushes the result to the stack:
- Pop operands: Remove
offset and size from stack (in that order)
- Validate: Ensure offset/size fit in u32 range; calculate gas costs
- Charge gas: Base (30) + per-word (6 * ceil(size/32)) + memory expansion
- Expand memory: If accessing memory beyond current size, allocate word-aligned pages
- Read data: Copy bytes
[offset, offset+size) from memory
- Hash: Compute Keccak-256 digest (32 bytes)
- Push result: Convert hash to u256 (big-endian) and push to stack
- Increment PC: Move to next instruction
Special case: If size=0, return cached hash of empty data (0xc5d2460186f7…) without memory access.
Examples
Computing a Function Selector
Event Topic Hash
Storage Key Generation
Gas Cost Calculation
Base Gas
All SHA3 operations cost minimum 30 gas (GasKeccak256Base).
Per-Word Gas
Additional 6 gas per 32-byte word (rounded up):
Memory Expansion Cost
Reading memory beyond current size triggers expansion cost:
Total Cost
Common Usage
Event Signatures
Function Selectors
State Root Hashing
Merkle tree construction hashes account storage:
Commit-Reveal Pattern
Prevents transaction front-running:
Access Control (Legacy)
Implementation
Testing
Test Coverage
Security
Preimage Resistance
Keccak-256 is a cryptographic one-way function: finding input x given keccak256(x) = h requires ~2^256 operations.
Used securely for:
- Transaction hashing and signature verification
- State root computation
- Storage key generation
Collision Resistance
Finding two different inputs with the same hash requires ~2^128 operations (birthday paradox bound). This guarantees:
- Merkle tree integrity for account storage
- Uniqueness of function selectors (extremely unlikely to collide accidentally)
Domain Separation (Keccak vs NIST SHA3)
Critical: Ethereum uses Keccak-256, NOT NIST SHA3-256. Never assume compatibility:
Predictable Randomness Anti-Pattern
⚠️ NEVER use for randomness:
Edge Cases
Maximum Memory Access
Uninitialized Memory Reads
Integer Overflow Prevention
Stack values are u256, memory offsets are u32. Validation ensures no overflow:
Benchmarks
Gas costs reflect computational and memory expenses:
References