openvm_sha256_circuit/sha256_chip/
mod.rs

1//! Sha256 hasher. Handles full sha256 hashing with padding.
2//! variable length inputs read from VM memory.
3
4use openvm_circuit::arch::*;
5use openvm_circuit_primitives::{
6    bitwise_op_lookup::SharedBitwiseOperationLookupChip, encoder::Encoder,
7};
8use openvm_instructions::riscv::RV32_CELL_BITS;
9use openvm_sha256_air::{Sha256FillerHelper, SHA256_BLOCK_BITS};
10use sha2::{Digest, Sha256};
11
12mod air;
13mod columns;
14mod execution;
15mod trace;
16
17pub use air::*;
18pub use columns::*;
19pub use trace::*;
20
21#[cfg(feature = "cuda")]
22mod cuda;
23#[cfg(feature = "cuda")]
24pub use cuda::*;
25
26#[cfg(test)]
27mod tests;
28
29// ==== Constants for register/memory adapter ====
30/// Register reads to get dst, src, len
31const SHA256_REGISTER_READS: usize = 3;
32/// Number of cells to read in a single memory access
33const SHA256_READ_SIZE: usize = 16;
34/// Number of cells to write in a single memory access
35const SHA256_WRITE_SIZE: usize = 32;
36/// Number of rv32 cells read in a SHA256 block
37pub const SHA256_BLOCK_CELLS: usize = SHA256_BLOCK_BITS / RV32_CELL_BITS;
38/// Number of rows we will do a read on for each SHA256 block
39pub const SHA256_NUM_READ_ROWS: usize = SHA256_BLOCK_CELLS / SHA256_READ_SIZE;
40/// Maximum message length that this chip supports in bytes
41pub const SHA256_MAX_MESSAGE_LEN: usize = 1 << 29;
42
43pub type Sha256VmChip<F> = VmChipWrapper<F, Sha256VmFiller>;
44
45#[derive(derive_new::new, Clone)]
46pub struct Sha256VmExecutor {
47    pub offset: usize,
48    pub pointer_max_bits: usize,
49}
50
51pub struct Sha256VmFiller {
52    pub inner: Sha256FillerHelper,
53    pub padding_encoder: Encoder,
54    pub bitwise_lookup_chip: SharedBitwiseOperationLookupChip<RV32_CELL_BITS>,
55    pub pointer_max_bits: usize,
56}
57
58impl Sha256VmFiller {
59    pub fn new(
60        bitwise_lookup_chip: SharedBitwiseOperationLookupChip<RV32_CELL_BITS>,
61        pointer_max_bits: usize,
62    ) -> Self {
63        Self {
64            inner: Sha256FillerHelper::new(),
65            padding_encoder: Encoder::new(PaddingFlags::COUNT, 2, false),
66            bitwise_lookup_chip,
67            pointer_max_bits,
68        }
69    }
70}
71
72pub fn sha256_solve(input_message: &[u8]) -> [u8; SHA256_WRITE_SIZE] {
73    let mut hasher = Sha256::new();
74    hasher.update(input_message);
75    let mut output = [0u8; SHA256_WRITE_SIZE];
76    output.copy_from_slice(hasher.finalize().as_ref());
77    output
78}