openvm_native_circuit/poseidon2/
chip.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use std::{array::from_fn, sync::Arc};

use openvm_circuit::{
    arch::{ExecutionBridge, ExecutionBus, ExecutionError, ExecutionState, InstructionExecutor},
    system::{
        memory::{
            offline_checker::{MemoryReadAuxCols, MemoryWriteAuxCols},
            MemoryAuxColsFactory, MemoryControllerRef, MemoryReadRecord, MemoryWriteRecord,
        },
        program::ProgramBus,
    },
};
use openvm_instructions::{
    instruction::Instruction, program::DEFAULT_PC_STEP, Poseidon2Opcode, UsizeOpcode,
};
use openvm_poseidon2_air::{Poseidon2Config, Poseidon2SubChip};
use openvm_stark_backend::p3_field::{Field, PrimeField32};

use super::{
    NativePoseidon2Air, NativePoseidon2MemoryCols, NATIVE_POSEIDON2_CHUNK_SIZE,
    NATIVE_POSEIDON2_WIDTH,
};

#[derive(Debug)]
pub struct NativePoseidon2BaseChip<F: Field, const SBOX_REGISTERS: usize> {
    pub air: Arc<NativePoseidon2Air<F, SBOX_REGISTERS>>,
    pub subchip: Poseidon2SubChip<F, SBOX_REGISTERS>,
    pub memory_controller: MemoryControllerRef<F>,
    pub records: Vec<Option<NativePoseidon2ChipRecord<F>>>,
}

#[derive(Clone, Debug)]
pub struct NativePoseidon2ChipRecord<F> {
    pub from_state: ExecutionState<u32>,
    pub opcode: Poseidon2Opcode,
    pub input: [F; NATIVE_POSEIDON2_WIDTH],
    pub c: F,
    pub rd: MemoryReadRecord<F, 1>,
    pub rs1: MemoryReadRecord<F, 1>,
    pub rs2: Option<MemoryReadRecord<F, 1>>,

    pub read1: MemoryReadRecord<F, NATIVE_POSEIDON2_CHUNK_SIZE>,
    pub read2: MemoryReadRecord<F, NATIVE_POSEIDON2_CHUNK_SIZE>,

    pub write1: MemoryWriteRecord<F, NATIVE_POSEIDON2_CHUNK_SIZE>,
    pub write2: Option<MemoryWriteRecord<F, NATIVE_POSEIDON2_CHUNK_SIZE>>,
}

impl<F: PrimeField32, const SBOX_REGISTERS: usize> NativePoseidon2BaseChip<F, SBOX_REGISTERS> {
    pub fn new(
        execution_bus: ExecutionBus,
        program_bus: ProgramBus,
        memory_controller: MemoryControllerRef<F>,
        poseidon2_config: Poseidon2Config<F>,
        offset: usize,
    ) -> Self {
        let memory_bridge = memory_controller.borrow().memory_bridge();
        let subchip = Poseidon2SubChip::new(poseidon2_config);
        Self {
            air: Arc::new(NativePoseidon2Air::new(
                ExecutionBridge::new(execution_bus, program_bus),
                memory_bridge,
                subchip.air.clone(),
                offset,
            )),
            subchip,
            memory_controller,
            records: vec![],
        }
    }
}

impl<F: PrimeField32, const SBOX_REGISTERS: usize> InstructionExecutor<F>
    for NativePoseidon2BaseChip<F, SBOX_REGISTERS>
{
    fn execute(
        &mut self,
        instruction: Instruction<F>,
        from_state: ExecutionState<u32>,
    ) -> Result<ExecutionState<u32>, ExecutionError> {
        let Instruction {
            opcode,
            a,
            b,
            c,
            d,
            e,
            ..
        } = instruction;
        let local_opcode = Poseidon2Opcode::from_usize(opcode.local_opcode_idx(self.air.offset));
        let mut memory = self.memory_controller.borrow_mut();

        let rd = memory.read_cell(d, a);
        let rs1 = memory.read_cell(d, b);
        let rs2 = match local_opcode {
            Poseidon2Opcode::PERM_POS2 => {
                memory.increment_timestamp();
                None
            }
            Poseidon2Opcode::COMP_POS2 => Some(memory.read_cell(d, c)),
        };

        let read1 = memory.read::<NATIVE_POSEIDON2_CHUNK_SIZE>(e, rs1.data[0]);
        let read2 = memory.read::<NATIVE_POSEIDON2_CHUNK_SIZE>(
            e,
            match rs2 {
                Some(rs2) => rs2.data[0],
                None => rs1.data[0] + F::from_canonical_usize(NATIVE_POSEIDON2_CHUNK_SIZE),
            },
        );

        let mut input_state: [F; NATIVE_POSEIDON2_WIDTH] = [F::ZERO; NATIVE_POSEIDON2_WIDTH];
        input_state[..NATIVE_POSEIDON2_CHUNK_SIZE].copy_from_slice(&read1.data);
        input_state[NATIVE_POSEIDON2_CHUNK_SIZE..].copy_from_slice(&read2.data);

        let output_state = self.subchip.permute(input_state);

        let output1: [F; NATIVE_POSEIDON2_CHUNK_SIZE] = from_fn(|i| output_state[i]);
        let output2: [F; NATIVE_POSEIDON2_CHUNK_SIZE] =
            from_fn(|i| output_state[NATIVE_POSEIDON2_CHUNK_SIZE + i]);

        let write1 = memory.write::<NATIVE_POSEIDON2_CHUNK_SIZE>(e, rd.data[0], output1);
        let write2 = match local_opcode {
            Poseidon2Opcode::PERM_POS2 => Some(memory.write::<NATIVE_POSEIDON2_CHUNK_SIZE>(
                e,
                rd.data[0] + F::from_canonical_usize(NATIVE_POSEIDON2_CHUNK_SIZE),
                output2,
            )),
            Poseidon2Opcode::COMP_POS2 => {
                memory.increment_timestamp();
                None
            }
        };

        self.records.push(Some(NativePoseidon2ChipRecord {
            from_state,
            opcode: local_opcode,
            input: input_state,
            c,
            rd,
            rs1,
            rs2,
            read1,
            read2,
            write1,
            write2,
        }));

        Ok(ExecutionState {
            pc: from_state.pc + DEFAULT_PC_STEP,
            timestamp: memory.timestamp(),
        })
    }

    fn get_opcode_name(&self, opcode: usize) -> String {
        format!(
            "{:?}",
            Poseidon2Opcode::from_usize(opcode - self.air.offset)
        )
    }
}

impl<F: PrimeField32 + Sync> NativePoseidon2ChipRecord<F> {
    pub fn to_memory_cols(
        &self,
        aux_cols_factory: &MemoryAuxColsFactory<F>,
    ) -> NativePoseidon2MemoryCols<F> {
        let (rs2_ptr, rs2_val, rs2_read_aux) = match self.rs2 {
            Some(rs2) => (
                rs2.pointer,
                rs2.data[0],
                aux_cols_factory.make_read_aux_cols(rs2),
            ),
            None => (
                F::ZERO,
                self.rs1.data[0] + F::from_canonical_usize(NATIVE_POSEIDON2_CHUNK_SIZE),
                MemoryReadAuxCols::disabled(),
            ),
        };
        NativePoseidon2MemoryCols {
            from_state: self.from_state.map(F::from_canonical_u32),
            opcode_flag: match self.opcode {
                Poseidon2Opcode::PERM_POS2 => F::ONE,
                Poseidon2Opcode::COMP_POS2 => F::TWO,
            },
            ptr_as: self.rd.address_space,
            chunk_as: self.read1.address_space,
            c: self.c,
            rs_ptr: [self.rs1.pointer, rs2_ptr],
            rd_ptr: self.rd.pointer,
            rs_val: [self.rs1.data[0], rs2_val],
            rd_val: self.rd.data[0],
            rs_read_aux: [aux_cols_factory.make_read_aux_cols(self.rs1), rs2_read_aux],
            rd_read_aux: aux_cols_factory.make_read_aux_cols(self.rd),
            chunk_read_aux: [
                aux_cols_factory.make_read_aux_cols(self.read1),
                aux_cols_factory.make_read_aux_cols(self.read2),
            ],
            chunk_write_aux: [
                aux_cols_factory.make_write_aux_cols(self.write1),
                self.write2.map_or(MemoryWriteAuxCols::disabled(), |w| {
                    aux_cols_factory.make_write_aux_cols(w)
                }),
            ],
        }
    }
}