Skip to content

Commit 7925df2

Browse files
add qm31 operations to VM
1 parent d733ade commit 7925df2

File tree

10 files changed

+475
-35
lines changed

10 files changed

+475
-35
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/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ pub mod hint_processor;
6161
pub mod math_utils;
6262
pub mod program_hash;
6363
pub mod serde;
64+
pub mod typed_operations;
6465
pub mod types;
6566
pub mod utils;
6667
pub mod vm;

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/typed_operations.rs

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
use crate::math_utils::{
2+
qm31_packed_reduced_add, qm31_packed_reduced_div, qm31_packed_reduced_mul,
3+
qm31_packed_reduced_sub,
4+
};
5+
use crate::stdlib::prelude::*;
6+
use crate::types::relocatable::MaybeRelocatable;
7+
use crate::types::{errors::math_errors::MathError, instruction::OpcodeExtension};
8+
use crate::vm::errors::vm_errors::VirtualMachineError;
9+
use crate::Felt252;
10+
11+
/// Adds two MaybeRelocatable values according to the specified OpcodeExtension and returns the
12+
/// result as a MaybeRelocatable value.
13+
/// If the OpcodeExtension is Stone it adds them as MaybeRelocatable::add does.
14+
/// If the OpcodeExtension is QM31Operation it requires them both to be Int and it adds them
15+
/// as packed reduced QM31 elements.
16+
pub fn typed_add(
17+
x: &MaybeRelocatable,
18+
y: &MaybeRelocatable,
19+
opcode_extension: OpcodeExtension,
20+
) -> Result<MaybeRelocatable, VirtualMachineError> {
21+
match opcode_extension {
22+
OpcodeExtension::Stone => Ok(x.add(y)?),
23+
OpcodeExtension::QM31Operation => {
24+
if let (MaybeRelocatable::Int(num_x), MaybeRelocatable::Int(num_y)) = (x, y) {
25+
Ok(MaybeRelocatable::Int(qm31_packed_reduced_add(
26+
*num_x, *num_y,
27+
)?))
28+
} else {
29+
Err(VirtualMachineError::Math(MathError::RelocatableQM31Add(
30+
Box::new((x.clone(), y.clone())),
31+
)))
32+
}
33+
}
34+
_ => Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(
35+
"typed_add".to_owned().into_boxed_str(),
36+
)),
37+
}
38+
}
39+
40+
/// Substracts two MaybeRelocatable values according to the specified OpcodeExtension and returns
41+
/// the result as a MaybeRelocatable value.
42+
/// If the OpcodeExtension is Stone it subtracts them as MaybeRelocatable::sub does.
43+
/// If the OpcodeExtension is QM31Operation it requires them both to be Int and it subtracts
44+
/// them as packed reduced QM31 elements.
45+
pub fn typed_sub(
46+
x: &MaybeRelocatable,
47+
y: &MaybeRelocatable,
48+
opcode_extension: OpcodeExtension,
49+
) -> Result<MaybeRelocatable, VirtualMachineError> {
50+
match opcode_extension {
51+
OpcodeExtension::Stone => Ok(x.sub(y)?),
52+
OpcodeExtension::QM31Operation => {
53+
if let (MaybeRelocatable::Int(num_x), MaybeRelocatable::Int(num_y)) = (x, y) {
54+
Ok(MaybeRelocatable::Int(qm31_packed_reduced_sub(
55+
*num_x, *num_y,
56+
)?))
57+
} else {
58+
Err(VirtualMachineError::Math(MathError::RelocatableQM31Sub(
59+
Box::new((x.clone(), y.clone())),
60+
)))
61+
}
62+
}
63+
_ => Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(
64+
"typed_sub".to_owned().into_boxed_str(),
65+
)),
66+
}
67+
}
68+
69+
/// Multiplies two MaybeRelocatable values according to the specified OpcodeExtension and returns
70+
/// the result as a MaybeRelocatable value.
71+
/// Requires both operands to be Int.
72+
/// If the OpcodeExtension is Stone it multiplies them as Felts.
73+
/// If the OpcodeExtension is QM31Operation it multiplies them as packed reduced QM31 elements.
74+
pub fn typed_mul(
75+
x: &MaybeRelocatable,
76+
y: &MaybeRelocatable,
77+
opcode_extension: OpcodeExtension,
78+
) -> Result<MaybeRelocatable, VirtualMachineError> {
79+
if let (MaybeRelocatable::Int(num_x), MaybeRelocatable::Int(num_y)) = (x, y) {
80+
match opcode_extension {
81+
OpcodeExtension::Stone => Ok(MaybeRelocatable::Int(num_x * num_y)),
82+
OpcodeExtension::QM31Operation => Ok(MaybeRelocatable::Int(qm31_packed_reduced_mul(
83+
*num_x, *num_y,
84+
)?)),
85+
_ => Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(
86+
"typed_mul".to_owned().into_boxed_str(),
87+
)),
88+
}
89+
} else {
90+
Err(VirtualMachineError::ComputeResRelocatableMul(Box::new((
91+
x.clone(),
92+
y.clone(),
93+
))))
94+
}
95+
}
96+
97+
/// Divides two Felt252 values according to the specified OpcodeExtension and returns the result
98+
/// as a Felt252 value.
99+
/// If the OpcodeExtension is Stone it divides them as Felts.
100+
/// If the OpcodeExtension is QM31Operation it divides them as packed reduced QM31 elements.
101+
pub fn typed_div(
102+
x: &Felt252,
103+
y: &Felt252,
104+
opcode_extension: OpcodeExtension,
105+
) -> Result<Felt252, VirtualMachineError> {
106+
match opcode_extension {
107+
OpcodeExtension::Stone => {
108+
Ok(x.field_div(&y.try_into().map_err(|_| MathError::DividedByZero)?))
109+
}
110+
OpcodeExtension::QM31Operation => Ok(qm31_packed_reduced_div(*x, *y)?),
111+
_ => Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(
112+
"typed_div".to_owned().into_boxed_str(),
113+
)),
114+
}
115+
}
116+
#[cfg(test)]
117+
mod decoder_test {
118+
use super::*;
119+
use assert_matches::assert_matches;
120+
121+
#[cfg(target_arch = "wasm32")]
122+
use wasm_bindgen_test::*;
123+
124+
#[test]
125+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
126+
fn typed_add_blake() {
127+
let a = &MaybeRelocatable::from(5);
128+
let b = &MaybeRelocatable::from(6);
129+
let error = typed_add(a, b, OpcodeExtension::Blake);
130+
assert_matches!(
131+
error,
132+
Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(ref message)) if message.as_ref() == "typed_add"
133+
);
134+
}
135+
136+
#[test]
137+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
138+
fn typed_sub_blake() {
139+
let a = &MaybeRelocatable::from(7);
140+
let b = &MaybeRelocatable::from(3);
141+
let error = typed_sub(a, b, OpcodeExtension::Blake);
142+
assert_matches!(
143+
error,
144+
Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(ref message)) if message.as_ref() == "typed_sub"
145+
);
146+
}
147+
148+
#[test]
149+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
150+
fn relocatable_typed_sub_q31_operation() {
151+
let a = &MaybeRelocatable::from((6, 8));
152+
let b = &MaybeRelocatable::from(2);
153+
let error = typed_sub(a, b, OpcodeExtension::QM31Operation);
154+
assert_matches!(
155+
error,
156+
Err(VirtualMachineError::Math(MathError::RelocatableQM31Sub(bx))) if *bx ==
157+
(MaybeRelocatable::from((6, 8)), MaybeRelocatable::from(2))
158+
);
159+
}
160+
161+
#[test]
162+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
163+
fn typed_mul_blake_finalize() {
164+
let a = &MaybeRelocatable::from(4);
165+
let b = &MaybeRelocatable::from(9);
166+
let error = typed_mul(a, b, OpcodeExtension::BlakeFinalize);
167+
assert_matches!(
168+
error,
169+
Err(VirtualMachineError::InvalidTypedOperationOpcodeExtension(ref message)) if message.as_ref() == "typed_mul"
170+
);
171+
}
172+
}

vm/src/types/errors/math_errors.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ 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)>),
4549
#[error("Operation failed: {} - {}, can't subtract two relocatable values with different segment indexes", (*.0).0, (*.0).1)]
4650
RelocatableSubDiffIndex(Box<(Relocatable, Relocatable)>),
4751
#[error(

0 commit comments

Comments
 (0)