Overview
The SHA-256 inline provides an optimized implementation of the SHA-2 family hash function with 256-bit output. It offers significant performance improvements over standard SHA-256 implementations by using custom RISC-V instructions.API Reference
Sha256
Main hasher struct that supports both streaming and one-shot hashing.
Methods
new() -> Self
Creates a new SHA-256 hasher.
update(&mut self, input: &[u8])
Writes data to the hasher incrementally. Can be called multiple times.
finalize(self) -> [u8; 32]
Finalizes the hash and returns the 32-byte digest. Consumes the hasher.
digest(input: &[u8]) -> [u8; 32]
Computes SHA-256 hash in one call. Recommended for most use cases.
Usage Examples
Basic Usage
Streaming API
For large inputs or when data arrives in chunks:Merkle Tree Leaf Hashing
Implementation Details
Custom Instructions
The SHA-256 inline uses two custom RISC-V instructions:SHA256_COMPRESSION(funct3=0x00, funct7=0x00): Performs SHA-256 compression with existing stateSHA256_COMPRESSION_INITIAL(funct3=0x01, funct7=0x00): Performs compression with initial IV constants
Memory Layout
- Input block: 64 bytes (16 × 32-bit words)
- State: 32 bytes (8 × 32-bit words)
- Output: 32 bytes
Endianness Handling
The implementation automatically handles endianness:- On little-endian systems (RISC-V), uses
swap_bytes()to convert to big-endian - On big-endian systems, data is used directly
swap_bytes() function uses a custom virtual instruction on RISC-V for performance:
Performance Characteristics
- Block processing: ~64 bytes per compression (512 bits)
- Optimization: Initial block uses specialized instruction that embeds IV constants
- Memory efficiency: Uses
MaybeUninitfor buffer allocation to reduce initialization overhead
Comparison with Standard Implementation
When compared to the Rustsha2 crate:
- Cycle count: ~10-100x reduction in VM cycles
- Proving time: Proportionally faster proof generation
- Compatibility: Drop-in replacement with identical output
Feature Flags
host: Enables reference implementation for host-side execution- Guest code: Compile WITHOUT this feature
- Prover code: Compile WITH this feature
Safety Considerations
The implementation usesunsafe for:
- Inline assembly for custom RISC-V instructions
- Raw pointer operations for zero-copy buffer access
MaybeUninitfor performance optimization
Source Code Location
Constants
See Also
- Keccak-256 - Alternative hash function
- BLAKE2 - BLAKE2b hash function
- BLAKE3 - BLAKE3 hash function
- Inlines Overview - General information about cryptographic inlines