miden_stdlib/handlers/falcon_div.rs
1//! FALCON_DIV system event handler for the Miden VM.
2//!
3//! This handler implements the FALCON_DIV operation that pushes the result of dividing
4//! a [u64] by the Falcon prime (M = 12289) onto the advice stack.
5
6use alloc::{vec, vec::Vec};
7
8use miden_core::{EventName, ZERO};
9use miden_processor::{AdviceMutation, EventError, ProcessState};
10
11use crate::handlers::u64_to_u32_elements;
12
13/// Falcon signature prime.
14const M: u64 = 12289;
15
16/// Event name for the falcon_div operation.
17pub const FALCON_DIV_EVENT_NAME: EventName =
18 EventName::new("stdlib::crypto::dsa::rpo_falcon512::falcon_div");
19
20/// FALCON_DIV system event handler.
21///
22/// Pushes the result of divison (both the quotient and the remainder) of a [u64] by the Falcon
23/// prime (M = 12289) onto the advice stack.
24///
25/// Inputs:
26/// Operand stack: [event_id, a1, a0, ...]
27/// Advice stack: [...]
28///
29/// Outputs:
30/// Advice stack: [q1, q0, r, ...]
31///
32/// where (a0, a1) are the 32-bit limbs of the dividend (with a0 representing the 32 least
33/// significant bits and a1 representing the 32 most significant bits).
34/// Similarly, (q0, q1) represent the quotient and r the remainder.
35///
36/// # Errors
37/// - Returns an error if the divisor is ZERO.
38/// - Returns an error if either a0 or a1 is not a u32.
39pub fn handle_falcon_div(process: &ProcessState) -> Result<Vec<AdviceMutation>, EventError> {
40 let dividend_hi = process.get_stack_item(1).as_int();
41 let dividend_lo = process.get_stack_item(2).as_int();
42
43 if dividend_lo > u32::MAX.into() {
44 return Err(FalconDivError::InputNotU32 {
45 value: dividend_lo,
46 position: "dividend_lo",
47 }
48 .into());
49 }
50 if dividend_hi > u32::MAX.into() {
51 return Err(FalconDivError::InputNotU32 {
52 value: dividend_hi,
53 position: "dividend_hi",
54 }
55 .into());
56 }
57
58 let dividend = (dividend_hi << 32) + dividend_lo;
59
60 let (quotient, remainder) = (dividend / M, dividend % M);
61
62 let (q_hi, q_lo) = u64_to_u32_elements(quotient);
63 let (r_hi, r_lo) = u64_to_u32_elements(remainder);
64
65 // Assertion from the original code: r_hi should always be zero for Falcon modulus
66 assert_eq!(r_hi, ZERO);
67
68 // Create mutations to extend the advice stack with the result.
69 // The values are pushed in the order: r_lo, q_lo, q_hi
70 let mutation = AdviceMutation::extend_stack([r_lo, q_lo, q_hi]);
71 Ok(vec![mutation])
72}
73
74// ERROR TYPES
75// ================================================================================================
76
77/// Error types that can occur during FALCON_DIV operations.
78#[derive(Debug, thiserror::Error)]
79pub enum FalconDivError {
80 /// Input value is not a valid u32.
81 #[error("input value {value} at {position} is not a valid u32")]
82 InputNotU32 { value: u64, position: &'static str },
83}