Keccak-256 opcode that hashes arbitrary memory regions
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:0x20Introduced: 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:
offset (top - memory byte offset)size (number of bytes to hash)
/** * SHA3/KECCAK256 opcode (0x20) - Hash memory region */export function sha3(frame: FrameType): EvmError | null { // Pop offset and size from stack const offsetResult = popStack(frame); if (offsetResult.error) return offsetResult.error; const offset = offsetResult.value; const lengthResult = popStack(frame); if (lengthResult.error) return lengthResult.error; const length = lengthResult.value; // Validate fit in safe integer range if (offset > Number.MAX_SAFE_INTEGER) { return { type: "OutOfBounds" }; } if (length > Number.MAX_SAFE_INTEGER) { return { type: "OutOfBounds" }; } const off = Number(offset); const len = Number(length); // Calculate gas: base (30) + word_count * per_word (6) const wordCount = len === 0 ? 0n : BigInt(Math.ceil(len / 32)); const dynamicGas = 30n + 6n * wordCount; // Charge gas const gasErr = consumeGas(frame, dynamicGas); if (gasErr) return gasErr; // Charge memory expansion if (len > 0) { const endBytes = off + len; const memCost = memoryExpansionCost(frame, endBytes); const memGasErr = consumeGas(frame, memCost); if (memGasErr) return memGasErr; // Update memory size const alignedSize = Math.ceil(endBytes / 32) * 32; if (alignedSize > frame.memorySize) { frame.memorySize = alignedSize; } } // Handle empty data if (len === 0) { const emptyHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470n; const pushErr = pushStack(frame, emptyHash); if (pushErr) return pushErr; frame.pc += 1; return null; } // Read data from memory const data = new Uint8Array(len); for (let i = 0; i < len; i++) { data[i] = readMemory(frame, off + i); } // Compute Keccak-256 hash const hashBytes = hash(data); // Convert to u256 (big-endian) let hashValue = 0n; for (let i = 0; i < 32; i++) { hashValue = (hashValue << 8n) | BigInt(hashBytes[i]); } // Push result const pushErr = pushStack(frame, hashValue); if (pushErr) return pushErr; frame.pc += 1; return null;}
Testing
Test Coverage
import { describe, it, expect } from 'vitest';import { sha3 } from './0x20_SHA3.js';describe('SHA3 (0x20)', () => { it('hashes empty data', () => { const frame = createFrame([0n, 0n]); expect(sha3(frame)).toBeNull(); expect(frame.stack[0]).toBe( 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470n ); }); it('hashes "hello world"', () => { const frame = createFrame(); const data = new TextEncoder().encode("hello world"); for (let i = 0; i < data.length; i++) { frame.memory.set(i, data[i]); } frame.stack.push(11n, 0n); expect(sha3(frame)).toBeNull(); expect(frame.stack[0]).toBe( 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fadn ); }); it('charges correct gas', () => { const frame = createFrame([32n, 0n], 100n); sha3(frame); expect(frame.gasRemaining).toBe(100n - 36n); // 30 + 6*1 word }); it('expands memory correctly', () => { const frame = createFrame([10n, 0n]); expect(frame.memorySize).toBe(0); sha3(frame); expect(frame.memorySize).toBe(32); // 1 word }); it('handles offset correctly', () => { const frame = createFrame(); const data = new TextEncoder().encode("test"); for (let i = 0; i < data.length; i++) { frame.memory.set(100 + i, data[i]); } frame.stack.push(4n, 100n); sha3(frame); expect(frame.stack[0]).toBe( 0x9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658n ); });});
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:
// These are DIFFERENT:const evmHash = keccak256("data"); // Ethereum opcodeconst nistHash = sha3_256("data"); // NIST standard (with 0x06 padding)// evmHash !== nistHash
Predictable Randomness Anti-Pattern
⚠️ NEVER use for randomness:
// WRONG: Predictable by miners/validatorsbytes32 randomness = keccak256(abi.encodePacked(block.timestamp, msg.sender));// Miners can choose when to include transaction, or validator can reorder// CORRECT: Use Chainlink VRF or similar oracle
Edge Cases
Maximum Memory Access
// SHA3 with very large size triggers quadratic memory expansion costconst frame = createFrame();frame.stack.push(0x100000n); // 1MB of dataframe.stack.push(0n); // offset 0// Gas cost is astronomical due to memory expansion// Even with large gas limit, operation may fail
Uninitialized Memory Reads
// Reading from uninitialized memory returns zerosbytes memory empty = new bytes(10); // 10 zero bytes (not the same as "")bytes32 hash1 = keccak256(""); // = 0xc5d2460186f7...bytes32 hash2 = keccak256(empty); // Different (hash of 10 zeros)assert(hash1 != hash2);
Integer Overflow Prevention
Stack values are u256, memory offsets are u32. Validation ensures no overflow:
// If offset + size > 2^32, operation fails// This prevents integer overflow in memory address calculation
Benchmarks
Gas costs reflect computational and memory expenses:
Input Size
Words
Base Gas
Word Gas
Memory
Total
Per Byte
0 bytes
0
30
0
3
33
-
1 byte
1
30
6
3
39
39.0
32 bytes
1
30
6
3
39
1.2
64 bytes
2
30
12
6
48
0.75
256 bytes
8
30
48
12
90
0.35
1024 bytes
32
30
192
48
270
0.26
References
Yellow Paper - Section 9.1 (Cryptographic Functions)