Skip to content

Commit 8074661

Browse files
add qm31 operations to VM
1 parent 29ce31e commit 8074661

File tree

9 files changed

+531
-39
lines changed

9 files changed

+531
-39
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
#### Upcoming Changes
44

5+
* feat: implement an opcode that computes QM31 arithmetics (add, sub, mul, div) in the VM [#1938](https://github.com/lambdaclass/cairo-vm/pull/1938)
6+
57
* feat: add functions that compute packed reduced qm31 arithmetics to `math_utils` [#1944](https://github.com/lambdaclass/cairo-vm/pull/1944)
68

79
* feat: implement `Blake2sLastBlock` opcode in VM [#1932](https://github.com/lambdaclass/cairo-vm/pull/1932)
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
from starkware.cairo.common.alloc import alloc
2+
from starkware.cairo.common.bool import FALSE, TRUE
3+
4+
// Tests the QM31_add_mul opcode runners using specific examples as reference.
5+
// The test is comprised of 10 test cases, each of which tests a different combination of missing_operand, is_imm, and is_mul.
6+
// is_mul determines whether the operation is a multiplication or an addition of QM31 elements.
7+
// is_imm determines whether op1 is an immediate.
8+
// missing_operand determines which operand is missing and needs to be computed by the VM (0 for dst, 1 for op0, 2 fo op1).
9+
// the combination of is_imm=TRUE with missig_operand=2 is not tested because we do not use arithmetic opcodes to deduce immediates.
10+
func main{}() {
11+
let qm31_op0_coordinates_a = 0x544b2fba;
12+
let qm31_op0_coordinates_b = 0x673cff77;
13+
let qm31_op0_coordinates_c = 0x60713d44;
14+
let qm31_op0_coordinates_d = 0x499602d2;
15+
let qm31_op0 = qm31_op0_coordinates_a + qm31_op0_coordinates_b*(2**36) + qm31_op0_coordinates_c*(2**72) + qm31_op0_coordinates_d*(2**108);
16+
17+
let qm31_op1_coordinates_a = 0x4b18de99;
18+
let qm31_op1_coordinates_b = 0x55f6fb62;
19+
let qm31_op1_coordinates_c = 0x6e2290d9;
20+
let qm31_op1_coordinates_d = 0x7cd851b9;
21+
let qm31_op1 = qm31_op1_coordinates_a + qm31_op1_coordinates_b*(2**36) + qm31_op1_coordinates_c*(2**72) + qm31_op1_coordinates_d*(2**108);
22+
23+
let qm31_add_dst_coordinates_a = 0x1f640e54;
24+
let qm31_add_dst_coordinates_b = 0x3d33fada;
25+
let qm31_add_dst_coordinates_c = 0x4e93ce1e;
26+
let qm31_add_dst_coordinates_d = 0x466e548c;
27+
let qm31_add_dst = qm31_add_dst_coordinates_a + qm31_add_dst_coordinates_b*(2**36) + qm31_add_dst_coordinates_c*(2**72) + qm31_add_dst_coordinates_d*(2**108);
28+
29+
let qm31_mul_dst_coordinates_a = 0x38810ab4;
30+
let qm31_mul_dst_coordinates_b = 0x5a0fd30a;
31+
let qm31_mul_dst_coordinates_c = 0x2527b81e;
32+
let qm31_mul_dst_coordinates_d = 0x4b1ed1cd;
33+
let qm31_mul_dst = qm31_mul_dst_coordinates_a + qm31_mul_dst_coordinates_b*(2**36) + qm31_mul_dst_coordinates_c*(2**72) + qm31_mul_dst_coordinates_d*(2**108);
34+
35+
let runner_output_mul_dst = run_qm31_operation(missing_operand=0, is_imm=FALSE, is_mul=TRUE, dst_or_op0=qm31_op0, op0_or_op1=qm31_op1);
36+
assert runner_output_mul_dst = qm31_mul_dst;
37+
let runner_output_add_dst = run_qm31_operation(missing_operand=0, is_imm=FALSE, is_mul=FALSE, dst_or_op0=qm31_op0, op0_or_op1=qm31_op1);
38+
assert runner_output_add_dst = qm31_add_dst;
39+
40+
let runner_output_mul_op0 = run_qm31_operation(missing_operand=1, is_imm=FALSE, is_mul=TRUE, dst_or_op0=qm31_mul_dst, op0_or_op1=qm31_op1);
41+
assert runner_output_mul_op0 = qm31_op0;
42+
let runner_output_add_op0 = run_qm31_operation(missing_operand=1, is_imm=FALSE, is_mul=FALSE, dst_or_op0=qm31_add_dst, op0_or_op1=qm31_op1);
43+
assert runner_output_add_op0 = qm31_op0;
44+
45+
let runner_output_mul_op1 = run_qm31_operation(missing_operand=2, is_imm=FALSE, is_mul=TRUE, dst_or_op0=qm31_mul_dst, op0_or_op1=qm31_op0);
46+
assert runner_output_mul_op1 = qm31_op1;
47+
let runner_output_add_op1 = run_qm31_operation(missing_operand=2, is_imm=FALSE, is_mul=FALSE, dst_or_op0=qm31_add_dst, op0_or_op1=qm31_op0);
48+
assert runner_output_add_op1 = qm31_op1;
49+
50+
let runner_output_mul_dst = run_qm31_operation(missing_operand=0, is_imm=TRUE, is_mul=TRUE, dst_or_op0=qm31_op0, op0_or_op1=qm31_op1);
51+
assert runner_output_mul_dst = qm31_mul_dst;
52+
let runner_output_add_dst = run_qm31_operation(missing_operand=0, is_imm=TRUE, is_mul=FALSE, dst_or_op0=qm31_op0, op0_or_op1=qm31_op1);
53+
assert runner_output_add_dst = qm31_add_dst;
54+
55+
let runner_output_mul_op0 = run_qm31_operation(missing_operand=1, is_imm=TRUE, is_mul=TRUE, dst_or_op0=qm31_mul_dst, op0_or_op1=qm31_op1);
56+
assert runner_output_mul_op0 = qm31_op0;
57+
let runner_output_add_op0 = run_qm31_operation(missing_operand=1, is_imm=TRUE, is_mul=FALSE, dst_or_op0=qm31_add_dst, op0_or_op1=qm31_op1);
58+
assert runner_output_add_op0 = qm31_op0;
59+
60+
return ();
61+
}
62+
63+
// Forces the runner to execute the QM31_add_mul opcode with the given operands.
64+
// missing_operand, is_imm, is_mul determine the configuration of the operation as described above.
65+
// dst_or_op0 is a felt representing the value of either the op0 (if missing_operand=0) or dst (otherwise) operand.
66+
// op0_or_op1 is a felt representing the value of either the op0 (if missing_operand=2) or op1 (otherwise) operand.
67+
// dst_or_op0 and op0_or_op1 are stored within addresses fp-4 and fp-3 respectively, they are passed to the instruction
68+
// using offsets wrt fp (unless is_imm=TRUE, in which case op1 has offset 1 relative to pc).
69+
// The missing operand has offset 0 relative to ap.
70+
// An instruction encoding with the appropriate flags and offsets is built, then written to [pc] and the runner is forced to execute QM31_add_mul.
71+
// The missing operand is deduced to [ap] and returned.
72+
func run_qm31_operation(
73+
missing_operand: felt,
74+
is_imm: felt,
75+
is_mul: felt,
76+
dst_or_op0: felt,
77+
op0_or_op1: felt,
78+
) -> felt {
79+
alloc_locals;
80+
81+
// Set flags and offsets.
82+
let (local offsets) = alloc();
83+
let (local flags) = alloc();
84+
85+
assert offsets[missing_operand] = 2**15; // the missing operand will be written to [ap]
86+
87+
assert flags[2] = is_imm; // flag_op1_imm = 0;
88+
assert flags[5] = 1-is_mul; // flag_res_add = 1-is_mul;
89+
assert flags[6] = is_mul; // flag_res_mul = is_mul;
90+
assert flags[7] = 0; // flag_PC_update_jump = 0;
91+
assert flags[8] = 0; // flag_PC_update_jump_rel = 0;
92+
assert flags[9] = 0; // flag_PC_update_jnz = 0;
93+
assert flags[10] = 0; // flag_ap_update_add = 0;
94+
assert flags[11] = 0; // flag_ap_update_add_1 = 0;
95+
assert flags[12] = 0; // flag_opcode_call = 0;
96+
assert flags[13] = 0; // flag_opcode_ret = 0;
97+
assert flags[14] = 1; // flag_opcode_assert_eq = 1;
98+
99+
if (missing_operand == 0) {
100+
assert offsets[1] = 2**15 - 4;
101+
assert offsets[2] = 2**15 - 3 + 4 * is_imm;
102+
assert flags[0] = 0; // flag_dst_base_fp
103+
assert flags[1] = 1; // flag_op0_base_fp
104+
}
105+
if (missing_operand == 1) {
106+
assert offsets[0] = 2**15 - 4;
107+
assert offsets[2] = 2**15 - 3 + 4 * is_imm;
108+
assert flags[0] = 1; // flag_dst_base_fp
109+
assert flags[1] = 0; // flag_op0_base_fp
110+
}
111+
if (missing_operand == 2) {
112+
assert is_imm = FALSE;
113+
assert offsets[0] = 2**15 - 4;
114+
assert offsets[1] = 2**15 - 3;
115+
assert flags[0] = 1; // flag_dst_base_fp
116+
assert flags[1] = 1; // flag_op0_base_fp
117+
}
118+
assert flags[3] = 2 - is_imm - flags[0] - flags[1]; // flag_op1_base_fp
119+
assert flags[4] = 1 - is_imm - flags[3]; // flag_op1_base_ap
120+
121+
// Compute the instruction encoding.
122+
let flag_num = flags[0] + flags[1]*(2**1) + flags[2]*(2**2) + flags[3]*(2**3) + flags[4]*(2**4) + flags[5]*(2**5) + flags[6]*(2**6) + flags[14]*(2**14);
123+
let qm31_opcode_extension_num = 3;
124+
let instruction_encoding = offsets[0] + offsets[1]*(2**16) + offsets[2]*(2**32) + flag_num*(2**48) + qm31_opcode_extension_num*(2**63);
125+
126+
// Run the instruction and return the result.
127+
if (is_imm == TRUE) {
128+
assert op0_or_op1 = 0x7cd851b906e2290d9055f6fb6204b18de99;
129+
if (missing_operand == 0) {
130+
if (is_mul == TRUE) {
131+
assert instruction_encoding=0x1c04680017ffc8000;
132+
dw 0x1c04680017ffc8000;
133+
dw 0x7cd851b906e2290d9055f6fb6204b18de99;
134+
return [ap];
135+
}
136+
assert instruction_encoding=0x1c02680017ffc8000;
137+
dw 0x1c02680017ffc8000;
138+
dw 0x7cd851b906e2290d9055f6fb6204b18de99;
139+
return [ap];
140+
}
141+
if (missing_operand == 1) {
142+
if (is_mul == TRUE) {
143+
assert instruction_encoding=0x1c045800180007ffc;
144+
dw 0x1c045800180007ffc;
145+
dw 0x7cd851b906e2290d9055f6fb6204b18de99;
146+
return [ap];
147+
}
148+
assert instruction_encoding=0x1c025800180007ffc;
149+
dw 0x1c025800180007ffc;
150+
dw 0x7cd851b906e2290d9055f6fb6204b18de99;
151+
return [ap];
152+
}
153+
}
154+
155+
if (missing_operand == 0) {
156+
if (is_mul == TRUE) {
157+
assert instruction_encoding=0x1c04a7ffd7ffc8000;
158+
dw 0x1c04a7ffd7ffc8000;
159+
return [ap];
160+
}
161+
assert instruction_encoding=0x1c02a7ffd7ffc8000;
162+
dw 0x1c02a7ffd7ffc8000;
163+
return [ap];
164+
}
165+
if (missing_operand == 1) {
166+
if (is_mul == TRUE) {
167+
assert instruction_encoding=0x1c0497ffd80007ffc;
168+
dw 0x1c0497ffd80007ffc;
169+
return [ap];
170+
}
171+
assert instruction_encoding=0x1c0297ffd80007ffc;
172+
dw 0x1c0297ffd80007ffc;
173+
return [ap];
174+
}
175+
if (is_mul == TRUE) {
176+
dw 0x1c05380007ffd7ffc;
177+
return [ap];
178+
}
179+
dw 0x1c03380007ffd7ffc;
180+
return [ap];
181+
}

vm/src/tests/cairo_run_test.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,14 @@ fn blake2s_opcode_test() {
576576
run_program_simple(program_data.as_slice());
577577
}
578578

579+
#[test]
580+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
581+
fn qm31_opcodes_test() {
582+
let program_data =
583+
include_bytes!("../../../cairo_programs/stwo_exclusive_programs/qm31_opcodes_test.json");
584+
run_program_simple(program_data.as_slice());
585+
}
586+
579587
#[test]
580588
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
581589
fn relocate_segments() {

vm/src/types/errors/math_errors.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,24 @@ pub enum MathError {
4242
RelocatableAddUsizeOffsetExceeded(Box<(Relocatable, usize)>),
4343
#[error("Operation failed: {} + {}, can't add two relocatable values", (*.0).0, (*.0).1)]
4444
RelocatableAdd(Box<(Relocatable, Relocatable)>),
45+
#[error("Operation failed: {} - {}, can't add a relocatable value as a QM31 element", (*.0).0, (*.0).1)]
46+
RelocatableQM31Add(Box<(MaybeRelocatable, MaybeRelocatable)>),
47+
#[error("Operation failed: {} - {}, can't subtract a relocatable value or from a relocatable value as a QM31 element", (*.0).0, (*.0).1)]
48+
RelocatableQM31Sub(Box<(MaybeRelocatable, MaybeRelocatable)>),
49+
#[error("Operation failed: {} * {}, can't multiply a relocatable value", (*.0).0, (*.0).1)]
50+
RelocatableMul(Box<(MaybeRelocatable, MaybeRelocatable)>),
51+
#[error(
52+
"Operation failed: typed_add for an OpcodeExtension that is neither Stone nor QM31Operation"
53+
)]
54+
InvalidAddOpcodeExtension(),
55+
#[error(
56+
"Operation failed: typed_mul for an OpcodeExtension that is neither Stone nor QM31Operation"
57+
)]
58+
InvalidSubOpcodeExtension(),
59+
#[error(
60+
"Operation failed: typed_sub for an OpcodeExtension that is neither Stone nor QM31Operation"
61+
)]
62+
InvalidMulOpcodeExtension(),
4563
#[error("Operation failed: {} - {}, can't subtract two relocatable values with different segment indexes", (*.0).0, (*.0).1)]
4664
RelocatableSubDiffIndex(Box<(Relocatable, Relocatable)>),
4765
#[error(

vm/src/types/instruction.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ pub enum OpcodeExtension {
8282
Stone,
8383
Blake,
8484
BlakeFinalize,
85+
QM31Operation,
8586
}
8687

8788
impl Instruction {

vm/src/types/relocatable.rs

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,14 @@ use crate::stdlib::{
44
prelude::*,
55
};
66

7+
use crate::math_utils::{
8+
qm31_packed_reduced_add, qm31_packed_reduced_mul, qm31_packed_reduced_sub,
9+
};
710
use crate::Felt252;
811
use crate::{
9-
relocatable, types::errors::math_errors::MathError, vm::errors::memory_errors::MemoryError,
12+
relocatable,
13+
types::{errors::math_errors::MathError, instruction::OpcodeExtension},
14+
vm::errors::memory_errors::MemoryError,
1015
};
1116
use num_traits::ToPrimitive;
1217
use serde::{Deserialize, Serialize};
@@ -330,6 +335,89 @@ impl MaybeRelocatable {
330335
}
331336
}
332337

338+
/// Substracts a MaybeRelocatable value from self according to the specified OpcodeExtension.
339+
/// If the OpcodeExtension is Stone it subtracts as MaybeRelocatable::sub does.
340+
/// If the OpcodeExtension is QM31Operation it requires them both to be Int and it subtracts
341+
/// them as packed reduced QM31 elements.
342+
pub fn typed_add(
343+
&self,
344+
other: &MaybeRelocatable,
345+
opcode_extension: OpcodeExtension,
346+
) -> Result<MaybeRelocatable, MathError> {
347+
match opcode_extension {
348+
OpcodeExtension::Stone => self.add(other),
349+
OpcodeExtension::QM31Operation => {
350+
if let (MaybeRelocatable::Int(num_self), MaybeRelocatable::Int(num_other)) =
351+
(self, other)
352+
{
353+
Ok(MaybeRelocatable::Int(qm31_packed_reduced_add(
354+
*num_self, *num_other,
355+
)?))
356+
} else {
357+
Err(MathError::RelocatableQM31Add(Box::new((
358+
self.clone(),
359+
other.clone(),
360+
))))
361+
}
362+
}
363+
_ => Err(MathError::InvalidAddOpcodeExtension()),
364+
}
365+
}
366+
367+
/// Substracts a MaybeRelocatable value from self according to the specified OpcodeExtension.
368+
/// If the OpcodeExtension is Stone it subtracts as MaybeRelocatable::sub does.
369+
/// If the OpcodeExtension is QM31Operation it requires them both to be Int and it subtracts
370+
/// them as packed reduced QM31 elements.
371+
pub fn typed_sub(
372+
&self,
373+
other: &MaybeRelocatable,
374+
opcode_extension: OpcodeExtension,
375+
) -> Result<MaybeRelocatable, MathError> {
376+
match opcode_extension {
377+
OpcodeExtension::Stone => self.sub(other),
378+
OpcodeExtension::QM31Operation => {
379+
if let (MaybeRelocatable::Int(num_self), MaybeRelocatable::Int(num_other)) =
380+
(self, other)
381+
{
382+
Ok(MaybeRelocatable::Int(qm31_packed_reduced_sub(
383+
*num_self, *num_other,
384+
)?))
385+
} else {
386+
Err(MathError::RelocatableQM31Sub(Box::new((
387+
self.clone(),
388+
other.clone(),
389+
))))
390+
}
391+
}
392+
_ => Err(MathError::InvalidSubOpcodeExtension()),
393+
}
394+
}
395+
396+
/// Multiplies self and another MaybeRelocatable value according to the specified OpcodeExtension.
397+
/// Requires both operands to be Int.
398+
/// If the OpcodeExtension is Stone it multiplies them as Felts.
399+
/// If the OpcodeExtension is QM31Operation it multiplies them as packed reduced QM31 elements.
400+
pub fn typed_mul(
401+
&self,
402+
other: &MaybeRelocatable,
403+
opcode_extension: OpcodeExtension,
404+
) -> Result<MaybeRelocatable, MathError> {
405+
if let (MaybeRelocatable::Int(num_self), MaybeRelocatable::Int(num_other)) = (self, other) {
406+
match opcode_extension {
407+
OpcodeExtension::Stone => Ok(MaybeRelocatable::Int(num_self * num_other)),
408+
OpcodeExtension::QM31Operation => Ok(MaybeRelocatable::Int(
409+
qm31_packed_reduced_mul(*num_self, *num_other)?,
410+
)),
411+
_ => Err(MathError::InvalidMulOpcodeExtension()),
412+
}
413+
} else {
414+
Err(MathError::RelocatableMul(Box::new((
415+
self.clone(),
416+
other.clone(),
417+
))))
418+
}
419+
}
420+
333421
// TODO: Check if its more performant to use get_int instead
334422
/// Returns a reference to the inner value if it is a Felt252, returns None otherwise.
335423
pub fn get_int_ref(&self) -> Option<&Felt252> {
@@ -678,6 +766,48 @@ mod tests {
678766
);
679767
}
680768

769+
#[test]
770+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
771+
fn typed_add_blake() {
772+
let a = &MaybeRelocatable::from(5);
773+
let b = &MaybeRelocatable::from(6);
774+
let error = a.typed_add(b, OpcodeExtension::Blake);
775+
assert_eq!(error, Err(MathError::InvalidAddOpcodeExtension()));
776+
}
777+
778+
#[test]
779+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
780+
fn typed_sub_blake() {
781+
let a = &MaybeRelocatable::from(7);
782+
let b = &MaybeRelocatable::from(3);
783+
let error = a.typed_sub(b, OpcodeExtension::Blake);
784+
assert_eq!(error, Err(MathError::InvalidSubOpcodeExtension()));
785+
}
786+
787+
#[test]
788+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
789+
fn relocatable_typed_sub_q31_operation() {
790+
let a = &MaybeRelocatable::from((6, 8));
791+
let b = &MaybeRelocatable::from(2);
792+
let error = a.typed_sub(b, OpcodeExtension::QM31Operation);
793+
assert_eq!(
794+
error,
795+
Err(MathError::RelocatableQM31Sub(Box::new((
796+
MaybeRelocatable::from((6, 8)),
797+
MaybeRelocatable::from(2)
798+
))))
799+
);
800+
}
801+
802+
#[test]
803+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
804+
fn typed_mul_blake_finalize() {
805+
let a = &MaybeRelocatable::from(4);
806+
let b = &MaybeRelocatable::from(9);
807+
let error = a.typed_mul(b, OpcodeExtension::BlakeFinalize);
808+
assert_eq!(error, Err(MathError::InvalidMulOpcodeExtension()));
809+
}
810+
681811
#[test]
682812
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
683813
fn divmod_working() {

0 commit comments

Comments
 (0)