Supported Opcodes
| Opcode | Hex | Stack Input | Stack Output | Description |
|---|---|---|---|---|
| KECCAK256 | 0x20 | data | hash | Keccak-256 hash of data |
KECCAK256 (0x20)
Computes the Keccak-256 hash of input data. Keccak-256 is the hash function used throughout Ethereum for various purposes. Stack Input:data: The input data to hash (as a 32-byte value)
hash: The 32-byte Keccak-256 hash
What is Keccak-256?
Keccak-256 is a cryptographic hash function that:- Produces fixed output: Always returns a 32-byte (256-bit) hash
- Deterministic: Same input always produces same output
- One-way: Cannot reverse the hash to get original data
- Collision resistant: Nearly impossible to find two inputs with same hash
- Avalanche effect: Small change in input drastically changes output
Example
Implementation
The KECCAK256 opcode is implemented insrc/vm.rs:255-277 using the tiny_keccak crate:
Key Implementation Details
- Leading zero trimming: The implementation removes leading zeros from the input before hashing
- Byte conversion: Input is converted from Bytes32 to a byte vector
- Hex encoding: Output hash is converted to hexadecimal string
- tiny_keccak library: Uses the standard Keccak implementation
Common Use Cases
1. Data Integrity
Hash data to create a unique fingerprint:2. Unique Identifiers
Generate unique IDs from input data:3. Storage Key Generation
Create storage keys for mappings (similar to Solidity):4. Signature Verification
Hash messages before signature verification:Properties of Keccak-256
Important properties:
- Output size: Always 32 bytes (64 hex characters)
- Input size: Can hash any size data (in EVM, limited by stack)
- Speed: Relatively fast hash function
- Security: Cryptographically secure, no known practical attacks
Keccak vs SHA-3
Examples with Different Inputs
Empty input:Testing Your Hashes
Verify your Keccak-256 hashes using these tools: Foundry Cast:Best Practices
- Use for uniqueness: Hash data to create unique identifiers
- Don’t hash sensitive data alone: Add salt when hashing passwords or secrets
- Consistent encoding: Always encode data the same way before hashing
- Verify externally: Test hashes with external tools during development
- Mind the input: Leading zeros are trimmed in Cubipods implementation
Real-World Applications
Keccak-256 is used throughout Ethereum for:- Contract addresses:
keccak256(rlp([sender, nonce]))[12:] - Function selectors:
keccak256("transfer(address,uint256)")[0:4] - Event signatures:
keccak256("Transfer(address,address,uint256)") - Storage keys:
keccak256(abi.encodePacked(key, slot)) - Message hashing: Before ECDSA signature verification