Skip to content

Commit

Permalink
Cairo v0.11.0 (pre2).
Browse files Browse the repository at this point in the history
  • Loading branch information
liorgold2 committed Mar 17, 2023
1 parent 12ca9e9 commit 706ae5f
Show file tree
Hide file tree
Showing 98 changed files with 3,078 additions and 868 deletions.
2 changes: 1 addition & 1 deletion scripts/requirements-gen.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ prometheus-client
pytest
pytest-asyncio
PyYAML
typeguard
typeguard<3.0.0
sympy
Web3
27 changes: 27 additions & 0 deletions src/cmake_utils/python_rules.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,30 @@ function(full_python_test TEST_NAME)
${CODE_COVERAGE_SUPPRESSION_FLAG}
)
endfunction()

function(starknet_contract_v1 NAME)
# Parse arguments.
set(options)
set(oneValueArgs MAIN COMPILED_SIERRA_NAME COMPILED_CASM_NAME)
set(multiValueArgs)
cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_SIERRA_NAME}
COMMAND
${CMAKE_BINARY_DIR}/src/starkware/starknet/compiler/v1/cairo/bin/starknet-compile
${CMAKE_CURRENT_SOURCE_DIR}/${ARGS_MAIN}
${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_SIERRA_NAME}
DEPENDS get_cairo_compiler ${CMAKE_CURRENT_SOURCE_DIR}/${ARGS_MAIN}
)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_CASM_NAME}
COMMAND
${CMAKE_BINARY_DIR}/src/starkware/starknet/compiler/v1/cairo/bin/starknet-sierra-compile
--add-pythonic-hints
${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_SIERRA_NAME}
${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_CASM_NAME}
DEPENDS get_cairo_compiler ${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_SIERRA_NAME}
)
add_custom_target(${NAME} ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_SIERRA_NAME} ${CMAKE_CURRENT_BINARY_DIR}/${ARGS_COMPILED_CASM_NAME})
endfunction()
2 changes: 2 additions & 0 deletions src/starkware/cairo/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ python_lib(cairo_common_lib
merkle_update.cairo
patricia_utils.py
patricia_with_sponge.cairo
patricia_with_poseidon.cairo
patricia_utils.cairo
patricia.cairo
poseidon_state.cairo
pow.cairo
Expand Down
5 changes: 2 additions & 3 deletions src/starkware/cairo/common/cairo_function_runner.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from collections.abc import Iterable
from typing import Any, Dict, Optional, Tuple, Union, cast

from starkware.cairo.common.poseidon_utils import PoseidonParams
from starkware.cairo.common.structs import CairoStructFactory
from starkware.cairo.lang.builtins.bitwise.bitwise_builtin_runner import BitwiseBuiltinRunner
from starkware.cairo.lang.builtins.bitwise.instance_def import BitwiseInstanceDef
Expand Down Expand Up @@ -78,7 +77,6 @@ def __init__(self, *args, **kwargs):
included=True,
instance_def=PoseidonInstanceDef(
ratio=1,
params=PoseidonParams.get_default_poseidon_params(),
partial_rounds_partition=[64, 22],
),
)
Expand Down Expand Up @@ -246,6 +244,7 @@ def run_from_entrypoint(
verify_secure: Optional[bool] = None,
program_segment_size: Optional[int] = None,
apply_modulo_to_args: Optional[bool] = None,
allow_tmp_segments: bool = False,
):
"""
Runs the program from the given entrypoint.
Expand Down Expand Up @@ -276,7 +275,7 @@ def run_from_entrypoint(
self.initialize_vm(hint_locals=hint_locals, static_locals=static_locals)

self.run_until_pc(addr=end, run_resources=run_resources)
self.end_run()
self.end_run(allow_tmp_segments=allow_tmp_segments)

if verify_secure:
verify_secure_runner(
Expand Down
4 changes: 2 additions & 2 deletions src/starkware/cairo/common/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ def new_dict(self, segments, initial_dict):
)
return base

def new_default_dict(self, segments, default_value):
def new_default_dict(self, segments, default_value, temp_segment: bool = False):
"""
Creates a new Cairo default dictionary.
"""
base = segments.add()
base = segments.add_temp_segment() if temp_segment else segments.add()
assert base.segment_index not in self.trackers
self.trackers[base.segment_index] = DictTracker(
data=defaultdict(lambda: default_value),
Expand Down
30 changes: 6 additions & 24 deletions src/starkware/cairo/common/patricia.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,15 @@ from starkware.cairo.common.math import (
assert_nn_le,
assert_not_zero,
)
from starkware.cairo.common.patricia_utils import (
MAX_LENGTH,
NodeEdge,
ParticiaGlobals,
PatriciaUpdateConstants,
)

// ADDITIONAL_IMPORTS_MACRO()

// Maximum length of an edge.
const MAX_LENGTH = 251;

// A struct of globals that are passed throughout the algorithm.
struct ParticiaGlobals {
// An array of size MAX_LENGTH, where pow2[i] = 2**i.
pow2: felt*,
// Offset of the relevant value field in DictAccess.
// 1 if the previous tree is traversed and 2 if the new tree is traversed.
access_offset: felt,
}

// Represents an edge node: a subtree with a path, s.t. all leaves not under that path are 0.
struct NodeEdge {
length: felt,
path: felt,
bottom: felt,
}

// Holds the constants needed for Patricia updates.
struct PatriciaUpdateConstants {
globals_pow2: felt*,
}

// Given an edge node hash, opens the hash using the preimage hint, and returns a NodeEdge object.
func open_edge{hash_ptr: HashBuiltin*, range_check_ptr}(globals: ParticiaGlobals*, node: felt) -> (
edge: NodeEdge*
Expand Down
23 changes: 23 additions & 0 deletions src/starkware/cairo/common/patricia_utils.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Maximum length of an edge.
const MAX_LENGTH = 251;

// A struct of globals that are passed throughout the algorithm.
struct ParticiaGlobals {
// An array of size MAX_LENGTH, where pow2[i] = 2**i.
pow2: felt*,
// Offset of the relevant value field in DictAccess.
// 1 if the previous tree is traversed and 2 if the new tree is traversed.
access_offset: felt,
}

// Represents an edge node: a subtree with a path, s.t. all leaves not under that path are 0.
struct NodeEdge {
length: felt,
path: felt,
bottom: felt,
}

// Holds the constants needed for Patricia updates.
struct PatriciaUpdateConstants {
globals_pow2: felt*,
}
34 changes: 34 additions & 0 deletions src/starkware/cairo/common/patricia_with_poseidon.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from starkware.cairo.common.cairo_builtins import PoseidonBuiltin
from starkware.cairo.common.dict import DictAccess
from starkware.cairo.common.patricia_utils import PatriciaUpdateConstants
from starkware.cairo.common.patricia_with_sponge import (
patricia_update_using_update_constants as patricia_update_using_update_constants_with_sponge,
)
from starkware.cairo.common.sponge_as_hash import SpongeHashBuiltin

func patricia_update_using_update_constants{poseidon_ptr: PoseidonBuiltin*, range_check_ptr}(
patricia_update_constants: PatriciaUpdateConstants*,
update_ptr: DictAccess*,
n_updates: felt,
height: felt,
prev_root: felt,
new_root: felt,
) {
let hash_ptr = cast(poseidon_ptr, SpongeHashBuiltin*);

with hash_ptr {
patricia_update_using_update_constants_with_sponge(
patricia_update_constants=patricia_update_constants,
update_ptr=update_ptr,
n_updates=n_updates,
height=height,
prev_root=prev_root,
new_root=new_root,
);
}

// Update poseidon_ptr.
let poseidon_ptr = cast(hash_ptr, PoseidonBuiltin*);

return ();
}
30 changes: 6 additions & 24 deletions src/starkware/cairo/common/patricia_with_sponge.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,15 @@ from starkware.cairo.common.math import (
assert_nn_le,
assert_not_zero,
)
from starkware.cairo.common.patricia_utils import (
MAX_LENGTH,
NodeEdge,
ParticiaGlobals,
PatriciaUpdateConstants,
)
from starkware.cairo.common.sponge_as_hash import SpongeHashBuiltin as HashBuiltin
from starkware.cairo.common.sponge_as_hash import sponge_hash2 as hash2

// Maximum length of an edge.
const MAX_LENGTH = 251;

// A struct of globals that are passed throughout the algorithm.
struct ParticiaGlobals {
// An array of size MAX_LENGTH, where pow2[i] = 2**i.
pow2: felt*,
// Offset of the relevant value field in DictAccess.
// 1 if the previous tree is traversed and 2 if the new tree is traversed.
access_offset: felt,
}

// Represents an edge node: a subtree with a path, s.t. all leaves not under that path are 0.
struct NodeEdge {
length: felt,
path: felt,
bottom: felt,
}

// Holds the constants needed for Patricia updates.
struct PatriciaUpdateConstants {
globals_pow2: felt*,
}

// Given an edge node hash, opens the hash using the preimage hint, and returns a NodeEdge object.
func open_edge{hash_ptr: HashBuiltin*, range_check_ptr}(globals: ParticiaGlobals*, node: felt) -> (
edge: NodeEdge*
Expand Down
2 changes: 1 addition & 1 deletion src/starkware/cairo/lang/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.11.0a0
0.11.0a1
1 change: 1 addition & 0 deletions src/starkware/cairo/lang/builtins/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ python_lib(cairo_run_builtins_lib
LIBS
cairo_common_lib
cairo_relocatable_lib
cairo_vm_crypto_lib
cairo_vm_lib
starkware_python_utils_lib
)
Expand Down
7 changes: 2 additions & 5 deletions src/starkware/cairo/lang/builtins/poseidon/instance_def.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import dataclasses
from typing import List, Optional

from starkware.cairo.common.poseidon_utils import PoseidonParams
POSEIDON_M = 3


@dataclasses.dataclass
Expand All @@ -10,15 +10,12 @@ class PoseidonInstanceDef:
# None means dynamic ratio.
ratio: Optional[int]

# Defines the Hades permutation.
params: PoseidonParams

# Defines the partition of the partial rounds to virtual columns.
partial_rounds_partition: List[int]

@property
def cells_per_builtin(self):
return 2 * self.params.m
return 2 * POSEIDON_M

@property
def range_check_units_per_builtin(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from typing import Any, Dict, Set

from starkware.cairo.common.poseidon_utils import hades_permutation
from starkware.cairo.lang.builtins.poseidon.instance_def import PoseidonInstanceDef
from starkware.cairo.lang.vm.builtin_runner import SimpleBuiltinRunner
from starkware.cairo.lang.vm.crypto import poseidon_perm
from starkware.cairo.lang.vm.relocatable import MaybeRelocatable, RelocatableValue
from starkware.python.math_utils import safe_div

Expand Down Expand Up @@ -45,7 +45,7 @@ def rule(vm, addr, verified_addresses):
+ f"Got: {value}."
)
input_state = memory.get_range(first_input_addr, self.n_input_cells)
output_state = hades_permutation(input_state, self.instance_def.params)
output_state = poseidon_perm(*input_state)
for i in range(self.n_input_cells):
self.cache[first_output_addr + i] = output_state[i]
return self.cache[addr]
Expand Down
17 changes: 1 addition & 16 deletions src/starkware/cairo/lang/compiler/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,7 @@ def run_validity_checks(self):


@marshmallow_dataclass.dataclass(repr=False)
class HintedProgram(ProgramBase, SerializableMarshmallowDataclass):
"""
A Serializable Cairo Program with hints.
"""

class Program(ProgramBase, SerializableMarshmallowDataclass):
prime: int = field(metadata=additional_metadata(marshmallow_field=IntAsHex(required=True)))
data: List[int] = field(
metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex(), required=True))
Expand All @@ -95,17 +91,6 @@ class HintedProgram(ProgramBase, SerializableMarshmallowDataclass):
compiler_version: Optional[str] = field(
metadata=dict(marshmallow_field=mfields.String(required=False, load_default=None))
)

def stripped(self) -> StrippedProgram:
raise NotImplementedError("HintedProgram does not have a main entrypoint.")

@property
def main(self) -> Optional[int]: # type: ignore
raise NotImplementedError("HintedProgram does not have a main entrypoint.")


@marshmallow_dataclass.dataclass(repr=False)
class Program(HintedProgram):
main_scope: ScopedName = field(
metadata=additional_metadata(marshmallow_field=ScopedNameAsStr())
)
Expand Down
4 changes: 0 additions & 4 deletions src/starkware/cairo/lang/instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from dataclasses import field
from typing import Any, Dict, Optional

from starkware.cairo.common.poseidon_utils import PoseidonParams
from starkware.cairo.lang.builtins.bitwise.instance_def import BitwiseInstanceDef
from starkware.cairo.lang.builtins.ec.instance_def import EcOpInstanceDef
from starkware.cairo.lang.builtins.hash.instance_def import PedersenInstanceDef
Expand Down Expand Up @@ -195,7 +194,6 @@ def build_dynamic_layout(**ratios) -> CairoLayout:
),
poseidon=PoseidonInstanceDef(
ratio=32,
params=PoseidonParams.get_default_poseidon_params(),
partial_rounds_partition=[64, 22],
),
),
Expand Down Expand Up @@ -247,7 +245,6 @@ def build_dynamic_layout(**ratios) -> CairoLayout:
),
poseidon=PoseidonInstanceDef(
ratio=32,
params=PoseidonParams.get_default_poseidon_params(),
partial_rounds_partition=[64, 22],
),
),
Expand Down Expand Up @@ -366,7 +363,6 @@ def build_dynamic_layout(**ratios) -> CairoLayout:
),
poseidon=PoseidonInstanceDef(
ratio=256,
params=PoseidonParams.get_default_poseidon_params(),
partial_rounds_partition=[64, 22],
),
),
Expand Down
2 changes: 1 addition & 1 deletion src/starkware/cairo/lang/tracer/tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
def trace_runner(runner):
runner.vm_memory.relocate_memory()
runner.vm_memory.freeze()
runner.segments.compute_effective_sizes(include_tmp_segments=True)
runner.segments.compute_effective_sizes(allow_tmp_segments=True)
if not hasattr(runner, "relocated_trace"):
runner.relocate()

Expand Down
Loading

0 comments on commit 706ae5f

Please sign in to comment.