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

Fix CairoPie serialization. #1444

Merged
merged 19 commits into from
Sep 18, 2023
Merged
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ cairo-vm-pypy-env/*
*.tar

ensure-no_std/Cargo.lock

!vm/src/tests/cairo_pie_test_output.json
28 changes: 15 additions & 13 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#### Upcoming Changes

* fix: Remove Deserialize derive from CairoPie and fix Serialize implementation to match Python's [#1444](https://github.com/lambdaclass/cairo-vm/pull/1444)

* fix: ec_recover hints no longer panic when divisor is 0 [#1433](https://github.com/lambdaclass/cairo-vm/pull/1433)

* feat: Implement the Serialize and Deserialize traits for the CairoPie struct [#1438](https://github.com/lambdaclass/cairo-vm/pull/1438)
Expand Down Expand Up @@ -107,7 +109,7 @@
`get_hint_data(self, &[HintReference], &mut dyn HintProcessor) -> Result<Vec<Box<dyn Any>, VirtualMachineError>`
* Hook methods receive `&[Box<dyn Any>]` rather than `&HashMap<usize, Vec<Box<dyn Any>>>`

#### [0.8.4]
pefontana marked this conversation as resolved.
Show resolved Hide resolved
#### [0.8.4]
**YANKED**

#### [0.8.3]
Expand Down Expand Up @@ -194,12 +196,12 @@

* BREAKING: Change `RunResources` usage:
* Modify field type `RunResources.n_steps: Option<usize>,`

* Public Api Changes:
* CairoRunner::run_until_pc: Now receive a `&mut RunResources` instead of an `&mut Option<RunResources>`
* CairoRunner::run_from_entrypoint: Now receive a `&mut RunResources` instead of an `&mut Option<RunResources>`
* VirtualMachine::Step: Add `&mut RunResources` as input
* Trait HintProcessor::execute_hint: Add `&mut RunResources` as an input
* Trait HintProcessor::execute_hint: Add `&mut RunResources` as an input

* perf: accumulate `min` and `max` instruction offsets during run to speed up range check [#1080](https://github.com/lambdaclass/cairo-vm/pull/)
BREAKING: `Cairo_runner::get_perm_range_check_limits` no longer returns an error when called without trace enabled, as it no longer depends on it
Expand All @@ -213,7 +215,7 @@
* BREAKING: Add no_std compatibility to cairo-vm (cairo-1-hints feature still not supported)
* Move the vm to its own directory and crate, different from the workspace [#1215](https://github.com/lambdaclass/cairo-vm/pull/1215)

* Add an `ensure_no_std` crate that the CI will use to check that new changes don't revert `no_std` support [#1215](https://github.com/lambdaclass/cairo-vm/pull/1215) [#1232](https://github.com/lambdaclass/cairo-vm/pull/1232)
* Add an `ensure_no_std` crate that the CI will use to check that new changes don't revert `no_std` support [#1215](https://github.com/lambdaclass/cairo-vm/pull/1215) [#1232](https://github.com/lambdaclass/cairo-vm/pull/1232)

* replace the use of `num-prime::is_prime` by a custom implementation, therefore restoring `no_std` compatibility [#1238](https://github.com/lambdaclass/cairo-vm/pull/1238)

Expand Down Expand Up @@ -514,7 +516,7 @@

value = x_inv = div_mod(1, x, SECP_P)
```

* Implement hint for `starkware.cairo.common.cairo_keccak.keccak._copy_inputs` as described by whitelist `starknet/security/whitelists/cairo_keccak.json` [#1058](https://github.com/lambdaclass/cairo-vm/pull/1058)

`BuiltinHintProcessor` now supports the following hint:
Expand Down Expand Up @@ -1163,7 +1165,7 @@
* Implement hint on vrf.json lib [#1049](https://github.com/lambdaclass/cairo-vm/pull/1049)

`BuiltinHintProcessor` now supports the following hint:

```python
def split(num: int, num_bits_shift: int, length: int):
a = []
Expand Down Expand Up @@ -1306,19 +1308,19 @@
* Implement hint on uint384_extension lib [#983](https://github.com/lambdaclass/cairo-vm/pull/983)

`BuiltinHintProcessor` now supports the following hint:

```python
def split(num: int, num_bits_shift: int, length: int):
a = []
for _ in range(length):
a.append( num & ((1 << num_bits_shift) - 1) )
num = num >> num_bits_shift
num = num >> num_bits_shift
return tuple(a)

def pack(z, num_bits_shift: int) -> int:
limbs = (z.d0, z.d1, z.d2)
return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))

def pack_extended(z, num_bits_shift: int) -> int:
limbs = (z.d0, z.d1, z.d2, z.d3, z.d4, z.d5)
return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
Expand Down Expand Up @@ -1354,13 +1356,13 @@
* Add missing hints [#1014](https://github.com/lambdaclass/cairo-vm/pull/1014):
`BuiltinHintProcessor` now supports the following hints:
```python
from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P as SECP_P
from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P as SECP_P
```
and:
and:
```python
from starkware.cairo.common.cairo_secp.secp_utils import pack
from starkware.python.math_utils import line_slope

# Compute the slope.
x0 = pack(ids.point0.x, PRIME)
y0 = pack(ids.point0.y, PRIME)
Expand All @@ -1379,7 +1381,7 @@
s = pack(ids.s, PRIME) % N
value = res = div_mod(x, s, N)
```
and:
and:
```python
value = k = safe_div(res * s - x, N)
```
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,7 @@
use crate::{
stdlib::{collections::HashMap, prelude::*},
vm::runners::cairo_pie::CairoPie,
};

use felt::felt_str;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{
string::{String, ToString},
vec::Vec,
};

use crate::{
cairo_run::{cairo_run, CairoRunConfig},
hint_processor::builtin_hint_processor::builtin_hint_processor_definition::BuiltinHintProcessor,
stdlib::{collections::HashMap, prelude::*},
types::relocatable::Relocatable,
vm::runners::{
builtin_runner::{
Expand All @@ -29,6 +14,16 @@ use crate::{
cairo_runner::ExecutionResources,
},
};
use felt::felt_str;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{
string::{String, ToString},
vec::Vec,
};

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
Expand Down Expand Up @@ -251,14 +246,14 @@ fn relocate_segments() {

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn serialize_and_deserialize_cairo_pie() {
fn serialize_cairo_pie() {
// Run the program
let program_content = include_bytes!("../../../cairo_programs/relocate_segments.json");
let program_content = include_bytes!("../../../cairo_programs/print.json");
let mut hint_processor = BuiltinHintProcessor::new_empty();
let result = cairo_run(
program_content,
&CairoRunConfig {
layout: "all_cairo",
layout: "small",
..Default::default()
},
&mut hint_processor,
Expand All @@ -269,7 +264,10 @@ fn serialize_and_deserialize_cairo_pie() {
let result = runner.get_cairo_pie(&vm);
assert!(result.is_ok());
let cairo_pie = result.unwrap();
let cairo_pie_serialized = serde_json::to_string(&cairo_pie).unwrap();
let cairo_pie_deserialized: CairoPie = serde_json::from_str(&cairo_pie_serialized).unwrap();
assert_eq!(cairo_pie_deserialized, cairo_pie);

assert_eq!(
serde_json::to_value(cairo_pie).unwrap(),
serde_json::from_str::<serde_json::Value>(include_str!("cairo_pie_test_output.json"))
.unwrap(),
);
}
110 changes: 110 additions & 0 deletions vm/src/tests/cairo_pie_test_output.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
{
"additional_data": {
"output_builtin": {
"pages": {},
"attributes": {}
}
},
"execution_resources": {
"n_memory_holes": 0,
"builtin_instance_counter": {
"output_builtin": 1
},
"n_steps": 7
},
"memory": [
[
4612671182993129469,
5198983563776393216,
1,
2345108766317314046,
5191102247248822272,
5189976364521848832,
1234,
1226245742482522112,
3618502788666131213697322783095070105623107215331596699973092056135872020474,
2345108766317314046
],
[
[
2,
0
],
[
3,
0
],
[
4,
0
],
[
2,
0
],
1234,
[
1,
3
],
[
0,
9
],
[
2,
1
]
],
[
1234
]
],
"metadata": {
"extra_segments": [],
"ret_pc_segment": {
"size": 0,
"index": 4
},
"execution_segment": {
"size": 8,
"index": 1
},
"program": {
"builtins": [
"output"
],
"prime": 3618502788666131213697322783095070105623107215331596699973092056135872020481,
"main": 4,
"data": [
4612671182993129469,
5198983563776393216,
1,
2345108766317314046,
5191102247248822272,
5189976364521848832,
1234,
1226245742482522112,
3618502788666131213697322783095070105623107215331596699973092056135872020474,
2345108766317314046
]
},
"ret_fp_segment": {
"size": 0,
"index": 3
},
"builtin_segments": {
"output": {
"size": 1,
"index": 2
}
},
"program_segment": {
"size": 10,
"index": 0
}
},
"version": {
"cairo_pie": "1.1"
}
}
2 changes: 1 addition & 1 deletion vm/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ mod cairo_run_test;
mod pedersen_test;
mod struct_test;

mod get_cairo_pie_tests;
mod cairo_pie_test;
#[cfg(feature = "skip_next_instruction_hint")]
mod skip_instruction_test;

Expand Down
20 changes: 8 additions & 12 deletions vm/src/types/program.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use crate::stdlib::{
collections::{BTreeMap, HashMap},
prelude::*,
sync::Arc,
use crate::{
stdlib::{
collections::{BTreeMap, HashMap},
prelude::*,
sync::Arc,
},
vm::runners::cairo_pie::StrippedProgram,
};

#[cfg(feature = "cairo-1-hints")]
Expand All @@ -20,7 +23,6 @@ use crate::{
use cairo_lang_starknet::casm_contract_class::CasmContractClass;
use core::num::NonZeroUsize;
use felt::{Felt252, PRIME_STR};
use serde::{Deserialize, Serialize};

#[cfg(feature = "std")]
use std::path::Path;
Expand Down Expand Up @@ -164,13 +166,6 @@ pub struct Program {
pub(crate) builtins: Vec<BuiltinName>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct StrippedProgram {
pub data: Vec<MaybeRelocatable>,
pub builtins: Vec<BuiltinName>,
pub main: usize,
}

impl Program {
#[allow(clippy::too_many_arguments)]
pub fn new(
Expand Down Expand Up @@ -332,6 +327,7 @@ impl Program {
.shared_program_data
.main
.ok_or(ProgramError::StrippedProgramNoMain)?,
prime: (),
})
}
}
Expand Down
Loading