Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dummy circuit for large ecalls #1

Open
wants to merge 7 commits into
base: ecall-keccak
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions ceno_emul/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@ pub use elf::Program;
pub mod disassemble;

mod syscalls;
pub use syscalls::{KECCAK_PERMUTE, keccak_permute::KECCAK_WORDS};

pub mod test_utils;
123 changes: 123 additions & 0 deletions ceno_emul/src/rv32im_encode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
use crate::{InsnKind, rv32im::InsnFormat};

const MASK_4_BITS: u32 = 0xF;
const MASK_5_BITS: u32 = 0x1F;
const MASK_6_BITS: u32 = 0x3F;
const MASK_7_BITS: u32 = 0x7F;
const MASK_8_BITS: u32 = 0xFF;
const MASK_10_BITS: u32 = 0x3FF;
const MASK_12_BITS: u32 = 0xFFF;

/// Generate bit encoding of a RISC-V instruction.
///
/// Values `rs1`, `rs2` and `rd1` are 5-bit register indices, and `imm` is of
/// bit length depending on the requirements of the instruction format type.
///
/// Fields not required by the instruction's format type are ignored, so one can
/// safely pass an arbitrary value for these, say 0.
pub const fn encode_rv32(kind: InsnKind, rs1: u32, rs2: u32, rd: u32, imm: u32) -> u32 {
match kind.codes().format {
InsnFormat::R => encode_r(kind, rs1, rs2, rd),
InsnFormat::I => encode_i(kind, rs1, rd, imm),
InsnFormat::S => encode_s(kind, rs1, rs2, imm),
InsnFormat::B => encode_b(kind, rs1, rs2, imm),
InsnFormat::U => encode_u(kind, rd, imm),
InsnFormat::J => encode_j(kind, rd, imm),
}
}

pub const fn load_immediate(rd: u32, imm: u32) -> [u32; 2] {
[
encode_rv32(InsnKind::LUI, 0, 0, rd, imm),
encode_rv32(InsnKind::ORI, rd, 0, rd, imm),
]
}

// R-Type
// 25 20 15 12 7 0
// +------+-----+-----+--------+----+-------+
// funct7 | rs2 | rs1 | funct3 | rd | opcode
const fn encode_r(kind: InsnKind, rs1: u32, rs2: u32, rd: u32) -> u32 {
let rs2 = rs2 & MASK_5_BITS; // 5-bits mask
let rs1 = rs1 & MASK_5_BITS;
let rd = rd & MASK_5_BITS;
let func7 = kind.codes().func7;
let func3 = kind.codes().func3;
let opcode = kind.codes().opcode;
func7 << 25 | rs2 << 20 | rs1 << 15 | func3 << 12 | rd << 7 | opcode
}

// I-Type
// 20 15 12 7 0
// +---------+-----+--------+----+-------+
// imm[0:11] | rs1 | funct3 | rd | opcode
const fn encode_i(kind: InsnKind, rs1: u32, rd: u32, imm: u32) -> u32 {
let rs1 = rs1 & MASK_5_BITS;
let rd = rd & MASK_5_BITS;
let func3 = kind.codes().func3;
let opcode = kind.codes().opcode;
// SRLI/SRAI use a specialization of the I-type format with the shift type in imm[10].
let is_arithmetic_right_shift = (matches!(kind, InsnKind::SRAI) as u32) << 10;
let imm = imm & MASK_12_BITS | is_arithmetic_right_shift;
imm << 20 | rs1 << 15 | func3 << 12 | rd << 7 | opcode
}

// S-Type
// 25 20 15 12 7 0
// +---------+-----+-----+--------+----------+-------+
// imm[5:11] | rs2 | rs1 | funct3 | imm[0:4] | opcode
const fn encode_s(kind: InsnKind, rs1: u32, rs2: u32, imm: u32) -> u32 {
let rs2 = rs2 & MASK_5_BITS;
let rs1 = rs1 & MASK_5_BITS;
let func3 = kind.codes().func3;
let opcode = kind.codes().opcode;
let imm_lo = imm & MASK_5_BITS;
let imm_hi = (imm >> 5) & MASK_7_BITS; // 7-bits mask
imm_hi << 25 | rs2 << 20 | rs1 << 15 | func3 << 12 | imm_lo << 7 | opcode
}

// B-Type
// 31 25 20 15 12 8 7 0
// +-------+-----------+-----+-----+--------+----------+---------+-------+
// imm[12] | imm[5:10] | rs2 | rs1 | funct3 | imm[1:4] | imm[11] | opcode
const fn encode_b(kind: InsnKind, rs1: u32, rs2: u32, imm: u32) -> u32 {
let rs2 = rs2 & MASK_5_BITS;
let rs1 = rs1 & MASK_5_BITS;
let func3 = kind.codes().func3;
let opcode = kind.codes().opcode;
let imm_1_4 = (imm >> 1) & MASK_4_BITS; // skip imm[0]
let imm_5_10 = (imm >> 5) & MASK_6_BITS;
((imm >> 12) & 1) << 31
| imm_5_10 << 25
| rs2 << 20
| rs1 << 15
| func3 << 12
| imm_1_4 << 8
| ((imm >> 11) & 1) << 7
| opcode
}

// J-Type
// 31 21 20 12 7 0
// +-------+-----------+---------+------------+----+-------+
// imm[20] | imm[1:10] | imm[11] | imm[12:19] | rd | opcode
const fn encode_j(kind: InsnKind, rd: u32, imm: u32) -> u32 {
let rd = rd & MASK_5_BITS;
let opcode = kind.codes().opcode;
let imm_1_10 = (imm >> 1) & MASK_10_BITS; // skip imm[0]
let imm_12_19 = (imm >> 12) & MASK_8_BITS;
((imm >> 20) & 1) << 31
| imm_1_10 << 21
| ((imm >> 11) & 1) << 20
| imm_12_19 << 12
| rd << 7
| opcode
}

// U-Type
// 12 7 0
// +----------+----+--------+
// imm[12:31] | rd | opcode
const fn encode_u(kind: InsnKind, rd: u32, imm: u32) -> u32 {
(imm >> 12) << 12 | (rd & MASK_5_BITS) << 7 | kind.codes().opcode
}
18 changes: 10 additions & 8 deletions ceno_emul/src/syscalls.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::{RegIdx, Tracer, VMState, Word, WordAddr, WriteOp};
use anyhow::Result;
use itertools::chain;

mod keccak_permute;
pub mod keccak_permute;

// Using the same function codes as sp1:
// https://github.com/succinctlabs/sp1/blob/013c24ea2fa15a0e7ed94f7d11a7ada4baa39ab9/crates/core/executor/src/syscalls/code.rs
Expand All @@ -20,8 +19,8 @@ pub fn handle_syscall(vm: &VMState, function_code: u32) -> Result<SyscallEffects
/// A syscall event, available to the circuit witness generators.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SyscallWitness {
pub mem_writes: Vec<WriteOp>,
pub reg_accesses: Vec<WriteOp>,
pub mem_ops: Vec<WriteOp>,
pub reg_ops: Vec<WriteOp>,
}

/// The effects of a syscall to apply on the VM.
Expand All @@ -38,23 +37,26 @@ impl SyscallEffects {
/// Iterate over the register values after the syscall.
pub fn iter_reg_values(&self) -> impl Iterator<Item = (RegIdx, Word)> + '_ {
self.witness
.reg_accesses
.reg_ops
.iter()
.map(|op| (op.register_index(), op.value.after))
}

/// Iterate over the memory values after the syscall.
pub fn iter_mem_values(&self) -> impl Iterator<Item = (WordAddr, Word)> + '_ {
self.witness
.mem_writes
.mem_ops
.iter()
.map(|op| (op.addr, op.value.after))
}

/// Keep track of the cycles of registers and memory accesses.
pub fn finalize(mut self, tracer: &mut Tracer) -> SyscallWitness {
for op in chain(&mut self.witness.reg_accesses, &mut self.witness.mem_writes) {
op.previous_cycle = tracer.track_access(op.addr, 0);
for op in &mut self.witness.reg_ops {
op.previous_cycle = tracer.track_access(op.addr, Tracer::SUBCYCLE_RD);
}
for op in &mut self.witness.mem_ops {
op.previous_cycle = tracer.track_access(op.addr, Tracer::SUBCYCLE_MEM);
}
self.witness
}
Expand Down
13 changes: 5 additions & 8 deletions ceno_emul/src/syscalls/keccak_permute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{Change, EmuContext, Platform, VMState, WORD_SIZE, WordAddr, WriteOp}
use super::{SyscallEffects, SyscallWitness};

const KECCAK_CELLS: usize = 25; // u64 cells
const KECCAK_WORDS: usize = KECCAK_CELLS * 2; // u32 words
pub const KECCAK_WORDS: usize = KECCAK_CELLS * 2; // u32 words

/// Trace the execution of a Keccak permutation.
///
Expand All @@ -18,7 +18,7 @@ pub fn keccak_permute(vm: &VMState) -> SyscallEffects {
let state_ptr = vm.peek_register(Platform::reg_arg0());

// Read the argument `state_ptr`.
let reg_accesses = vec![WriteOp::new_register_op(
let reg_ops = vec![WriteOp::new_register_op(
Platform::reg_arg0(),
Change::new(state_ptr, state_ptr),
0, // Cycle set later in finalize().
Expand Down Expand Up @@ -49,20 +49,17 @@ pub fn keccak_permute(vm: &VMState) -> SyscallEffects {
};

// Write permuted state.
let mem_writes = izip!(addrs, input, output)
let mem_ops = izip!(addrs, input, output)
.map(|(addr, before, after)| WriteOp {
addr,
value: Change { before, after },
previous_cycle: 0, // Cycle set later in finalize().
})
.collect_vec();

assert_eq!(mem_writes.len(), KECCAK_WORDS);
assert_eq!(mem_ops.len(), KECCAK_WORDS);
SyscallEffects {
witness: SyscallWitness {
mem_writes,
reg_accesses,
},
witness: SyscallWitness { mem_ops, reg_ops },
next_pc: None,
}
}
28 changes: 28 additions & 0 deletions ceno_emul/src/test_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use crate::{
CENO_PLATFORM, InsnKind, Instruction, Platform, Program, StepRecord, VMState, encode_rv32,
encode_rv32u, syscalls::KECCAK_PERMUTE,
};
use anyhow::Result;

pub fn keccak_step() -> (StepRecord, Vec<Instruction>) {
let instructions = vec![
// Call Keccak-f.
load_immediate(Platform::reg_arg0() as u32, CENO_PLATFORM.ram.start),
load_immediate(Platform::reg_ecall() as u32, KECCAK_PERMUTE),
encode_rv32(InsnKind::ECALL, 0, 0, 0, 0),
// Halt.
load_immediate(Platform::reg_ecall() as u32, Platform::ecall_halt()),
encode_rv32(InsnKind::ECALL, 0, 0, 0, 0),
];

let pc = CENO_PLATFORM.pc_base();
let program = Program::new(pc, pc, instructions.clone(), Default::default());
let mut vm = VMState::new(CENO_PLATFORM, program.into());
let steps = vm.iter_until_halt().collect::<Result<Vec<_>>>().unwrap();

(steps[2].clone(), instructions)
}

const fn load_immediate(rd: u32, imm: u32) -> Instruction {
encode_rv32u(InsnKind::ADDI, 0, 0, rd, imm)
}
11 changes: 4 additions & 7 deletions ceno_emul/tests/test_elf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,12 @@ fn test_ceno_rt_keccak() -> Result<()> {

// Check the syscall effects.
for (witness, expect) in izip!(syscalls, keccak_outs) {
assert_eq!(witness.reg_accesses.len(), 1);
assert_eq!(
witness.reg_accesses[0].register_index(),
Platform::reg_arg0()
);
assert_eq!(witness.reg_ops.len(), 1);
assert_eq!(witness.reg_ops[0].register_index(), Platform::reg_arg0());

assert_eq!(witness.mem_writes.len(), expect.len() * 2);
assert_eq!(witness.mem_ops.len(), expect.len() * 2);
let got = witness
.mem_writes
.mem_ops
.chunks_exact(2)
.map(|write_ops| {
assert_eq!(
Expand Down
8 changes: 6 additions & 2 deletions ceno_zkvm/src/instructions/riscv/dummy/dummy_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub struct DummyConfig<E: ExtensionField> {

impl<E: ExtensionField> DummyConfig<E> {
#[allow(clippy::too_many_arguments)]
fn construct_circuit(
pub(super) fn construct_circuit(
circuit_builder: &mut CircuitBuilder<E>,
kind: InsnKind,
with_rs1: bool,
Expand Down Expand Up @@ -213,7 +213,7 @@ impl<E: ExtensionField> DummyConfig<E> {
})
}

fn assign_instance(
pub(super) fn assign_instance(
&self,
instance: &mut [<E as ExtensionField>::BaseField],
lk_multiplicity: &mut LkMultiplicity,
Expand Down Expand Up @@ -264,4 +264,8 @@ impl<E: ExtensionField> DummyConfig<E> {

Ok(())
}

pub(super) fn ts(&self) -> WitIn {
self.vm_state.ts
}
}
Loading