repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/coupon.rs | src/types/coupon.rs | //! # Coupon type.
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
coupon::CouponConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::llvm,
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<CouponConcreteType>,
) -> Result<Type<'ctx>> {
Ok(llvm::r#type::array(IntegerType::new(context, 8).into(), 0))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/box.rs | src/types/box.rs | //! # Box type
//!
//! The type box for a given type `T`.
//!
//! ## Layout
//!
//! Its layout is that of whatever it wraps. In other words, if it was Rust it would be equivalent
//! to the following:
//!
//! ```
//! #[repr(transparent)]
//! pub struct Box<T>(pub T);
//! ```
use super::WithSelf;
use crate::{
error::Result,
metadata::{
drop_overrides::DropOverridesMeta, dup_overrides::DupOverridesMeta,
realloc_bindings::ReallocBindingsMeta, MetadataStorage,
},
types::TypeBuilder,
utils::ProgramRegistryExt,
};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::{func, llvm, ods},
helpers::{ArithBlockExt, BuiltinBlockExt, LlvmBlockExt},
ir::{
attribute::IntegerAttribute, r#type::IntegerType, Block, BlockLike, Location, Module,
Region, Type,
},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
DupOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// There's no need to build the type here because it'll always be built within
// `build_dup`.
Ok(Some(build_dup(context, module, registry, metadata, &info)?))
},
)?;
DropOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// There's no need to build the type here because it'll always be built within
// `build_drop`.
Ok(Some(build_drop(
context, module, registry, metadata, &info,
)?))
},
)?;
Ok(llvm::r#type::pointer(context, 0))
}
fn build_dup<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
let inner_ty = registry.get_type(&info.ty)?;
let inner_len = inner_ty.layout(registry)?.pad_to_align().size();
let inner_ty = inner_ty.build(context, module, registry, metadata, &info.ty)?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
let null_ptr =
entry.append_op_result(llvm::zero(llvm::r#type::pointer(context, 0), location))?;
let inner_len_val = entry.const_int(context, location, inner_len, 64)?;
let src_value = entry.arg(0)?;
let dst_value = entry.append_op_result(ReallocBindingsMeta::realloc(
context,
null_ptr,
inner_len_val,
location,
)?)?;
if DupOverridesMeta::is_overriden(metadata, &info.ty) {
let value = entry.load(context, location, src_value, inner_ty)?;
let values = DupOverridesMeta::invoke_override(
context, registry, module, &entry, &entry, location, metadata, &info.ty, value,
)?;
entry.store(context, location, src_value, values.0)?;
entry.store(context, location, dst_value, values.1)?;
} else {
entry.append_operation(
ods::llvm::intr_memcpy_inline(
context,
dst_value,
src_value,
IntegerAttribute::new(IntegerType::new(context, 64).into(), inner_len as i64),
IntegerAttribute::new(IntegerType::new(context, 1).into(), 0),
location,
)
.into(),
);
}
entry.append_operation(func::r#return(&[src_value, dst_value], location));
Ok(region)
}
fn build_drop<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
let inner_ty = registry.build_type(context, module, metadata, &info.ty)?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
let value = entry.arg(0)?;
if DropOverridesMeta::is_overriden(metadata, &info.ty) {
let value = entry.load(context, location, value, inner_ty)?;
DropOverridesMeta::invoke_override(
context, registry, module, &entry, &entry, location, metadata, &info.ty, value,
)?;
}
entry.append_operation(ReallocBindingsMeta::free(context, value, location)?);
entry.append_operation(func::r#return(&[], location));
Ok(region)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/uint32.rs | src/types/uint32.rs | //! # Unsigned 32-bit integer type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 32).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/ec_op.rs | src/types/ec_op.rs | //! # Elliptic curve operation type
//!
//! The ec operation type is used in the VM for computing bitwise operations. Since this can be done
//! natively in MLIR, this type is effectively an unit type.
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 64).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/int_range.rs | src/types/int_range.rs | //! # Int range of type T
//!
//! A range [x, y) where x <= y
//!
//! ## Layout
//!
//! A struct with 2 fields of type T
//!
//! ```
//! #[repr(transparent)]
//! pub struct NonZero<T>(pub T);
//! ```
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage, utils::ProgramRegistryExt};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
// TODO: Can its inner type require dup or drop? probably not since they are integers
let inner = registry.build_type(context, module, metadata, &info.ty)?;
Ok(melior::dialect::llvm::r#type::r#struct(
context,
&[inner, inner],
false,
))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/bounded_int.rs | src/types/bounded_int.rs | //! # `BoundedInt` type
//!
//! A `BoundedInt` is a int with a lower and high bound.
//!
//! It's represented as the offseted range using the minimal number of bits. For example:
//! - 10 as `BoundedInt<10, 20>` is represented as `0 : i4`.
//! - 15 as `BoundedInt<10, 20>` is represented as `5 : i4`.
//! - 1 as `BoundedInt<1, 1>` is represented as `0 : i0`.
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage, utils::RangeExt};
use cairo_lang_sierra::{
extensions::{
bounded_int::BoundedIntConcreteType,
core::{CoreLibfunc, CoreType},
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
info: WithSelf<BoundedIntConcreteType>,
) -> Result<Type<'ctx>> {
let n_bits = info.range.offset_bit_width();
Ok(IntegerType::new(context, n_bits).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/pedersen.rs | src/types/pedersen.rs | //! # Pedersen type
//!
//! Type representing the Pedersen hash builtin.
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 64).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/uint128.rs | src/types/uint128.rs | //! # Unsigned 128-bit integer type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 128).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/felt252_dict_entry.rs | src/types/felt252_dict_entry.rs | //! # `Felt` dictionary entry type
//!
//! The entry type returning when getting a value from a dictionary.
//!
//! It is represented as the following struct:
//!
//! | Index | Type | Description |
//! | ----- | -------------- | -------------------------------------------- |
//! | 0 | `!llvm.ptr` | Pointer to the dictionary (Rust). |
//! | 1 | `!llvm.ptr` | Pointer to the entry's value pointer (Rust). |
//!
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::llvm,
ir::{Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
// Note: This is neither droppable nor cloneable.
Ok(llvm::r#type::r#struct(
context,
&[
llvm::r#type::pointer(context, 0), // dict ptr
llvm::r#type::pointer(context, 0), // value ptr
],
false,
))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/gas_reserve.rs | src/types/gas_reserve.rs | use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 128).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/uninitialized.rs | src/types/uninitialized.rs | //! # Uninitialized type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage, utils::ProgramRegistryExt};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
registry.build_type(context, module, metadata, &info.ty)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/builtin_costs.rs | src/types/builtin_costs.rs | //! # Builtin costs type
//!
//! A ptr to a list of u64, this list will not change at runtime in size and thus we only really need to store the pointer,
//! it can be allocated on the stack on rust side and passed.
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::llvm,
ir::{Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
// A ptr to a list of u64
Ok(llvm::r#type::pointer(context, 0))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/ec_point.rs | src/types/ec_point.rs | //! # Elliptic curve point type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::llvm,
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
let felt252_ty = IntegerType::new(context, 252).into();
Ok(llvm::r#type::r#struct(
context,
&[felt252_ty, felt252_ty],
false,
))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/nullable.rs | src/types/nullable.rs | //! # Nullable type
//!
//! Nullable is represented as a pointer, usually the null value will point to a alloca in the stack.
//!
//! A nullable is functionally equivalent to Rust's `Option<Box<T>>`. Since it's always paired with
//! `Box<T>` we can reuse its pointer, just leaving it null when there's no value.
use super::{TypeBuilder, WithSelf};
use crate::{
error::Result,
metadata::{
drop_overrides::DropOverridesMeta, dup_overrides::DupOverridesMeta,
realloc_bindings::ReallocBindingsMeta, MetadataStorage,
},
utils::ProgramRegistryExt,
};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::{cf, func},
helpers::{ArithBlockExt, BuiltinBlockExt, LlvmBlockExt},
ir::{BlockLike, Region},
};
use melior::{
dialect::{llvm, ods},
ir::{attribute::IntegerAttribute, r#type::IntegerType, Block, Location, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
DupOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// There's no need to build the type here because it'll always be built within
// `build_dup`.
Ok(Some(build_dup(context, module, registry, metadata, &info)?))
},
)?;
DropOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// There's no need to build the type here because it'll always be built within
// `build_drop`.
Ok(Some(build_drop(
context, module, registry, metadata, &info,
)?))
},
)?;
// A nullable is represented by a pointer (equivalent to a box). A null value means no value.
Ok(llvm::r#type::pointer(context, 0))
}
fn build_dup<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
let inner_ty = registry.get_type(&info.ty)?;
let inner_len = inner_ty.layout(registry)?.pad_to_align().size();
let inner_ty = inner_ty.build(context, module, registry, metadata, &info.ty)?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
let null_ptr =
entry.append_op_result(llvm::zero(llvm::r#type::pointer(context, 0), location))?;
let inner_len_val = entry.const_int(context, location, inner_len, 64)?;
let src_value = entry.arg(0)?;
let src_is_null = entry.append_op_result(
ods::llvm::icmp(
context,
IntegerType::new(context, 1).into(),
src_value,
null_ptr,
IntegerAttribute::new(IntegerType::new(context, 64).into(), 0).into(),
location,
)
.into(),
)?;
let block_realloc = region.append_block(Block::new(&[]));
let block_finish =
region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
entry.append_operation(cf::cond_br(
context,
src_is_null,
&block_finish,
&block_realloc,
&[null_ptr],
&[],
location,
));
{
let dst_value = block_realloc.append_op_result(ReallocBindingsMeta::realloc(
context,
null_ptr,
inner_len_val,
location,
)?)?;
if DupOverridesMeta::is_overriden(metadata, &info.ty) {
let value = block_realloc.load(context, location, src_value, inner_ty)?;
let values = DupOverridesMeta::invoke_override(
context,
registry,
module,
&block_realloc,
&block_realloc,
location,
metadata,
&info.ty,
value,
)?;
block_realloc.store(context, location, src_value, values.0)?;
block_realloc.store(context, location, dst_value, values.1)?;
} else {
block_realloc.append_operation(
ods::llvm::intr_memcpy_inline(
context,
dst_value,
src_value,
IntegerAttribute::new(IntegerType::new(context, 64).into(), inner_len as i64),
IntegerAttribute::new(IntegerType::new(context, 1).into(), 0),
location,
)
.into(),
);
}
block_realloc.append_operation(cf::br(&block_finish, &[dst_value], location));
}
block_finish.append_operation(func::r#return(&[src_value, block_finish.arg(0)?], location));
Ok(region)
}
fn build_drop<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
let inner_ty = registry.build_type(context, module, metadata, &info.ty)?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
let null_ptr =
entry.append_op_result(llvm::zero(llvm::r#type::pointer(context, 0), location))?;
let value = entry.arg(0)?;
let is_null = entry.append_op_result(
ods::llvm::icmp(
context,
IntegerType::new(context, 1).into(),
value,
null_ptr,
IntegerAttribute::new(IntegerType::new(context, 64).into(), 0).into(),
location,
)
.into(),
)?;
let block_free = region.append_block(Block::new(&[]));
let block_finish =
region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
entry.append_operation(cf::cond_br(
context,
is_null,
&block_finish,
&block_free,
&[null_ptr],
&[],
location,
));
{
if DropOverridesMeta::is_overriden(metadata, &info.ty) {
let value = block_free.load(context, location, value, inner_ty)?;
DropOverridesMeta::invoke_override(
context,
registry,
module,
&block_free,
&block_free,
location,
metadata,
&info.ty,
value,
)?;
}
block_free.append_operation(ReallocBindingsMeta::free(context, value, location)?);
block_free.append_operation(func::r#return(&[], location));
}
block_finish.append_operation(func::r#return(&[], location));
Ok(region)
}
#[cfg(test)]
mod test {
use crate::{jit_enum, jit_struct, load_cairo, utils::testing::run_program, values::Value};
use pretty_assertions_sorted::assert_eq;
#[test]
fn test_nullable_deep_clone() {
let program = load_cairo! {
use core::array::ArrayTrait;
use core::NullableTrait;
fn run_test() -> @Nullable<Array<felt252>> {
let mut x = NullableTrait::new(array![1, 2, 3]);
let x_s = @x;
let mut y = NullableTrait::deref(x);
y.append(4);
x_s
}
};
let result = run_program(&program, "run_test", &[]).return_value;
assert_eq!(
result,
jit_enum!(
0,
jit_struct!(Value::Array(vec![
Value::Felt252(1.into()),
Value::Felt252(2.into()),
Value::Felt252(3.into()),
]))
),
);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/starknet.rs | src/types/starknet.rs | //! # Starknet types
//!
//! ## ClassHash
//! Type for Starknet class hash, a value in the range [0, 2 ** 251).
//!
//! ## ContractAddress
//! Type for Starknet contract address, a value in the range [0, 2 ** 251).
//!
//! ## StorageBaseAddress
//! Type for Starknet storage base address, a value in the range [0, 2 ** 251 - 256).
//!
//! ## StorageAddress
//! Type for Starknet storage base address, a value in the range [0, 2 ** 251).
//!
//! ## System
//! Type for Starknet system object.
//! Used to make system calls.
//!
//! ## Secp256Point
//! TODO
// TODO: Maybe the types used here can be i251 instead of i252. See https://github.com/lambdaclass/cairo_native/issues/1226
use super::WithSelf;
use crate::{
error::Result,
metadata::{
drop_overrides::DropOverridesMeta, dup_overrides::DupOverridesMeta,
realloc_bindings::ReallocBindingsMeta, MetadataStorage,
},
};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
starknet::{secp256::Secp256PointTypeConcrete, StarknetTypeConcrete},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::{func, llvm, ods},
helpers::{ArithBlockExt, BuiltinBlockExt},
ir::{
attribute::IntegerAttribute, r#type::IntegerType, Block, BlockLike, Location, Module,
Region, Type,
},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
selector: WithSelf<StarknetTypeConcrete>,
) -> Result<Type<'ctx>> {
match &*selector {
StarknetTypeConcrete::ClassHash(info) => build_class_hash(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
StarknetTypeConcrete::ContractAddress(info) => build_contract_address(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
StarknetTypeConcrete::StorageBaseAddress(info) => build_storage_base_address(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
StarknetTypeConcrete::StorageAddress(info) => build_storage_address(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
StarknetTypeConcrete::System(info) => build_system(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
StarknetTypeConcrete::Secp256Point(info) => build_secp256_point(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
StarknetTypeConcrete::Sha256StateHandle(info) => build_sha256_state_handle(
context,
module,
registry,
metadata,
WithSelf::new(selector.self_ty(), info),
),
}
}
pub fn build_class_hash<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
// it's a felt252 value
super::felt252::build(context, module, registry, metadata, info)
}
pub fn build_contract_address<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
// it's a felt252 value
super::felt252::build(context, module, registry, metadata, info)
}
pub fn build_storage_base_address<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
// it's a felt252 value
super::felt252::build(context, module, registry, metadata, info)
}
pub fn build_storage_address<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
// it's a felt252 value
super::felt252::build(context, module, registry, metadata, info)
}
pub fn build_system<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(llvm::r#type::pointer(context, 0))
}
pub fn build_secp256_point<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<Secp256PointTypeConcrete>,
) -> Result<Type<'ctx>> {
Ok(llvm::r#type::r#struct(
context,
&[
llvm::r#type::r#struct(
context,
&[
IntegerType::new(context, 128).into(),
IntegerType::new(context, 128).into(),
],
false,
),
llvm::r#type::r#struct(
context,
&[
IntegerType::new(context, 128).into(),
IntegerType::new(context, 128).into(),
],
false,
),
IntegerType::new(context, 1).into(),
],
false,
))
}
pub fn build_sha256_state_handle<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
DupOverridesMeta::register_with(context, module, registry, metadata, info.self_ty(), |_| {
let region = Region::new();
let block =
region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
let null_ptr =
block.append_op_result(llvm::zero(llvm::r#type::pointer(context, 0), location))?;
let k32 = block.const_int(context, location, 32, 64)?;
let new_ptr = block.append_op_result(ReallocBindingsMeta::realloc(
context, null_ptr, k32, location,
)?)?;
block.append_operation(
ods::llvm::intr_memcpy_inline(
context,
new_ptr,
block.arg(0)?,
IntegerAttribute::new(IntegerType::new(context, 64).into(), 32),
IntegerAttribute::new(IntegerType::new(context, 1).into(), 0),
location,
)
.into(),
);
block.append_operation(func::r#return(&[block.arg(0)?, new_ptr], location));
Ok(Some(region))
})?;
DropOverridesMeta::register_with(context, module, registry, metadata, info.self_ty(), |_| {
let region = Region::new();
let block =
region.append_block(Block::new(&[(llvm::r#type::pointer(context, 0), location)]));
block.append_operation(ReallocBindingsMeta::free(context, block.arg(0)?, location)?);
block.append_operation(func::r#return(&[], location));
Ok(Some(region))
})?;
// A ptr to a heap (realloc) allocated [u32; 8]
Ok(llvm::r#type::pointer(context, 0))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/segment_arena.rs | src/types/segment_arena.rs | //! # Segment arena type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 64).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/felt252.rs | src/types/felt252.rs | //! # `felt252` type
//!
//! A `felt252` is a 252-bit number within a
//! [finite field](https://en.wikipedia.org/wiki/Finite_field) modulo
//! [a prime number](crate::utils::PRIME).
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 252).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/bytes31.rs | src/types/bytes31.rs | //! # `bytes31` type
//!
//! A `bytes31` is a 248-bit number (31 bytes).
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: &InfoOnlyConcreteType,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 248).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/uint16.rs | src/types/uint16.rs | //! # Unsigned 16-bit integer type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 16).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/squashed_felt252_dict.rs | src/types/squashed_felt252_dict.rs | //! # Squashed `Felt` dictionary type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
super::felt252_dict::build(context, module, registry, metadata, info)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/snapshot.rs | src/types/snapshot.rs | //! # Snapshot type
//!
//! The type snapshot for a given type `T`.
//!
//! ## Layout
//!
//! Its layout is that of whatever it wraps. In other words, if it was Rust it would be equivalent
//! to the following:
//!
//! ```
//! #[repr(transparent)]
//! pub struct Snapshot<T>(pub T);
//! ```
use super::{TypeBuilder, WithSelf};
use crate::{
error::Result,
metadata::{
drop_overrides::DropOverridesMeta, dup_overrides::DupOverridesMeta,
enum_snapshot_variants::EnumSnapshotVariantsMeta, MetadataStorage,
},
utils::ProgramRegistryExt,
};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::func,
helpers::BuiltinBlockExt,
ir::{Block, BlockLike, Location, Module, Region, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
// This type is like a `Cow<T>` that clones whenever the original type is modified to keep the
// original data. Since implementing that is complicated we can just clone the entire value for
// now.
// Register enum variants for the snapshot.
if let Some(variants) = registry.get_type(&info.ty)?.variants() {
metadata
.get_or_insert_with(EnumSnapshotVariantsMeta::default)
.set_mapping(info.self_ty, variants);
}
// Register clone override (if required).
DupOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
registry.build_type(context, module, metadata, &info.ty)?;
DupOverridesMeta::is_overriden(metadata, &info.ty)
.then(|| build_dup(context, module, registry, metadata, &info))
.transpose()
},
)?;
// Register clone override (if required).
DropOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
registry.build_type(context, module, metadata, &info.ty)?;
DropOverridesMeta::is_overriden(metadata, &info.ty)
.then(|| build_drop(context, module, registry, metadata, &info))
.transpose()
},
)?;
registry.build_type(context, module, metadata, &info.ty)
}
fn build_dup<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
let inner_ty = registry.build_type(context, module, metadata, &info.ty)?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(inner_ty, location)]));
let values = DupOverridesMeta::invoke_override(
context,
registry,
module,
&entry,
&entry,
location,
metadata,
&info.ty,
entry.arg(0)?,
)?;
entry.append_operation(func::r#return(&[values.0, values.1], location));
Ok(region)
}
fn build_drop<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
let inner_ty = registry.build_type(context, module, metadata, &info.ty)?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(inner_ty, location)]));
DropOverridesMeta::invoke_override(
context,
registry,
module,
&entry,
&entry,
location,
metadata,
&info.ty,
entry.arg(0)?,
)?;
entry.append_operation(func::r#return(&[], location));
Ok(region)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/felt252_dict.rs | src/types/felt252_dict.rs | //! # `Felt` dictionary type
//!
//! A key value storage for values whose type implement Copy. The key is always a felt.
//!
//! This type is represented as a pointer to a tuple of a heap allocated Rust hashmap along with a u64
//! used to count accesses to the dictionary. The type is interacted through the runtime functions to
//! insert, get elements and increment the access counter.
use super::WithSelf;
use crate::{
error::{Error, Result},
metadata::{
drop_overrides::DropOverridesMeta, dup_overrides::DupOverridesMeta,
felt252_dict::Felt252DictOverrides, realloc_bindings::ReallocBindingsMeta,
runtime_bindings::RuntimeBindingsMeta, MetadataStorage,
},
utils::ProgramRegistryExt,
};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::{func, llvm},
helpers::BuiltinBlockExt,
ir::{Block, BlockLike, Location, Module, Region, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
DupOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// There's no need to build the type here because it'll always be built within
// `build_dup`.
Ok(Some(build_dup(context, module, registry, metadata, &info)?))
},
)?;
DropOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// There's no need to build the type here because it'll always be built within
// `build_drop`.
Ok(Some(build_drop(
context, module, registry, metadata, &info,
)?))
},
)?;
Ok(llvm::r#type::pointer(context, 0))
}
fn build_dup<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
let value_ty = registry.build_type(context, module, metadata, info.self_ty())?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(value_ty, location)]));
// The following unwrap is unreachable because the registration logic will always insert it.
let value0 = entry.arg(0)?;
let value1 = metadata
.get_mut::<RuntimeBindingsMeta>()
.ok_or(Error::MissingMetadata)?
.dict_dup(context, module, &entry, value0, location)?;
entry.append_operation(func::r#return(&[value0, value1], location));
Ok(region)
}
fn build_drop<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<InfoAndTypeConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
if metadata.get::<ReallocBindingsMeta>().is_none() {
metadata.insert(ReallocBindingsMeta::new(context, module));
}
let value_ty = registry.build_type(context, module, metadata, info.self_ty())?;
{
let mut dict_overrides = metadata
.remove::<Felt252DictOverrides>()
.unwrap_or_default();
dict_overrides.build_drop_fn(context, module, registry, metadata, &info.ty)?;
metadata.insert(dict_overrides);
}
let region = Region::new();
let entry = region.append_block(Block::new(&[(value_ty, location)]));
// The following unwrap is unreachable because the registration logic will always insert it.
let runtime_bindings_meta = metadata
.get_mut::<RuntimeBindingsMeta>()
.ok_or(Error::MissingMetadata)?;
runtime_bindings_meta.dict_drop(context, module, &entry, entry.arg(0)?, location)?;
entry.append_operation(func::r#return(&[], location));
Ok(region)
}
#[cfg(test)]
mod test {
use crate::{jit_dict, load_cairo, utils::testing::run_program, values::Value};
use pretty_assertions_sorted::assert_eq;
use starknet_types_core::felt::Felt;
use std::collections::HashMap;
#[test]
fn dict_snapshot_take() {
let program = load_cairo! {
fn run_test() -> @Felt252Dict<u32> {
let mut dict: Felt252Dict<u32> = Default::default();
dict.insert(2, 1_u32);
@dict
}
};
let result = run_program(&program, "run_test", &[]).return_value;
assert_eq!(
result,
jit_dict!(
2 => 1u32
),
);
}
#[test]
fn dict_snapshot_take_complex() {
let program = load_cairo! {
fn run_test() -> @Felt252Dict<Nullable<Array<u32>>> {
let mut dict: Felt252Dict<Nullable<Array<u32>>> = Default::default();
dict.insert(2, NullableTrait::new(array![3, 4]));
@dict
}
};
let result = run_program(&program, "run_test", &[]).return_value;
assert_eq!(
result,
jit_dict!(
2 => Value::Array(vec![3u32.into(), 4u32.into()])
),
);
}
#[test]
fn dict_snapshot_take_compare() {
let program = load_cairo! {
fn run_test() -> @Felt252Dict<Nullable<Array<u32>>> {
let mut dict: Felt252Dict<Nullable<Array<u32>>> = Default::default();
dict.insert(2, NullableTrait::new(array![3, 4]));
@dict
}
};
let program2 = load_cairo! {
fn run_test() -> Felt252Dict<Nullable<Array<u32>>> {
let mut dict: Felt252Dict<Nullable<Array<u32>>> = Default::default();
dict.insert(2, NullableTrait::new(array![3, 4]));
dict
}
};
let result1 = run_program(&program, "run_test", &[]).return_value;
let result2 = run_program(&program2, "run_test", &[]).return_value;
assert_eq!(result1, result2);
}
/// Ensure that a dictionary of booleans compiles.
#[test]
fn dict_type_bool() {
let program = load_cairo! {
fn run_program() -> Felt252Dict<bool> {
let mut x: Felt252Dict<bool> = Default::default();
x.insert(0, false);
x.insert(1, true);
x
}
};
let result = run_program(&program, "run_program", &[]);
assert_eq!(
result.return_value,
Value::Felt252Dict {
value: HashMap::from([
(
Felt::ZERO,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: Vec::new(),
debug_name: None
}),
debug_name: None,
},
),
(
Felt::ONE,
Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: Vec::new(),
debug_name: None
}),
debug_name: None,
},
),
]),
debug_name: None,
},
);
}
/// Ensure that a dictionary of felts compiles.
#[test]
fn dict_type_felt252() {
let program = load_cairo! {
fn run_program() -> Felt252Dict<felt252> {
let mut x: Felt252Dict<felt252> = Default::default();
x.insert(0, 0);
x.insert(1, 1);
x.insert(2, 2);
x.insert(3, 3);
x
}
};
let result = run_program(&program, "run_program", &[]);
assert_eq!(
result.return_value,
Value::Felt252Dict {
value: HashMap::from([
(Felt::ZERO, Value::Felt252(Felt::ZERO)),
(Felt::ONE, Value::Felt252(Felt::ONE)),
(Felt::TWO, Value::Felt252(Felt::TWO)),
(Felt::THREE, Value::Felt252(Felt::THREE)),
]),
debug_name: None,
},
);
}
/// Ensure that a dictionary of nullables compiles.
#[test]
fn dict_type_nullable() {
let program = load_cairo! {
#[derive(Drop)]
struct MyStruct {
a: u8,
b: i16,
c: felt252,
}
fn run_program() -> Felt252Dict<Nullable<MyStruct>> {
let mut x: Felt252Dict<Nullable<MyStruct>> = Default::default();
x.insert(0, Default::default());
x.insert(1, NullableTrait::new(MyStruct { a: 0, b: 1, c: 2 }));
x.insert(2, NullableTrait::new(MyStruct { a: 1, b: -2, c: 3 }));
x.insert(3, NullableTrait::new(MyStruct { a: 2, b: 3, c: 4 }));
x
}
};
let result = run_program(&program, "run_program", &[]);
pretty_assertions_sorted::assert_eq_sorted!(
result.return_value,
Value::Felt252Dict {
value: HashMap::from([
(Felt::ZERO, Value::Null),
(
Felt::ONE,
Value::Struct {
fields: Vec::from([
Value::Uint8(0),
Value::Sint16(1),
Value::Felt252(2.into()),
]),
debug_name: None,
},
),
(
Felt::TWO,
Value::Struct {
fields: Vec::from([
Value::Uint8(1),
Value::Sint16(-2),
Value::Felt252(3.into()),
]),
debug_name: None,
},
),
(
Felt::THREE,
Value::Struct {
fields: Vec::from([
Value::Uint8(2),
Value::Sint16(3),
Value::Felt252(4.into()),
]),
debug_name: None,
},
),
]),
debug_name: None,
},
);
}
/// Ensure that a dictionary of unsigned integers compiles.
#[test]
fn dict_type_unsigned() {
let program = load_cairo! {
fn run_program() -> Felt252Dict<u128> {
let mut x: Felt252Dict<u128> = Default::default();
x.insert(0, 0_u128);
x.insert(1, 1_u128);
x.insert(2, 2_u128);
x.insert(3, 3_u128);
x
}
};
let result = run_program(&program, "run_program", &[]);
assert_eq!(
result.return_value,
Value::Felt252Dict {
value: HashMap::from([
(Felt::ZERO, Value::Uint128(0)),
(Felt::ONE, Value::Uint128(1)),
(Felt::TWO, Value::Uint128(2)),
(Felt::THREE, Value::Uint128(3)),
]),
debug_name: None,
},
);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/poseidon.rs | src/types/poseidon.rs | //! # Poseidon type
//!
//! Type representing the Poseidon builtin.
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 64).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/enum.rs | src/types/enum.rs | //! # Enum type
//!
//! Enumerations are special because they can potentially represent an unlimited amount of things at
//! the same time. They are similar to Rust enums since they can contain data along with the
//! discriminator.
//!
//! ## Layout
//!
//! | Index | Type | Description |
//! | ----- | -------------------- | ------------------------ |
//! | 0 | `iN` | Discriminant. |
//! | 1 | Depends on variants. | Payload. |
//!
//! As seen in the table above, an enum's layout is not as simple as concatenating the discriminant
//! with the payload.
//!
//! The discriminant will have the bit width required to store all possible values. The following
//! table contains an example of some number of variants with their discriminant type:
//!
//! | Number of variants | Discriminant type | ABI (in Rust types) |
//! | ------------------ | ----------------- | ------------------- |
//! | 0 or 1 | `i0` | `()` |
//! | 2 | `i1` | `u8` |
//! | 3 or 4 | `i2` | `u8` |
//! | 5, 6, 7 or 8 | `i3` | `u8` |
//! | 9 to 16 | `i4` | `u8` |
//! | 129 to 256 | `i8` | `u8` |
//! | 257 to 512 | `i9` | `u16` |
//! | 32769 to 65536 | `i16` | `u16` |
//! | 65537 to 131072 | `i17` | `u32` |
//!
//! In Rust, the number of bits and bytes required can be obtained using the following formula,
//! where `n` is the number of bits required, and `m` is the number of bytes required, and
//! `v` is the number of variants.
//!
//! ```math
//! n = { 0 if v == 0
//! { ⌈log₂(v)⌉ if v != 0
//!
//! m = ⌈n/8⌉
//! ```
//!
//! The payload will then be appended to the discriminant after applying its alignment rules. This
//! will cause unused space between the tag and the payload in most cases.
//!
//! ## Example
//!
//! As an example, the following enum will have the layouts described in the table below.
//!
//! ```cairo
//! enum MyEnum {
//! U8: u8,
//! U16: u16,
//! U32: u32,
//! U64: u64,
//! Felt: Felt,
//! }
//! ```
//!
//! ### MyEnum::U8
//!
//! | Index | Type | ABI (in Rust types) | Alignment | Size | Description |
//! | ----- | ----- | ------------------- | --------- | ---- | ------------- |
//! | 0 | `i3` | `u8` | 1 | 1 | Discriminant. |
//! | 1 | `i8` | `u8` | 1 | 1 | Payload. |
//! | N/A | N/A | `[u8; 38]` | 1 | 38 | Padding. |
//!
//! ### MyEnum::U16
//!
//! | Index | Type | ABI (in Rust types) | Alignment | Size | Description |
//! | ----- | ----- | ------------------- | --------- | ---- | ------------- |
//! | 0 | `i3` | `u8` | 1 | 1 | Discriminant. |
//! | N/A | N/A | `[u8; 1]` | 1 | 1 | Padding. |
//! | 1 | `i16` | `u16` | 2 | 2 | Payload. |
//! | N/A | N/A | `[u8; 36]` | 1 | 36 | Padding. |
//!
//! ### MyEnum::U32
//!
//! | Index | Type | ABI (in Rust types) | Alignment | Size | Description |
//! | ----- | ----- | ------------------- | --------- | ---- | ------------- |
//! | 0 | `i3` | `u8` | 1 | 1 | Discriminant. |
//! | N/A | N/A | `[u8; 3]` | 1 | 3 | Padding. |
//! | 1 | `i32` | `u32` | 4 | 4 | Payload. |
//! | N/A | N/A | `[u8; 32]` | 1 | 32 | Padding. |
//!
//! ### MyEnum::U64
//!
//! | Index | Type | ABI (in Rust types) | Alignment | Size | Description |
//! | ----- | ----- | ------------------- | --------- | ---- | ------------- |
//! | 0 | `i3` | `u8` | 1 | 1 | Discriminant. |
//! | N/A | N/A | `[u8; 7]` | 1 | 7 | Padding. |
//! | 1 | `i64` | `u64` | 8 | 8 | Payload. |
//! | N/A | N/A | `[u8; 24]` | 1 | 24 | Padding. |
//!
//! ### MyEnum::Felt
//!
//! | Index | Type | ABI (in Rust types) | Alignment | Size | Description |
//! | ----- | ------ | ------------------- | --------- | ---- | ------------- |
//! | 0 | `i3` | `u8` | 1 | 1 | Discriminant. |
//! | N/A | N/A | `[u8; 7]` | 1 | 7 | Padding. |
//! | 1 | `i252` | `[u64; 4]` | 8 | 32 | Payload. |
//!
//! As seen above, while the discriminant is always at the same offset, the payloads don't necessary
//! have the same offset between all variants. It depends on the payload's alignment.
//!
//! In reality, the first variant will have a zero-sized padding between the discriminant and the
//! payload to keep everything consistent and the padding will have its own index, shifting every
//! index below it by one. However all that's been ignored for documenting purposes.
//!
//! An MLIR type cannot be an enumeration (it doesn't exist). We cannot use the type of the largest
//! variant either. This is because the payload of different variants could start at different offsets,
//! so the padding of the largest variant could be part of the payload of a smaller variant. As an
//! optimization, LLVM does not copy the value of the padding, which implies that some data is lost.
//!
//! Instead, we represent enums as an opaque structure that contains an integer and a byte array.
//! The integer is used to ensure that the alignment information is not lost, as we use an integer
//! with the same alignment as the variant with biggest alignment.
//!
//! | Index | Type | ABI (in Rust types) | Alignment | Size | Description |
//! | ----- | ---------- | ------------------- | --------- | ---- | ----------------- |
//! | 0 | `i64` | `u64` | 8 | 8 | Forces alignment. |
//! | 1 | `[u8; 32]` | `[u8; 32]` | 1 | 32 | Remaining data. |
//!
//! This data type can then be reinterpreted safely into any of the concrete variants.
use super::{TypeBuilder, WithSelf};
use crate::{
error::Result,
metadata::{
drop_overrides::DropOverridesMeta, dup_overrides::DupOverridesMeta, MetadataStorage,
},
native_panic,
utils::{get_integer_layout, ProgramRegistryExt},
};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
enm::EnumConcreteType,
},
ids::ConcreteTypeId,
program_registry::ProgramRegistry,
};
use melior::{
dialect::{cf, func, llvm},
helpers::{BuiltinBlockExt, LlvmBlockExt},
ir::{r#type::IntegerType, Block, BlockLike, Location, Module, Region, Type, Value},
Context,
};
use std::{
alloc::Layout,
collections::{hash_map::Entry, HashMap},
};
/// An MLIR type with its memory layout.
pub type TypeLayout<'ctx> = (Type<'ctx>, Layout);
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<EnumConcreteType>,
) -> Result<Type<'ctx>> {
// Register enum's clone impl (if required).
DupOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
let mut needs_override = false;
for variant in &info.variants {
registry.build_type(context, module, metadata, variant)?;
if DupOverridesMeta::is_overriden(metadata, variant) {
needs_override = true;
break;
}
}
needs_override
.then(|| build_dup(context, module, registry, metadata, &info))
.transpose()
},
)?;
DropOverridesMeta::register_with(
context,
module,
registry,
metadata,
info.self_ty(),
|metadata| {
// The following unwrap is unreachable because `register_with` will always insert it
// before calling this closure.
let mut needs_override = false;
for variant in &info.variants {
registry.build_type(context, module, metadata, variant)?;
if DropOverridesMeta::is_overriden(metadata, variant) {
needs_override = true;
break;
}
}
needs_override
.then(|| build_drop(context, module, registry, metadata, &info))
.transpose()
},
)?;
let tag_bits = info.variants.len().next_power_of_two().trailing_zeros();
let tag_layout = get_integer_layout(tag_bits);
let layout = info.variants.iter().try_fold(tag_layout, |acc, id| {
let layout = tag_layout
.extend(registry.get_type(id)?.layout(registry)?)?
.0;
Result::Ok(Layout::from_size_align(
acc.size().max(layout.size()),
acc.align().max(layout.align()),
)?)
})?;
let i8_ty = IntegerType::new(context, 8).into();
Ok(match info.variants.len() {
0 => llvm::r#type::array(IntegerType::new(context, 8).into(), 0),
1 => registry.build_type(context, module, metadata, &info.variants[0])?,
_ if 'block: {
for type_id in &info.variants {
if !registry.get_type(type_id)?.is_zst(registry)? {
break 'block false;
}
}
true
} =>
{
llvm::r#type::r#struct(
context,
&[
IntegerType::new(context, tag_bits).into(),
llvm::r#type::array(i8_ty, 0),
],
false,
)
}
_ => llvm::r#type::r#struct(
context,
&[
IntegerType::new(context, (8 * layout.align()) as u32).into(),
llvm::r#type::array(i8_ty, (layout.size() - layout.align()) as u32),
],
false,
),
})
}
fn build_dup<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<EnumConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
let self_ty = registry.build_type(context, module, metadata, info.self_ty())?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(self_ty, location)]));
let (layout, (tag_ty, _), variant_tys) = crate::types::r#enum::get_type_for_variants(
context,
module,
registry,
metadata,
&info.variants,
)?;
match variant_tys.len() {
0 => native_panic!("attempt to clone a zero-variant enum"),
1 => {
let values = DupOverridesMeta::invoke_override(
context,
registry,
module,
&entry,
&entry,
location,
metadata,
&info.variants[0],
entry.arg(0)?,
)?;
entry.append_operation(func::r#return(&[values.0, values.1], location));
}
_ => {
let ptr = entry.alloca1(context, location, self_ty, layout.align())?;
entry.store(context, location, ptr, entry.arg(0)?)?;
let mut variant_blocks = HashMap::new();
for (variant_id, variant_ty) in info
.variants
.iter()
.zip(variant_tys.iter().map(|(x, _)| *x))
{
if let Entry::Vacant(entry) = variant_blocks.entry(variant_id.id) {
let block = entry.insert(region.append_block(Block::new(&[])));
let container = block.load(
context,
location,
ptr,
llvm::r#type::r#struct(context, &[tag_ty, variant_ty], false),
)?;
let value = block.extract_value(context, location, container, variant_ty, 1)?;
let values = DupOverridesMeta::invoke_override(
context, registry, module, block, block, location, metadata, variant_id,
value,
)?;
let value = block.insert_value(context, location, container, values.0, 1)?;
block.store(context, location, ptr, value)?;
let value0 = block.load(context, location, ptr, self_ty)?;
let value = block.insert_value(context, location, container, values.1, 1)?;
block.store(context, location, ptr, value)?;
let value1 = block.load(context, location, ptr, self_ty)?;
block.append_operation(func::r#return(&[value0, value1], location));
}
}
let default_block = region.append_block(Block::new(&[]));
let tag_value = entry.load(context, location, ptr, tag_ty)?;
entry.append_operation(cf::switch(
context,
&(0..info.variants.len() as _).collect::<Vec<_>>(),
tag_value,
tag_ty,
(&default_block, &[]),
&info
.variants
.iter()
.map(|id| (&*variant_blocks[&id.id], &[] as &[Value]))
.collect::<Vec<_>>(),
location,
)?);
default_block.append_operation(llvm::unreachable(location));
}
}
Ok(region)
}
fn build_drop<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: &WithSelf<EnumConcreteType>,
) -> Result<Region<'ctx>> {
let location = Location::unknown(context);
let self_ty = registry.build_type(context, module, metadata, info.self_ty())?;
let region = Region::new();
let entry = region.append_block(Block::new(&[(self_ty, location)]));
let (layout, (tag_ty, _), variant_tys) = crate::types::r#enum::get_type_for_variants(
context,
module,
registry,
metadata,
&info.variants,
)?;
match variant_tys.len() {
0 => native_panic!("attempt to drop a zero-variant enum"),
1 => {
DropOverridesMeta::invoke_override(
context,
registry,
module,
&entry,
&entry,
location,
metadata,
&info.variants[0],
entry.arg(0)?,
)?;
entry.append_operation(func::r#return(&[], location));
}
_ => {
let ptr = entry.alloca1(context, location, self_ty, layout.align())?;
entry.store(context, location, ptr, entry.arg(0)?)?;
let mut variant_blocks = HashMap::new();
for (variant_id, variant_ty) in info
.variants
.iter()
.zip(variant_tys.iter().map(|(x, _)| *x))
{
if let Entry::Vacant(entry) = variant_blocks.entry(variant_id.id) {
let block = entry.insert(region.append_block(Block::new(&[])));
let container = block.load(
context,
location,
ptr,
llvm::r#type::r#struct(context, &[tag_ty, variant_ty], false),
)?;
let value = block.extract_value(context, location, container, variant_ty, 1)?;
DropOverridesMeta::invoke_override(
context, registry, module, block, block, location, metadata, variant_id,
value,
)?;
block.append_operation(func::r#return(&[], location));
}
}
let default_block = region.append_block(Block::new(&[]));
let tag_value = entry.load(context, location, ptr, tag_ty)?;
entry.append_operation(cf::switch(
context,
&(0..info.variants.len() as _).collect::<Vec<_>>(),
tag_value,
tag_ty,
(&default_block, &[]),
&info
.variants
.iter()
.map(|id| (&*variant_blocks[&id.id], &[] as &[Value]))
.collect::<Vec<_>>(),
location,
)?);
default_block.append_operation(llvm::unreachable(location));
}
}
Ok(region)
}
/// Extract layout for the default enum representation, its discriminant and all its payloads.
pub fn get_layout_for_variants(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
variants: &[ConcreteTypeId],
) -> Result<(Layout, Layout, Vec<Layout>)> {
let tag_bits = variants.len().next_power_of_two().trailing_zeros();
let tag_layout = get_integer_layout(tag_bits);
let mut layout = tag_layout;
let mut output = Vec::with_capacity(variants.len());
for variant in variants {
let concrete_payload_ty = registry.get_type(variant)?;
let payload_layout = concrete_payload_ty.layout(registry)?;
let full_layout = tag_layout.extend(payload_layout)?.0;
layout = Layout::from_size_align(
layout.size().max(full_layout.size()),
layout.align().max(full_layout.align()),
)?;
output.push(payload_layout);
}
Ok((layout, tag_layout, output))
}
/// Extract the type and layout for the default enum representation, its discriminant and all its
/// payloads.
// TODO: Change this function to accept a slice of slices (for variants). Not all uses have a slice
// with one `ConcreteTypeId` per variant (deploy_syscalls has two types for the Ok() variant).
// See: https://github.com/lambdaclass/cairo_native/issues/1187/
pub fn get_type_for_variants<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
variants: &[ConcreteTypeId],
) -> Result<(Layout, TypeLayout<'ctx>, Vec<TypeLayout<'ctx>>)> {
let tag_bits = variants.len().next_power_of_two().trailing_zeros();
let tag_layout = get_integer_layout(tag_bits);
let tag_ty: Type = IntegerType::new(context, tag_bits).into();
let mut layout = tag_layout;
let mut output = Vec::with_capacity(variants.len());
for variant in variants {
let (payload_ty, payload_layout) =
registry.build_type_with_layout(context, module, metadata, variant)?;
let full_layout = tag_layout.extend(payload_layout)?.0;
layout = Layout::from_size_align(
layout.size().max(full_layout.size()),
layout.align().max(full_layout.align()),
)?;
output.push((payload_ty, payload_layout));
}
Ok((layout, (tag_ty, tag_layout), output))
}
#[cfg(test)]
mod test {
use crate::{load_cairo, metadata::MetadataStorage, types::TypeBuilder};
use cairo_lang_sierra::{
extensions::core::{CoreLibfunc, CoreType},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Location, Module},
Context,
};
#[test]
fn enum_type_single_variant_no_i0() {
let (_, program) = load_cairo! {
enum MyEnum {
A: felt252,
}
fn run_program(x: MyEnum) -> MyEnum {
x
}
};
let context = Context::new();
let registry = ProgramRegistry::<CoreType, CoreLibfunc>::new(&program).unwrap();
let module = Module::new(Location::unknown(&context));
let mut metadata = MetadataStorage::new();
let i0_ty = IntegerType::new(&context, 0).into();
program
.type_declarations
.iter()
.map(|ty| (&ty.id, registry.get_type(&ty.id).unwrap()))
.map(|(id, ty)| {
ty.build(&context, &module, ®istry, &mut metadata, id)
.unwrap()
})
.any(|width| width == i0_ty);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/uint64.rs | src/types/uint64.rs | //! # Unsigned 64-bit integer type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
Ok(IntegerType::new(context, 64).into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/ec_state.rs | src/types/ec_state.rs | //! # Elliptic curve state type
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoOnlyConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
dialect::llvm,
ir::{r#type::IntegerType, Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
_module: &Module<'ctx>,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_metadata: &mut MetadataStorage,
_info: WithSelf<InfoOnlyConcreteType>,
) -> Result<Type<'ctx>> {
let felt252_ty = IntegerType::new(context, 252).into();
Ok(llvm::r#type::r#struct(
context,
&[felt252_ty, felt252_ty, felt252_ty, felt252_ty],
false,
))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/types/non_zero.rs | src/types/non_zero.rs | //! # Non-zero type
//!
//! The non-zero generic type guarantees that whatever value it has is not zero.
//!
//! ## Layout
//!
//! Its layout is that of whatever it wraps. In other words, if it was Rust it would be equivalent
//! to the following:
//!
//! ```
//! #[repr(transparent)]
//! pub struct NonZero<T>(pub T);
//! ```
use super::WithSelf;
use crate::{error::Result, metadata::MetadataStorage, utils::ProgramRegistryExt};
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType},
types::InfoAndTypeConcreteType,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{Module, Type},
Context,
};
/// Build the MLIR type.
///
/// Check out [the module](self) for more info.
pub fn build<'ctx>(
context: &'ctx Context,
module: &Module<'ctx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
metadata: &mut MetadataStorage,
info: WithSelf<InfoAndTypeConcreteType>,
) -> Result<Type<'ctx>> {
// TODO: Can its inner type require dup or drop?
registry.build_type(context, module, metadata, &info.ty)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/arch/x86_64.rs | src/arch/x86_64.rs | //! # Implementations of `AbiArgument` for the `x86_64` architecture.
//!
//! The x86_64 architecture uses 6 64-bit registers for arguments. This means that the first 48
//! bytes of the buffer will go into registers while the rest will be on the stack.
//!
//! The values that span multiple registers may be split or moved into the stack completely in some
//! cases, having to pad a register. In those cases the amount of usable register space is reduced
//! to only 40 bytes.
#![cfg(target_arch = "x86_64")]
use super::AbiArgument;
use crate::{error::Error, starknet::U256, utils::get_integer_layout};
use cairo_lang_sierra::ids::ConcreteTypeId;
use num_traits::ToBytes;
use starknet_types_core::felt::Felt;
use std::ffi::c_void;
fn align_to(buffer: &mut Vec<u8>, align: usize) {
buffer.resize(buffer.len().next_multiple_of(align), 0);
}
impl AbiArgument for bool {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for u8 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i8 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for u16 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i16 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for u32 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i32 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
Ok(())
}
}
impl AbiArgument for u64 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i64 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for u128 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 40 {
align_to(buffer, get_integer_layout(128).align());
}
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i128 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 40 {
align_to(buffer, get_integer_layout(128).align());
}
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for Felt {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 40 {
align_to(buffer, get_integer_layout(252).align());
}
buffer.extend_from_slice(&self.to_bytes_le());
Ok(())
}
}
impl AbiArgument for U256 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
self.lo.to_bytes(buffer, find_dict_drop_override)?;
self.hi.to_bytes(buffer, find_dict_drop_override)
}
}
impl AbiArgument for [u8; 31] {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
// The `bytes31` type is treated as a 248-bit integer, therefore it follows the same
// splitting rules as them.
if buffer.len() >= 40 {
align_to(buffer, get_integer_layout(252).align());
}
buffer.extend_from_slice(self);
buffer.push(0);
Ok(())
}
}
impl<T> AbiArgument for *const T {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
<u64 as AbiArgument>::to_bytes(&(*self as u64), buffer, find_dict_drop_override)
}
}
impl<T> AbiArgument for *mut T {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
<u64 as AbiArgument>::to_bytes(&(*self as u64), buffer, find_dict_drop_override)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn u128_stack_split() {
let mut buffer = vec![0; 40];
u128::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 48].into_iter().chain([0xFF; 16]).collect::<Vec<_>>()
);
}
#[test]
fn felt_stack_split() {
// Only a single u64 spilled into the stack.
let mut buffer = vec![0; 24];
Felt::from_hex("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
.unwrap()
.to_bytes(&mut buffer, |_| unreachable!())
.unwrap();
assert_eq!(
buffer,
[0; 24]
.into_iter()
.chain([0xFF; 31])
.chain([0x00])
.collect::<Vec<_>>()
);
// Half the felt spilled into the stack.
let mut buffer = vec![0; 32];
Felt::from_hex("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
.unwrap()
.to_bytes(&mut buffer, |_| unreachable!())
.unwrap();
assert_eq!(
buffer,
[0; 32]
.into_iter()
.chain([0xFF; 31])
.chain([0x00])
.collect::<Vec<_>>()
);
// All the felt spilled into the stack (with padding).
let mut buffer = vec![0; 40];
Felt::from_hex("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
.unwrap()
.to_bytes(&mut buffer, |_| unreachable!())
.unwrap();
assert_eq!(
buffer,
[0; 48]
.into_iter()
.chain([0xFF; 31])
.chain([0x00])
.collect::<Vec<_>>()
);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/arch/aarch64.rs | src/arch/aarch64.rs | //! # Implementations of `AbiArgument` for the `aarch64` architecture.
//!
//! The aarch64 architecture uses 8 64-bit registers for arguments. This means that the first 64
//! bytes of the buffer will go into registers while the rest will be on the stack.
//!
//! The values that span multiple registers may be split or moved into the stack completely in some
//! cases, having to pad a register. In those cases the amount of usable register space is reduced
//! to only 56 bytes.
#![cfg(target_arch = "aarch64")]
use super::AbiArgument;
use crate::{error::Error, starknet::U256, utils::get_integer_layout};
use cairo_lang_sierra::ids::ConcreteTypeId;
use num_traits::ToBytes;
use starknet_types_core::felt::Felt;
use std::ffi::c_void;
fn align_to(buffer: &mut Vec<u8>, align: usize) {
buffer.resize(buffer.len().next_multiple_of(align), 0);
}
impl AbiArgument for bool {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(1).align());
buffer.push((*self) as u8);
}
Ok(())
}
}
impl AbiArgument for u8 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(8).align());
buffer.push(*self);
}
Ok(())
}
}
impl AbiArgument for i8 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(8).align());
buffer.extend_from_slice(&self.to_ne_bytes());
}
Ok(())
}
}
impl AbiArgument for u16 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(16).align());
buffer.extend_from_slice(&self.to_ne_bytes());
}
Ok(())
}
}
impl AbiArgument for i16 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(16).align());
buffer.extend_from_slice(&self.to_ne_bytes());
}
Ok(())
}
}
impl AbiArgument for u32 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(32).align());
buffer.extend_from_slice(&self.to_ne_bytes());
}
Ok(())
}
}
impl AbiArgument for i32 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() < 64 {
buffer.extend_from_slice(&(*self as u64).to_ne_bytes());
} else {
align_to(buffer, get_integer_layout(32).align());
buffer.extend_from_slice(&self.to_ne_bytes());
}
Ok(())
}
}
impl AbiArgument for u64 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 64 {
align_to(buffer, get_integer_layout(64).align());
}
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i64 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 64 {
align_to(buffer, get_integer_layout(64).align());
}
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for u128 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 56 {
align_to(buffer, get_integer_layout(128).align());
}
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for i128 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 56 {
align_to(buffer, get_integer_layout(128).align());
}
buffer.extend_from_slice(&self.to_ne_bytes());
Ok(())
}
}
impl AbiArgument for Felt {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
if buffer.len() >= 56 {
align_to(buffer, get_integer_layout(252).align());
}
buffer.extend_from_slice(&self.to_bytes_le());
Ok(())
}
}
impl AbiArgument for U256 {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
self.lo.to_bytes(buffer, find_dict_drop_override)?;
self.hi.to_bytes(buffer, find_dict_drop_override)
}
}
impl AbiArgument for [u8; 31] {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
_find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
// The `bytes31` type is treated as a 248-bit integer, therefore it follows the same
// splitting rules as them.
if buffer.len() >= 56 {
align_to(buffer, get_integer_layout(252).align());
}
buffer.extend_from_slice(self);
buffer.push(0);
Ok(())
}
}
impl<T> AbiArgument for *const T {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
<u64 as AbiArgument>::to_bytes(&(*self as u64), buffer, find_dict_drop_override)
}
}
impl<T> AbiArgument for *mut T {
fn to_bytes(
&self,
buffer: &mut Vec<u8>,
find_dict_drop_override: impl Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)>,
) -> Result<(), Error> {
<u64 as AbiArgument>::to_bytes(&(*self as u64), buffer, find_dict_drop_override)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn u8_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
u8::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, [u8::MAX, 0, 0, 0, 0, 0, 0, 0]);
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
u8::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 70].into_iter().chain([u8::MAX]).collect::<Vec<_>>()
);
}
#[test]
fn i8_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
i8::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, [i8::MAX as u8, 0, 0, 0, 0, 0, 0, 0]);
// Buffer initially empty with negative value
let mut buffer = vec![];
i8::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, [128, 255, 255, 255, 255, 255, 255, 255]);
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
i8::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 70]
.into_iter()
.chain([i8::MAX as u8])
.collect::<Vec<_>>()
);
// Buffer initially filled with 70 zeros (len > 64) and negative value
let mut buffer = vec![0; 70];
i8::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, [0; 70].into_iter().chain([128]).collect::<Vec<_>>());
}
#[test]
fn u16_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
u16::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, vec![u8::MAX, u8::MAX, 0, 0, 0, 0, 0, 0]);
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
u16::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 70]
.into_iter()
.chain(vec![u8::MAX, u8::MAX])
.collect::<Vec<_>>()
);
}
#[test]
fn i16_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
i16::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, vec![u8::MAX, i8::MAX as u8, 0, 0, 0, 0, 0, 0]);
// Buffer initially empty with negative value
let mut buffer = vec![];
i16::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, [0, 128, 255, 255, 255, 255, 255, 255]);
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
i16::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 70]
.into_iter()
.chain(vec![u8::MAX, i8::MAX as u8])
.collect::<Vec<_>>()
);
// Buffer initially filled with 70 zeros (len > 64) and negative value
let mut buffer = vec![0; 70];
i16::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 70].into_iter().chain([0, 128]).collect::<Vec<_>>()
);
}
#[test]
fn u32_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
u32::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
vec![u8::MAX; 4]
.into_iter()
.chain(vec![0; 4])
.collect::<Vec<_>>()
);
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
u32::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 72]
.into_iter()
.chain(vec![u8::MAX; 4])
.collect::<Vec<_>>()
);
}
#[test]
fn i32_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
i32::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
vec![u8::MAX, u8::MAX, u8::MAX, i8::MAX as u8, 0, 0, 0, 0]
);
// Buffer initially empty with negative value
let mut buffer = vec![];
i32::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, [0, 0, 0, 128, 255, 255, 255, 255]);
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
i32::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 72]
.into_iter()
.chain(vec![u8::MAX, u8::MAX, u8::MAX, i8::MAX as u8])
.collect::<Vec<_>>()
);
// Buffer initially filled with 70 zeros (len > 64) and negative value
let mut buffer = vec![0; 70];
i32::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 72]
.into_iter()
.chain([0, 0, 0, 128])
.collect::<Vec<_>>()
);
}
#[test]
fn u64_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
u64::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, u64::MAX.to_ne_bytes().to_vec());
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
u64::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 72]
.into_iter()
.chain(u64::MAX.to_ne_bytes().to_vec())
.collect::<Vec<_>>()
);
}
#[test]
fn i64_to_bytes() {
// Buffer initially empty
let mut buffer = vec![];
i64::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, i64::MAX.to_ne_bytes().to_vec());
// Buffer initially empty with negative value
let mut buffer = vec![];
i64::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(buffer, i64::MIN.to_ne_bytes().to_vec());
// Buffer initially filled with 70 zeros (len > 64)
let mut buffer = vec![0; 70];
i64::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 72]
.into_iter()
.chain(i64::MAX.to_ne_bytes().to_vec())
.collect::<Vec<_>>()
);
// Buffer initially filled with 70 zeros (len > 64) and negative value
let mut buffer = vec![0; 70];
i64::MIN.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 72]
.into_iter()
.chain(i64::MIN.to_ne_bytes().to_vec())
.collect::<Vec<_>>()
);
}
#[test]
fn u128_stack_split() {
let mut buffer = vec![0; 56];
u128::MAX.to_bytes(&mut buffer, |_| unreachable!()).unwrap();
assert_eq!(
buffer,
[0; 64].into_iter().chain([0xFF; 16]).collect::<Vec<_>>()
);
}
#[test]
fn felt_stack_split() {
// Only a single u64 spilled into the stack.
let mut buffer = vec![0; 40];
Felt::from_hex("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
.unwrap()
.to_bytes(&mut buffer, |_| unreachable!())
.unwrap();
assert_eq!(
buffer,
[0; 40]
.into_iter()
.chain([0xFF; 31])
.chain([0x00])
.collect::<Vec<_>>()
);
// Half the felt spilled into the stack.
let mut buffer = vec![0; 48];
Felt::from_hex("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
.unwrap()
.to_bytes(&mut buffer, |_| unreachable!())
.unwrap();
assert_eq!(
buffer,
[0; 48]
.into_iter()
.chain([0xFF; 31])
.chain([0x00])
.collect::<Vec<_>>()
);
// All the felt spilled into the stack (with padding).
let mut buffer = vec![0; 56];
Felt::from_hex("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
.unwrap()
.to_bytes(&mut buffer, |_| unreachable!())
.unwrap();
assert_eq!(
buffer,
[0; 64]
.into_iter()
.chain([0xFF; 31])
.chain([0x00])
.collect::<Vec<_>>()
);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/executor/contract.rs | src/executor/contract.rs | //! A specialized executor for Starknet contracts, avoiding the overhead of storing the sierra program registry and
//! enabling efficient serialization of the program/data once compiled.
//!
//! This executor heavily relies on the stability of the contract entry point argument order.
//!
//! Right now this order is like the following:
//!
//! 1. One or more builtins (rangecheck, etc)
//! 2. Gas builtin
//! 3. System builtin (the syscall handler)
//! 4. A Array of felts (calldata)
//!
//! ## How it works:
//!
//! The only variable data we need to know at call time is the builtins order,
//! to save this, when first compiling the sierra program (with [`ContractExecutor::new`]) it iterates through all the user
//! defined functions (this includes the contract wrappers, which are the ones that matter)
//! and saves the builtin arguments in a `Vec`.
//!
//! The API provides two more methods: [`ContractExecutor::save`] and [`ContractExecutor::load`].
//!
//! Save can be used to save the compiled program into the given path, alongside it will be saved
//! a json file with the entry points and their builtins (as seen in the example)
//!
//! ```json
//! {"0":{"builtins":[]},"1":{"builtins":["RangeCheck","Gas","System"]}}
//! ```
//!
//! If the given path is "program.so", then at the same location, "program.json" will be saved.
//!
//! When loading, passing the "program.so" path will make it load the program and the "program.json" alongside it.
//!
use crate::{
arch::AbiArgument,
clone_option_mut,
context::NativeContext,
debug::libfunc_to_name,
error::{panic::ToNativeAssertError, Error, Result},
execution_result::{
BuiltinStats, ContractExecutionResult, ADD_MOD_BUILTIN_SIZE, BITWISE_BUILTIN_SIZE,
EC_OP_BUILTIN_SIZE, MUL_MOD_BUILTIN_SIZE, PEDERSEN_BUILTIN_SIZE, POSEIDON_BUILTIN_SIZE,
RANGE_CHECK96_BUILTIN_SIZE, RANGE_CHECK_BUILTIN_SIZE, SEGMENT_ARENA_BUILTIN_SIZE,
},
executor::{invoke_trampoline, BuiltinCostsGuard},
metadata::runtime_bindings::setup_runtime,
module::NativeModule,
native_assert, native_panic,
starknet::{handler::StarknetSyscallHandlerCallbacks, StarknetSyscallHandler},
statistics::{SierraDeclaredTypeStats, SierraFuncStats, Statistics},
types::TypeBuilder,
utils::{
decode_error_message, generate_function_name, get_integer_layout, get_types_total_size,
libc_free, libc_malloc, BuiltinCosts,
},
OptLevel,
};
use bumpalo::Bump;
use cairo_lang_sierra::{
extensions::{
circuit::CircuitTypeConcrete,
core::{CoreConcreteLibfunc, CoreLibfunc, CoreType, CoreTypeConcrete},
gas::CostTokenType,
starknet::StarknetTypeConcrete,
ConcreteLibfunc,
},
ids::FunctionId,
program::{GenFunction, GenStatement, Program, StatementIdx},
program_registry::ProgramRegistry,
};
use cairo_lang_sierra_to_casm::metadata::MetadataComputationConfig;
use cairo_lang_starknet_classes::contract_class::ContractEntryPoints;
use cairo_lang_starknet_classes::{
casm_contract_class::ENTRY_POINT_COST, compiler_version::VersionId,
};
use cairo_lang_utils::small_ordered_map::SmallOrderedMap;
use educe::Educe;
use itertools::{chain, Itertools};
use libloading::Library;
use serde::{Deserialize, Serialize};
use starknet_types_core::felt::Felt;
use std::{
alloc::Layout,
cmp::Ordering,
collections::BTreeMap,
ffi::c_void,
fs::{self, File},
io,
path::{Path, PathBuf},
ptr::{self, NonNull},
sync::Arc,
time::Instant,
};
use tempfile::NamedTempFile;
/// Please look at the [module level docs](self).
#[derive(Educe, Clone)]
#[educe(Debug)]
pub struct AotContractExecutor {
#[educe(Debug(ignore))]
library: Arc<Library>,
path: PathBuf,
contract_info: NativeContractInfo,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NativeContractInfo {
pub version: ContractInfoVersion,
pub entry_points: BTreeMap<Felt, EntryPointInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum ContractInfoVersion {
V0,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct EntryPointInfo {
pub function_id: u64,
pub builtins: Vec<BuiltinType>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum BuiltinType {
Bitwise,
EcOp,
RangeCheck,
SegmentArena,
Poseidon,
Pedersen,
RangeCheck96,
CircuitAdd,
CircuitMul,
Gas,
System,
BuiltinCosts,
}
impl BuiltinType {
pub const fn size_in_bytes(&self) -> usize {
size_of::<u64>()
}
}
impl AotContractExecutor {
/// Compile and load a program using a temporary shared library.
///
/// When enabled, compilation stats will be saved to the `stats`. The
/// initial statistics can be build using the default builder.
pub fn new(
program: &Program,
entry_points: &ContractEntryPoints,
sierra_version: VersionId,
opt_level: OptLevel,
stats: Option<&mut Statistics>,
) -> Result<Self> {
let output_path = NamedTempFile::new()?
.into_temp_path()
.keep()
.to_native_assert_error("can only fail on windows")?;
let executor = Self::new_into(
program,
entry_points,
sierra_version,
output_path,
opt_level,
stats,
)?
.to_native_assert_error("temporary contract path collision")?;
fs::remove_file(&executor.path)?;
fs::remove_file(executor.path.with_extension("json"))?;
Ok(executor)
}
/// Compile and load a program into a shared library.
///
/// This function uses a lockfile to support cache sharing between multiple processes. An
/// attempt to compile a program while the `output_path` is already locked will result in
/// `Ok(None)` being returned. When this happens, the user should wait until the lock is
/// released, at which point they can use `AotContractExecutor::from_path` to load it.
///
/// When enabled, compilation stats will be saved to the `stats`. The
/// initial statistics can be build using the default builder.
pub fn new_into(
program: &Program,
entry_points: &ContractEntryPoints,
sierra_version: VersionId,
output_path: impl Into<PathBuf>,
opt_level: OptLevel,
stats: Option<&mut Statistics>,
) -> Result<Option<Self>> {
let output_path = output_path.into();
let lock_file = match LockFile::new(&output_path)? {
Some(x) => x,
None => return Ok(None),
};
let pre_compilation_instant = Instant::now();
let context = NativeContext::new();
let no_eq_solver = match sierra_version.major.cmp(&1) {
Ordering::Less => false,
Ordering::Equal => sierra_version.minor >= 4,
Ordering::Greater => true,
};
if let Some(&mut ref mut stats) = stats {
stats.sierra_type_count = Some(program.type_declarations.len());
stats.sierra_libfunc_count = Some(program.libfunc_declarations.len());
stats.sierra_statement_count = Some(program.statements.len());
stats.sierra_func_count = Some(program.funcs.len());
}
// Compile the Sierra program.
let NativeModule {
module, registry, ..
} = context.compile(
program,
true,
Some(MetadataComputationConfig {
function_set_costs: chain!(
entry_points.constructor.iter(),
entry_points.external.iter(),
entry_points.l1_handler.iter(),
)
.map(|x| {
(
FunctionId::new(x.function_idx as u64),
SmallOrderedMap::from_iter([(CostTokenType::Const, ENTRY_POINT_COST)]),
)
})
.collect(),
linear_gas_solver: no_eq_solver,
linear_ap_change_solver: no_eq_solver,
skip_non_linear_solver_comparisons: false,
compute_runtime_costs: false,
}),
clone_option_mut!(stats),
)?;
if let Some(&mut ref mut stats) = stats {
for type_declaration in &program.type_declarations {
if let Ok(type_concrete) = registry.get_type(&type_declaration.id) {
let type_id = type_declaration.id.id;
let type_size = type_concrete.layout(®istry)?.size();
stats.sierra_declared_types_stats.insert(
type_id,
SierraDeclaredTypeStats {
size: type_size,
as_param_count: 0,
},
);
if let CoreTypeConcrete::Circuit(CircuitTypeConcrete::Circuit(info)) =
type_concrete
{
stats.add_circuit_gates(&info.circuit_info)?;
}
}
}
for statement in &program.statements {
if let GenStatement::Invocation(invocation) = statement {
let libfunc = registry.get_libfunc(&invocation.libfunc_id)?;
let name = libfunc_to_name(libfunc).to_string();
*stats.sierra_libfunc_frequency.entry(name).or_insert(0) += 1;
for param in libfunc.param_signatures() {
let param_type_id = param.ty.id;
if let Some(type_stats) =
stats.sierra_declared_types_stats.get_mut(¶m_type_id)
{
type_stats.as_param_count += 1;
}
}
}
}
for func in &program.funcs {
let func_id = func.id.id;
// Params
let params_total_size =
get_types_total_size(&func.signature.param_types, ®istry)?;
// Return types
let return_types_total_size =
get_types_total_size(&func.signature.ret_types, ®istry)?;
stats.sierra_func_stats.insert(
func_id,
SierraFuncStats {
params_total_size,
return_types_total_size,
times_called: 0,
},
);
}
for statement in &program.statements {
match statement {
GenStatement::Invocation(gen_invocation) => {
let libfunc = registry.get_libfunc(&gen_invocation.libfunc_id)?;
if let CoreConcreteLibfunc::FunctionCall(function_call_libfunc) = libfunc {
let func_id = function_call_libfunc.function.id.id;
let func_entry = stats
.sierra_func_stats
.get_mut(&func_id)
.to_native_assert_error(&format!(
"Function ID {func_id}, should be present in the stats"
))?;
func_entry.times_called += 1;
}
}
GenStatement::Return(_) => continue,
}
}
}
// Generate mappings between the entry point's selectors and their function indexes.
let entry_point_mappings = chain!(
entry_points.constructor.iter(),
entry_points.external.iter(),
entry_points.l1_handler.iter(),
)
.map(|x| {
let function_id = x.function_idx as u64;
let function = registry
.get_function(&FunctionId::new(function_id))
.to_native_assert_error("unreachable")?;
let builtins = find_entrypoint_builtins(function, ®istry)?;
Ok((
Felt::from(&x.selector),
EntryPointInfo {
function_id: x.function_idx as u64,
builtins,
},
))
})
.collect::<Result<BTreeMap<_, _>>>()?;
let object_data = crate::module_to_object(&module, opt_level, clone_option_mut!(stats))?;
if let Some(&mut ref mut stats) = stats {
stats.object_size_bytes = Some(object_data.len());
}
// Build the shared library into the lockfile, to avoid using a tmp file.
crate::object_to_shared_lib(&object_data, &lock_file.0, clone_option_mut!(stats))?;
let compilation_time = pre_compilation_instant.elapsed().as_millis();
if let Some(&mut ref mut stats) = stats {
stats.compilation_total_time_ms = Some(compilation_time);
}
// Write the contract info.
fs::write(
output_path.with_extension("json"),
serde_json::to_string(&NativeContractInfo {
version: ContractInfoVersion::V0,
entry_points: entry_point_mappings,
})?,
)?;
if let Some(&mut ref mut stats) = stats {
native_assert!(stats.validate(), "some statistics are missing");
}
// Atomically move the built shared library to the correct path. This will avoid data races
// when loading contracts.
lock_file.rename(&output_path)?;
Self::from_path(output_path)
}
/// Load a program from a shared library.
///
/// This function will check for the existence of a lockfile. If found, it'll return `Ok(None)`.
/// When this happens, the user should wait until the lock is released, then try loading it
/// again.
pub fn from_path(path: impl Into<PathBuf>) -> Result<Option<Self>> {
let path = path.into();
// Note: Library should load first, otherwise there could theoretically be a race condition.
// See the `new_into` function's code for details.
let library = Arc::new(unsafe { Library::new(&path)? });
let contract_info =
serde_json::from_str(&fs::read_to_string(path.with_extension("json"))?)?;
let executor = Self {
library,
path,
contract_info,
};
setup_runtime(|x| executor.find_symbol_ptr(x));
#[cfg(feature = "with-debug-utils")]
crate::metadata::debug_utils::setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-trace-dump")]
crate::metadata::trace_dump::setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-libfunc-profiling")]
crate::metadata::profiler::setup_runtime(|name| executor.find_symbol_ptr(name));
Ok(Some(executor))
}
/// Runs the entry point by the given selector.
///
/// - selector: The selector of the entry point to run.
/// - args: The calldata.
/// - gas: The gas for the execution.
/// - builtin_costs: An optional argument to customize the costs of the builtins.
/// - syscall_handler: The syscall handler implementation to use when executing the contract.
///
/// The entry point gas cost is not deducted from the gas counter.
pub fn run(
&self,
selector: Felt,
args: &[Felt],
gas: u64,
builtin_costs: Option<BuiltinCosts>,
mut syscall_handler: impl StarknetSyscallHandler,
) -> Result<ContractExecutionResult> {
let arena = Bump::new();
let mut invoke_data = Vec::<u8>::new();
let function_id = FunctionId {
id: self
.contract_info
.entry_points
.get(&selector)
.ok_or(Error::SelectorNotFound)?
.function_id,
debug_name: None,
};
let function_ptr = self.find_function_ptr(&function_id, true)?;
// Initialize syscall handler and builtin costs.
// We may be inside a recursive contract, save the possible saved builtin costs to restore it after our call.
let mut syscall_handler = StarknetSyscallHandlerCallbacks::new(&mut syscall_handler);
let builtin_costs = builtin_costs.unwrap_or_default();
let builtin_costs_guard = BuiltinCostsGuard::install(builtin_costs);
// it can vary from contract to contract thats why we need to store/ load it.
let builtins_size: usize = self.contract_info.entry_points[&selector]
.builtins
.iter()
.map(|x| x.size_in_bytes())
.sum();
// There is always a return ptr because contracts always return more than 1 thing (builtin counters, syscall, enum)
let return_ptr = arena.alloc_layout(unsafe {
// 56 = size of enum
Layout::from_size_align_unchecked(128 + builtins_size, 16)
});
return_ptr
.as_ptr()
.to_bytes(&mut invoke_data, |_| unreachable!())?;
for b in &self.contract_info.entry_points[&selector].builtins {
match b {
BuiltinType::Gas => {
gas.to_bytes(&mut invoke_data, |_| unreachable!())?;
}
BuiltinType::BuiltinCosts => {
builtin_costs.to_bytes(&mut invoke_data, |_| unreachable!())?;
}
BuiltinType::System => {
(&mut syscall_handler as *mut StarknetSyscallHandlerCallbacks<_>)
.to_bytes(&mut invoke_data, |_| unreachable!())?;
}
_ => {
0u64.to_bytes(&mut invoke_data, |_| unreachable!())?;
}
}
}
let felt_layout = get_integer_layout(252).pad_to_align();
let refcount_offset = crate::types::array::calc_data_prefix_offset(felt_layout);
let len_u32: u32 = args
.len()
.try_into()
.to_native_assert_error("number of arguments should fit into a u32")?;
let array_ptr = match args.len() {
0 => std::ptr::null_mut(),
_ => unsafe {
let array_ptr: *mut () =
libc_malloc(felt_layout.size() * args.len() + refcount_offset).cast();
// Write reference count.
array_ptr.cast::<(u32, u32)>().write((1, len_u32));
array_ptr.byte_add(refcount_offset)
},
};
for (idx, elem) in args.iter().enumerate() {
let f = elem.to_bytes_le();
unsafe {
std::ptr::copy_nonoverlapping(
f.as_ptr().cast::<u8>(),
array_ptr.byte_add(idx * felt_layout.size()).cast::<u8>(),
felt_layout.size(),
)
};
}
// Make double pointer.
let array_ptr_ptr = if array_ptr.is_null() {
ptr::null_mut()
} else {
unsafe {
let array_ptr_ptr = libc_malloc(size_of::<*mut ()>()).cast::<*mut ()>();
array_ptr_ptr.write(array_ptr);
array_ptr_ptr
}
};
array_ptr_ptr.to_bytes(&mut invoke_data, |_| unreachable!())?;
if cfg!(target_arch = "aarch64") {
0u32.to_bytes(&mut invoke_data, |_| unreachable!())?; // start
len_u32.to_bytes(&mut invoke_data, |_| unreachable!())?; // end
len_u32.to_bytes(&mut invoke_data, |_| unreachable!())?; // cap
} else if cfg!(target_arch = "x86_64") {
(0u32 as u64).to_bytes(&mut invoke_data, |_| unreachable!())?; // start
(len_u32 as u64).to_bytes(&mut invoke_data, |_| unreachable!())?; // end
(len_u32 as u64).to_bytes(&mut invoke_data, |_| unreachable!())?; // cap
} else {
unreachable!("unsupported architecture");
}
// Pad invoke data to the 16 byte boundary avoid segfaults.
#[cfg(target_arch = "aarch64")]
const REGISTER_BYTES: usize = 64;
#[cfg(target_arch = "x86_64")]
const REGISTER_BYTES: usize = 48;
if invoke_data.len() > REGISTER_BYTES {
invoke_data.resize(
REGISTER_BYTES + (invoke_data.len() - REGISTER_BYTES).next_multiple_of(16),
0,
);
}
// Invoke the trampoline.
#[cfg(target_arch = "x86_64")]
let mut ret_registers = [0; 2];
#[cfg(target_arch = "aarch64")]
let mut ret_registers = [0; 4];
#[allow(unused_mut)]
let mut run_trampoline = || unsafe {
invoke_trampoline(
function_ptr,
invoke_data.as_ptr().cast(),
invoke_data.len() >> 3,
ret_registers.as_mut_ptr(),
);
};
#[cfg(feature = "with-segfault-catcher")]
crate::utils::safe_runner::run_safely(run_trampoline).map_err(Error::SafeRunner)?;
#[cfg(not(feature = "with-segfault-catcher"))]
run_trampoline();
// Parse final gas.
unsafe fn read_value<T>(ptr: &mut NonNull<()>) -> &T {
let align_offset = ptr
.cast::<u8>()
.as_ptr()
.align_offset(std::mem::align_of::<T>());
let value_ptr = ptr.cast::<u8>().as_ptr().add(align_offset).cast::<T>();
*ptr = NonNull::new_unchecked(value_ptr.add(1)).cast();
&*value_ptr
}
let mut remaining_gas = 0;
let mut builtin_stats = BuiltinStats::default();
let return_ptr = &mut return_ptr.cast();
for b in &self.contract_info.entry_points[&selector].builtins {
match b {
BuiltinType::Gas => {
remaining_gas = unsafe { *read_value::<u64>(return_ptr) };
}
BuiltinType::System => {
unsafe { read_value::<*mut ()>(return_ptr) };
}
BuiltinType::BuiltinCosts => {
unsafe { read_value::<*mut ()>(return_ptr) };
// ptr holds the builtin costs, but they dont change, so its of no use, but we read to advance the ptr.
}
x => {
let value = unsafe { *read_value::<u64>(return_ptr) } as usize;
match x {
BuiltinType::RangeCheck => {
builtin_stats.range_check = value / RANGE_CHECK_BUILTIN_SIZE
}
BuiltinType::Pedersen => {
builtin_stats.pedersen = value / PEDERSEN_BUILTIN_SIZE
}
BuiltinType::Bitwise => {
builtin_stats.bitwise = value / BITWISE_BUILTIN_SIZE
}
BuiltinType::EcOp => builtin_stats.ec_op = value / EC_OP_BUILTIN_SIZE,
BuiltinType::Poseidon => {
builtin_stats.poseidon = value / POSEIDON_BUILTIN_SIZE
}
BuiltinType::SegmentArena => {
builtin_stats.segment_arena = value / SEGMENT_ARENA_BUILTIN_SIZE
}
BuiltinType::RangeCheck96 => {
builtin_stats.range_check96 = value / RANGE_CHECK96_BUILTIN_SIZE
}
BuiltinType::CircuitAdd => {
builtin_stats.add_mod = value / ADD_MOD_BUILTIN_SIZE
}
BuiltinType::CircuitMul => {
builtin_stats.mul_mod = value / MUL_MOD_BUILTIN_SIZE
}
BuiltinType::Gas => {}
BuiltinType::System => {}
BuiltinType::BuiltinCosts => {}
}
}
}
}
// align the pointer
// layout of the enum type.
let layout = unsafe { Layout::from_size_align_unchecked(32, 8) };
let align_offset = return_ptr
.cast::<u8>()
.as_ptr()
.align_offset(layout.align());
let tag_layout = Layout::from_size_align(1, 1)?;
let enum_ptr = unsafe {
NonNull::new(return_ptr.cast::<u8>().as_ptr().add(align_offset))
.to_native_assert_error("return ptr should not be null")?
};
let tag = *unsafe { enum_ptr.cast::<u8>().as_ref() } as usize;
let tag = tag & 0x01; // Filter out bits that are not part of the enum's tag.
let value_layout = unsafe { Layout::from_size_align_unchecked(24, 8) };
let mut value_ptr = unsafe { enum_ptr.byte_add(tag_layout.extend(value_layout)?.1).cast() };
let array_ptr_ptr = unsafe { *read_value::<*mut NonNull<()>>(&mut value_ptr) };
let array_start = unsafe { *read_value::<u32>(&mut value_ptr) };
let array_end = unsafe { *read_value::<u32>(&mut value_ptr) };
let _array_capacity = unsafe { *read_value::<u32>(&mut value_ptr) };
let mut array_value = Vec::with_capacity((array_end - array_start) as usize);
if !array_ptr_ptr.is_null() {
let array_ptr = unsafe { array_ptr_ptr.read() };
let elem_stride = felt_layout.pad_to_align().size();
for i in array_start..array_end {
let cur_elem_ptr = unsafe { array_ptr.byte_add(elem_stride * i as usize) };
let mut data = unsafe { cur_elem_ptr.cast::<[u8; 32]>().read() };
data[31] &= 0x0F; // Filter out first 4 bits (they're outside an i252).
array_value.push(Felt::from_bytes_le(&data));
}
unsafe {
let array_ptr = array_ptr.byte_sub(refcount_offset);
native_assert!(
array_ptr.cast::<u32>().read() == 1,
"return array should have a reference count of 1"
);
libc_free(array_ptr.as_ptr().cast());
libc_free(array_ptr_ptr.cast());
}
}
let error_msg = match tag {
0 => None,
_ => {
Some(decode_error_message(
&array_value
.iter()
.flat_map(|felt| felt.to_bytes_be().to_vec())
// remove null chars
.filter(|b| *b != 0)
.collect::<Vec<_>>(),
))
}
};
// Restore the original builtin costs pointer.
drop(builtin_costs_guard);
#[cfg(feature = "with-mem-tracing")]
crate::utils::mem_tracing::report_stats();
Ok(ContractExecutionResult {
remaining_gas,
failure_flag: tag != 0,
return_values: array_value,
error_msg,
builtin_stats,
})
}
pub fn find_function_ptr(
&self,
function_id: &FunctionId,
is_for_contract_executor: bool,
) -> Result<*mut c_void> {
let function_name = generate_function_name(function_id, is_for_contract_executor);
let function_name = format!("_mlir_ciface_{function_name}");
// Arguments and return values are hardcoded since they'll be handled by the trampoline.
Ok(unsafe {
self.library
.get::<extern "C" fn()>(function_name.as_bytes())?
.into_raw()
.into_raw()
})
}
pub fn find_symbol_ptr(&self, name: &str) -> Option<*mut c_void> {
unsafe {
self.library
.get::<*mut ()>(name.as_bytes())
.ok()
.map(|x| x.into_raw().into_raw())
}
}
}
fn find_entrypoint_builtins(
function: &GenFunction<StatementIdx>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
) -> Result<Vec<BuiltinType>> {
let param_type_infos = function
.params
.iter()
.map(|x| -> Result<_> {
let ty = registry.get_type(&x.ty)?;
let is_zst = ty.is_zst(registry)?;
Ok((ty, is_zst))
})
.try_collect::<_, Vec<_>, _>()?;
param_type_infos
.iter()
.take_while(|(ty, _)| ty.is_builtin())
.filter(|(_, is_zst)| !is_zst)
.map(|(ty, _)| -> Result<_> {
Ok(match ty {
CoreTypeConcrete::Bitwise(_) => BuiltinType::Bitwise,
CoreTypeConcrete::EcOp(_) => BuiltinType::EcOp,
CoreTypeConcrete::RangeCheck(_) => BuiltinType::RangeCheck,
CoreTypeConcrete::Pedersen(_) => BuiltinType::Pedersen,
CoreTypeConcrete::Poseidon(_) => BuiltinType::Poseidon,
CoreTypeConcrete::BuiltinCosts(_) => BuiltinType::BuiltinCosts,
CoreTypeConcrete::SegmentArena(_) => BuiltinType::SegmentArena,
CoreTypeConcrete::RangeCheck96(_) => BuiltinType::RangeCheck96,
CoreTypeConcrete::Circuit(CircuitTypeConcrete::AddMod(_)) => {
BuiltinType::CircuitAdd
}
CoreTypeConcrete::Circuit(CircuitTypeConcrete::MulMod(_)) => {
BuiltinType::CircuitMul
}
CoreTypeConcrete::GasBuiltin(_) => BuiltinType::Gas,
CoreTypeConcrete::Starknet(StarknetTypeConcrete::System(_)) => BuiltinType::System,
_ => native_panic!("unknown builtin type for function {}", function),
})
})
.try_collect()
}
#[derive(Debug)]
struct LockFile(PathBuf);
impl LockFile {
pub fn new(path: impl Into<PathBuf>) -> io::Result<Option<Self>> {
let path: PathBuf = path.into();
let path = path.with_extension("lock");
match File::create_new(&path) {
Ok(_) => Ok(Some(Self(path))),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(None),
Err(e) => Err(e),
}
}
pub fn rename(self, path: impl AsRef<Path>) -> io::Result<()> {
fs::rename(&self.0, path.as_ref())?;
// don't remove lockfile, as we just renamed it
std::mem::forget(self);
Ok(())
}
}
impl Drop for LockFile {
fn drop(&mut self) {
let _ = fs::remove_file(&self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{load_starknet_contract, starknet_stub::StubSyscallHandler};
use cairo_lang_starknet_classes::contract_class::{
version_id_from_serialized_sierra_program, ContractClass,
};
use rayon::iter::ParallelBridge;
use rstest::*;
// todo add recursive contract test See: https://github.com/lambdaclass/cairo_native/issues/1220
#[fixture]
fn starknet_program() -> ContractClass {
let (_, program) = load_starknet_contract! {
#[starknet::interface]
trait ISimpleStorage<TContractState> {
fn get(self: @TContractState, x: felt252) -> (felt252, felt252);
}
#[starknet::contract]
mod contract {
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl ISimpleStorageImpl of super::ISimpleStorage<ContractState> {
fn get(self: @ContractState, x: felt252) -> (felt252, felt252) {
(x, x * 2)
}
}
}
};
program
}
#[fixture]
fn starknet_program_factorial() -> ContractClass {
let (_, program) = load_starknet_contract! {
#[starknet::interface]
trait ISimpleStorage<TContractState> {
fn get(self: @TContractState, x: felt252) -> felt252;
}
#[starknet::contract]
mod contract {
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl ISimpleStorageImpl of super::ISimpleStorage<ContractState> {
fn get(self: @ContractState, x: felt252) -> felt252 {
factorial(1, x)
}
}
fn factorial(value: felt252, n: felt252) -> felt252 {
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | true |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/executor/aot.rs | src/executor/aot.rs | use crate::{
error::Error,
execution_result::{ContractExecutionResult, ExecutionResult},
metadata::{
felt252_dict::Felt252DictOverrides, gas::GasMetadata, runtime_bindings::setup_runtime,
},
module::NativeModule,
starknet::{DummySyscallHandler, StarknetSyscallHandler},
utils::generate_function_name,
values::Value,
OptLevel,
};
use cairo_lang_sierra::{
extensions::core::{CoreLibfunc, CoreType},
ids::{ConcreteTypeId, FunctionId},
program::FunctionSignature,
program_registry::ProgramRegistry,
};
use educe::Educe;
use libc::c_void;
use libloading::Library;
use starknet_types_core::felt::Felt;
use std::{io, mem::transmute};
use tempfile::NamedTempFile;
#[derive(Educe)]
#[educe(Debug)]
pub struct AotNativeExecutor {
#[educe(Debug(ignore))]
library: Library,
#[educe(Debug(ignore))]
registry: ProgramRegistry<CoreType, CoreLibfunc>,
gas_metadata: GasMetadata,
dict_overrides: Felt252DictOverrides,
}
unsafe impl Send for AotNativeExecutor {}
unsafe impl Sync for AotNativeExecutor {}
impl AotNativeExecutor {
pub fn new(
library: Library,
registry: ProgramRegistry<CoreType, CoreLibfunc>,
gas_metadata: GasMetadata,
dict_overrides: Felt252DictOverrides,
) -> Self {
let executor = Self {
library,
registry,
gas_metadata,
dict_overrides,
};
setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-debug-utils")]
crate::metadata::debug_utils::setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-trace-dump")]
crate::metadata::trace_dump::setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-libfunc-profiling")]
crate::metadata::profiler::setup_runtime(|name| executor.find_symbol_ptr(name));
executor
}
/// Utility to convert a [`NativeModule`] into an [`AotNativeExecutor`].
pub fn from_native_module(module: NativeModule, opt_level: OptLevel) -> Result<Self, Error> {
let NativeModule {
module,
registry,
mut metadata,
} = module;
let library_path = NamedTempFile::new()?
.into_temp_path()
.keep()
.map_err(io::Error::from)?;
let object_data = crate::module_to_object(&module, opt_level, None)?;
crate::object_to_shared_lib(&object_data, &library_path, None)?;
Ok(Self::new(
unsafe { Library::new(&library_path)? },
registry,
metadata.remove().ok_or(Error::MissingMetadata)?,
metadata.remove().unwrap_or_default(),
))
}
pub fn invoke_dynamic(
&self,
function_id: &FunctionId,
args: &[Value],
gas: Option<u64>,
) -> Result<ExecutionResult, Error> {
let available_gas = self
.gas_metadata
.get_initial_available_gas(function_id, gas)?;
super::invoke_dynamic(
&self.registry,
self.find_function_ptr(function_id)?,
self.extract_signature(function_id)?,
args,
available_gas,
Option::<DummySyscallHandler>::None,
self.build_find_dict_drop_override(),
)
}
pub fn invoke_dynamic_with_syscall_handler(
&self,
function_id: &FunctionId,
args: &[Value],
gas: Option<u64>,
syscall_handler: impl StarknetSyscallHandler,
) -> Result<ExecutionResult, Error> {
let available_gas = self
.gas_metadata
.get_initial_available_gas(function_id, gas)?;
super::invoke_dynamic(
&self.registry,
self.find_function_ptr(function_id)?,
self.extract_signature(function_id)?,
args,
available_gas,
Some(syscall_handler),
self.build_find_dict_drop_override(),
)
}
pub fn invoke_contract_dynamic(
&self,
function_id: &FunctionId,
args: &[Felt],
gas: Option<u64>,
syscall_handler: impl StarknetSyscallHandler,
) -> Result<ContractExecutionResult, Error> {
let available_gas = self
.gas_metadata
.get_initial_available_gas(function_id, gas)?;
ContractExecutionResult::from_execution_result(super::invoke_dynamic(
&self.registry,
self.find_function_ptr(function_id)?,
self.extract_signature(function_id)?,
&[Value::Struct {
fields: vec![Value::Array(
args.iter().cloned().map(Value::Felt252).collect(),
)],
debug_name: None,
}],
available_gas,
Some(syscall_handler),
self.build_find_dict_drop_override(),
)?)
}
pub fn find_function_ptr(&self, function_id: &FunctionId) -> Result<*mut c_void, Error> {
let function_name = generate_function_name(function_id, false);
let function_name = format!("_mlir_ciface_{function_name}");
// Arguments and return values are hardcoded since they'll be handled by the trampoline.
unsafe {
Ok(self
.library
.get::<extern "C" fn()>(function_name.as_bytes())?
.into_raw()
.into_raw())
}
}
pub fn find_symbol_ptr(&self, name: &str) -> Option<*mut c_void> {
unsafe {
self.library
.get::<*mut ()>(name.as_bytes())
.ok()
.map(|x| x.into_raw().into_raw())
}
}
fn extract_signature(&self, function_id: &FunctionId) -> Result<&FunctionSignature, Error> {
Ok(&self.registry.get_function(function_id)?.signature)
}
fn build_find_dict_drop_override(
&self,
) -> impl '_ + Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)> {
|type_id| {
self.dict_overrides
.get_drop_fn(type_id)
.and_then(|symbol| self.find_symbol_ptr(symbol))
.map(|ptr| unsafe { transmute(ptr as *const ()) })
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
context::NativeContext,
starknet_stub::StubSyscallHandler,
{load_cairo, load_starknet},
};
use cairo_lang_sierra::program::Program;
use rstest::*;
#[fixture]
fn program() -> Program {
let (_, program) = load_cairo! {
use starknet::{SyscallResultTrait, get_block_hash_syscall};
fn run_test() -> felt252 {
42
}
fn get_block_hash() -> felt252 {
get_block_hash_syscall(1).unwrap_syscall()
}
};
program
}
#[fixture]
fn starknet_program() -> Program {
let (_, program) = load_starknet! {
#[starknet::interface]
trait ISimpleStorage<TContractState> {
fn get(self: @TContractState) -> u128;
}
#[starknet::contract]
mod contract {
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl ISimpleStorageImpl of super::ISimpleStorage<ContractState> {
fn get(self: @ContractState) -> u128 {
42
}
}
}
};
program
}
#[rstest]
#[case(OptLevel::None)]
#[case(OptLevel::Default)]
#[case(OptLevel::Aggressive)]
fn test_invoke_dynamic(program: Program, #[case] optlevel: OptLevel) {
let native_context = NativeContext::new();
let module = native_context
.compile(&program, false, Some(Default::default()), None)
.expect("failed to compile context");
let executor = AotNativeExecutor::from_native_module(module, optlevel).unwrap();
// The first function in the program is `run_test`.
let entrypoint_function_id = &program.funcs.first().expect("should have a function").id;
let result = executor
.invoke_dynamic(entrypoint_function_id, &[], Some(u64::MAX))
.unwrap();
assert_eq!(result.return_value, Value::Felt252(Felt::from(42)));
}
#[rstest]
#[case(OptLevel::None)]
#[case(OptLevel::Default)]
#[case(OptLevel::Aggressive)]
fn test_invoke_dynamic_with_syscall_handler(program: Program, #[case] optlevel: OptLevel) {
let native_context = NativeContext::new();
let module = native_context
.compile(&program, false, Some(Default::default()), None)
.expect("failed to compile context");
let executor = AotNativeExecutor::from_native_module(module, optlevel).unwrap();
// The second function in the program is `get_block_hash`.
let entrypoint_function_id = &program.funcs.get(1).expect("should have a function").id;
let syscall_handler = &mut StubSyscallHandler::default();
let expected_value = Felt::from(123);
syscall_handler.block_hash.insert(1, expected_value);
let result = executor
.invoke_dynamic_with_syscall_handler(
entrypoint_function_id,
&[],
Some(u64::MAX),
syscall_handler,
)
.unwrap();
let expected_value = Value::Enum {
tag: 0,
value: Value::Struct {
fields: vec![Value::Felt252(expected_value)],
debug_name: Some("Tuple<felt252>".into()),
}
.into(),
debug_name: Some("core::panics::PanicResult::<(core::felt252,)>".into()),
};
assert_eq!(result.return_value, expected_value);
}
#[rstest]
#[case(OptLevel::None)]
#[case(OptLevel::Default)]
#[case(OptLevel::Aggressive)]
fn test_invoke_contract_dynamic(starknet_program: Program, #[case] optlevel: OptLevel) {
let native_context = NativeContext::new();
let module = native_context
.compile(&starknet_program, false, Some(Default::default()), None)
.expect("failed to compile context");
let executor = AotNativeExecutor::from_native_module(module, optlevel).unwrap();
let entrypoint_function_id = &starknet_program
.funcs
.iter()
.find(|f| {
f.id.debug_name
.as_ref()
.map(|name| name.contains("__wrapper__ISimpleStorageImpl__get"))
.unwrap_or_default()
})
.expect("should have a function")
.id;
let result = executor
.invoke_contract_dynamic(
entrypoint_function_id,
&[],
Some(u64::MAX),
&mut StubSyscallHandler::default(),
)
.unwrap();
assert_eq!(result.return_values, vec![Felt::from(42)]);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/src/executor/jit.rs | src/executor/jit.rs | use crate::{
error::Error,
execution_result::{ContractExecutionResult, ExecutionResult},
metadata::{
felt252_dict::Felt252DictOverrides, gas::GasMetadata, runtime_bindings::setup_runtime,
},
module::NativeModule,
starknet::{DummySyscallHandler, StarknetSyscallHandler},
utils::{create_engine, generate_function_name},
values::Value,
OptLevel,
};
use cairo_lang_sierra::{
extensions::core::{CoreLibfunc, CoreType},
ids::{ConcreteTypeId, FunctionId},
program::FunctionSignature,
program_registry::ProgramRegistry,
};
use libc::c_void;
use melior::{ir::Module, ExecutionEngine};
use starknet_types_core::felt::Felt;
use std::mem::transmute;
/// A MLIR JIT execution engine in the context of Cairo Native.
pub struct JitNativeExecutor<'m> {
engine: ExecutionEngine,
module: Module<'m>,
registry: ProgramRegistry<CoreType, CoreLibfunc>,
gas_metadata: GasMetadata,
dict_overrides: Felt252DictOverrides,
}
unsafe impl Send for JitNativeExecutor<'_> {}
unsafe impl Sync for JitNativeExecutor<'_> {}
impl std::fmt::Debug for JitNativeExecutor<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JitNativeExecutor")
.field("module", &self.module)
.field("gas_metadata", &self.gas_metadata)
.finish()
}
}
impl<'m> JitNativeExecutor<'m> {
pub fn from_native_module(
native_module: NativeModule<'m>,
opt_level: OptLevel,
) -> Result<Self, Error> {
let NativeModule {
module,
registry,
mut metadata,
} = native_module;
let executor = Self {
engine: create_engine(&module, &metadata, opt_level),
module,
registry,
gas_metadata: metadata.remove().ok_or(Error::MissingMetadata)?,
dict_overrides: metadata.remove().unwrap_or_default(),
};
setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-debug-utils")]
crate::metadata::debug_utils::setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-trace-dump")]
crate::metadata::trace_dump::setup_runtime(|name| executor.find_symbol_ptr(name));
#[cfg(feature = "with-libfunc-profiling")]
crate::metadata::profiler::setup_runtime(|name| executor.find_symbol_ptr(name));
Ok(executor)
}
pub const fn program_registry(&self) -> &ProgramRegistry<CoreType, CoreLibfunc> {
&self.registry
}
pub const fn module(&self) -> &Module<'m> {
&self.module
}
/// Execute a program with the given params.
pub fn invoke_dynamic(
&self,
function_id: &FunctionId,
args: &[Value],
gas: Option<u64>,
) -> Result<ExecutionResult, Error> {
let available_gas = self
.gas_metadata
.get_initial_available_gas(function_id, gas)?;
super::invoke_dynamic(
&self.registry,
self.find_function_ptr(function_id),
self.extract_signature(function_id)?,
args,
available_gas,
Option::<DummySyscallHandler>::None,
self.build_find_dict_drop_override(),
)
}
/// Execute a program with the given params.
pub fn invoke_dynamic_with_syscall_handler(
&self,
function_id: &FunctionId,
args: &[Value],
gas: Option<u64>,
syscall_handler: impl StarknetSyscallHandler,
) -> Result<ExecutionResult, Error> {
let available_gas = self
.gas_metadata
.get_initial_available_gas(function_id, gas)?;
super::invoke_dynamic(
&self.registry,
self.find_function_ptr(function_id),
self.extract_signature(function_id)?,
args,
available_gas,
Some(syscall_handler),
self.build_find_dict_drop_override(),
)
}
pub fn invoke_contract_dynamic(
&self,
function_id: &FunctionId,
args: &[Felt],
gas: Option<u64>,
syscall_handler: impl StarknetSyscallHandler,
) -> Result<ContractExecutionResult, Error> {
let available_gas = self
.gas_metadata
.get_initial_available_gas(function_id, gas)?;
ContractExecutionResult::from_execution_result(super::invoke_dynamic(
&self.registry,
self.find_function_ptr(function_id),
self.extract_signature(function_id)?,
&[Value::Struct {
fields: vec![Value::Array(
args.iter().cloned().map(Value::Felt252).collect(),
)],
debug_name: None,
}],
available_gas,
Some(syscall_handler),
self.build_find_dict_drop_override(),
)?)
}
pub fn find_function_ptr(&self, function_id: &FunctionId) -> *mut c_void {
let function_name = generate_function_name(function_id, false);
let function_name = format!("_mlir_ciface_{function_name}");
// Arguments and return values are hardcoded since they'll be handled by the trampoline.
self.engine.lookup(&function_name) as *mut c_void
}
pub fn find_symbol_ptr(&self, name: &str) -> Option<*mut c_void> {
let ptr = self.engine.lookup(name) as *mut c_void;
if ptr.is_null() {
None
} else {
Some(ptr)
}
}
fn extract_signature(&self, function_id: &FunctionId) -> Result<&FunctionSignature, Error> {
Ok(self
.program_registry()
.get_function(function_id)
.map(|func| &func.signature)?)
}
fn build_find_dict_drop_override(
&self,
) -> impl '_ + Copy + Fn(&ConcreteTypeId) -> Option<extern "C" fn(*mut c_void)> {
|type_id| {
self.dict_overrides
.get_drop_fn(type_id)
.and_then(|symbol| self.find_symbol_ptr(symbol))
.map(|ptr| unsafe { transmute(ptr as *const ()) })
}
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/common.rs | tests/common.rs | //! This module contains common code used by all integration tests, which use proptest to compare various outputs based on the inputs
//! The general idea is to have a test for each libfunc if possible.
#![allow(dead_code)]
use ark_ff::One;
use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
};
use cairo_lang_filesystem::{db::init_dev_corelib, ids::CrateInput};
use cairo_lang_runner::{
Arg, RunResultStarknet, RunResultValue, RunnerError, SierraCasmRunner, StarknetState,
};
use cairo_lang_sierra::{
extensions::{
circuit::CircuitTypeConcrete,
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
starknet::StarknetTypeConcrete,
utils::Range,
ConcreteType,
},
ids::{ConcreteTypeId, FunctionId},
program::Program,
program_registry::ProgramRegistry,
};
use cairo_lang_sierra_generator::replace_ids::{DebugReplacer, SierraIdReplacer};
use cairo_lang_starknet::{
compile::compile_contract_in_prepared_db,
contract::{find_contracts, get_contracts_info},
starknet_plugin_suite,
};
use cairo_lang_starknet_classes::{
casm_contract_class::{CasmContractClass, ENTRY_POINT_COST},
contract_class::{version_id_from_serialized_sierra_program, ContractClass},
};
use cairo_native::{
context::NativeContext,
execution_result::{ContractExecutionResult, ExecutionResult},
executor::{AotContractExecutor, JitNativeExecutor},
starknet::{DummySyscallHandler, StarknetSyscallHandler},
utils::{find_entry_point_by_idx, HALF_PRIME, PRIME},
OptLevel, Value,
};
use cairo_vm::{
hint_processor::cairo_1_hint_processor::hint_processor::Cairo1HintProcessor,
types::{builtin_name::BuiltinName, layout_name::LayoutName, relocatable::MaybeRelocatable},
vm::runners::cairo_runner::{CairoArg, CairoRunner, RunResources},
};
use itertools::Itertools;
use lambdaworks_math::{
field::{
element::FieldElement, fields::montgomery_backed_prime_fields::MontgomeryBackendPrimeField,
},
unsigned_integer::element::UnsignedInteger,
};
use num_bigint::{BigInt, BigUint, Sign};
use pretty_assertions_sorted::assert_eq_sorted;
use proptest::{strategy::Strategy, test_runner::TestCaseError};
use starknet_types_core::felt::Felt;
use std::{collections::HashMap, env::var, fs, ops::Neg, path::Path};
#[allow(unused_macros)]
macro_rules! load_cairo {
( $( $program:tt )+ ) => {
$crate::common::load_cairo_str(stringify!($($program)+))
};
}
#[allow(unused_imports)]
pub(crate) use load_cairo;
use num_traits::ToPrimitive;
pub const DEFAULT_GAS: u64 = u64::MAX;
// Parse numeric string into felt, wrapping negatives around the prime modulo.
pub fn felt(value: &str) -> [u32; 8] {
let value = value.parse::<BigInt>().unwrap();
let value = match value.sign() {
Sign::Minus => &*PRIME - value.neg().to_biguint().unwrap(),
_ => value.to_biguint().unwrap(),
};
let mut u32_digits = value.to_u32_digits();
u32_digits.resize(8, 0);
u32_digits.try_into().unwrap()
}
/// Parse any type that can be a bigint to a felt that can be used in the cairo-native input.
pub fn feltn(value: impl Into<BigInt>) -> [u32; 8] {
let value: BigInt = value.into();
let value = match value.sign() {
Sign::Minus => &*PRIME - value.neg().to_biguint().unwrap(),
_ => value.to_biguint().unwrap(),
};
let mut u32_digits = value.to_u32_digits();
u32_digits.resize(8, 0);
u32_digits.try_into().unwrap()
}
/// Converts a casm variant to sierra.
pub const fn casm_variant_to_sierra(idx: i64, num_variants: i64) -> i64 {
num_variants - 1 - (idx >> 1)
}
pub fn get_run_result(r: &RunResultValue) -> Vec<String> {
match r {
RunResultValue::Success(x) | RunResultValue::Panic(x) => {
x.iter().map(ToString::to_string).collect()
}
}
}
pub fn load_cairo_str(program_str: &str) -> (String, Program, SierraCasmRunner) {
let mut program_file = tempfile::Builder::new()
.prefix("test_")
.suffix(".cairo")
.tempfile()
.unwrap();
fs::write(&mut program_file, program_str).unwrap();
let mut db = RootDatabase::builder().detect_corelib().build().unwrap();
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, program_file.as_ref()).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let sierra_program_with_dbg = compile_prepared_db(
&db,
main_crate_ids.clone(),
CompilerConfig {
replace_ids: true,
..Default::default()
},
)
.unwrap();
let program = sierra_program_with_dbg.program;
let module_name = program_file.path().with_extension("");
let module_name = module_name.file_name().unwrap().to_str().unwrap();
let replacer = DebugReplacer { db: &db };
let contracts = find_contracts(&db, &main_crate_ids);
let contracts_info = get_contracts_info(&db, contracts, &replacer).unwrap();
let runner = SierraCasmRunner::new(
program.clone(),
Some(Default::default()),
contracts_info,
None,
)
.unwrap();
(module_name.to_string(), program, runner)
}
pub fn load_cairo_path(program_path: &str) -> (String, Program, SierraCasmRunner) {
let program_file = Path::new(program_path);
let mut db = RootDatabase::default();
init_dev_corelib(
&mut db,
Path::new(&var("CARGO_MANIFEST_DIR").unwrap()).join("corelib/src"),
);
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, program_file).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let sierra_program_with_dbg = compile_prepared_db(
&db,
main_crate_ids.clone(),
CompilerConfig {
replace_ids: true,
..Default::default()
},
)
.unwrap();
let mut program = sierra_program_with_dbg.program;
let module_name = program_file.with_extension("");
let module_name = module_name.file_name().unwrap().to_str().unwrap();
let replacer = DebugReplacer { db: &db };
replacer.enrich_function_names(&mut program);
let contracts = find_contracts(&db, &main_crate_ids);
let contracts_info = get_contracts_info(&db, contracts, &replacer).unwrap();
let program = replacer.apply(&program);
let runner = SierraCasmRunner::new(
program.clone(),
Some(Default::default()),
contracts_info,
None,
)
.unwrap();
(module_name.to_string(), program, runner)
}
/// Compiles a cairo starknet contract from the given path
pub fn load_cairo_contract_path(path: &str) -> ContractClass {
let mut db = RootDatabase::builder()
.detect_corelib()
.with_default_plugin_suite(starknet_plugin_suite())
.build()
.expect("failed to build database");
let main_crate_ids = {
let main_crate_inputs = setup_project(&mut db, path.as_ref())
.expect("path should be a valid cairo project or file");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
compile_contract_in_prepared_db(
&db,
None,
main_crate_ids.clone(),
CompilerConfig {
replace_ids: true,
..Default::default()
},
)
.expect("path should contain a single valid contract")
}
pub fn run_native_program(
program: &(String, Program, SierraCasmRunner),
entry_point: &str,
args: &[Value],
gas: Option<u64>,
syscall_handler: Option<impl StarknetSyscallHandler>,
) -> ExecutionResult {
let entry_point = format!("{0}::{0}::{1}", program.0, entry_point);
let program = &program.1;
let entry_point_id = &program
.funcs
.iter()
.find(|x| x.id.debug_name.as_deref() == Some(&entry_point))
.expect("Test program entry point not found.")
.id;
let context = NativeContext::new();
let module = context
.compile(program, false, Some(Default::default()), None)
.expect("Could not compile test program to MLIR.");
assert!(
module.module().as_operation().verify(),
"Test program generated invalid MLIR:\n{}",
module.module().as_operation()
);
// FIXME: There are some bugs with non-zero LLVM optimization levels.
let executor = JitNativeExecutor::from_native_module(module, OptLevel::None).unwrap();
match syscall_handler {
Some(syscall_handler) => executor
.invoke_dynamic_with_syscall_handler(entry_point_id, args, gas, syscall_handler)
.unwrap(),
None => executor.invoke_dynamic(entry_point_id, args, gas).unwrap(),
}
}
/// Runs the program on the cairo-vm
pub fn run_vm_program(
program: &(String, Program, SierraCasmRunner),
entry_point: &str,
args: Vec<Arg>,
gas: Option<usize>,
) -> Result<RunResultStarknet, RunnerError> {
let runner = &program.2;
runner.run_function_with_starknet_context(
runner.find_function(entry_point).unwrap(),
args,
gas,
StarknetState::default(),
)
}
/// Runs the contract on the cairo-vm
pub fn run_vm_contract(
cairo_contract: &ContractClass,
selector: &BigUint,
args: &[Felt],
) -> Vec<Felt> {
let args = args
.iter()
.map(|arg| MaybeRelocatable::Int(*arg))
.collect_vec();
let contract =
CasmContractClass::from_contract_class(cairo_contract.clone(), false, usize::MAX)
.expect("failed to compile sierra contract to casm");
let program = contract
.clone()
.try_into()
.expect("failed to extract program from casm contract");
// Initialize runner and builtins
let mut runner = CairoRunner::new(&program, LayoutName::all_cairo, None, false, false, false)
.expect("failed to build runner");
let entrypoint = contract
.entry_points_by_type
.external
.iter()
.find(|e| e.selector == *selector)
.expect("given entrypoint index should exist");
let program_builtins = entrypoint
.builtins
.iter()
.map(|s| BuiltinName::from_str(s).expect("invalid builtin name"))
.collect_vec();
runner
.initialize_function_runner_cairo_1(&program_builtins)
.expect("failed to initialize runner");
// Initialize implicit Args
let builtins = runner.get_program_builtins();
let mut implicit_args: Vec<MaybeRelocatable> = runner
.vm
.get_builtin_runners()
.iter()
.filter(|b| builtins.contains(&b.name()))
.flat_map(|b| b.initial_stack())
.collect();
let initial_gas = MaybeRelocatable::from(usize::MAX);
implicit_args.extend([initial_gas]);
let syscall_segment = MaybeRelocatable::from(runner.vm.add_memory_segment());
implicit_args.extend([syscall_segment]);
// Load builtin costs
let builtin_costs: Vec<MaybeRelocatable> =
vec![0.into(), 0.into(), 0.into(), 0.into(), 0.into()];
let builtin_costs_ptr = runner.vm.add_memory_segment();
runner
.vm
.load_data(builtin_costs_ptr, &builtin_costs)
.expect("failed to load builtin costs data to vm");
// Load extra data
let core_program_end_ptr = (runner.program_base.expect("program base is missing")
+ runner.get_program().data_len())
.expect("memory pointer overflowed");
let program_extra_data: Vec<MaybeRelocatable> =
vec![0x208B7FFF7FFF7FFE.into(), builtin_costs_ptr.into()];
runner
.vm
.load_data(core_program_end_ptr, &program_extra_data)
.expect("failed to load extra data to vm");
// Load calldata
let calldata_start = runner.vm.add_memory_segment();
let calldata_end = runner
.vm
.load_data(calldata_start, &args.to_vec())
.expect("failed to load calldata to vm");
// Create entrypoint_args
let mut entrypoint_args: Vec<CairoArg> = implicit_args
.iter()
.map(|m| CairoArg::from(m.clone()))
.collect();
entrypoint_args.extend([
MaybeRelocatable::from(calldata_start).into(),
MaybeRelocatable::from(calldata_end).into(),
]);
let entrypoint_args: Vec<&CairoArg> = entrypoint_args.iter().collect();
// Run contract entrypoint
let mut hint_processor =
Cairo1HintProcessor::new(&contract.hints, RunResources::default(), false);
runner
.run_from_entrypoint(
entrypoint.offset,
&entrypoint_args,
true,
Some(runner.get_program().data_len() + program_extra_data.len()),
&mut hint_processor,
)
.expect("failed to execute contract");
// Extract return values
let return_values = runner
.vm
.get_return_values(5)
.expect("failed to extract return values");
let retdata_start = return_values[3]
.get_relocatable()
.expect("failed to get return data start");
let retdata_end = return_values[4]
.get_relocatable()
.expect("failed to get return data end");
runner
.vm
.get_integer_range(
retdata_start,
(retdata_end - retdata_start).expect("return data length should not be negative"),
)
.expect("failed to access vm memory")
.iter()
.map(|c| c.clone().into_owned())
.collect_vec()
}
pub fn compare_inputless_program(program_path: &str) {
let program: (String, Program, SierraCasmRunner) = load_cairo_path(program_path);
let program = &program;
let result_vm = run_vm_program(program, "main", vec![], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"main",
&[],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("main").unwrap().id,
&result_vm,
&result_native,
)
.expect("compare error");
}
/// Runs the program using cairo-native JIT.
pub fn run_native_starknet_contract(
sierra_program: &Program,
entry_point_function_idx: usize,
args: &[Felt],
handler: impl StarknetSyscallHandler,
) -> ContractExecutionResult {
let native_context = NativeContext::new();
let native_program = native_context
.compile(sierra_program, false, Some(Default::default()), None)
.unwrap();
let entry_point_fn = find_entry_point_by_idx(sierra_program, entry_point_function_idx).unwrap();
let entry_point_id = &entry_point_fn.id;
let native_executor =
JitNativeExecutor::from_native_module(native_program, Default::default()).unwrap();
native_executor
.invoke_contract_dynamic(entry_point_id, args, u64::MAX.into(), handler)
.expect("failed to execute the given contract")
}
pub fn run_native_starknet_aot_contract(
contract: &ContractClass,
selector: &BigUint,
args: &[Felt],
handler: impl StarknetSyscallHandler,
) -> ContractExecutionResult {
let (sierra_version, _) =
version_id_from_serialized_sierra_program(&contract.sierra_program).unwrap();
let native_executor = AotContractExecutor::new(
&contract.extract_sierra_program().unwrap(),
&contract.entry_points_by_type,
sierra_version,
Default::default(),
None,
)
.unwrap();
native_executor
// substract ENTRY_POINT_COST so gas matches
.run(
Felt::from(selector),
args,
u64::MAX - ENTRY_POINT_COST as u64,
None,
handler,
)
.expect("failed to execute the given contract")
}
/// Given the result of the cairo-vm and cairo-native of the same program, it compares
/// the results automatically, triggering a proptest assert if there is a mismatch.
///
/// Left of report of the assert is the cairo vm result, right side is cairo native
pub fn compare_outputs(
program: &Program,
entry_point: &FunctionId,
vm_result: &RunResultStarknet,
native_result: &ExecutionResult,
) -> Result<(), TestCaseError> {
let registry = ProgramRegistry::<CoreType, CoreLibfunc>::new(program).unwrap();
let function = registry.get_function(entry_point).unwrap();
fn map_vm_sizes(
size_cache: &mut HashMap<ConcreteTypeId, usize>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
ty: &ConcreteTypeId,
) -> usize {
match size_cache.get(ty) {
Some(&type_size) => type_size,
None => {
let type_size = match registry.get_type(ty).unwrap() {
CoreTypeConcrete::Array(_) | CoreTypeConcrete::EcPoint(_) => 2,
CoreTypeConcrete::Felt252(_)
| CoreTypeConcrete::Uint128(_)
| CoreTypeConcrete::Uint64(_)
| CoreTypeConcrete::Uint32(_)
| CoreTypeConcrete::Uint16(_)
| CoreTypeConcrete::Uint8(_)
| CoreTypeConcrete::Sint128(_)
| CoreTypeConcrete::Sint64(_)
| CoreTypeConcrete::Sint32(_)
| CoreTypeConcrete::Sint16(_)
| CoreTypeConcrete::Sint8(_)
| CoreTypeConcrete::Box(_)
| CoreTypeConcrete::BoundedInt(_)
| CoreTypeConcrete::Circuit(CircuitTypeConcrete::U96Guarantee(_))
| CoreTypeConcrete::Nullable(_) => 1,
CoreTypeConcrete::Enum(info) => {
1 + info
.variants
.iter()
.map(|variant_ty| map_vm_sizes(size_cache, registry, variant_ty))
.max()
.unwrap_or_default()
}
CoreTypeConcrete::Struct(info) => info
.members
.iter()
.map(|member_ty| map_vm_sizes(size_cache, registry, member_ty))
.sum(),
CoreTypeConcrete::NonZero(info) => map_vm_sizes(size_cache, registry, &info.ty),
CoreTypeConcrete::EcState(_) => 4,
CoreTypeConcrete::Snapshot(info) => {
map_vm_sizes(size_cache, registry, &info.ty)
}
CoreTypeConcrete::SquashedFelt252Dict(_) => 2,
x => todo!("vm size not yet implemented: {:?}", x.info()),
};
size_cache.insert(ty.clone(), type_size);
type_size
}
}
}
fn map_vm_values(
size_cache: &mut HashMap<ConcreteTypeId, usize>,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
memory: &[Option<Felt>],
mut values: &[Felt],
ty: &ConcreteTypeId,
) -> Value {
match registry.get_type(ty).unwrap() {
CoreTypeConcrete::Array(info) => {
assert_eq!(values.len(), 2);
let since_ptr = values[0].to_usize().unwrap();
let until_ptr = values[1].to_usize().unwrap();
let total_len = until_ptr - since_ptr;
let elem_size = map_vm_sizes(size_cache, registry, &info.ty);
assert_eq!(total_len % elem_size, 0);
Value::Array(
memory[since_ptr..until_ptr]
.chunks(elem_size)
.map(|data| data.iter().cloned().map(Option::unwrap).collect::<Vec<_>>())
.map(|data| map_vm_values(size_cache, registry, memory, &data, &info.ty))
.collect(),
)
}
CoreTypeConcrete::Felt252(_) => {
Value::Felt252(Felt::from_bytes_le(&values[0].to_bytes_le()))
}
CoreTypeConcrete::Uint128(_) => Value::Uint128(values[0].to_u128().unwrap()),
CoreTypeConcrete::Uint64(_) => Value::Uint64(values[0].to_u64().unwrap()),
CoreTypeConcrete::Uint32(_) => Value::Uint32(values[0].to_u32().unwrap()),
CoreTypeConcrete::Uint16(_) => Value::Uint16(values[0].to_u16().unwrap()),
CoreTypeConcrete::Uint8(_) => Value::Uint8(values[0].to_u8().unwrap()),
CoreTypeConcrete::Sint128(_) => {
Value::Sint128(if values[0].to_biguint() >= *HALF_PRIME {
-(&*PRIME - &values[0].to_biguint()).to_i128().unwrap()
} else {
values[0].to_biguint().to_i128().unwrap()
})
}
CoreTypeConcrete::Sint64(_) => {
Value::Sint64(if values[0].to_biguint() >= *HALF_PRIME {
-(&*PRIME - &values[0].to_biguint()).to_i64().unwrap()
} else {
values[0].to_biguint().to_i64().unwrap()
})
}
CoreTypeConcrete::Sint32(_) => {
Value::Sint32(if values[0].to_biguint() >= *HALF_PRIME {
-(&*PRIME - &values[0].to_biguint()).to_i32().unwrap()
} else {
values[0].to_biguint().to_i32().unwrap()
})
}
CoreTypeConcrete::Sint16(_) => {
Value::Sint16(if values[0].to_biguint() >= *HALF_PRIME {
-(&*PRIME - &values[0].to_biguint()).to_i16().unwrap()
} else {
values[0].to_biguint().to_i16().unwrap()
})
}
CoreTypeConcrete::Sint8(_) => Value::Sint8(if values[0].to_biguint() >= *HALF_PRIME {
-(&*PRIME - &values[0].to_biguint()).to_i8().unwrap()
} else {
values[0].to_biguint().to_i8().unwrap()
}),
CoreTypeConcrete::BoundedInt(info) => Value::BoundedInt {
value: values[0],
range: info.range.clone(),
},
CoreTypeConcrete::Circuit(CircuitTypeConcrete::U96Guarantee(_)) => Value::BoundedInt {
value: values[0],
range: Range {
lower: BigInt::ZERO,
upper: BigInt::one() << 96,
},
},
CoreTypeConcrete::Enum(info) => {
let enum_size = map_vm_sizes(size_cache, registry, ty);
assert_eq!(values.len(), enum_size);
let (tag, data);
(tag, values) = values.split_first().unwrap();
let mut tag = tag.to_usize().unwrap();
if info.variants.len() > 2 {
tag = info.variants.len() - ((tag + 1) >> 1);
}
assert!(tag <= info.variants.len());
data = &values[enum_size - size_cache[&info.variants[tag]] - 1..];
Value::Enum {
tag,
value: Box::new(map_vm_values(
size_cache,
registry,
memory,
data,
&info.variants[tag],
)),
debug_name: ty.debug_name.as_deref().map(String::from),
}
}
CoreTypeConcrete::Struct(info) => Value::Struct {
fields: info
.members
.iter()
.map(|member_ty| {
let data;
(data, values) =
values.split_at(map_vm_sizes(size_cache, registry, member_ty));
map_vm_values(size_cache, registry, memory, data, member_ty)
})
.collect(),
debug_name: ty.debug_name.as_deref().map(String::from),
},
CoreTypeConcrete::SquashedFelt252Dict(info) => Value::Felt252Dict {
value: (values[0].to_usize().unwrap()..values[1].to_usize().unwrap())
.step_by(3)
.map(|index| {
(
Felt::from_bytes_le(&memory[index].unwrap().to_bytes_le()),
match &info.info.long_id.generic_args[0] {
cairo_lang_sierra::program::GenericArg::Type(ty) => map_vm_values(
size_cache,
registry,
memory,
&[memory[index + 2].unwrap()],
ty,
),
_ => unimplemented!("unsupported dict value type"),
},
)
})
.collect(),
debug_name: ty.debug_name.as_deref().map(String::from),
},
CoreTypeConcrete::Snapshot(info) => {
map_vm_values(size_cache, registry, memory, values, &info.ty)
}
CoreTypeConcrete::Nullable(info) => {
assert_eq!(values.len(), 1);
let ty_size = map_vm_sizes(size_cache, registry, &info.ty);
match values[0].to_usize().unwrap() {
0 => Value::Null,
ptr if ty_size == 0 => {
assert_eq!(ptr, 1);
map_vm_values(size_cache, registry, memory, &[], &info.ty)
}
ptr => map_vm_values(
size_cache,
registry,
memory,
&memory[ptr..ptr + ty_size]
.iter()
.cloned()
.map(Option::unwrap)
.collect::<Vec<_>>(),
&info.ty,
),
}
}
CoreTypeConcrete::Box(info) => {
assert_eq!(values.len(), 1);
let ty_size = map_vm_sizes(size_cache, registry, &info.ty);
match values[0].to_usize().unwrap() {
ptr if ty_size == 0 => {
assert_eq!(ptr, 1);
map_vm_values(size_cache, registry, memory, &[], &info.ty)
}
ptr => map_vm_values(
size_cache,
registry,
memory,
&memory[ptr..ptr + ty_size]
.iter()
.cloned()
.map(Option::unwrap)
.collect::<Vec<_>>(),
&info.ty,
),
}
}
CoreTypeConcrete::NonZero(info) => {
map_vm_values(size_cache, registry, memory, values, &info.ty)
}
CoreTypeConcrete::EcPoint(_) => {
assert_eq!(values.len(), 2);
Value::EcPoint(
Felt::from_bytes_le(&values[0].to_bytes_le()),
Felt::from_bytes_le(&values[1].to_bytes_le()),
)
}
CoreTypeConcrete::EcState(_) => {
assert_eq!(values.len(), 4);
Value::EcState(
Felt::from_bytes_le(&values[0].to_bytes_le()),
Felt::from_bytes_le(&values[1].to_bytes_le()),
Felt::from_bytes_le(&values[2].to_bytes_le()),
Felt::from_bytes_le(&values[3].to_bytes_le()),
)
}
CoreTypeConcrete::Bytes31(_) => {
let mut bytes = values[0].to_bytes_le().to_vec();
bytes.pop();
Value::Bytes31(bytes.try_into().unwrap())
}
CoreTypeConcrete::Coupon(_) => todo!(),
CoreTypeConcrete::Bitwise(_) => unreachable!(),
CoreTypeConcrete::Const(_) => unreachable!(),
CoreTypeConcrete::EcOp(_) => unreachable!(),
CoreTypeConcrete::GasBuiltin(_) => unreachable!(),
CoreTypeConcrete::BuiltinCosts(_) => unreachable!(),
CoreTypeConcrete::RangeCheck(_) => unreachable!(),
CoreTypeConcrete::Pedersen(_) => unreachable!(),
CoreTypeConcrete::Poseidon(_) => unreachable!(),
CoreTypeConcrete::SegmentArena(_) => unreachable!(),
x => {
todo!("vm value not yet implemented: {:?}", x.info())
}
}
}
let mut size_cache = HashMap::new();
let ty = function.signature.ret_types.last();
let is_builtin = ty.is_some_and(|ty| {
matches!(
registry.get_type(ty).unwrap(),
CoreTypeConcrete::Bitwise(_)
| CoreTypeConcrete::EcOp(_)
| CoreTypeConcrete::GasBuiltin(_)
| CoreTypeConcrete::BuiltinCosts(_)
| CoreTypeConcrete::RangeCheck(_)
| CoreTypeConcrete::RangeCheck96(_)
| CoreTypeConcrete::Pedersen(_)
| CoreTypeConcrete::Poseidon(_)
| CoreTypeConcrete::Coupon(_)
| CoreTypeConcrete::Starknet(StarknetTypeConcrete::System(_))
| CoreTypeConcrete::SegmentArena(_)
| CoreTypeConcrete::Circuit(CircuitTypeConcrete::AddMod(_))
| CoreTypeConcrete::Circuit(CircuitTypeConcrete::MulMod(_))
)
});
let returns_panic = ty.is_some_and(|ty| {
ty.debug_name
.as_ref()
.map(|x| x.starts_with("core::panics::PanicResult"))
.unwrap_or(false)
});
assert_eq!(
vm_result
.gas_counter
.unwrap_or_else(|| Felt::from(0))
.to_bigint(),
Felt::from(native_result.remaining_gas.unwrap_or(0)).to_bigint(),
"gas mismatch"
);
let native_builtins = {
let mut native_builtins = HashMap::new();
native_builtins.insert("range_check", native_result.builtin_stats.range_check);
native_builtins.insert("pedersen", native_result.builtin_stats.pedersen);
native_builtins.insert("bitwise", native_result.builtin_stats.bitwise);
native_builtins.insert("ec_op", native_result.builtin_stats.ec_op);
native_builtins.insert("poseidon", native_result.builtin_stats.poseidon);
// don't include the segment arena builtin, as its not included in the VM output either.
native_builtins.insert("range_check96", native_result.builtin_stats.range_check96);
native_builtins.insert("add_mod", native_result.builtin_stats.add_mod);
native_builtins.insert("mul_mod", native_result.builtin_stats.mul_mod);
native_builtins.retain(|_, &mut v| v != 0);
native_builtins
};
let vm_builtins: HashMap<&str, usize> = vm_result
.used_resources
.basic_resources
.filter_unused_builtins()
.builtin_instance_counter
.iter()
.map(|(k, v)| (k.to_str(), *v))
.collect();
assert_eq_sorted!(vm_builtins, native_builtins, "builtin mismatch",);
let vm_result = match &vm_result.value {
RunResultValue::Success(values) if !values.is_empty() | returns_panic => {
if returns_panic {
let inner_ty = match registry.get_type(ty.unwrap())? {
CoreTypeConcrete::Enum(info) => &info.variants[0],
_ => unreachable!(),
};
Value::Enum {
tag: 0,
value: Box::new(map_vm_values(
&mut size_cache,
®istry,
&vm_result.memory,
values,
inner_ty,
)),
debug_name: None,
}
} else if !is_builtin {
map_vm_values(
&mut size_cache,
®istry,
&vm_result.memory,
values,
ty.unwrap(),
)
} else {
Value::Struct {
fields: Vec::new(),
debug_name: None,
}
}
}
RunResultValue::Panic(values) => Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: vec![
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | true |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/entry.rs | tests/entry.rs | //! To avoid generating lot of test executables, this is the single entry point of all tests.
pub mod common;
pub mod tests;
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/circuit.rs | tests/tests/circuit.rs | use crate::common::{compare_outputs, DEFAULT_GAS};
use crate::common::{load_cairo, run_native_program, run_vm_program};
use cairo_lang_runner::SierraCasmRunner;
use cairo_lang_sierra::program::Program;
use cairo_native::starknet::DummySyscallHandler;
use cairo_native::Value;
use lazy_static::lazy_static;
lazy_static! {
// Taken from: https://github.com/starkware-libs/sequencer/blob/7ee6f4c8a81def87402c626c9d72a33c74bc3243/crates/blockifier/feature_contracts/cairo1/test_contract.cairo#L656
static ref TEST: (String, Program, SierraCasmRunner) = load_cairo! {
use core::circuit::{
CircuitData, CircuitElement, CircuitInput, circuit_add, circuit_sub, circuit_mul, circuit_inverse,
EvalCircuitResult, EvalCircuitTrait, u384, CircuitOutputsTrait, CircuitModulus, into_u96_guarantee, U96Guarantee,
CircuitInputs, AddInputResultTrait, AddInputResult, IntoCircuitInputValue, add_circuit_input
};
#[feature("bounded-int-utils")]
use core::internal::bounded_int::BoundedInt;
fn test_guarantee_first_limb() {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let add = circuit_add(in1, in2);
let inv = circuit_inverse(add);
let sub = circuit_sub(inv, in2);
let mul = circuit_mul(inv, sub);
let modulus = TryInto::<_, CircuitModulus>::try_into([7, 0, 0, 0]).unwrap();
let outputs = (mul,)
.new_inputs()
.next([3, 0, 0, 0])
.next([6, 0, 0, 0])
.done()
.eval(modulus)
.unwrap();
assert!(outputs.get_output(mul) == u384 { limb0: 6, limb1: 0, limb2: 0, limb3: 0 });
}
fn test_guarantee_last_limb() {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let add = circuit_add(in1, in2);
let modulus = TryInto::<_, CircuitModulus>::try_into([7, 0, 0, 1]).unwrap();
let outputs = (add,)
.new_inputs()
.next([5, 0, 0, 0])
.next([9, 0, 0, 0])
.done()
.eval(modulus)
.unwrap();
assert!(outputs.get_output(add) == u384 { limb0: 14, limb1: 0, limb2: 0, limb3: 0 });
}
fn test_guarantee_middle_limb() {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let add = circuit_add(in1, in2);
let modulus = TryInto::<_, CircuitModulus>::try_into([7, 0, 1, 0]).unwrap();
let outputs = (add,)
.new_inputs()
.next([5, 0, 0, 0])
.next([9, 0, 0, 0])
.done()
.eval(modulus)
.unwrap();
assert!(outputs.get_output(add) == u384 { limb0: 14, limb1: 0, limb2: 0, limb3: 0 });
}
fn test_circuit_add() -> u384 {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let add = circuit_add(in1, in2);
let modulus = TryInto::<_, CircuitModulus>::try_into([12, 12, 12, 12]).unwrap();
let outputs = (add,)
.new_inputs()
.next([3, 3, 3, 3])
.next([6, 6, 6, 6])
.done()
.eval(modulus)
.unwrap();
outputs.get_output(add)
}
fn test_circuit_sub() -> u384 {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let sub = circuit_sub(in1, in2);
let modulus = TryInto::<_, CircuitModulus>::try_into([12, 12, 12, 12]).unwrap();
let outputs = (sub,)
.new_inputs()
.next([6, 6, 6, 6])
.next([3, 3, 3, 3])
.done()
.eval(modulus)
.unwrap();
outputs.get_output(sub)
}
fn test_circuit_mul() -> u384 {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let mul = circuit_mul(in1, in2);
let modulus = TryInto::<_, CircuitModulus>::try_into([12, 12, 12, 12]).unwrap();
let outputs = (mul,)
.new_inputs()
.next([3, 0, 0, 0])
.next([3, 3, 3, 3])
.done()
.eval(modulus)
.unwrap();
outputs.get_output(mul)
}
fn test_circuit_inv() -> u384 {
let in1 = CircuitElement::<CircuitInput<0>> {};
let inv = circuit_inverse(in1);
let modulus = TryInto::<_, CircuitModulus>::try_into([11, 0, 0, 0]).unwrap();
let outputs = (inv,)
.new_inputs()
.next([2, 0, 0, 0])
.done()
.eval(modulus)
.unwrap();
outputs.get_output(inv)
}
fn test_circuit_full() -> u384 {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let add1 = circuit_add(in1, in2);
let mul1 = circuit_mul(add1, in1);
let mul2 = circuit_mul(mul1, add1);
let inv1 = circuit_inverse(mul2);
let sub1 = circuit_sub(inv1, in2);
let sub2 = circuit_sub(sub1, mul2);
let inv2 = circuit_inverse(sub2);
let add2 = circuit_add(inv2, inv2);
let modulus = TryInto::<_, CircuitModulus>::try_into([17, 14, 14, 14]).unwrap();
let outputs = (add2,)
.new_inputs()
.next([9, 2, 9, 3])
.next([5, 7, 0, 8])
.done()
.eval(modulus)
.unwrap();
outputs.get_output(add2)
}
fn test_circuit_fail() -> u384 {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let add = circuit_add(in1, in2);
let modulus = TryInto::<_, CircuitModulus>::try_into([0, 0, 0, 0]).unwrap(); // Having this modulus makes eval panic
let outputs = (add,)
.new_inputs()
.next([3, 3, 3, 3])
.next([6, 6, 6, 6])
.done()
.eval(modulus)
.unwrap();
outputs.get_output(add)
}
fn test_into_u96_guarantee() -> (U96Guarantee, U96Guarantee, U96Guarantee) {
(
into_u96_guarantee::<BoundedInt<0, 79228162514264337593543950335>>(123),
into_u96_guarantee::<BoundedInt<100, 1000>>(123),
into_u96_guarantee::<u8>(123),
)
}
};
}
/*
https://github.com/keep-starknet-strange/garaga
MIT License
Copyright (c) 2023 Keep StarkNet Strange
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
lazy_static! {
static ref GARAGA_CIRCUITS: (String, Program, SierraCasmRunner) = load_cairo! {
use core::circuit::{
CircuitData, CircuitElement, CircuitInput, circuit_add, circuit_sub, circuit_mul, circuit_inverse,
EvalCircuitResult, EvalCircuitTrait, u384, CircuitOutputsTrait, CircuitModulus, into_u96_guarantee, U96Guarantee,
CircuitInputs, AddInputResultTrait, AddInputResult, IntoCircuitInputValue, add_circuit_input
};
#[generate_trait]
pub impl AddInputResultImpl2<C> of AddInputResultTrait2<C> {
fn next_2<Value, +IntoCircuitInputValue<Value>, +Drop<Value>>(
self: AddInputResult<C>, value: Value,
) -> AddInputResult<C> {
match self {
AddInputResult::More(accumulator) => add_circuit_input(
accumulator, value.into_circuit_input_value(),
),
AddInputResult::Done(_) => panic!("All inputs have been filled"),
}
}
#[inline(always)]
fn done_2(self: AddInputResult<C>) -> CircuitData<C> {
match self {
AddInputResult::Done(data) => data,
AddInputResult::More(_) => panic!("not all inputs filled"),
}
}
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/definitions/curves.cairo#L336
// Returns the modulus of BN254
#[inline(always)]
fn get_BN254_modulus() -> CircuitModulus {
let modulus = TryInto::<
_, CircuitModulus,
>::try_into([0x6871ca8d3c208c16d87cfd47, 0xb85045b68181585d97816a91, 0x30644e72e131a029, 0x0])
.unwrap();
modulus
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/basic_field_ops.cairo#L60
// Computes (in1 - in2) * (in3 ** -1)
fn compute_yInvXnegOverY_BN254() -> (u384, u384) {
let in1 = CircuitElement::<CircuitInput<0>> {};
let in2 = CircuitElement::<CircuitInput<1>> {};
let in3 = CircuitElement::<CircuitInput<2>> {};
let yInv = circuit_inverse(in3);
let xNeg = circuit_sub(in1, in2);
let xNegOverY = circuit_mul(xNeg, yInv);
let modulus = get_BN254_modulus(); // BN254 prime field modulus
let outputs = (yInv, xNegOverY)
.new_inputs()
.next_2([
0xae40a8b5aee95e54aedee2e7,
0x6e0699501c5035eed8fc5162,
0xbee76829b76806d1b6617bf8,
0x5026c3305c1267922077393,
])
.next_2([
0x10c08c4b0a70e02491c3c435,
0x591ef738050b3ce067e2016f,
0xdd6e0a179e2ce3c1399c5273,
0xd5c9af9b97e94f90cb4aba3,
])
.next_2([
0x93be53660cebb92c90d4fa87,
0xfbf63ca94e1d0ffd65801863,
0xd24fd9a06d72f1dc57f15f0a,
0x100dbfd4f271378e85171313,
])
.done_2()
.eval(modulus)
.unwrap();
return (outputs.get_output(yInv), outputs.get_output(xNegOverY));
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/basic_field_ops.cairo#L174
// In the original function, the modulus is a parameter. Here we will use BN254 modulus.
// Computes _x * _c0 + _y * _c0 ** 2 + _z * _c0 ** 3
#[inline(always)]
pub fn batch_3_mod_bn254() -> u384 {
let _x = CircuitElement::<CircuitInput<0>> {};
let _y = CircuitElement::<CircuitInput<1>> {};
let _z = CircuitElement::<CircuitInput<2>> {};
let _c0 = CircuitElement::<CircuitInput<3>> {};
let _c1 = circuit_mul(_c0, _c0);
let _c2 = circuit_mul(_c1, _c0);
let _mul1 = circuit_mul(_x, _c0);
let _mul2 = circuit_mul(_y, _c1);
let _mul3 = circuit_mul(_z, _c2);
let res = circuit_add(circuit_add(_mul1, _mul2), _mul3);
let modulus = get_BN254_modulus(); // BN254 prime field modulus
let outputs = (res,)
.new_inputs()
.next_2([
0xb7296e587409163eecd3ef5d,
0x8a065d6871fa185d15703e78,
0x8a85fb95bb90eb5c7a0d81a9,
0x157cf362e91a3c96640bd973
])
.next_2([
0x2131be4b061714de5a11407d,
0xd41318f9bcade1fee985310b,
0xb2669e638a7b78b7ba5c6751,
0xa5284fb2911d4e2f445e714,
])
.next_2([
0x712edcaf95ed642a8237e6fd,
0xed6fccd7b64896ebb6ffb3d9,
0xfcb88d23294a46657b8d2482,
0x143ef485b660d37036fc18e2,
])
.next_2([
0xaa5b7ff57bdbf47e6ab49121,
0xc14cded56b4a44e022320616,
0xdd5105feb3fdc5b10edb5afa,
0x175d2c78538490ce02fcead8,
])
.done_2()
.eval(modulus)
.unwrap();
return outputs.get_output(res);
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/definitions/structs/points.cairo#L27
// Represents a point on G2, the group of rational points on an elliptic curve over an extension field.
#[derive(Copy, Drop, Debug, PartialEq)]
pub struct G2Point {
pub x0: u384,
pub x1: u384,
pub y0: u384,
pub y1: u384,
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/circuits/ec.cairo#L324
// Adds 2 ec G2Points without checking if:
// - They are on the curve
// - They are on infinity (same x but opposite y)
#[inline(always)]
pub fn run_ADD_EC_POINTS_G2_circuit() -> (G2Point,) {
let p = G2Point {
x0: u384 {
limb0: 0xf3611b78c952aacab827a053,
limb1: 0xe1ea1e1e4d00dbae81f14b0b,
limb2: 0xcc7ed5863bc0b995b8825e0e,
limb3: 0x1638533957d540a9d2370f17,
},
x1: u384 {
limb0: 0xb57ec72a6178288c47c33577,
limb1: 0x728114d1031e1572c6c886f6,
limb2: 0x730a124fd70662a904ba1074,
limb3: 0xa4edef9c1ed7f729f520e47,
},
y0: u384 {
limb0: 0x764bf3bd999d95d71e4c9899,
limb1: 0xbfe6bd221e47aa8ae88dece9,
limb2: 0x2b5256789a66da69bf91009c,
limb3: 0x468fb440d82b0630aeb8dca,
},
y1: u384 {
limb0: 0xa59c8967acdefd8b6e36ccf3,
limb1: 0x97003f7a13c308f5422e1aa0,
limb2: 0x3f887136a43253d9c66c4116,
limb3: 0xf6d4552fa65dd2638b36154,
},
};
let q = G2Point {
x0: u384 {
limb0: 0x866f09d516020ef82324afae,
limb1: 0xa0c75df1c04d6d7a50a030fc,
limb2: 0xdccb23ae691ae54329781315,
limb3: 0x122915c824a0857e2ee414a3,
},
x1: u384 {
limb0: 0x937cc6d9d6a44aaa56ca66dc,
limb1: 0x5062650f8d251c96eb480673,
limb2: 0x7e0550ff2ac480905396eda5,
limb3: 0x9380275bbc8e5dcea7dc4dd,
},
y0: u384 {
limb0: 0x8b52fdf2455e44813ecfd892,
limb1: 0x326ac738fef5c721479dfd94,
limb2: 0xbc1a6f0136961d1e3b20b1a7,
limb3: 0xb21da7955969e61010c7a1a,
},
y1: u384 {
limb0: 0xb975b9edea56d53f23a0e849,
limb1: 0x714150a166bfbd6bcf6b3b58,
limb2: 0xa36cfe5f62a7e42e0bf1c1ed,
limb3: 0x8f239ba329b3967fe48d718,
},
};
// CONSTANT stack
let in0 = CircuitElement::<CircuitInput<0>> {}; // 0x0
// INPUT stack
let (in1, in2, in3) = (CircuitElement::<CircuitInput<1>> {}, CircuitElement::<CircuitInput<2>> {}, CircuitElement::<CircuitInput<3>> {});
let (in4, in5, in6) = (CircuitElement::<CircuitInput<4>> {}, CircuitElement::<CircuitInput<5>> {}, CircuitElement::<CircuitInput<6>> {});
let (in7, in8) = (CircuitElement::<CircuitInput<7>> {}, CircuitElement::<CircuitInput<8>> {});
let t0 = circuit_sub(in3, in7); // Fp2 sub coeff 0/1
let t1 = circuit_sub(in4, in8); // Fp2 sub coeff 1/1
let t2 = circuit_sub(in1, in5); // Fp2 sub coeff 0/1
let t3 = circuit_sub(in2, in6); // Fp2 sub coeff 1/1
let t4 = circuit_mul(t2, t2); // Fp2 Inv start
let t5 = circuit_mul(t3, t3);
let t6 = circuit_add(t4, t5);
let t7 = circuit_inverse(t6);
let t8 = circuit_mul(t2, t7); // Fp2 Inv real part end
let t9 = circuit_mul(t3, t7);
let t10 = circuit_sub(in0, t9); // Fp2 Inv imag part end
let t11 = circuit_mul(t0, t8); // Fp2 mul start
let t12 = circuit_mul(t1, t10);
let t13 = circuit_sub(t11, t12); // Fp2 mul real part end
let t14 = circuit_mul(t0, t10);
let t15 = circuit_mul(t1, t8);
let t16 = circuit_add(t14, t15); // Fp2 mul imag part end
let t17 = circuit_add(t13, t16);
let t18 = circuit_sub(t13, t16);
let t19 = circuit_mul(t17, t18);
let t20 = circuit_mul(t13, t16);
let t21 = circuit_add(t20, t20);
let t22 = circuit_sub(t19, in1); // Fp2 sub coeff 0/1
let t23 = circuit_sub(t21, in2); // Fp2 sub coeff 1/1
let t24 = circuit_sub(t22, in5); // Fp2 sub coeff 0/1
let t25 = circuit_sub(t23, in6); // Fp2 sub coeff 1/1
let t26 = circuit_sub(in1, t24); // Fp2 sub coeff 0/1
let t27 = circuit_sub(in2, t25); // Fp2 sub coeff 1/1
let t28 = circuit_mul(t13, t26); // Fp2 mul start
let t29 = circuit_mul(t16, t27);
let t30 = circuit_sub(t28, t29); // Fp2 mul real part end
let t31 = circuit_mul(t13, t27);
let t32 = circuit_mul(t16, t26);
let t33 = circuit_add(t31, t32); // Fp2 mul imag part end
let t34 = circuit_sub(t30, in3); // Fp2 sub coeff 0/1
let t35 = circuit_sub(t33, in4); // Fp2 sub coeff 1/1
let modulus = get_BN254_modulus();
let mut circuit_inputs = (t24, t25, t34, t35).new_inputs();
// Prefill constants:
circuit_inputs = circuit_inputs.next_2([0x0, 0x0, 0x0, 0x0]); // in0
// Fill inputs:
circuit_inputs = circuit_inputs.next_2(p.x0); // in1
circuit_inputs = circuit_inputs.next_2(p.x1); // in2
circuit_inputs = circuit_inputs.next_2(p.y0); // in3
circuit_inputs = circuit_inputs.next_2(p.y1); // in4
circuit_inputs = circuit_inputs.next_2(q.x0); // in5
circuit_inputs = circuit_inputs.next_2(q.x1); // in6
circuit_inputs = circuit_inputs.next_2(q.y0); // in7
circuit_inputs = circuit_inputs.next_2(q.y1); // in8
let outputs = circuit_inputs.done_2().eval(modulus).unwrap();
let result: G2Point = G2Point {
x0: outputs.get_output(t24),
x1: outputs.get_output(t25),
y0: outputs.get_output(t34),
y1: outputs.get_output(t35),
};
return (result,);
}
};
}
/*
https://github.com/kkrt-labs/kakarot
MIT License
Copyright (c) 2022 Abdel @ StarkWare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
lazy_static! {
// Taken from: https://github.com/kkrt-labs/kakarot/blob/563af42d5fe9888f8f49cf22003d2085612bf42c/cairo/kakarot-ssj/crates/evm/src/precompiles/ec_operations/ec_add.cairo#L143
static ref KAKAROT_CIRCUIT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::circuit::{
CircuitData, CircuitElement, CircuitInput, circuit_add, circuit_sub, circuit_mul, circuit_inverse,
EvalCircuitResult, EvalCircuitTrait, u384, u96, CircuitOutputsTrait, CircuitModulus, into_u96_guarantee, U96Guarantee,
CircuitInputs, AddInputResultTrait, AddInputResult, IntoCircuitInputValue, add_circuit_input
};
const BN254_PRIME_LIMBS: [
u96
; 4] = [
0x6871ca8d3c208c16d87cfd47, 0xb85045b68181585d97816a91, 0x30644e72e131a029, 0x0
];
#[generate_trait]
pub impl AddInputResultImpl2<C> of AddInputResultTrait2<C> {
fn next_2<Value, +IntoCircuitInputValue<Value>, +Drop<Value>>(
self: AddInputResult<C>, value: Value,
) -> AddInputResult<C> {
match self {
AddInputResult::More(accumulator) => add_circuit_input(
accumulator, value.into_circuit_input_value(),
),
AddInputResult::Done(_) => panic!("All inputs have been filled"),
}
}
#[inline(always)]
fn done_2(self: AddInputResult<C>) -> CircuitData<C> {
match self {
AddInputResult::Done(data) => data,
AddInputResult::More(_) => panic!("not all inputs filled"),
}
}
}
// Add two BN254 EC points without checking if:
// - the points are on the curve
// - the points are not the same
// - none of the points are the point at infinity
fn add_ec_point_unchecked() -> (u384, u384) {
let xP = u384 {
limb0: 0xb3e77acb0d776ee38973b578,
limb1: 0x7290c49d0303a7a719325387,
limb2: 0x3104f09f1439bbd9b6e47310,
limb3: 0x1794c7df23dbcfd21f7c96f5,
};
let yP = u384 {
limb0: 0xd0ccdf6e1de037c5f25dbd53,
limb1: 0x254a0c8d3849192e33a21665,
limb2: 0xcc0375e474dc85925319c5ad,
limb3: 0x59163bc09c3bb5cd5864b34,
};
let xQ = u384 {
limb0: 0x42951c5be1c30dd1f90a8da3,
limb1: 0xffa3bb5d4cc66b3c5c927fe8,
limb2: 0xb2bef79be9fc2df478672961,
limb3: 0x13b08e1d6ece19818bc96ea9,
};
let yQ = u384 {
limb0: 0x93fd3339f961a2b9c29235bc,
limb1: 0xf9bbad7b2c116dfe3ed68c7a,
limb2: 0xbd2f1d7614ffe6107af3312d,
limb3: 0x565882562afe825ad18d630,
};
// INPUT stack
let (_xP, _yP, _xQ, _yQ) = (CircuitElement::<CircuitInput<0>> {}, CircuitElement::<CircuitInput<1>> {}, CircuitElement::<CircuitInput<2>> {}, CircuitElement::<CircuitInput<3>> {});
let num = circuit_sub(_yP, _yQ);
let den = circuit_sub(_xP, _xQ);
let inv_den = circuit_inverse(den);
let slope = circuit_mul(num, inv_den);
let slope_sqr = circuit_mul(slope, slope);
let nx = circuit_sub(circuit_sub(slope_sqr, _xP), _xQ);
let ny = circuit_sub(circuit_mul(slope, circuit_sub(_xP, nx)), _yP);
let modulus = TryInto::<_, CircuitModulus>::try_into(BN254_PRIME_LIMBS).unwrap(); // BN254 prime field modulus
let mut circuit_inputs = (nx, ny,).new_inputs();
// Fill inputs:
circuit_inputs = circuit_inputs.next_2(xP); // in1
circuit_inputs = circuit_inputs.next_2(yP); // in2
circuit_inputs = circuit_inputs.next_2(xQ); // in3
circuit_inputs = circuit_inputs.next_2(yQ); // in4
let outputs = circuit_inputs.done_2().eval(modulus).unwrap();
(outputs.get_output(nx), outputs.get_output(ny))
}
};
}
/*
https://github.com/keep-starknet-strange/garaga
MIT License
Copyright (c) 2023 Keep StarkNet Strange
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
lazy_static! {
static ref BIG_CIRCUIT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::circuit::{
CircuitData, CircuitElement as CE, CircuitInput as CI, circuit_add, circuit_sub, circuit_mul, circuit_inverse,
EvalCircuitResult, EvalCircuitTrait, u384, CircuitOutputsTrait, CircuitModulus,
CircuitInputs, AddInputResultTrait, AddInputResult, IntoCircuitInputValue, add_circuit_input
};
#[generate_trait]
pub impl AddInputResultImpl2<C> of AddInputResultTrait2<C> {
fn next_2<Value, +IntoCircuitInputValue<Value>, +Drop<Value>>(
self: AddInputResult<C>, value: Value,
) -> AddInputResult<C> {
match self {
AddInputResult::More(accumulator) => add_circuit_input(
accumulator, value.into_circuit_input_value(),
),
AddInputResult::Done(_) => panic!("All inputs have been filled"),
}
}
#[inline(always)]
fn done_2(self: AddInputResult<C>) -> CircuitData<C> {
match self {
AddInputResult::Done(data) => data,
AddInputResult::More(_) => panic!("not all inputs filled"),
}
}
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/definitions/structs/points.cairo#L8
// Represents a point on G1, the group of rational points on an elliptic curve over the base field.
#[derive(Copy, Drop, Debug, PartialEq)]
pub struct G1Point {
pub x: u384,
pub y: u384,
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/definitions/curves.cairo#L322
#[inline(always)]
pub fn get_BLS12_381_modulus() -> CircuitModulus {
let modulus = TryInto::<
_, CircuitModulus,
>::try_into(
[
0xb153ffffb9feffffffffaaab, 0x6730d2a0f6b0f6241eabfffe, 0x434bacd764774b84f38512bf,
0x1a0111ea397fe69a4b1ba7b6,
],
)
.unwrap();
modulus
}
// Taken from: https://github.com/keep-starknet-strange/garaga/blob/5c5859e6dc5515f542c310cb38a149602e774112/src/src/circuits/ec.cairo#L425
// Clear cofactor of a point in the BLS12-381 elliptic curve
#[inline(always)]
pub fn run_CLEAR_COFACTOR_BLS12_381_circuit() -> (G1Point, G1Point, G1Point, G1Point) {
let P = G1Point {
x: u384 {
limb0: 0x23893f1bb0fdb0533584b05f,
limb1: 0x420d425d79dcd48b26d87814,
limb2: 0xc932fa90468e6b9dfd658cc9,
limb3: 0xe5fac70e9096e97adc6dd89,
},
y: u384 {
limb0: 0x90d1a47263d9c179e9d6bab3,
limb1: 0xc8f52b7ac4908e42515e61a6,
limb2: 0x85c60896512fc21fc50ce238,
limb3: 0x15bb2157a1b9aab29d66c644,
},
};
let modulus = get_BLS12_381_modulus();
// CONSTANT stack
let in0 = CE::<CI<0>> {}; // 0x3
// INPUT stack
let (in1, in2) = (CE::<CI<1>> {}, CE::<CI<2>> {});
let t0 = circuit_mul(in1, in1);
let t1 = circuit_mul(in0, t0);
let t2 = circuit_add(in2, in2);
let t3 = circuit_inverse(t2);
let t4 = circuit_mul(t1, t3);
let t5 = circuit_mul(t4, t4);
let t6 = circuit_sub(t5, in1);
let t7 = circuit_sub(t6, in1);
let t8 = circuit_sub(in1, t7);
let t9 = circuit_mul(t4, t8);
let t10 = circuit_sub(t9, in2);
let t11 = circuit_sub(t10, in2);
let t12 = circuit_sub(t7, in1);
let t13 = circuit_inverse(t12);
let t14 = circuit_mul(t11, t13);
let t15 = circuit_mul(t14, t14);
let t16 = circuit_sub(t15, t7);
let t17 = circuit_sub(t16, in1);
let t18 = circuit_sub(t7, t17);
let t19 = circuit_mul(t14, t18);
let t20 = circuit_sub(t19, t10);
let t21 = circuit_mul(t17, t17);
let t22 = circuit_mul(in0, t21);
let t23 = circuit_add(t20, t20);
let t24 = circuit_inverse(t23);
let t25 = circuit_mul(t22, t24);
let t26 = circuit_mul(t25, t25);
let t27 = circuit_sub(t26, t17);
let t28 = circuit_sub(t27, t17);
let t29 = circuit_sub(t17, t28);
let t30 = circuit_mul(t25, t29);
let t31 = circuit_sub(t30, t20);
let t32 = circuit_mul(t28, t28);
let t33 = circuit_mul(in0, t32);
let t34 = circuit_add(t31, t31);
let t35 = circuit_inverse(t34);
let t36 = circuit_mul(t33, t35);
let t37 = circuit_mul(t36, t36);
let t38 = circuit_sub(t37, t28);
let t39 = circuit_sub(t38, t28);
let t40 = circuit_sub(t28, t39);
let t41 = circuit_mul(t36, t40);
let t42 = circuit_sub(t41, t31);
let t43 = circuit_sub(t42, in2);
let t44 = circuit_sub(t39, in1);
let t45 = circuit_inverse(t44);
let t46 = circuit_mul(t43, t45);
let t47 = circuit_mul(t46, t46);
let t48 = circuit_sub(t47, t39);
let t49 = circuit_sub(t48, in1);
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | true |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/boolean.rs | tests/tests/boolean.rs | use crate::common::{compare_outputs, load_cairo, run_native_program, run_vm_program, DEFAULT_GAS};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::{starknet::DummySyscallHandler, Value};
use lazy_static::lazy_static;
use proptest::prelude::*;
use starknet_types_core::felt::Felt;
lazy_static! {
static ref FELT252_TO_BOOL: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
fn felt_to_bool(x: felt252) -> bool {
x == 1
}
fn run_test(a: felt252) -> bool {
felt_to_bool(a)
}
};
static ref BOOL_NOT: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
use traits::TryInto;
use core::option::OptionTrait;
fn felt_to_bool(x: felt252) -> bool {
x.try_into().unwrap() == 1_u8
}
fn program(a: bool) -> bool {
!a
}
fn run_test(a: felt252) -> bool {
program(felt_to_bool(a))
}
};
static ref BOOL_AND: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
use traits::TryInto;
use core::option::OptionTrait;
fn felt_to_bool(x: felt252) -> bool {
x.try_into().unwrap() == 1_u8
}
fn program(a: bool, b: bool) -> bool {
a && b
}
fn run_test(a: felt252, b: felt252) -> bool {
program(felt_to_bool(a), felt_to_bool(b))
}
};
static ref BOOL_OR: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
use traits::TryInto;
use core::option::OptionTrait;
fn felt_to_bool(x: felt252) -> bool {
x.try_into().unwrap() == 1_u8
}
fn program(a: bool, b: bool) -> bool {
a || b
}
fn run_test(a: felt252, b: felt252) -> bool {
program(felt_to_bool(a), felt_to_bool(b))
}
};
static ref BOOL_XOR: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
use traits::TryInto;
use core::option::OptionTrait;
fn felt_to_bool(x: felt252) -> bool {
x.try_into().unwrap() == 1_u8
}
fn program(a: bool, b: bool) -> bool {
a ^ b
}
fn run_test(a: felt252, b: felt252) -> bool {
program(felt_to_bool(a), felt_to_bool(b))
}
};
static ref BOOL_TO_FELT252: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
use core::bool_to_felt252;
use traits::TryInto;
use core::option::OptionTrait;
fn felt_to_bool(x: felt252) -> bool {
x.try_into().unwrap() == 1_u8
}
fn program(a: bool) -> felt252 {
bool_to_felt252(a)
}
fn run_test(a: felt252) -> felt252 {
program(felt_to_bool(a))
}
};
}
#[test]
fn felt252_to_bool_bug() {
let program = &FELT252_TO_BOOL;
let a = true;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from(a))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
let a = false;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from(a))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
proptest! {
#[test]
fn bool_to_felt252_proptest(a: bool) {
let program = &BOOL_TO_FELT252;
let result_vm = run_vm_program(program, "run_test", vec![
Arg::Value(Felt::from(a)),
], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn bool_not_proptest(a: bool) {
let program = &BOOL_NOT;
let result_vm = run_vm_program(program, "run_test", vec![
Arg::Value(Felt::from(a)),
], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn bool_and_proptest(a: bool, b: bool) {
let program = &BOOL_AND;
let result_vm = run_vm_program(program, "run_test", vec![
Arg::Value(Felt::from(a)),
Arg::Value(Felt::from(b))
], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn bool_or_proptest(a: bool, b: bool) {
let program = &BOOL_OR;
let result_vm = run_vm_program(program, "run_test", vec![
Arg::Value(Felt::from(a)),
Arg::Value(Felt::from(b))
], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn bool_xor_proptest(a: bool, b: bool) {
let program = &BOOL_XOR;
let result_vm = run_vm_program(program, "run_test", vec![
Arg::Value(Felt::from(a)),
Arg::Value(Felt::from(b))
], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/trampoline.rs | tests/tests/trampoline.rs | use crate::common::load_cairo;
use cairo_lang_sierra::program::Program;
use cairo_native::{
context::NativeContext,
execution_result::{BuiltinStats, ExecutionResult},
executor::JitNativeExecutor,
utils::find_function_id,
OptLevel, Value,
};
use starknet_types_core::felt::Felt;
fn run_program(program: &Program, entry_point: &str, args: &[Value]) -> ExecutionResult {
let entry_point_id = find_function_id(program, entry_point).expect("entry point not found");
let context = NativeContext::new();
let module = context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// FIXME: There are some bugs with non-zero LLVM optimization levels.
let executor = JitNativeExecutor::from_native_module(module, OptLevel::None).unwrap();
executor.invoke_dynamic(entry_point_id, args, None).unwrap()
}
#[test]
fn invoke0() {
let (module_name, program, _) = load_cairo! {
fn main() {}
};
assert_eq!(
run_program(&program, &format!("{0}::{0}::main", module_name), &[]),
ExecutionResult {
remaining_gas: None,
return_value: Value::Struct {
fields: Vec::new(),
debug_name: None,
},
builtin_stats: BuiltinStats::default(),
},
);
}
#[test]
fn invoke1_felt252() {
let (module_name, program, _) = load_cairo! {
fn main(x: felt252) -> felt252 {
x
}
};
let r = |x: Felt| {
let x = Value::Felt252(x);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0.into());
r(1.into());
r(10.into());
r(Felt::MAX);
}
#[test]
fn invoke1_u8() {
let (module_name, program, _) = load_cairo! {
fn main(x: u8) -> u8 {
x
}
};
let r = |x: u8| {
let x = Value::Uint8(x);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0);
r(1);
r(10);
r(u8::MAX);
}
#[test]
fn invoke1_u16() {
let (module_name, program, _) = load_cairo! {
fn main(x: u16) -> u16 {
x
}
};
let r = |x: u16| {
let x = Value::Uint16(x);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0);
r(1);
r(10);
r(u16::MAX);
}
#[test]
fn invoke1_u32() {
let (module_name, program, _) = load_cairo! {
fn main(x: u32) -> u32 {
x
}
};
let r = |x: u32| {
let x = Value::Uint32(x);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0);
r(1);
r(10);
r(u32::MAX);
}
#[test]
fn invoke1_u64() {
let (module_name, program, _) = load_cairo! {
fn main(x: u64) -> u64 {
x
}
};
let r = |x: u64| {
let x = Value::Uint64(x);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0);
r(1);
r(10);
r(u64::MAX);
}
#[test]
fn invoke1_u128() {
let (module_name, program, _) = load_cairo! {
fn main(x: u128) -> u128 {
x
}
};
let r = |x: u128| {
let x = Value::Uint128(x);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0);
r(1);
r(10);
r(u128::MAX);
}
#[test]
fn invoke1_tuple1_felt252() {
let (module_name, program, _) = load_cairo! {
fn main(x: (felt252,)) -> (felt252,) {
x
}
};
let r = |x: (Felt,)| {
let x = Value::Struct {
fields: vec![Value::Felt252(x.0)],
debug_name: None,
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r((0.into(),));
r((1.into(),));
r((10.into(),));
r((Felt::MAX,));
}
#[test]
fn invoke1_tuple1_u64() {
let (module_name, program, _) = load_cairo! {
fn main(x: (u64,)) -> (u64,) {
x
}
};
let r = |x: (u64,)| {
let x = Value::Struct {
fields: vec![Value::Uint64(x.0)],
debug_name: None,
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r((0,));
r((1,));
r((10,));
r((u64::MAX,));
}
#[test]
fn invoke1_tuple5_u8_u16_u32_u64_u128() {
let (module_name, program, _) = load_cairo! {
fn main(x: (u8, u16, u32, u64, u128)) -> (u8, u16, u32, u64, u128) {
x
}
};
let r = |x: (u8, u16, u32, u64, u128)| {
let x = Value::Struct {
fields: vec![
Value::Uint8(x.0),
Value::Uint16(x.1),
Value::Uint32(x.2),
Value::Uint64(x.3),
Value::Uint128(x.4),
],
debug_name: None,
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r((0, 0, 0, 0, 0));
r((1, 1, 1, 1, 1));
r((10, 10, 10, 10, 10));
r((u8::MAX, u16::MAX, u32::MAX, u64::MAX, u128::MAX));
}
#[test]
fn invoke1_array_felt252() {
let (module_name, program, _) = load_cairo! {
fn main(x: Array<felt252>) -> Array<felt252> {
x
}
};
let r = |x: Vec<Felt>| {
let x = Value::Array(x.into_iter().map(Value::Felt252).collect());
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(vec![]);
r(vec![0.into()]);
r(vec![0.into(), 1.into()]);
r(vec![0.into(), 1.into(), 10.into()]);
r(vec![0.into(), 1.into(), 10.into(), Felt::MAX]);
}
#[test]
fn invoke1_enum1_unit() {
let (module_name, program, _) = load_cairo! {
enum MyEnum {
A: ()
}
fn main(x: MyEnum) -> MyEnum {
x
}
};
let x = Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: Vec::new(),
debug_name: None,
}),
debug_name: Some("MyEnum".into()),
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
}
#[test]
fn invoke1_enum1_u64() {
let (module_name, program, _) = load_cairo! {
enum MyEnum {
A: u64
}
fn main(x: MyEnum) -> MyEnum {
x
}
};
let r = |x: u64| {
let x = Value::Enum {
tag: 0,
value: Box::new(Value::Uint64(x)),
debug_name: Some("MyEnum".into()),
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0);
r(1);
r(10);
r(u64::MAX);
}
#[test]
fn invoke1_enum1_felt252() {
let (module_name, program, _) = load_cairo! {
enum MyEnum {
A: felt252
}
fn main(x: MyEnum) -> MyEnum {
x
}
};
let r = |x: Felt| {
let x = Value::Enum {
tag: 0,
value: Box::new(Value::Felt252(x)),
debug_name: Some("MyEnum".into()),
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(0.into());
r(1.into());
r(10.into());
r(Felt::MAX);
}
#[test]
fn invoke1_enum2_u8_u16() {
let (module_name, program, _) = load_cairo! {
enum MyEnum {
A: u8,
B: u16,
}
fn main(x: MyEnum) -> MyEnum {
x
}
};
enum MyEnum {
A(u8),
B(u16),
}
let r = |x: MyEnum| {
let x = match x {
MyEnum::A(x) => Value::Enum {
tag: 0,
value: Box::new(Value::Uint8(x)),
debug_name: Some("MyEnum".into()),
},
MyEnum::B(x) => Value::Enum {
tag: 1,
value: Box::new(Value::Uint16(x)),
debug_name: Some("MyEnum".into()),
},
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
std::slice::from_ref(&x)
),
ExecutionResult {
remaining_gas: None,
return_value: x,
builtin_stats: BuiltinStats::default(),
},
);
};
r(MyEnum::A(0));
r(MyEnum::A(1));
r(MyEnum::A(10));
r(MyEnum::A(u8::MAX));
r(MyEnum::B(0));
r(MyEnum::B(1));
r(MyEnum::B(10));
r(MyEnum::B(u16::MAX));
}
#[test]
fn invoke1_box_felt252() {
let (module_name, program, _) = load_cairo! {
fn main(x: Box<felt252>) -> felt252 {
x.unbox()
}
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
&[Value::Felt252(42.into())],
),
ExecutionResult {
remaining_gas: None,
return_value: Value::Felt252(42.into()),
builtin_stats: BuiltinStats::default(),
}
);
}
#[test]
fn invoke1_nullable_felt252() {
let (module_name, program, _) = load_cairo! {
use core::nullable::{match_nullable, FromNullableResult};
fn main(x: Nullable<felt252>) -> Option<felt252> {
match match_nullable(x) {
FromNullableResult::Null(()) => Option::None(()),
FromNullableResult::NotNull(x) => Option::Some(x.unbox()),
}
}
};
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
&[Value::Felt252(42.into())],
),
ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 0,
value: Box::new(Value::Felt252(42.into())),
debug_name: None
},
builtin_stats: BuiltinStats::default(),
}
);
assert_eq!(
run_program(
&program,
&format!("{0}::{0}::main", module_name),
&[Value::Null],
),
ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: Vec::new(),
debug_name: None
}),
debug_name: None
},
builtin_stats: BuiltinStats::default(),
}
);
}
#[test]
fn test_deserialize_param_bug() {
let (module_name, program, _) = load_cairo! {
fn main(
b0: u64, // Pedersen
b1: u64, // RangeCheck
b2: u64, // Bitwise
b3: u128, // GasBuiltin
b4: u64, // System
arg0: Span<felt252> // Arguments
) -> (u64, u64, u64, u128, u64, Span<felt252>) {
(b0, b1, b2, b3, b4, arg0)
}
};
let args = vec![
Value::Uint64(0),
Value::Uint64(0),
Value::Uint64(0),
Value::Uint128(0),
Value::Uint64(0),
Value::Struct {
fields: vec![Value::Array(vec![
Value::Felt252(1.into()),
Value::Felt252(2.into()),
])],
debug_name: None,
},
];
assert_eq!(
run_program(&program, &format!("{0}::{0}::main", module_name), &args),
ExecutionResult {
remaining_gas: None,
return_value: Value::Struct {
fields: args,
debug_name: None
},
builtin_stats: BuiltinStats::default(),
},
);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/arrays.rs | tests/tests/arrays.rs | use crate::common::{any_felt, load_cairo, run_native_program, run_vm_program};
use crate::common::{compare_outputs, DEFAULT_GAS};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::starknet::DummySyscallHandler;
use cairo_native::Value;
use lazy_static::lazy_static;
use proptest::prelude::*;
use starknet_types_core::felt::Felt;
lazy_static! {
static ref ARRAY_GET: (String, Program, SierraCasmRunner) = load_cairo! {
use array::ArrayTrait;
use traits::TryInto;
use core::option::OptionTrait;
fn run_test(value: felt252, idx: felt252) -> felt252 {
let mut numbers: Array<felt252> = ArrayTrait::new();
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
numbers.append(value);
*numbers.at(idx.try_into().unwrap())
}
};
}
#[test]
fn array_get_test() {
let program = &ARRAY_GET;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from(10)), Arg::Value(Felt::from(5))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(10.into()), Value::Felt252(5.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
proptest! {
#[test]
fn array_get_test_proptest(value in any_felt(), idx in 0u32..26) {
let program = &ARRAY_GET;
let result_vm = run_vm_program(program, "run_test", vec![
Arg::Value(Felt::from_bytes_be(&value.to_bytes_be())),
Arg::Value(Felt::from(idx))
], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(value), Value::Felt252(idx.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/alexandria.rs | tests/tests/alexandria.rs | use crate::common::{compare_outputs, run_native_program, run_vm_program, DEFAULT_GAS};
use cairo_lang_runner::SierraCasmRunner;
use cairo_lang_sierra::program::Program;
use cairo_native::starknet::DummySyscallHandler;
use std::{fs::File, io::BufReader};
use test_case::test_case;
#[track_caller]
fn compare_inputless_function(function_name: &str) {
// Load file compiled using `scarb build``
let file = File::open("tests/alexandria/target/dev/alexandria.sierra.json").unwrap();
let reader = BufReader::new(file);
let program: Program = serde_json::from_reader(reader).unwrap();
let module_name = "alexandria";
let runner = SierraCasmRunner::new(
program.clone(),
Some(Default::default()),
Default::default(),
None,
)
.unwrap();
let program: (String, Program, SierraCasmRunner) = (module_name.to_string(), program, runner);
let program = &program;
let result_vm =
run_vm_program(program, function_name, vec![], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
function_name,
&[],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function(function_name).unwrap().id,
&result_vm,
&result_native,
)
.expect("compare error");
}
// alexandria_math
#[test_case("fib")]
#[test_case("karatsuba")]
#[test_case("armstrong_number")]
#[test_case("collatz_sequence")]
#[test_case("aliquot_sum")]
#[test_case("extended_euclidean_algorithm")]
// alexandria_data_structures
#[test_case("vec")]
#[test_case("stack")]
#[test_case("queue")]
#[test_case("bit_array")]
// alexandria_encoding
#[test_case("base64_encode")]
#[test_case("reverse_bits")]
#[test_case("reverse_bytes")]
fn test_cases(function_name: &str) {
compare_inputless_function(function_name)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/uint.rs | tests/tests/uint.rs | use crate::common::{compare_outputs, load_cairo, run_native_program, run_vm_program, DEFAULT_GAS};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::{starknet::DummySyscallHandler, Value};
use lazy_static::lazy_static;
use proptest::prelude::*;
lazy_static! {
static ref U8_OVERFLOWING_ADD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u8, rhs: u8) -> u8 {
lhs + rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u8 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U8_OVERFLOWING_SUB: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u8, rhs: u8) -> u8 {
lhs - rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u8 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U8_SAFE_DIVMOD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u8, rhs: u8) -> (u8, u8) {
let q = lhs / rhs;
let r = lhs % rhs;
(q, r)
}
fn run_test(lhs: felt252, rhs: felt252) -> (u8, u8) {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U8_EQUAL: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u8, rhs: u8) -> bool {
lhs == rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> bool {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U8_IS_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
use zeroable::IsZeroResult;
extern fn u8_is_zero(a: u8) -> IsZeroResult<u8> implicits() nopanic;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u8) -> bool {
match u8_is_zero(value) {
IsZeroResult::Zero(_) => true,
IsZeroResult::NonZero(_) => false,
}
}
fn run_test(value: felt252) -> bool {
program(value.try_into().unwrap())
}
};
static ref U8_SQRT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::integer::u8_sqrt;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u8) -> u8 {
u8_sqrt(value)
}
fn run_test(value: felt252) -> u8 {
program(value.try_into().unwrap())
}
};
// U16
static ref U16_OVERFLOWING_ADD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u16, rhs: u16) -> u16 {
lhs + rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u16 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U16_OVERFLOWING_SUB: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u16, rhs: u16) -> u16 {
lhs - rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u16 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U16_SAFE_DIVMOD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u16, rhs: u16) -> (u16, u16) {
let q = lhs / rhs;
let r = lhs % rhs;
(q, r)
}
fn run_test(lhs: felt252, rhs: felt252) -> (u16, u16) {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U16_EQUAL: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u16, rhs: u16) -> bool {
lhs == rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> bool {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U16_IS_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
use zeroable::IsZeroResult;
extern fn u16_is_zero(a: u16) -> IsZeroResult<u16> implicits() nopanic;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u16) -> bool {
match u16_is_zero(value) {
IsZeroResult::Zero(_) => true,
IsZeroResult::NonZero(_) => false,
}
}
fn run_test(value: felt252) -> bool {
program(value.try_into().unwrap())
}
};
static ref U16_SQRT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::integer::u16_sqrt;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u16) -> u16 {
u16_sqrt(value)
}
fn run_test(value: felt252) -> u16 {
program(value.try_into().unwrap())
}
};
// U32
static ref U32_OVERFLOWING_ADD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u32, rhs: u32) -> u32 {
lhs + rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u32 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U32_OVERFLOWING_SUB: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u32, rhs: u32) -> u32 {
lhs - rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u32 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U32_SAFE_DIVMOD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u32, rhs: u32) -> (u32, u32) {
let q = lhs / rhs;
let r = lhs % rhs;
(q, r)
}
fn run_test(lhs: felt252, rhs: felt252) -> (u32, u32) {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U32_EQUAL: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u32, rhs: u32) -> bool {
lhs == rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> bool {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U32_IS_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
use zeroable::IsZeroResult;
extern fn u32_is_zero(a: u32) -> IsZeroResult<u32> implicits() nopanic;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u32) -> bool {
match u32_is_zero(value) {
IsZeroResult::Zero(_) => true,
IsZeroResult::NonZero(_) => false,
}
}
fn run_test(value: felt252) -> bool {
program(value.try_into().unwrap())
}
};
static ref U32_SQRT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::integer::u32_sqrt;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u32) -> u32 {
u32_sqrt(value)
}
fn run_test(value: felt252) -> u32 {
program(value.try_into().unwrap())
}
};
// U64
static ref U64_OVERFLOWING_ADD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u64, rhs: u64) -> u64 {
lhs + rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u64 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U64_OVERFLOWING_SUB: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u64, rhs: u64) -> u64 {
lhs - rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u64 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U64_SAFE_DIVMOD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u64, rhs: u64) -> (u64, u64) {
let q = lhs / rhs;
let r = lhs % rhs;
(q, r)
}
fn run_test(lhs: felt252, rhs: felt252) -> (u64, u64) {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U64_EQUAL: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u64, rhs: u64) -> bool {
lhs == rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> bool {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U64_IS_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
use zeroable::IsZeroResult;
extern fn u64_is_zero(a: u64) -> IsZeroResult<u64> implicits() nopanic;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u64) -> bool {
match u64_is_zero(value) {
IsZeroResult::Zero(_) => true,
IsZeroResult::NonZero(_) => false,
}
}
fn run_test(value: felt252) -> bool {
program(value.try_into().unwrap())
}
};
static ref U64_SQRT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::integer::u64_sqrt;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u64) -> u64 {
u64_sqrt(value)
}
fn run_test(value: felt252) -> u64 {
program(value.try_into().unwrap())
}
};
// U128
static ref U128_OVERFLOWING_ADD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u128, rhs: u128) -> u128 {
lhs + rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u128 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U128_OVERFLOWING_SUB: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u128, rhs: u128) -> u128 {
lhs - rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> u128 {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U128_SAFE_DIVMOD: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u128, rhs: u128) -> (u128, u128) {
let q = lhs / rhs;
let r = lhs % rhs;
(q, r)
}
fn run_test(lhs: felt252, rhs: felt252) -> (u128, u128) {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U128_EQUAL: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::TryInto;
use core::option::OptionTrait;
fn program(lhs: u128, rhs: u128) -> bool {
lhs == rhs
}
fn run_test(lhs: felt252, rhs: felt252) -> bool {
program(lhs.try_into().unwrap(), rhs.try_into().unwrap())
}
};
static ref U128_IS_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
use zeroable::IsZeroResult;
extern fn u128_is_zero(a: u128) -> IsZeroResult<u128> implicits() nopanic;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u128) -> bool {
match u128_is_zero(value) {
IsZeroResult::Zero(_) => true,
IsZeroResult::NonZero(_) => false,
}
}
fn run_test(value: felt252) -> bool {
program(value.try_into().unwrap())
}
};
static ref U128_SQRT: (String, Program, SierraCasmRunner) = load_cairo! {
use core::integer::u128_sqrt;
use traits::TryInto;
use core::option::OptionTrait;
fn program(value: u128) -> u128 {
u128_sqrt(value)
}
fn run_test(value: felt252) -> u128 {
program(value.try_into().unwrap())
}
};
}
proptest! {
#[test]
fn u8_overflowing_add_proptest(a in 0..u8::MAX, b in 0..u8::MAX) {
let program = &U8_OVERFLOWING_ADD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u8_overflowing_sub_proptest(a in 0..u8::MAX, b in 0..u8::MAX) {
let program = &U8_OVERFLOWING_SUB;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u8_safe_divmod_proptest(a in 0..u8::MAX, b in 0..u8::MAX) {
let program = &U8_SAFE_DIVMOD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u8_equal_proptest(a in 0..u8::MAX, b in 0..u8::MAX) {
let program = &U8_EQUAL;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u8_is_zero_proptest(a in 0..u8::MAX) {
let program = &U8_IS_ZERO;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
// u16
#[test]
fn u16_overflowing_add_proptest(a in 0..u16::MAX, b in 0..u16::MAX) {
let program = &U16_OVERFLOWING_ADD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u16_overflowing_sub_proptest(a in 0..u16::MAX, b in 0..u16::MAX) {
let program = &U16_OVERFLOWING_SUB;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u16_safe_divmod_proptest(a in 0..u16::MAX, b in 0..u16::MAX) {
let program = &U16_SAFE_DIVMOD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u16_equal_proptest(a in 0..u16::MAX, b in 0..u16::MAX) {
let program = &U16_EQUAL;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u16_is_zero_proptest(a in 0..u16::MAX) {
let program = &U16_IS_ZERO;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
// u32
#[test]
fn u32_overflowing_add_proptest(a in 0..u32::MAX, b in 0..u32::MAX) {
let program = &U32_OVERFLOWING_ADD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u32_overflowing_sub_proptest(a in 0..u32::MAX, b in 0..u32::MAX) {
let program = &U32_OVERFLOWING_SUB;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u32_safe_divmod_proptest(a in 0..u32::MAX, b in 0..u32::MAX) {
let program = &U32_SAFE_DIVMOD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u32_equal_proptest(a in 0..u32::MAX, b in 0..u32::MAX) {
let program = &U32_EQUAL;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u32_is_zero_proptest(a in 0..u32::MAX) {
let program = &U32_IS_ZERO;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
// u64
#[test]
fn u64_overflowing_add_proptest(a in 0..u64::MAX, b in 0..u64::MAX) {
let program = &U64_OVERFLOWING_ADD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u64_overflowing_sub_proptest(a in 0..u64::MAX, b in 0..u64::MAX) {
let program = &U64_OVERFLOWING_SUB;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u64_safe_divmod_proptest(a in 0..u64::MAX, b in 0..u64::MAX) {
let program = &U64_SAFE_DIVMOD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u64_equal_proptest(a in 0..u64::MAX, b in 0..u64::MAX) {
let program = &U64_EQUAL;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u64_is_zero_proptest(a in 0..u64::MAX) {
let program = &U64_IS_ZERO;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
// u128
#[test]
fn u128_overflowing_add_proptest(a in 0..u128::MAX, b in 0..u128::MAX) {
let program = &U128_OVERFLOWING_ADD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u128_overflowing_sub_proptest(a in 0..u128::MAX, b in 0..u128::MAX) {
let program = &U128_OVERFLOWING_SUB;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u128_safe_divmod_proptest(a in 0..u128::MAX, b in 0..u128::MAX) {
let program = &U128_SAFE_DIVMOD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u128_equal_proptest(a in 0..u128::MAX, b in 0..u128::MAX) {
let program = &U128_EQUAL;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into()), Arg::Value(b.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into()), Value::Felt252(b.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn u128_is_zero_proptest(a in 0..u128::MAX) {
let program = &U128_IS_ZERO;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(a.into())],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/result.rs | tests/tests/result.rs | use cairo_native::{
execution_result::{BuiltinStats, ContractExecutionResult, ExecutionResult},
Value,
};
use test_case::test_case;
fn from_execution_result(
res: ExecutionResult,
) -> Result<ContractExecutionResult, cairo_native::error::Error> {
ContractExecutionResult::from_execution_result(res)
}
#[test_case(
Value::Enum {
tag: 0,
value: Box::new(Value::Uint8(0)),
debug_name: None,
} => panics "wrong type, expected: Struct { Struct { Array<felt252> } }, value: Uint8(0)")]
#[test_case(
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
debug_name: None,
fields: vec![Value::Uint8(0)]
}),
debug_name: None,
} => panics "wrong type, expected: Struct { Struct { Array<felt252> } }, value: Struct { fields: [Uint8(0)], debug_name: None }")]
#[test_case(
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
debug_name: None,
fields: vec![Value::Struct {
debug_name: None,
fields: vec![Value::Uint8(0)]
}]
}),
debug_name: None,
} => panics "wrong type, expected: Struct { Struct { Array<felt252> } }, value: Struct { fields: [Struct { fields: [Uint8(0)], debug_name: None }], debug_name: None }")]
#[test_case(
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
debug_name: None,
fields: vec![Value::Struct {
debug_name: None,
fields: vec![Value::Array(vec![Value::Uint8(0)])]
}]
}),
debug_name: None,
} => panics "should always be a felt")]
#[test_case(
Value::Enum {
tag: 1,
value: Box::new(Value::Uint8(0)),
debug_name: None,
} => panics "wrong type, expected: Struct { [X, Array<felt252>] }, value: Uint8(0)")]
#[test_case(
Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
debug_name: None,
fields: vec![Value::Uint8(0)]
}),
debug_name: None,
} => panics "wrong type, expect: struct.fields.len() >= 2, value: [Uint8(0)]")]
#[test_case(
Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
debug_name: None,
fields: vec![Value::Uint8(0), Value::Uint8(0)]
}),
debug_name: None,
} => panics "wrong type, expected: Struct { [X, Array<felt252>] }, value: Struct { fields: [Uint8(0), Uint8(0)], debug_name: None }")]
#[test_case(
Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
debug_name: None,
fields: vec![
Value::Uint8(0),
Value::Array(vec![Value::Uint8(0)])
]
}),
debug_name: None,
} => panics "should always be a felt")]
fn test_cases(return_value: Value) {
let _ = from_execution_result(ExecutionResult {
return_value,
remaining_gas: None,
builtin_stats: BuiltinStats::default(),
})
.unwrap();
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/libfuncs.rs | tests/tests/libfuncs.rs | use crate::common::{compare_outputs, load_cairo, run_native_program, run_vm_program};
use cairo_native::starknet::DummySyscallHandler;
#[test]
fn enum_init() {
let program = load_cairo! {
enum MySmallEnum {
A: felt252,
}
enum MyEnum {
A: felt252,
B: u8,
C: u16,
D: u32,
E: u64,
}
fn run_test() -> (MySmallEnum, MyEnum, MyEnum, MyEnum, MyEnum, MyEnum) {
(
MySmallEnum::A(-1),
MyEnum::A(5678),
MyEnum::B(90),
MyEnum::C(9012),
MyEnum::D(34567890),
MyEnum::E(1234567890123456),
)
}
};
let result_vm = run_vm_program(&program, "run_test", vec![], None).unwrap();
let result_native = run_native_program(
&program,
"run_test",
&[],
None,
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn enum_match() {
let program = load_cairo! {
enum MyEnum {
A: felt252,
B: u8,
C: u16,
D: u32,
E: u64,
}
fn match_a() -> felt252 {
let x = MyEnum::A(5);
match x {
MyEnum::A(x) => x,
MyEnum::B(_) => 0,
MyEnum::C(_) => 1,
MyEnum::D(_) => 2,
MyEnum::E(_) => 3,
}
}
fn match_b() -> u8 {
let x = MyEnum::B(5_u8);
match x {
MyEnum::A(_) => 0_u8,
MyEnum::B(x) => x,
MyEnum::C(_) => 1_u8,
MyEnum::D(_) => 2_u8,
MyEnum::E(_) => 3_u8,
}
}
};
let result_vm = run_vm_program(&program, "match_a", vec![], None).unwrap();
let result_native = run_native_program(
&program,
"match_a",
&[],
None,
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("match_a").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
let result_vm = run_vm_program(&program, "match_b", vec![], None).unwrap();
let result_native = run_native_program(
&program,
"match_b",
&[],
None,
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("match_b").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/compile_library.rs | tests/tests/compile_library.rs | use crate::common::load_cairo;
use cairo_native::context::NativeContext;
use std::error::Error;
use tempfile::NamedTempFile;
#[test]
pub fn compile_library() -> Result<(), Box<dyn Error>> {
// Load the program.
let context = NativeContext::new();
let program = load_cairo! {
fn run_test(lhs: felt252, rhs: felt252) -> felt252 {
lhs + rhs
}
};
let module = context.compile(&program.1, false, Some(Default::default()), None)?;
let object = cairo_native::module_to_object(module.module(), Default::default(), None)?;
let file = NamedTempFile::new()?.into_temp_path();
cairo_native::object_to_shared_lib(&object, &file, None)?;
Ok(())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/mod.rs | tests/tests/mod.rs | pub mod alexandria;
pub mod arrays;
pub mod boolean;
pub mod cases;
pub mod circuit;
pub mod compile_library;
pub mod dict;
pub mod ec;
pub mod felt252;
pub mod libfuncs;
pub mod programs;
pub mod result;
pub mod starknet;
pub mod trampoline;
pub mod uint;
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/felt252.rs | tests/tests/felt252.rs | use crate::common::{
any_felt, compare_outputs, load_cairo, nonzero_felt, run_native_program, run_vm_program,
DEFAULT_GAS,
};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::{starknet::DummySyscallHandler, Value};
use lazy_static::lazy_static;
use proptest::prelude::*;
use starknet_types_core::felt::Felt;
lazy_static! {
static ref FELT252_ADD: (String, Program, SierraCasmRunner) = load_cairo! {
fn run_test(lhs: felt252, rhs: felt252) -> felt252 {
lhs + rhs
}
};
static ref FELT252_SUB: (String, Program, SierraCasmRunner) = load_cairo! {
fn run_test(lhs: felt252, rhs: felt252) -> felt252 {
lhs - rhs
}
};
static ref FELT252_MUL: (String, Program, SierraCasmRunner) = load_cairo! {
fn run_test(lhs: felt252, rhs: felt252) -> felt252 {
lhs * rhs
}
};
static ref FELT252_DIV: (String, Program, SierraCasmRunner) = load_cairo! {
fn run_test(lhs: felt252, rhs: felt252) -> felt252 {
felt252_div(lhs, rhs.try_into().unwrap())
}
};
// TODO: Add test program for `felt252_add_const`.
// TODO: Add test program for `felt252_sub_const`.
// TODO: Add test program for `felt252_mul_const`.
// TODO: Add test program for `felt252_div_const`.
static ref FELT252_CONST: (String, Program, SierraCasmRunner) = load_cairo! {
fn run_test() -> (felt252, felt252, felt252, felt252) {
(0, 1, -2, -1)
}
};
static ref FELT252_IS_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
fn run_test(x: felt252) -> felt252 {
match x {
0 => 1,
_ => 0,
}
}
};
}
proptest! {
#[test]
fn felt_add_proptest(a in any_felt(), b in any_felt()) {
let program = &FELT252_ADD;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn felt_sub_proptest(a in any_felt(), b in any_felt()) {
let program = &FELT252_SUB;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn felt_mul_proptest(a in any_felt(), b in any_felt()) {
let program = &FELT252_MUL;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn felt_div_proptest(a in any_felt(), b in nonzero_felt()) {
let program = &FELT252_DIV;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/ec.rs | tests/tests/ec.rs | use crate::common::{
any_felt, compare_outputs, load_cairo, run_native_program, run_vm_program, DEFAULT_GAS,
};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::{starknet::DummySyscallHandler, Value};
use lazy_static::lazy_static;
use num_bigint::BigUint;
use proptest::prelude::*;
use starknet_types_core::felt::Felt;
use std::str::FromStr;
lazy_static! {
static ref EC_POINT_TRY_NEW: (String, Program, SierraCasmRunner) = load_cairo! {
use core::{ec::{ec_point_try_new_nz, EcPoint}};
use core::zeroable::NonZero;
fn run_test(x: felt252, y: felt252) -> Option<NonZero<EcPoint>> {
ec_point_try_new_nz(x, y)
}
};
static ref EC_POINT_FROM_X: (String, Program, SierraCasmRunner) = load_cairo! {
use core::{ec::{ec_point_from_x_nz, EcPoint}};
use core::zeroable::NonZero;
fn run_test(x: felt252) -> Option<NonZero<EcPoint>> {
ec_point_from_x_nz(x)
}
};
static ref EC_POINT_ZERO: (String, Program, SierraCasmRunner) = load_cairo! {
use core::ec::{ec_point_zero, EcPoint};
fn run_test() -> EcPoint {
ec_point_zero()
}
};
}
#[test]
fn ec_point_zero() {
let program = &EC_POINT_ZERO;
let result_vm =
run_vm_program(program, "run_test", vec![], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
program,
"run_test",
&[],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn ec_point_from_x_big() {
let x = Felt::from(
BigUint::from_str(
"10503791839462130483045092717244804953879649418761481950933471772092536173",
)
.unwrap(),
);
let program = &EC_POINT_FROM_X;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(x)],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(Felt::from_bytes_be(&x.to_bytes_be()))],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn ec_point_from_x_small() {
let x = Felt::from(BigUint::from_str("1234").unwrap());
let program = &EC_POINT_FROM_X;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(x)],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(Felt::from_bytes_be(&x.to_bytes_be()))],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
proptest! {
#[test]
fn ec_point_try_new_proptest(a in any_felt(), b in any_felt()) {
let program = &EC_POINT_TRY_NEW;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn ec_point_from_x_proptest(a in any_felt()) {
let program = &EC_POINT_FROM_X;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/programs.rs | tests/tests/programs.rs | use crate::common::{any_felt, load_cairo, run_native_program, run_vm_program};
use crate::common::{compare_outputs, DEFAULT_GAS};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::starknet::DummySyscallHandler;
use cairo_native::utils::felt252_str;
use cairo_native::Value;
use lazy_static::lazy_static;
use proptest::prelude::*;
use starknet_types_core::felt::Felt;
lazy_static! {
pub static ref FACTORIAL: (String, Program, SierraCasmRunner) = load_cairo! {
fn factorial(value: felt252, n: felt252) -> felt252 {
if (n == 1) {
value
} else {
factorial(value * n, n - 1)
}
}
fn run_test(n: felt252) -> felt252 {
factorial(1, n)
}
};
pub static ref FIB: (String, Program, SierraCasmRunner) = load_cairo! {
fn fib(a: felt252, b: felt252, n: felt252) -> felt252 {
match n {
0 => a,
_ => fib(b, a + b, n - 1),
}
}
fn run_test(n: felt252) -> felt252 {
fib(0, 1, n)
}
};
pub static ref LOGISTIC_MAP: (String, Program, SierraCasmRunner) = load_cairo! {
fn iterate_map(r: felt252, x: felt252) -> felt252 {
r * x * -x
}
// good default: 1000
fn run_test(mut i: felt252) -> felt252 {
// Initial value.
let mut x = 1234567890123456789012345678901234567890;
// Iterate the map.
loop {
x = iterate_map(4, x);
if i == 0 {
break x;
}
i = i - 1;
}
}
};
pub static ref PEDERSEN: (String, Program, SierraCasmRunner) = load_cairo! {
use core::pedersen::pedersen;
fn run_test(a: felt252, b: felt252) -> felt252 {
pedersen(a, b)
}
};
pub static ref POSEIDON: (String, Program, SierraCasmRunner) = load_cairo! {
use core::poseidon::hades_permutation;
fn run_test(a: felt252, b: felt252, c: felt252) -> (felt252, felt252, felt252) {
hades_permutation(a, b, c)
}
};
pub static ref SELF_REFERENCING: (String, Program, SierraCasmRunner) = load_cairo! {
#[derive(Drop, Copy, PartialEq)]
enum ArrayItem {
Span: Span<u8>,
Recursive: Span<ArrayItem>
}
fn recursion(input: Span<u8>) -> Span<ArrayItem> {
let mut output: Array<ArrayItem> = Default::default();
let index = (*input.at(0));
if index < 5 {
output.append(ArrayItem::Span(input));
} else {
let res = recursion(input.slice(1, input.len() - 1));
output.append(ArrayItem::Recursive(res));
}
return output.span();
}
fn run_test() -> Span<ArrayItem> {
let arr = array![10, 9, 8, 7, 6, 4];
recursion(arr.span())
}
};
pub static ref NO_OP: (String, Program, SierraCasmRunner) = load_cairo! {
#[inline(never)]
fn no_op() {}
fn run_test() {
no_op();
}
};
}
#[test]
fn fib() {
let result_vm = run_vm_program(
&FIB,
"run_test",
vec![Arg::Value(Felt::from(10))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&FIB,
"run_test",
&[Value::Felt252(10.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&FIB.1,
&FIB.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn logistic_map() {
let result_vm = run_vm_program(
&LOGISTIC_MAP,
"run_test",
vec![Arg::Value(Felt::from(1000))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&LOGISTIC_MAP,
"run_test",
&[Value::Felt252(1000.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&LOGISTIC_MAP.1,
&LOGISTIC_MAP.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn pedersen() {
let result_vm = run_vm_program(
&PEDERSEN,
"run_test",
vec![
Arg::Value(
Felt::from_dec_str(
"2163739901324492107409690946633517860331020929182861814098856895601180685",
)
.unwrap(),
),
Arg::Value(
Felt::from_dec_str(
"2392090257937917229310563411601744459500735555884672871108624696010915493156",
)
.unwrap(),
),
],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&PEDERSEN,
"run_test",
&[
Value::Felt252(felt252_str(
"2163739901324492107409690946633517860331020929182861814098856895601180685",
)),
Value::Felt252(felt252_str(
"2392090257937917229310563411601744459500735555884672871108624696010915493156",
)),
],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&PEDERSEN.1,
&PEDERSEN.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn factorial() {
let result_vm = run_vm_program(
&FACTORIAL,
"run_test",
vec![Arg::Value(Felt::from(13))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&FACTORIAL,
"run_test",
&[Value::Felt252(13.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&FACTORIAL.1,
&FACTORIAL.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
proptest! {
#[test]
fn fib_proptest(n in 0..100i32) {
let result_vm = run_vm_program(
&FIB,
"run_test",
vec![Arg::Value(Felt::from(n))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&FIB,
"run_test",
&[Value::Felt252(n.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&FIB.1,
&FIB.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn logistic_map_proptest(n in 100..110i32) {
let result_vm = run_vm_program(
&LOGISTIC_MAP,
"run_test",
vec![Arg::Value(Felt::from(n))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&LOGISTIC_MAP,
"run_test",
&[Value::Felt252(n.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&LOGISTIC_MAP.1,
&LOGISTIC_MAP.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn factorial_proptest(n in 1..100i32) {
let result_vm = run_vm_program(
&FACTORIAL,
"run_test",
vec![Arg::Value(Felt::from(n))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&FACTORIAL,
"run_test",
&[Value::Felt252(n.into())],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&FACTORIAL.1,
&FACTORIAL.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn pedersen_proptest(a in any_felt(), b in any_felt()) {
let result_vm = run_vm_program(
&PEDERSEN,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&PEDERSEN,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&PEDERSEN.1,
&PEDERSEN.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
#[test]
fn poseidon_proptest(a in any_felt(), b in any_felt(), c in any_felt()) {
let result_vm = run_vm_program(
&POSEIDON,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())),
Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be())),
Arg::Value(Felt::from_bytes_be(&c.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&POSEIDON,
"run_test",
&[Value::Felt252(a), Value::Felt252(b), Value::Felt252(c)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&POSEIDON.1,
&POSEIDON.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
}
#[test]
fn self_referencing_struct() {
let result_vm = run_vm_program(
&SELF_REFERENCING,
"run_test",
vec![],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
&SELF_REFERENCING,
"run_test",
&[],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&SELF_REFERENCING.1,
&SELF_REFERENCING.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
#[test]
fn no_op() {
let result_vm = run_vm_program(&NO_OP, "run_test", vec![], Some(DEFAULT_GAS as usize)).unwrap();
let result_native = run_native_program(
&NO_OP,
"run_test",
&[],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&NO_OP.1,
&NO_OP.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)
.unwrap();
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/cases.rs | tests/tests/cases.rs | use crate::common::{
compare_inputless_program, load_cairo_contract_path, run_native_starknet_contract,
run_vm_contract,
};
use cairo_native::starknet::DummySyscallHandler;
use itertools::Itertools;
use pretty_assertions_sorted::assert_eq_sorted;
use test_case::test_case;
// Test cases for programs without input, it checks the outputs are correct automatically.
// felt tests
#[test_case("tests/cases/felt_ops/add.cairo")]
#[test_case("tests/cases/felt_ops/sub.cairo")]
#[test_case("tests/cases/felt_ops/felt_is_zero.cairo")]
#[test_case("tests/cases/felt_ops/mul.cairo")]
#[test_case("tests/cases/felt_ops/negation.cairo")]
#[test_case("tests/cases/felt_ops/div.cairo")]
// generic tests
#[test_case("tests/cases/fib_counter.cairo")]
#[test_case("tests/cases/fib_local.cairo")]
#[test_case("tests/cases/pedersen_hash.cairo")]
#[test_case("tests/cases/unwrap_non_zero.cairo")]
#[test_case("tests/cases/poseidon.cairo")]
#[test_case("tests/cases/panic_array.cairo")]
#[test_case("tests/cases/generic_fn_loop.cairo")]
// enums
#[test_case("tests/cases/enums/enum_init_c_style.cairo")]
#[test_case("tests/cases/enums/enum_init_empty.cairo")]
#[test_case("tests/cases/enums/enum_init_multiple.cairo")]
#[test_case("tests/cases/enums/enum_init_nested_c_style.cairo")]
#[test_case("tests/cases/enums/enum_init_nested_empty.cairo")]
#[test_case("tests/cases/enums/enum_init_nested_multiple.cairo")]
#[test_case("tests/cases/enums/enum_init_nested_single_scalar.cairo")]
#[test_case("tests/cases/enums/enum_init_nested_single_struct.cairo")]
#[test_case("tests/cases/enums/enum_init_nested_single_tuple.cairo")]
#[test_case("tests/cases/enums/enum_init_single_scalar.cairo")]
#[test_case("tests/cases/enums/enum_init_single_struct.cairo")]
#[test_case("tests/cases/enums/enum_init_single_tuple.cairo")]
#[test_case("tests/cases/enums/enum_init.cairo")]
#[test_case("tests/cases/enums/single_value.cairo")]
#[test_case("tests/cases/enums/enum_match.cairo")]
#[test_case("tests/cases/enums/enum_snapshot_match_a.cairo")]
#[test_case("tests/cases/enums/enum_snapshot_match_b.cairo")]
// returns
#[test_case("tests/cases/returns/enums.cairo")]
#[test_case("tests/cases/returns/simple.cairo")]
#[test_case("tests/cases/returns/tuple.cairo")]
// dict
#[test_case("tests/cases/dict/insert_get.cairo")]
// uint
#[test_case("tests/cases/uint/compare.cairo")]
#[test_case("tests/cases/uint/consts.cairo")]
#[test_case("tests/cases/uint/downcasts.cairo")]
#[test_case("tests/cases/uint/safe_divmod.cairo")]
#[test_case("tests/cases/uint/uint_addition.cairo")]
#[test_case("tests/cases/uint/uint_subtraction.cairo")]
#[test_case("tests/cases/uint/uint_try_from_felt.cairo")]
#[test_case("tests/cases/uint/upcasts.cairo")]
#[test_case("tests/cases/uint/wide_mul.cairo")]
#[test_case("tests/cases/uint/u512_safe_divmod_by_u256.cairo")]
// sint
#[test_case("tests/cases/sint/eq.cairo")]
#[test_case("tests/cases/sint/to_from_felt252.cairo")]
// sint8
#[test_case("tests/cases/sint/i8_diff.cairo")]
#[test_case("tests/cases/sint/i8_add_sub.cairo")]
#[test_case("tests/cases/sint/i8_wide_mul.cairo")]
// sint16
#[test_case("tests/cases/sint/i16_diff.cairo")]
#[test_case("tests/cases/sint/i16_add_sub.cairo")]
#[test_case("tests/cases/sint/i16_wide_mul.cairo")]
// sint32
#[test_case("tests/cases/sint/i32_diff.cairo")]
#[test_case("tests/cases/sint/i32_add_sub.cairo")]
#[test_case("tests/cases/sint/i32_wide_mul.cairo")]
// sint64
#[test_case("tests/cases/sint/i64_diff.cairo")]
#[test_case("tests/cases/sint/i64_add_sub.cairo")]
#[test_case("tests/cases/sint/i64_wide_mul.cairo")]
// sint128
#[test_case("tests/cases/sint/i128_diff.cairo")]
#[test_case("tests/cases/sint/i128_add_sub.cairo")]
// structs
#[test_case("tests/cases/structs/basic.cairo")]
#[test_case("tests/cases/structs/bigger.cairo")]
#[test_case("tests/cases/structs/enum_member.cairo")]
#[test_case("tests/cases/structs/nested.cairo")]
#[test_case("tests/cases/structs/struct_snapshot_deconstruct.cairo")]
// gas
#[test_case("tests/cases/gas/available_gas.cairo")]
// bool
#[test_case("tests/cases/bool/and.cairo")]
#[test_case("tests/cases/bool/eq.cairo")]
#[test_case("tests/cases/bool/not.cairo")]
#[test_case("tests/cases/bool/or.cairo")]
#[test_case("tests/cases/bool/to_felt252.cairo")]
#[test_case("tests/cases/bool/xor.cairo")]
// bitwise
#[test_case("tests/cases/bitwise/and.cairo")]
#[test_case("tests/cases/bitwise/or.cairo")]
#[test_case("tests/cases/bitwise/xor.cairo")]
// array
#[test_case("tests/cases/array/append.cairo")]
#[test_case("tests/cases/array/index_invalid.cairo")]
#[test_case("tests/cases/array/pop_front_invalid.cairo")]
#[test_case("tests/cases/array/pop_front_valid.cairo")]
#[test_case("tests/cases/array/slice.cairo")]
// nullable
#[test_case("tests/cases/nullable/test_nullable.cairo")]
// Programs copied from the cairo-vm
// https://github.com/lambdaclass/cairo-vm/tree/main/cairo_programs/cairo-1-programs
#[test_case("tests/cases/cairo_vm/programs/array_append.cairo")]
#[test_case("tests/cases/cairo_vm/programs/array_get.cairo")]
#[test_case("tests/cases/cairo_vm/programs/array_integer_tuple.cairo")]
#[test_case("tests/cases/cairo_vm/programs/bitwise.cairo")]
#[test_case("tests/cases/cairo_vm/programs/bytes31_ret.cairo")]
#[test_case("tests/cases/cairo_vm/programs/dict_with_struct.cairo")]
#[test_case("tests/cases/cairo_vm/programs/dictionaries.cairo")]
#[test_case("tests/cases/cairo_vm/programs/ecdsa_recover.cairo")]
#[test_case("tests/cases/cairo_vm/programs/enum_flow.cairo")]
#[test_case("tests/cases/cairo_vm/programs/enum_match.cairo")]
#[test_case("tests/cases/cairo_vm/programs/factorial.cairo")]
#[test_case("tests/cases/cairo_vm/programs/felt_dict.cairo")]
#[test_case("tests/cases/cairo_vm/programs/felt_dict_squash.cairo")]
#[test_case("tests/cases/cairo_vm/programs/felt_span.cairo")]
#[test_case("tests/cases/cairo_vm/programs/fibonacci.cairo")]
#[test_case("tests/cases/cairo_vm/programs/hello.cairo")]
#[test_case("tests/cases/cairo_vm/programs/my_rectangle.cairo")]
#[test_case("tests/cases/cairo_vm/programs/null_ret.cairo")]
#[test_case("tests/cases/cairo_vm/programs/nullable_box_vec.cairo")]
#[test_case("tests/cases/cairo_vm/programs/nullable_dict.cairo")]
#[test_case("tests/cases/cairo_vm/programs/ops.cairo")]
#[test_case("tests/cases/cairo_vm/programs/pedersen_example.cairo")]
#[test_case("tests/cases/cairo_vm/programs/poseidon.cairo")]
#[test_case("tests/cases/cairo_vm/programs/poseidon_pedersen.cairo")]
#[test_case("tests/cases/cairo_vm/programs/primitive_types2.cairo")]
#[test_case("tests/cases/cairo_vm/programs/print.cairo")]
#[test_case("tests/cases/cairo_vm/programs/recursion.cairo")]
#[test_case("tests/cases/cairo_vm/programs/sample.cairo")]
#[test_case("tests/cases/cairo_vm/programs/short_string.cairo")]
#[test_case("tests/cases/cairo_vm/programs/simple.cairo")]
#[test_case("tests/cases/cairo_vm/programs/simple_struct.cairo")]
#[test_case("tests/cases/cairo_vm/programs/struct_span_return.cairo")]
#[test_case("tests/cases/cairo_vm/programs/tensor_new.cairo")]
#[test_case("tests/cases/brainfuck.cairo")]
// EVM related
#[test_case("tests/cases/stack.cairo")]
fn test_program_cases(program_path: &str) {
compare_inputless_program(program_path)
}
// Contracts copied from the cairo-vm
// https://github.com/lambdaclass/cairo-vm/tree/main/cairo_programs/cairo-1-contracts
#[test_case("tests/cases/cairo_vm/contracts/alloc_segment.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/assert_le_find_small_arcs.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/dict_test.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/divmod.cairo", &[100, 10])]
#[test_case("tests/cases/cairo_vm/contracts/factorial.cairo", &[10])]
#[test_case("tests/cases/cairo_vm/contracts/felt252_dict_entry_init.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/felt252_dict_entry_update.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/felt_252_dict.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/fib.cairo", &[10, 10, 10])]
#[test_case("tests/cases/cairo_vm/contracts/get_segment_arena_index.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/init_squash_data.cairo", &[10])]
#[test_case("tests/cases/cairo_vm/contracts/linear_split.cairo", &[10])]
#[test_case("tests/cases/cairo_vm/contracts/should_skip_squash_loop.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/test_less_than.cairo", &[10])]
#[test_case("tests/cases/cairo_vm/contracts/u128_sqrt.cairo", &[100])]
#[test_case("tests/cases/cairo_vm/contracts/u16_sqrt.cairo", &[100])]
#[test_case("tests/cases/cairo_vm/contracts/u256_sqrt.cairo", &[100])]
#[test_case("tests/cases/cairo_vm/contracts/u32_sqrt.cairo", &[100])]
#[test_case("tests/cases/cairo_vm/contracts/u64_sqrt.cairo", &[100])]
#[test_case("tests/cases/cairo_vm/contracts/u8_sqrt.cairo", &[100])]
#[test_case("tests/cases/cairo_vm/contracts/uint512_div_mod.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/widemul128.cairo", &[100, 100])]
#[test_case("tests/cases/cairo_vm/contracts/field_sqrt.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/random_ec_point.cairo", &[])]
#[test_case("tests/cases/cairo_vm/contracts/alloc_constant_size.cairo", &[10, 10, 10])]
fn test_contract_cases(program_path: &str, args: &[u128]) {
let args = args.iter().map(|&arg| arg.into()).collect_vec();
let contract = load_cairo_contract_path(program_path);
let entrypoint = contract
.entry_points_by_type
.external
.first()
.expect("contract should have at least one external entrypoint");
let program = contract
.extract_sierra_program()
.expect("contract bytes should be a valid sierra program");
let native_result = run_native_starknet_contract(
&program,
entrypoint.function_idx,
&args,
DummySyscallHandler,
);
assert!(
!native_result.failure_flag,
"native contract execution failed"
);
let native_output = native_result.return_values;
let vm_output = run_vm_contract(&contract, &entrypoint.selector, &args);
assert_eq_sorted!(vm_output, native_output);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/dict.rs | tests/tests/dict.rs | use crate::common::{
any_felt, compare_outputs, load_cairo, run_native_program, run_vm_program, DEFAULT_GAS,
};
use cairo_lang_runner::{Arg, SierraCasmRunner};
use cairo_lang_sierra::program::Program;
use cairo_native::{starknet::DummySyscallHandler, Value};
use lazy_static::lazy_static;
use proptest::prelude::*;
use starknet_types_core::felt::Felt;
lazy_static! {
static ref DICT_GET_INSERT: (String, Program, SierraCasmRunner) = load_cairo! {
use traits::Default;
use dict::Felt252DictTrait;
fn run_test(key: felt252, val: felt252) -> felt252 {
let mut dict: Felt252Dict<felt252> = Default::default();
dict.insert(key, val);
dict.get(key)
}
};
static ref SNAPSHOT_LOOP: (String, Program, SierraCasmRunner) = load_cairo! {
use core::dict::Felt252Dict;
fn run_test() {
let mut dict: Felt252Dict<u64> = Default::default();
for number in 0..50_u64 {
let snapshot = @dict;
let key = number.try_into().unwrap();
dict.insert(key, number);
drop(snapshot)
}
}
};
}
proptest! {
#[test]
fn dict_get_insert_proptest(a in any_felt(), b in any_felt()) {
let program = &DICT_GET_INSERT;
let result_vm = run_vm_program(
program,
"run_test",
vec![Arg::Value(Felt::from_bytes_be(&a.clone().to_bytes_be())), Arg::Value(Felt::from_bytes_be(&b.clone().to_bytes_be()))],
Some(DEFAULT_GAS as usize),
)
.unwrap();
let result_native = run_native_program(
program,
"run_test",
&[Value::Felt252(a), Value::Felt252(b)],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
compare_outputs(
&program.1,
&program.2.find_function("run_test").unwrap().id,
&result_vm,
&result_native,
)?;
}
}
#[test]
fn dict_snapshot_loop() {
let program = &SNAPSHOT_LOOP;
run_native_program(
program,
"run_test",
&[],
Some(DEFAULT_GAS),
Option::<DummySyscallHandler>::None,
);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/starknet/secp256.rs | tests/tests/starknet/secp256.rs | use crate::common::{load_cairo_path, run_native_program};
use cairo_lang_runner::SierraCasmRunner;
use cairo_lang_sierra::program::Program;
use cairo_native::{
starknet::{Secp256k1Point, Secp256r1Point, StarknetSyscallHandler, SyscallResult, U256},
Value,
};
use lazy_static::lazy_static;
use pretty_assertions_sorted::assert_eq;
use starknet_types_core::felt::Felt;
use std::collections::VecDeque;
#[derive(Debug, Default)]
struct SyscallHandler {
secp256k1_new: (VecDeque<(U256, U256)>, VecDeque<Option<Secp256k1Point>>),
secp256k1_add: (
VecDeque<(Secp256k1Point, Secp256k1Point)>,
VecDeque<Secp256k1Point>,
),
secp256k1_mul: (VecDeque<(Secp256k1Point, U256)>, VecDeque<Secp256k1Point>),
secp256k1_get_point_from_x: (VecDeque<(U256, bool)>, VecDeque<Option<Secp256k1Point>>),
secp256k1_get_xy: (VecDeque<Secp256k1Point>, VecDeque<(U256, U256)>),
secp256r1_new: (VecDeque<(U256, U256)>, VecDeque<Option<Secp256r1Point>>),
secp256r1_add: (
VecDeque<(Secp256r1Point, Secp256r1Point)>,
VecDeque<Secp256r1Point>,
),
secp256r1_mul: (VecDeque<(Secp256r1Point, U256)>, VecDeque<Secp256r1Point>),
secp256r1_get_point_from_x: (VecDeque<(U256, bool)>, VecDeque<Option<Secp256r1Point>>),
secp256r1_get_xy: (VecDeque<Secp256r1Point>, VecDeque<(U256, U256)>),
}
impl StarknetSyscallHandler for &mut SyscallHandler {
fn get_block_hash(
&mut self,
_block_number: u64,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
unimplemented!()
}
fn get_execution_info(
&mut self,
_remaining_gas: &mut u64,
) -> SyscallResult<cairo_native::starknet::ExecutionInfo> {
unimplemented!()
}
fn get_execution_info_v2(
&mut self,
_remaining_gas: &mut u64,
) -> SyscallResult<cairo_native::starknet::ExecutionInfoV2> {
unimplemented!()
}
fn get_execution_info_v3(
&mut self,
_remaining_gas: &mut u64,
) -> SyscallResult<cairo_native::starknet::ExecutionInfoV3> {
unimplemented!()
}
fn deploy(
&mut self,
_class_hash: Felt,
_contract_address_salt: Felt,
_calldata: &[Felt],
_deploy_from_zero: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<(Felt, Vec<Felt>)> {
unimplemented!()
}
fn replace_class(&mut self, _class_hash: Felt, _remaining_gas: &mut u64) -> SyscallResult<()> {
unimplemented!()
}
fn library_call(
&mut self,
_class_hash: Felt,
_function_selector: Felt,
_calldata: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
unimplemented!()
}
fn call_contract(
&mut self,
_address: Felt,
_entry_point_selector: Felt,
_calldata: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
unimplemented!()
}
fn storage_read(
&mut self,
_address_domain: u32,
_address: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
unimplemented!()
}
fn storage_write(
&mut self,
_address_domain: u32,
_address: Felt,
_value: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
unimplemented!()
}
fn emit_event(
&mut self,
_keys: &[Felt],
_data: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
unimplemented!()
}
fn send_message_to_l1(
&mut self,
_to_address: Felt,
_payload: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
unimplemented!()
}
fn keccak(&mut self, _input: &[u64], _remaining_gas: &mut u64) -> SyscallResult<U256> {
unimplemented!()
}
fn secp256k1_new(
&mut self,
x: U256,
y: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>> {
let (args, rets) = &mut self.secp256k1_new;
args.push_back((x, y));
Ok(rets.pop_front().unwrap())
}
fn secp256k1_add(
&mut self,
p0: Secp256k1Point,
p1: Secp256k1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point> {
let (args, rets) = &mut self.secp256k1_add;
args.push_back((p0, p1));
Ok(rets.pop_front().unwrap())
}
fn secp256k1_mul(
&mut self,
p: Secp256k1Point,
m: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point> {
let (args, rets) = &mut self.secp256k1_mul;
args.push_back((p, m));
Ok(rets.pop_front().unwrap())
}
fn secp256k1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>> {
let (args, rets) = &mut self.secp256k1_get_point_from_x;
args.push_back((x, y_parity));
Ok(rets.pop_front().unwrap())
}
fn secp256k1_get_xy(
&mut self,
p: Secp256k1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)> {
let (args, rets) = &mut self.secp256k1_get_xy;
args.push_back(p);
Ok(rets.pop_front().unwrap())
}
fn secp256r1_new(
&mut self,
x: U256,
y: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>> {
let (args, rets) = &mut self.secp256r1_new;
args.push_back((x, y));
Ok(rets.pop_front().unwrap())
}
fn secp256r1_add(
&mut self,
p0: Secp256r1Point,
p1: Secp256r1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point> {
let (args, rets) = &mut self.secp256r1_add;
args.push_back((p0, p1));
Ok(rets.pop_front().unwrap())
}
fn secp256r1_mul(
&mut self,
p: Secp256r1Point,
m: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point> {
let (args, rets) = &mut self.secp256r1_mul;
args.push_back((p, m));
Ok(rets.pop_front().unwrap())
}
fn secp256r1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>> {
let (args, rets) = &mut self.secp256r1_get_point_from_x;
args.push_back((x, y_parity));
Ok(rets.pop_front().unwrap())
}
fn secp256r1_get_xy(
&mut self,
p: Secp256r1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)> {
let (args, rets) = &mut self.secp256r1_get_xy;
args.push_back(p);
Ok(rets.pop_front().unwrap())
}
fn sha256_process_block(
&mut self,
_state: &mut [u32; 8],
_block: &[u32; 16],
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
unimplemented!()
}
fn get_class_hash_at(
&mut self,
_contract_address: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
unimplemented!()
}
fn meta_tx_v0(
&mut self,
_address: Felt,
_entry_point_selector: Felt,
_calldata: &[Felt],
_signature: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
unimplemented!()
}
}
lazy_static! {
static ref SECP256_PROGRAM: (String, Program, SierraCasmRunner) =
load_cairo_path("tests/tests/starknet/programs/secp256.cairo");
}
#[test]
fn secp256k1_new() {
let mut syscall_handler = SyscallHandler {
secp256k1_new: (
VecDeque::from([]),
VecDeque::from([
None,
Some(Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false,
}),
Some(Secp256k1Point {
x: U256 {
hi: u128::MAX,
lo: u128::MAX,
},
y: U256 {
hi: u128::MAX,
lo: u128::MAX,
},
is_infinity: false,
}),
]),
),
..Default::default()
};
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_new",
&[
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(0)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(0)],
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: vec![],
debug_name: None
}),
debug_name: None,
}),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_new",
&[
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(u128::MAX)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(0)],
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::default())),
debug_name: None,
}),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_new",
&[
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(u128::MAX)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(u128::MAX)],
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
u128::MAX,
u128::MAX,
u128::MAX,
false
))),
debug_name: None,
}),
debug_name: None,
},
);
assert_eq!(
syscall_handler.secp256k1_new.0,
[
(U256 { hi: 0, lo: 0 }, U256 { hi: 0, lo: 0 }),
(
U256 {
lo: 0,
hi: u128::MAX
},
U256 {
lo: u128::MAX,
hi: 0
}
),
(
U256 {
hi: u128::MAX,
lo: u128::MAX
},
U256 {
hi: u128::MAX,
lo: u128::MAX
}
),
],
);
assert!(syscall_handler.secp256k1_new.1.is_empty());
}
#[test]
fn secp256k1_add() {
let mut syscall_handler = SyscallHandler {
secp256k1_add: (
VecDeque::from([]),
VecDeque::from([
Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false,
},
Secp256k1Point {
x: U256 {
lo: u128::MAX,
hi: 0,
},
y: U256 {
lo: 0,
hi: u128::MAX,
},
is_infinity: false,
},
Secp256k1Point {
x: U256 {
lo: u128::MAX,
hi: u128::MAX,
},
y: U256 {
lo: u128::MAX,
hi: u128::MAX,
},
is_infinity: false,
},
]),
),
..Default::default()
};
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_add",
&[
Value::Secp256K1Point(Secp256k1Point::default()),
Value::Secp256K1Point(Secp256k1Point::default()),
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::default())),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_add",
&[
Value::Secp256K1Point(Secp256k1Point::new(0, u128::MAX, u128::MAX, 0, false)),
Value::Secp256K1Point(Secp256k1Point::new(u128::MAX, 0, 0, u128::MAX, false)),
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
0,
0,
u128::MAX,
false
))),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_add",
&[
Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
u128::MAX,
u128::MAX,
u128::MAX,
false,
)),
Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
u128::MAX,
u128::MAX,
u128::MAX,
false,
)),
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
u128::MAX,
u128::MAX,
u128::MAX,
false
))),
debug_name: None,
},
);
assert_eq!(
syscall_handler.secp256k1_add.0,
[
(
Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false,
},
Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false,
},
),
(
Secp256k1Point {
x: U256 {
hi: u128::MAX,
lo: 0
},
y: U256 {
hi: 0,
lo: u128::MAX
},
is_infinity: false,
},
Secp256k1Point {
x: U256 {
hi: 0,
lo: u128::MAX
},
y: U256 {
hi: u128::MAX,
lo: 0
},
is_infinity: false,
},
),
(
Secp256k1Point {
x: U256 {
lo: u128::MAX,
hi: u128::MAX
},
y: U256 {
lo: u128::MAX,
hi: u128::MAX
},
is_infinity: false,
},
Secp256k1Point {
x: U256 {
lo: u128::MAX,
hi: u128::MAX
},
y: U256 {
lo: u128::MAX,
hi: u128::MAX
},
is_infinity: false,
},
),
],
);
assert!(syscall_handler.secp256k1_add.1.is_empty());
}
#[test]
fn secp256k1_mul() {
let mut syscall_handler = SyscallHandler {
secp256k1_mul: (
VecDeque::from([]),
VecDeque::from([
Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false,
},
Secp256k1Point {
x: U256 {
hi: u128::MAX,
lo: 0,
},
y: U256 {
hi: 0,
lo: u128::MAX,
},
is_infinity: false,
},
Secp256k1Point {
x: U256 {
hi: u128::MAX,
lo: u128::MAX,
},
y: U256 {
hi: u128::MAX,
lo: u128::MAX,
},
is_infinity: false,
},
]),
),
..Default::default()
};
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_mul",
&[
Value::Secp256K1Point(Secp256k1Point::default()),
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(0)],
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::default())),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_mul",
&[
Value::Secp256K1Point(Secp256k1Point::new(u128::MAX, 0, 0, u128::MAX, false)),
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(0)],
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
0,
u128::MAX,
u128::MAX,
0,
false
))),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_mul",
&[
Value::Secp256K1Point(Secp256k1Point::new(u128::MAX, 0, 0, u128::MAX, false)),
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(0)],
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
u128::MAX,
u128::MAX,
u128::MAX,
false
))),
debug_name: None,
},
);
assert_eq!(
syscall_handler.secp256k1_mul.0,
[
(Secp256k1Point::default(), U256 { hi: 0, lo: 0 },),
(
Secp256k1Point::new(u128::MAX, 0, 0, u128::MAX, false),
U256 {
lo: u128::MAX,
hi: 0,
},
),
(
Secp256k1Point::new(u128::MAX, 0, 0, u128::MAX, false),
U256 {
hi: 0,
lo: u128::MAX,
},
),
],
);
assert!(syscall_handler.secp256k1_mul.1.is_empty());
}
#[test]
fn secp256k1_get_point_from_x() {
let mut syscall_handler = SyscallHandler {
secp256k1_get_point_from_x: (
VecDeque::from([]),
VecDeque::from([
None,
Some(Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false,
}),
Some(Secp256k1Point {
x: U256 {
hi: 0,
lo: u128::MAX,
},
y: U256 {
hi: u128::MAX,
lo: 0,
},
is_infinity: false,
}),
Some(Secp256k1Point {
x: U256 {
hi: u128::MAX,
lo: 0,
},
y: U256 {
hi: 0,
lo: u128::MAX,
},
is_infinity: false,
}),
]),
),
..Default::default()
};
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_point_from_x",
&[
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(0)],
debug_name: None,
},
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![],
debug_name: None,
}),
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: vec![],
debug_name: None,
}),
debug_name: None,
}),
debug_name: None
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_point_from_x",
&[
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(u128::MAX)],
debug_name: None,
},
Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: vec![],
debug_name: None,
}),
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::default())),
debug_name: None,
}),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_point_from_x",
&[
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(0)],
debug_name: None,
},
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![],
debug_name: None,
}),
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
0,
0,
u128::MAX,
false
))),
debug_name: None,
}),
debug_name: None,
},
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_point_from_x",
&[
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(u128::MAX)],
debug_name: None,
},
Value::Enum {
tag: 1,
value: Box::new(Value::Struct {
fields: vec![],
debug_name: None,
}),
debug_name: None,
},
],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Enum {
tag: 0,
value: Box::new(Value::Secp256K1Point(Secp256k1Point::new(
0,
u128::MAX,
u128::MAX,
0,
false
))),
debug_name: None,
}),
debug_name: None,
},
);
assert_eq!(
syscall_handler.secp256k1_get_point_from_x.0,
[
(U256 { hi: 0, lo: 0 }, false),
(
U256 {
lo: 0,
hi: u128::MAX,
},
true,
),
(
U256 {
lo: u128::MAX,
hi: 0,
},
false,
),
(
U256 {
hi: u128::MAX,
lo: u128::MAX,
},
true,
),
],
);
assert!(syscall_handler.secp256k1_get_point_from_x.1.is_empty());
}
#[test]
fn secp256k1_get_xy() {
let mut syscall_handler = SyscallHandler {
secp256k1_get_xy: (
VecDeque::from([]),
VecDeque::from([
(U256 { hi: 0, lo: 0 }, U256 { hi: 0, lo: 0 }),
(
U256 {
hi: 0,
lo: u128::MAX,
},
U256 {
hi: u128::MAX,
lo: 0,
},
),
(
U256 {
hi: u128::MAX,
lo: 0,
},
U256 {
hi: 0,
lo: u128::MAX,
},
),
(
U256 {
hi: u128::MAX,
lo: u128::MAX,
},
U256 {
hi: u128::MAX,
lo: u128::MAX,
},
),
]),
),
..Default::default()
};
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_xy",
&[Value::Secp256K1Point(Secp256k1Point::default())],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(0)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(0)],
debug_name: None,
},
],
debug_name: None,
}),
debug_name: None,
}
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_xy",
&[Value::Secp256K1Point(Secp256k1Point::new(
0,
u128::MAX,
u128::MAX,
0,
false,
))],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(0)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(u128::MAX)],
debug_name: None,
},
],
debug_name: None,
}),
debug_name: None,
}
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_xy",
&[Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
0,
0,
u128::MAX,
false,
))],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![Value::Uint128(0), Value::Uint128(u128::MAX)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(0)],
debug_name: None,
},
],
debug_name: None,
}),
debug_name: None,
}
);
let result = run_native_program(
&SECP256_PROGRAM,
"secp256k1_get_xy",
&[Value::Secp256K1Point(Secp256k1Point::new(
u128::MAX,
u128::MAX,
u128::MAX,
u128::MAX,
false,
))],
Some(u64::MAX),
Some(&mut syscall_handler),
);
assert_eq!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(u128::MAX)],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Uint128(u128::MAX), Value::Uint128(u128::MAX)],
debug_name: None,
},
],
debug_name: None,
}),
debug_name: None,
}
);
assert_eq!(
syscall_handler.secp256k1_get_xy.0,
[
Secp256k1Point {
x: U256 { hi: 0, lo: 0 },
y: U256 { hi: 0, lo: 0 },
is_infinity: false
},
Secp256k1Point {
x: U256 {
lo: 0,
hi: u128::MAX,
},
y: U256 {
lo: u128::MAX,
hi: 0,
},
is_infinity: false
},
Secp256k1Point {
x: U256 {
lo: u128::MAX,
hi: 0,
},
y: U256 {
lo: 0,
hi: u128::MAX,
},
is_infinity: false
},
Secp256k1Point {
x: U256 {
hi: u128::MAX,
lo: u128::MAX,
},
y: U256 {
hi: u128::MAX,
lo: u128::MAX,
},
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | true |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/starknet/syscalls.rs | tests/tests/starknet/syscalls.rs | use crate::common::{load_cairo_path, run_native_program};
use cairo_lang_runner::SierraCasmRunner;
use cairo_lang_sierra::program::Program;
use cairo_native::{
starknet::{
BlockInfo, ExecutionInfo, ExecutionInfoV2, ExecutionInfoV3, Secp256k1Point, Secp256r1Point,
StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, TxV3Info, U256,
},
Value,
};
use lazy_static::lazy_static;
use pretty_assertions_sorted::{assert_eq, assert_eq_sorted};
use starknet_types_core::felt::Felt;
use std::{
collections::{HashMap, VecDeque},
sync::{Arc, Mutex},
};
type Log = (Vec<Felt>, Vec<Felt>);
type L2ToL1Message = (Felt, Vec<Felt>);
#[derive(Debug, Default)]
struct ContractLogs {
events: VecDeque<Log>,
l2_to_l1_messages: VecDeque<L2ToL1Message>,
}
#[derive(Debug, Default)]
struct TestingState {
sequencer_address: Felt,
caller_address: Felt,
contract_address: Felt,
account_contract_address: Felt,
transaction_hash: Felt,
nonce: Felt,
chain_id: Felt,
version: Felt,
max_fee: u64,
block_number: u64,
block_timestamp: u64,
signature: Vec<Felt>,
logs: HashMap<Felt, ContractLogs>,
}
struct SyscallHandler {
/// Arc<Mutex> Is needed to test that the valures are set correct after the execution
testing_state: Arc<Mutex<TestingState>>,
}
impl SyscallHandler {
fn new() -> Self {
Self {
testing_state: Arc::new(Mutex::new(TestingState::default())),
}
}
fn with(state: Arc<Mutex<TestingState>>) -> Self {
Self {
testing_state: state,
}
}
}
impl StarknetSyscallHandler for SyscallHandler {
fn get_block_hash(
&mut self,
_block_number: u64,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
Ok(Felt::from_dec_str(
"1158579293198495875788224011889333769139150068959598053296510642728083832673",
)
.unwrap())
}
fn get_execution_info(&mut self, _remaining_gas: &mut u64) -> SyscallResult<ExecutionInfo> {
Ok(ExecutionInfo {
block_info: BlockInfo {
block_number: 10057862467973663535,
block_timestamp: 13878668747512495966,
sequencer_address: Felt::from_dec_str(
"1126241460712630201003776917997524449163698107789103849210792326381258973685",
)
.unwrap(),
},
tx_info: TxInfo {
version: Felt::from_dec_str(
"1724985403142256920476849371638528834056988111202434162793214195754735917407",
)
.unwrap(),
account_contract_address: Felt::from_dec_str(
"2419272378964094005143278046496347854926114240785059742454535261490265649110",
)
.unwrap(),
max_fee: 67871905340377755668863509019681938001,
signature: Vec::new(),
transaction_hash: Felt::from_dec_str(
"2073267424102447009330753642820908998776456851902897601865334818765025369132",
)
.unwrap(),
chain_id: Felt::from_dec_str(
"1727570805086347994328356733148206517040691113666039929118050093237140484117",
)
.unwrap(),
nonce: Felt::from_dec_str(
"2223335940097352947792108259394621577330089800429182023415494612506457867705",
)
.unwrap(),
},
caller_address: Felt::from_dec_str(
"2367044879643293830108311482898145302930693201376043522909298679498599559539",
)
.unwrap(),
contract_address: Felt::from_dec_str(
"2322490563038631685097154208793293355074547843057070254216662565231428808211",
)
.unwrap(),
entry_point_selector: Felt::from_dec_str(
"1501296828847480842982002010206952982741090100977850506550982801410247026532",
)
.unwrap(),
})
}
fn get_execution_info_v2(
&mut self,
_remaining_gas: &mut u64,
) -> SyscallResult<ExecutionInfoV2> {
Ok(ExecutionInfoV2 {
block_info: BlockInfo {
block_number: 10290342497028289173,
block_timestamp: 8376161426686560326,
sequencer_address: Felt::from_dec_str(
"1815189516202718271265591469295511271015058493881778555617445818147186579905",
)
.unwrap(),
},
tx_info: TxV2Info {
version: Felt::from_dec_str(
"1946630339019864531118751968563861838541265142438690346764722398811248737786",
)
.unwrap(),
account_contract_address: Felt::from_dec_str(
"2501333093425095943815772537228190103182643237630648877273495185321298605376",
)
.unwrap(),
max_fee: 268753657614351187400966367706860329387,
signature: Vec::new(),
transaction_hash: Felt::from_dec_str(
"1123336726531770778820945049824733201592457249587063926479184903627272350002",
)
.unwrap(),
chain_id: Felt::from_dec_str(
"2128916697180095451339935431635121484141376377516602728602049361615810538124",
)
.unwrap(),
nonce: Felt::from_dec_str(
"3012936192361023209451741736298028332652992971202997279327088951248532774884",
)
.unwrap(),
resource_bounds: Vec::new(),
tip: 215444579144685671333997376989135077200,
paymaster_data: Vec::new(),
nonce_data_availability_mode: 140600095,
fee_data_availability_mode: 988370659,
account_deployment_data: Vec::new(),
},
caller_address: Felt::from_dec_str(
"1185632056775552928459345712365014492063999606476424661067102766803470217687",
)
.unwrap(),
contract_address: Felt::from_dec_str(
"741063429140548584082645215539704615048011618665759826371923004739480130327",
)
.unwrap(),
entry_point_selector: Felt::from_dec_str(
"477501848519111015718660527024172361930966806556174677443839145770405114061",
)
.unwrap(),
})
}
fn get_execution_info_v3(
&mut self,
_remaining_gas: &mut u64,
) -> SyscallResult<ExecutionInfoV3> {
Ok(ExecutionInfoV3 {
block_info: BlockInfo {
block_number: 10290342497028289173,
block_timestamp: 8376161426686560326,
sequencer_address: Felt::from_dec_str(
"1815189516202718271265591469295511271015058493881778555617445818147186579905",
)
.unwrap(),
},
tx_info: TxV3Info {
version: Felt::from_dec_str(
"1946630339019864531118751968563861838541265142438690346764722398811248737786",
)
.unwrap(),
account_contract_address: Felt::from_dec_str(
"2501333093425095943815772537228190103182643237630648877273495185321298605376",
)
.unwrap(),
max_fee: 268753657614351187400966367706860329387,
signature: Vec::new(),
transaction_hash: Felt::from_dec_str(
"1123336726531770778820945049824733201592457249587063926479184903627272350002",
)
.unwrap(),
chain_id: Felt::from_dec_str(
"2128916697180095451339935431635121484141376377516602728602049361615810538124",
)
.unwrap(),
nonce: Felt::from_dec_str(
"3012936192361023209451741736298028332652992971202997279327088951248532774884",
)
.unwrap(),
resource_bounds: Vec::new(),
tip: 215444579144685671333997376989135077200,
paymaster_data: Vec::new(),
nonce_data_availability_mode: 140600095,
fee_data_availability_mode: 988370659,
account_deployment_data: Vec::new(),
proof_facts: vec![0.into(), 1.into(), 2.into()],
},
caller_address: Felt::from_dec_str(
"1185632056775552928459345712365014492063999606476424661067102766803470217687",
)
.unwrap(),
contract_address: Felt::from_dec_str(
"741063429140548584082645215539704615048011618665759826371923004739480130327",
)
.unwrap(),
entry_point_selector: Felt::from_dec_str(
"477501848519111015718660527024172361930966806556174677443839145770405114061",
)
.unwrap(),
})
}
fn deploy(
&mut self,
_class_hash: Felt,
_contract_address_salt: Felt,
_calldata: &[Felt],
_deploy_from_zero: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<(Felt, Vec<Felt>)> {
Ok((
Felt::from_dec_str(
"1833707083418045616336697070784512826809940908236872124572250196391719980392",
)
.unwrap(),
Vec::new(),
))
}
fn replace_class(&mut self, _class_hash: Felt, _remaining_gas: &mut u64) -> SyscallResult<()> {
Ok(())
}
fn library_call(
&mut self,
_class_hash: Felt,
_function_selector: Felt,
_calldata: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
Ok(vec![
Felt::from_dec_str(
"3358892263739032253767642605669710712087178958719188919195252597609334880396",
)
.unwrap(),
Felt::from_dec_str(
"1104291043781086177955655234103730593173963850634630109574183288837411031513",
)
.unwrap(),
Felt::from_dec_str(
"3346377229881115874907650557159666001431249650068516742483979624047277128413",
)
.unwrap(),
])
}
fn call_contract(
&mut self,
_address: Felt,
_entry_point_selector: Felt,
_calldata: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
Ok(vec![
Felt::from_dec_str(
"3358892263739032253767642605669710712087178958719188919195252597609334880396",
)
.unwrap(),
Felt::from_dec_str(
"1104291043781086177955655234103730593173963850634630109574183288837411031513",
)
.unwrap(),
Felt::from_dec_str(
"3346377229881115874907650557159666001431249650068516742483979624047277128413",
)
.unwrap(),
])
}
fn storage_read(
&mut self,
_address_domain: u32,
_address: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
Ok(Felt::from_dec_str(
"1013181629378419652272218169322268188846114273878719855200100663863924329981",
)
.unwrap())
}
fn storage_write(
&mut self,
_address_domain: u32,
_address: Felt,
_value: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
Ok(())
}
fn emit_event(
&mut self,
_keys: &[Felt],
_data: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
Ok(())
}
fn send_message_to_l1(
&mut self,
to_address: Felt,
payload: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
assert_eq!(
to_address,
3.into(),
"send_message_to_l1 to_address mismatch"
);
assert_eq!(payload, &[2.into()], "send_message_to_l1 payload mismatch");
Ok(())
}
fn keccak(&mut self, _input: &[u64], _remaining_gas: &mut u64) -> SyscallResult<U256> {
Ok(U256 {
hi: 330939983442938156232262046592599923289,
lo: 288102973244655531496349286021939642254,
})
}
fn secp256k1_new(
&mut self,
_x: U256,
_y: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256k1_add(
&mut self,
_p0: Secp256k1Point,
_p1: Secp256k1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256k1_mul(
&mut self,
_p: Secp256k1Point,
_m: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256k1_get_point_from_x(
&mut self,
_x: U256,
_y_parity: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256k1_get_xy(
&mut self,
_p: Secp256k1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256r1_new(
&mut self,
_x: U256,
_y: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256r1_add(
&mut self,
_p0: Secp256r1Point,
_p1: Secp256r1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256r1_mul(
&mut self,
_p: Secp256r1Point,
_m: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256r1_get_point_from_x(
&mut self,
_x: U256,
_y_parity: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn secp256r1_get_xy(
&mut self,
_p: Secp256r1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)> {
// Tested in `tests/tests/starknet/secp256.rs`.
unimplemented!()
}
fn sha256_process_block(
&mut self,
_state: &mut [u32; 8],
_block: &[u32; 16],
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
Ok(())
}
fn get_class_hash_at(
&mut self,
contract_address: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
Ok(contract_address)
}
fn meta_tx_v0(
&mut self,
_address: Felt,
_entry_point_selector: Felt,
_calldata: &[Felt],
_signature: &[Felt],
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
Ok(vec![
Felt::from_dec_str(
"3358892263739032253767642605669710712087178958719188919195252597609334880396",
)
.unwrap(),
Felt::from_dec_str(
"1104291043781086177955655234103730593173963850634630109574183288837411031513",
)
.unwrap(),
Felt::from_dec_str(
"3346377229881115874907650557159666001431249650068516742483979624047277128413",
)
.unwrap(),
])
}
fn cheatcode(&mut self, selector: Felt, input: &[Felt]) -> Vec<Felt> {
let selector_bytes = selector.to_bytes_be();
let selector = match std::str::from_utf8(&selector_bytes) {
Ok(selector) => selector.trim_start_matches('\0'),
Err(_) => return Vec::new(),
};
match selector {
"set_sequencer_address" => {
self.testing_state.lock().unwrap().sequencer_address = input[0];
vec![]
}
"set_caller_address" => {
self.testing_state.lock().unwrap().caller_address = input[0];
vec![]
}
"set_contract_address" => {
self.testing_state.lock().unwrap().contract_address = input[0];
vec![]
}
"set_account_contract_address" => {
self.testing_state.lock().unwrap().account_contract_address = input[0];
vec![]
}
"set_transaction_hash" => {
self.testing_state.lock().unwrap().transaction_hash = input[0];
vec![]
}
"set_nonce" => {
self.testing_state.lock().unwrap().nonce = input[0];
vec![]
}
"set_version" => {
self.testing_state.lock().unwrap().version = input[0];
vec![]
}
"set_chain_id" => {
self.testing_state.lock().unwrap().chain_id = input[0];
vec![]
}
"set_max_fee" => {
let max_fee = input[0].to_biguint().try_into().unwrap();
self.testing_state.lock().unwrap().max_fee = max_fee;
vec![]
}
"set_block_number" => {
let block_number = input[0].to_biguint().try_into().unwrap();
self.testing_state.lock().unwrap().block_number = block_number;
vec![]
}
"set_block_timestamp" => {
let block_timestamp = input[0].to_biguint().try_into().unwrap();
self.testing_state.lock().unwrap().block_timestamp = block_timestamp;
vec![]
}
"set_signature" => {
self.testing_state.lock().unwrap().signature = input.to_vec();
vec![]
}
"pop_log" => self
.testing_state
.lock()
.unwrap()
.logs
.get_mut(&input[0])
.and_then(|logs| logs.events.pop_front())
.map(|mut log| {
let mut serialized_log = Vec::new();
serialized_log.push(log.0.len().into());
serialized_log.append(&mut log.0);
serialized_log.push(log.1.len().into());
serialized_log.append(&mut log.1);
serialized_log
})
.unwrap_or_default(),
"pop_l2_to_l1_message" => self
.testing_state
.lock()
.unwrap()
.logs
.get_mut(&input[0])
.and_then(|logs| logs.l2_to_l1_messages.pop_front())
.map(|mut log| {
let mut serialized_log = Vec::new();
serialized_log.push(log.0);
serialized_log.push(log.1.len().into());
serialized_log.append(&mut log.1);
serialized_log
})
.unwrap_or_default(),
_ => vec![],
}
}
}
lazy_static! {
static ref SYSCALLS_PROGRAM: (String, Program, SierraCasmRunner) =
load_cairo_path("tests/tests/starknet/programs/syscalls.cairo");
}
#[test]
fn get_block_hash() {
let result = run_native_program(
&SYSCALLS_PROGRAM,
"get_block_hash",
&[],
Some(u64::MAX),
Some(SyscallHandler::new()),
);
assert_eq_sorted!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Felt252(
Felt::from_dec_str(
"1158579293198495875788224011889333769139150068959598053296510642728083832673",
)
.unwrap()
)),
debug_name: None,
},
);
}
#[test]
fn get_execution_info() {
let result = run_native_program(
&SYSCALLS_PROGRAM,
"get_execution_info",
&[],
Some(u64::MAX),
Some(SyscallHandler::new()),
);
assert_eq_sorted!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![
Value::Uint64(10057862467973663535),
Value::Uint64(13878668747512495966),
Value::Felt252(Felt::from_dec_str(
"1126241460712630201003776917997524449163698107789103849210792326381258973685",
)
.unwrap()),
],
debug_name: None,
},
Value::Struct {
fields: vec![
Value::Felt252(Felt::from_dec_str(
"1724985403142256920476849371638528834056988111202434162793214195754735917407",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2419272378964094005143278046496347854926114240785059742454535261490265649110",
)
.unwrap()),
Value::Uint128(67871905340377755668863509019681938001),
Value::Struct {
fields: vec![
Value::Array(Vec::new()),
],
debug_name: None
},
Value::Felt252(Felt::from_dec_str(
"2073267424102447009330753642820908998776456851902897601865334818765025369132",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"1727570805086347994328356733148206517040691113666039929118050093237140484117",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2223335940097352947792108259394621577330089800429182023415494612506457867705",
)
.unwrap()),
],
debug_name: None,
},
Value::Felt252(Felt::from_dec_str(
"2367044879643293830108311482898145302930693201376043522909298679498599559539",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2322490563038631685097154208793293355074547843057070254216662565231428808211",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"1501296828847480842982002010206952982741090100977850506550982801410247026532",
)
.unwrap()),
],
debug_name: None,
}),
debug_name: None,
},
);
}
#[test]
fn get_execution_info_v2() {
let result = run_native_program(
&SYSCALLS_PROGRAM,
"get_execution_info_v2",
&[],
Some(u64::MAX),
Some(SyscallHandler::new()),
);
assert_eq_sorted!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![
Value::Uint64(10290342497028289173),
Value::Uint64(8376161426686560326),
Value::Felt252(Felt::from_dec_str(
"1815189516202718271265591469295511271015058493881778555617445818147186579905",
)
.unwrap()),
],
debug_name: None,
},
Value::Struct {
fields: vec![
Value::Felt252(Felt::from_dec_str(
"1946630339019864531118751968563861838541265142438690346764722398811248737786",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2501333093425095943815772537228190103182643237630648877273495185321298605376",
)
.unwrap()),
Value::Uint128(268753657614351187400966367706860329387),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Felt252(Felt::from_dec_str(
"1123336726531770778820945049824733201592457249587063926479184903627272350002",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2128916697180095451339935431635121484141376377516602728602049361615810538124",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"3012936192361023209451741736298028332652992971202997279327088951248532774884",
)
.unwrap()),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Uint128(215444579144685671333997376989135077200),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Uint32(140600095),
Value::Uint32(988370659),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
],
debug_name: None,
},
Value::Felt252(Felt::from_dec_str(
"1185632056775552928459345712365014492063999606476424661067102766803470217687",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"741063429140548584082645215539704615048011618665759826371923004739480130327",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"477501848519111015718660527024172361930966806556174677443839145770405114061",
)
.unwrap()),
],
debug_name: None,
}),
debug_name: None,
},
);
}
#[test]
fn get_execution_info_v3() {
let result = run_native_program(
&SYSCALLS_PROGRAM,
"get_execution_info_v3",
&[],
Some(u64::MAX),
Some(SyscallHandler::new()),
);
assert_eq_sorted!(
result.return_value,
Value::Enum {
tag: 0,
value: Box::new(Value::Struct {
fields: vec![
Value::Struct {
fields: vec![
Value::Uint64(10290342497028289173),
Value::Uint64(8376161426686560326),
Value::Felt252(Felt::from_dec_str(
"1815189516202718271265591469295511271015058493881778555617445818147186579905",
)
.unwrap()),
],
debug_name: None,
},
Value::Struct {
fields: vec![
Value::Felt252(Felt::from_dec_str(
"1946630339019864531118751968563861838541265142438690346764722398811248737786",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2501333093425095943815772537228190103182643237630648877273495185321298605376",
)
.unwrap()),
Value::Uint128(268753657614351187400966367706860329387),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Felt252(Felt::from_dec_str(
"1123336726531770778820945049824733201592457249587063926479184903627272350002",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"2128916697180095451339935431635121484141376377516602728602049361615810538124",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"3012936192361023209451741736298028332652992971202997279327088951248532774884",
)
.unwrap()),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Uint128(215444579144685671333997376989135077200),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Uint32(140600095),
Value::Uint32(988370659),
Value::Struct {
fields: vec![Value::Array(Vec::new())],
debug_name: None,
},
Value::Struct {
fields: vec![Value::Array(vec![
Value::Felt252(0.into()),
Value::Felt252(1.into()),
Value::Felt252(2.into()),
])],
debug_name: None,
},
],
debug_name: None,
},
Value::Felt252(Felt::from_dec_str(
"1185632056775552928459345712365014492063999606476424661067102766803470217687",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"741063429140548584082645215539704615048011618665759826371923004739480130327",
)
.unwrap()),
Value::Felt252(Felt::from_dec_str(
"477501848519111015718660527024172361930966806556174677443839145770405114061",
)
.unwrap()),
],
debug_name: None,
}),
debug_name: None,
},
);
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | true |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/starknet/u256.rs | tests/tests/starknet/u256.rs | use crate::common::run_native_starknet_contract;
use cairo_lang_compiler::CompilerConfig;
use cairo_lang_lowering::utils::InliningStrategy;
use cairo_lang_starknet::compile::compile_path;
use cairo_native::starknet_stub::StubSyscallHandler;
use lazy_static::lazy_static;
use starknet_types_core::felt::Felt;
use std::path::Path;
lazy_static! {
static ref U256_CONTRACT: cairo_lang_starknet_classes::contract_class::ContractClass = {
let path = Path::new("tests/tests/starknet/contracts/test_u256_order.cairo");
compile_path(
path,
None,
CompilerConfig {
replace_ids: true,
..Default::default()
},
InliningStrategy::Default,
)
.unwrap()
};
}
#[test]
fn u256_test() {
let contract = &U256_CONTRACT;
let entry_point = contract.entry_points_by_type.external.first().unwrap();
let program = contract.extract_sierra_program().unwrap();
let result = run_native_starknet_contract(
&program,
entry_point.function_idx,
&[],
&mut StubSyscallHandler::default(),
);
assert!(!result.failure_flag);
assert_eq!(
result.return_values,
vec![Felt::from_hex("0xf70cba9bb86caa97b086fdfa3df602ed").unwrap()]
);
assert_eq!(result.remaining_gas, 18446744073709352905);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/starknet/keccak.rs | tests/tests/starknet/keccak.rs | use crate::common::{run_native_starknet_aot_contract, run_native_starknet_contract};
use cairo_lang_compiler::CompilerConfig;
use cairo_lang_lowering::utils::InliningStrategy;
use cairo_lang_starknet::compile::compile_path;
use cairo_native::starknet_stub::StubSyscallHandler;
use lazy_static::lazy_static;
use std::path::Path;
lazy_static! {
static ref KECCAK_CONTRACT: cairo_lang_starknet_classes::contract_class::ContractClass = {
let path = Path::new("tests/tests/starknet/contracts/test_keccak.cairo");
compile_path(
path,
None,
CompilerConfig {
replace_ids: true,
..Default::default()
},
InliningStrategy::Default,
)
.unwrap()
};
}
#[test]
fn keccak_test() {
let contract = &KECCAK_CONTRACT;
let entry_point = contract.entry_points_by_type.external.first().unwrap();
let program = contract.extract_sierra_program().unwrap();
let result = run_native_starknet_contract(
&program,
entry_point.function_idx,
&[],
&mut StubSyscallHandler::default(),
);
assert!(!result.failure_flag);
assert_eq!(result.remaining_gas, 18446744073709325515);
assert_eq!(result.return_values, vec![1.into()]);
let result_aot_ct = run_native_starknet_aot_contract(
contract,
&entry_point.selector,
&[],
&mut StubSyscallHandler::default(),
);
assert!(!result_aot_ct.failure_flag);
assert_eq!(result_aot_ct.remaining_gas, result.remaining_gas);
assert_eq!(result_aot_ct.return_values, vec![1.into()]);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/tests/tests/starknet/mod.rs | tests/tests/starknet/mod.rs | mod keccak;
mod secp256;
mod u256;
#[cfg(feature = "with-cheatcode")]
mod syscalls;
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/cairo-native-test/src/main.rs | binaries/cairo-native-test/src/main.rs | use anyhow::bail;
use cairo_lang_compiler::project::check_compiler_path;
use cairo_lang_test_plugin::TestsCompilationConfig;
use cairo_lang_test_runner::TestCompiler;
use cairo_native_bin_utils::{
test::{display_tests_summary, filter_test_cases, run_tests},
RunArgs,
};
use clap::Parser;
use std::path::PathBuf;
use tracing_subscriber::{EnvFilter, FmtSubscriber};
/// Compiles a Cairo project and runs all the functions marked as `#[test]`.
/// Exits with 1 if the compilation or run fails, otherwise 0.
#[derive(Parser, Debug)]
#[clap(version, verbatim_doc_comment)]
struct Args {
/// The Cairo project path to compile and run its tests.
path: PathBuf,
/// Whether path is a single file.
#[arg(short, long)]
single_file: bool,
/// Allows the compilation to succeed with warnings.
#[arg(long)]
allow_warnings: bool,
/// The filter for the tests, running only tests containing the filter string.
#[arg(short, long, default_value_t = String::default())]
filter: String,
/// Should we run ignored tests as well.
#[arg(long, default_value_t = false)]
include_ignored: bool,
/// Should we run only the ignored tests.
#[arg(long, default_value_t = false)]
ignored: bool,
/// Should we add the starknet plugin to run the tests.
#[arg(long, default_value_t = false)]
starknet: bool,
/// Optimization level, Valid: 0, 1, 2, 3. Values higher than 3 are considered as 3.
#[arg(short = 'O', long, default_value_t = 0)]
opt_level: u8,
/// Compares test result with Cairo VM.
#[arg(long, default_value_t = false)]
compare_with_cairo_vm: bool,
}
fn main() -> anyhow::Result<()> {
// Parse command-line arguments.
let args = Args::parse();
// Configure logging and error handling.
tracing::subscriber::set_global_default(
FmtSubscriber::builder()
.with_env_filter(EnvFilter::from_default_env())
.finish(),
)?;
check_compiler_path(args.single_file, &args.path)?;
let compiler = TestCompiler::try_new(
&args.path,
args.allow_warnings,
true,
TestsCompilationConfig {
starknet: args.starknet,
add_statements_functions: false,
add_statements_code_locations: false,
add_functions_debug_info: false,
contract_declarations: None,
contract_crate_ids: None,
executable_crate_ids: None,
},
)?;
let build_test_compilation = compiler.build()?;
let (compiled, filtered_out) = filter_test_cases(
build_test_compilation,
args.include_ignored,
args.ignored,
args.filter.clone(),
);
let summary = run_tests(
compiled.metadata.named_tests,
compiled.sierra_program.program,
compiled.metadata.function_set_costs,
compiled.metadata.contracts_info,
RunArgs {
opt_level: args.opt_level,
compare_with_vm: args.compare_with_cairo_vm,
},
)?;
display_tests_summary(&summary, filtered_out);
if !summary.failed.is_empty() || !summary.mismatch.is_empty() {
bail!("test failed")
}
Ok(())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/scarb-native-test/src/main.rs | binaries/scarb-native-test/src/main.rs | use anyhow::Context;
use cairo_lang_sierra::program::VersionedProgram;
use cairo_lang_test_plugin::{TestCompilation, TestCompilationMetadata};
use cairo_native_bin_utils::{
test::{display_tests_summary, filter_test_cases, find_testable_targets, run_tests},
RunArgs,
};
use clap::{Parser, ValueEnum};
use scarb_metadata::{Metadata, MetadataCommand, ScarbCommand};
use scarb_ui::args::PackagesFilter;
use std::{collections::HashSet, env, fs, path::Path};
/// Compiles all packages from a Scarb project matching `packages_filter` and
/// runs all functions marked with `#[test]`. Exits with 1 if the compilation
/// or run fails, otherwise 0.
#[derive(Parser, Clone, Debug)]
#[command(author, version, verbatim_doc_comment)]
struct Args {
#[command(flatten)]
packages_filter: PackagesFilter,
/// Run only tests whose name contain FILTER.
#[arg(short, long, default_value = "")]
filter: String,
/// Run ignored and not ignored tests.
#[arg(long, default_value_t = false)]
include_ignored: bool,
/// Run only ignored tests.
#[arg(long, default_value_t = false)]
ignored: bool,
/// Choose test kind to run.
#[arg(short, long)]
test_kind: Option<TestKind>,
/// Optimization level, Valid: 0, 1, 2, 3. Values higher than 3 are considered as 3.
#[arg(short = 'O', long, default_value_t = 0)]
opt_level: u8,
/// Compares test result with Cairo VM.
#[arg(long, default_value_t = false)]
compare_with_cairo_vm: bool,
}
#[derive(ValueEnum, Clone, Debug, Default)]
pub enum TestKind {
Unit,
Integration,
#[default]
All,
}
impl TestKind {
pub fn matches(&self, kind: &str) -> bool {
match self {
TestKind::Unit => kind == "unit",
TestKind::Integration => kind == "integration",
TestKind::All => true,
}
}
}
fn main() -> anyhow::Result<()> {
let args: Args = Args::parse();
let metadata = MetadataCommand::new().inherit_stderr().exec()?;
// Filter packages.
let matched = args.packages_filter.match_many(&metadata)?;
let filter = PackagesFilter::generate_for::<Metadata>(matched.iter());
let test_kind = args.test_kind.unwrap_or_default();
let target_names = matched
.iter()
.flat_map(|package| {
find_testable_targets(package)
.iter()
.filter(|target| {
test_kind.matches(
target
.params
.get("test-type")
.and_then(|v| v.as_str())
.unwrap_or_default(),
)
})
.map(|t| t.name.clone())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
// Build only the filtered packages.
ScarbCommand::new()
.arg("build")
.arg("--test")
.env("SCARB_TARGET_NAMES", target_names.clone().join(","))
.env("SCARB_PACKAGES_FILTER", filter.to_env())
.run()?;
// Get `target` directory.
let profile = env::var("SCARB_PROFILE").unwrap_or("dev".into());
let default_target_dir = metadata.runtime_manifest.join("target");
let target_dir = metadata
.target_dir
.clone()
.unwrap_or(default_target_dir)
.join(profile);
let mut deduplicator = TargetGroupDeduplicator::default();
for package in matched {
println!("testing {} ...", package.name);
// Iterate over the filtered targets.
for target in find_testable_targets(&package) {
if !target_names.contains(&target.name) {
continue;
}
let name = target
.params
.get("group-id")
.and_then(|v| v.as_str())
.map(ToString::to_string)
.unwrap_or(target.name.clone());
let already_seen = deduplicator.visit(package.name.clone(), name.clone());
if already_seen {
continue;
}
let compiled = deserialize_test_compilation(target_dir.as_std_path(), name.clone())?;
let (compiled, filtered_out) = filter_test_cases(
compiled,
args.include_ignored,
args.ignored,
args.filter.clone(),
);
let summary = run_tests(
compiled.metadata.named_tests,
compiled.sierra_program.program,
compiled.metadata.function_set_costs,
compiled.metadata.contracts_info,
RunArgs {
opt_level: args.opt_level,
compare_with_vm: args.compare_with_cairo_vm,
},
)?;
display_tests_summary(&summary, filtered_out);
}
}
Ok(())
}
#[derive(Default)]
struct TargetGroupDeduplicator {
seen: HashSet<(String, String)>,
}
impl TargetGroupDeduplicator {
/// Returns true if already visited.
pub fn visit(&mut self, package_name: String, group_name: String) -> bool {
!self.seen.insert((package_name, group_name))
}
}
fn deserialize_test_compilation(
target_dir: &Path,
name: String,
) -> anyhow::Result<TestCompilation<'_>> {
let file_path = target_dir.join(format!("{}.test.json", name));
let test_comp_metadata = serde_json::from_str::<TestCompilationMetadata>(
&fs::read_to_string(file_path.clone())
.with_context(|| format!("failed to read file: {file_path:?}"))?,
)
.with_context(|| {
format!("failed to deserialize compiled tests metadata file: {file_path:?}")
})?;
let file_path = target_dir.join(format!("{}.test.sierra.json", name));
let sierra_program = serde_json::from_str::<VersionedProgram>(
&fs::read_to_string(file_path.clone())
.with_context(|| format!("failed to read file: {file_path:?}"))?,
)
.with_context(|| format!("failed to deserialize compiled tests sierra file: {file_path:?}"))?;
Ok(TestCompilation {
sierra_program: sierra_program.into_v1()?,
metadata: test_comp_metadata,
})
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/cairo-native-bin-utils/src/test.rs | binaries/cairo-native-bin-utils/src/test.rs | use super::{find_function, format_for_panic, result_to_runresult, RunArgs};
use anyhow::Context;
use cairo_lang_runner::{RunResultValue, SierraCasmRunner};
use cairo_lang_sierra::{extensions::gas::CostTokenType, ids::FunctionId, program::Program};
use cairo_lang_sierra_to_casm::metadata::MetadataComputationConfig;
use cairo_lang_sierra_type_size::ProgramRegistryInfo;
use cairo_lang_starknet::contract::ContractInfo;
use cairo_lang_test_plugin::{
test_config::{PanicExpectation, TestExpectation},
TestConfig,
};
use cairo_lang_test_plugin::{TestCompilation, TestCompilationMetadata};
use cairo_lang_utils::{
casts::IntoOrPanic, ordered_hash_map::OrderedHashMap, small_ordered_map::SmallOrderedMap,
};
use cairo_native::{
context::NativeContext, executor::AotNativeExecutor, metadata::gas::GasMetadata,
starknet_stub::StubSyscallHandler,
};
use colored::Colorize;
use itertools::Itertools;
use num_traits::ToPrimitive;
#[cfg(feature = "scarb")]
use scarb_metadata::{PackageMetadata, TargetMetadata};
use starknet_types_core::felt::Felt;
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
/// Summary data of the ran tests.
pub struct TestsSummary {
pub passed: Vec<String>,
pub failed: Vec<String>,
pub ignored: Vec<String>,
pub mismatch: Vec<String>,
pub failed_run_results: Vec<RunResultValue>,
pub mismatch_reason: Vec<String>,
}
/// The result of a ran test.
struct TestResult {
/// The status of the run.
status: TestStatus,
/// The gas usage of the run if relevant.
gas_usage: Option<i64>,
}
/// The status of a ran test.
enum TestStatus {
Success,
Fail(RunResultValue),
Mismatch(String),
}
/// Find all testable targets in the Scarb package.
#[cfg(feature = "scarb")]
pub fn find_testable_targets(package: &PackageMetadata) -> Vec<&TargetMetadata> {
package
.targets
.iter()
.filter(|target| target.kind == "test")
.collect()
}
/// Filter compiled test cases with user provided arguments.
///
/// # Arguments
/// * `compiled` - Compiled test cases with metadata.
/// * `include_ignored` - Include ignored tests as well.
/// * `ignored` - Run ignored tests only.
/// * `filter` - Include only tests containing the filter string.
/// # Returns
/// * (`TestCompilation`, `usize`) - The filtered test cases and the number of filtered out cases.
pub fn filter_test_cases(
compiled: TestCompilation,
include_ignored: bool,
ignored: bool,
filter: String,
) -> (TestCompilation, usize) {
let total_tests_count = compiled.metadata.named_tests.len();
let named_tests = compiled
.metadata
.named_tests
.into_iter()
// Filtering unignored tests in `ignored` mode
.filter(|(_, test)| !ignored || test.ignored || include_ignored)
.map(|(func, mut test)| {
// Un-ignoring all the tests in `include-ignored` and `ignored` mode.
if include_ignored || ignored {
test.ignored = false;
}
(func, test)
})
.filter(|(name, _)| name.contains(&filter))
.collect_vec();
let filtered_out = total_tests_count - named_tests.len();
let tests = TestCompilation {
metadata: TestCompilationMetadata {
named_tests,
..compiled.metadata
},
..compiled
};
(tests, filtered_out)
}
/// Display the summary of the ran tests.
pub fn display_tests_summary(summary: &TestsSummary, filtered_out: usize) {
println!();
if !summary.failed.is_empty() || !summary.mismatch.is_empty() {
println!("failures:");
for (failure, run_result) in summary
.failed
.iter()
.zip_eq(summary.failed_run_results.clone())
{
print!(" {failure} - ");
match run_result {
RunResultValue::Success(_) => {
println!("expected panic but finished successfully.");
}
RunResultValue::Panic(values) => {
println!("{}", format_for_panic(values.into_iter()));
}
}
}
for (test_name, mismatch_reason) in summary
.mismatch
.iter()
.zip_eq(summary.mismatch_reason.clone())
{
println!(" {test_name} - {mismatch_reason}");
}
println!();
}
println!(
"test result: {}. {} passed; {} failed; {} ignored; {} filtered out;",
if summary.failed.is_empty() && summary.mismatch.is_empty() {
"ok".bright_green()
} else {
"FAILED".bright_red()
},
summary.passed.len(),
summary.failed.len() + summary.mismatch.len(),
summary.ignored.len(),
filtered_out
);
println!();
}
/// Runs the tests and process the results for a summary.
pub fn run_tests(
named_tests: Vec<(String, TestConfig)>,
sierra_program: Program,
function_set_costs: OrderedHashMap<FunctionId, SmallOrderedMap<CostTokenType, i32>>,
contracts_info: OrderedHashMap<Felt, ContractInfo>,
args: RunArgs,
) -> anyhow::Result<TestsSummary> {
let runner = if args.compare_with_vm {
Some(
SierraCasmRunner::new(
sierra_program.clone(),
Some(MetadataComputationConfig {
function_set_costs: function_set_costs.clone(),
linear_gas_solver: true,
linear_ap_change_solver: true,
skip_non_linear_solver_comparisons: false,
compute_runtime_costs: false,
}),
contracts_info.clone(),
None,
)
.with_context(|| "Failed setting up runner.")?,
)
} else {
None
};
let native_context = NativeContext::new();
// Compile the sierra program into a MLIR module.
let native_module = native_context
.compile(&sierra_program, false, Some(Default::default()), None)
.unwrap();
let native_executor = Arc::new(AotNativeExecutor::from_native_module(
native_module,
args.opt_level.into(),
)?);
let gas_metadata = GasMetadata::new(
&sierra_program,
&ProgramRegistryInfo::new(&sierra_program)?,
Some(MetadataComputationConfig {
function_set_costs,
linear_ap_change_solver: true,
linear_gas_solver: true,
skip_non_linear_solver_comparisons: false,
compute_runtime_costs: false,
}),
)
.unwrap();
println!("running {} tests", named_tests.len());
let wrapped_summary = Mutex::new(Ok(TestsSummary {
passed: vec![],
failed: vec![],
ignored: vec![],
mismatch: vec![],
failed_run_results: vec![],
mismatch_reason: vec![],
}));
named_tests
.into_iter()
.map(
|(name, test)| -> anyhow::Result<(String, Option<TestResult>)> {
if test.ignored {
return Ok((name, None));
}
tracing::trace!("running test {name:?}");
let func = find_function(&sierra_program, name.as_str())?;
let initial_gas = test.available_gas.map(|x| x.try_into().unwrap());
let syscall_handler = &mut StubSyscallHandler {
contracts_info: contracts_info.clone(),
executor: Some(native_executor.clone()),
..Default::default()
};
let mut native_result = native_executor.invoke_dynamic_with_syscall_handler(
&func.id,
&[],
initial_gas,
&mut *syscall_handler,
)?;
native_result.builtin_stats += syscall_handler.builtin_counters;
let run_result = result_to_runresult(&native_result)?;
let gas_usage = test
.available_gas
.zip(native_result.remaining_gas)
.map(|(before, after)| before.into_or_panic::<i64>() - after.to_i64().unwrap())
.or_else(|| {
gas_metadata
.initial_required_gas(&func.id)
.unwrap()
.map(|gas| gas.try_into().unwrap())
});
if let Some(runner) = &runner {
let vm_result = runner
.run_function_with_starknet_context(
func,
vec![],
test.available_gas,
Default::default(),
)
.with_context(|| {
format!("Failed to run the function `{}`.", name.as_str())
})?;
let vm_builtins: HashMap<&str, usize> = vm_result
.used_resources
.basic_resources
.filter_unused_builtins()
.builtin_instance_counter
.iter()
.map(|(k, v)| (k.to_str(), *v))
.collect();
let native_builtins = {
let mut native_builtins = HashMap::new();
native_builtins
.insert("range_check", native_result.builtin_stats.range_check);
native_builtins.insert("pedersen", native_result.builtin_stats.pedersen);
native_builtins.insert("bitwise", native_result.builtin_stats.bitwise);
native_builtins.insert("ec_op", native_result.builtin_stats.ec_op);
native_builtins.insert("poseidon", native_result.builtin_stats.poseidon);
// we don't include the segment arena builtin, as its not included in the VM output either.
native_builtins
.insert("range_check96", native_result.builtin_stats.range_check96);
native_builtins.insert("add_mod", native_result.builtin_stats.add_mod);
native_builtins.insert("mul_mod", native_result.builtin_stats.mul_mod);
for builtin_name in vm_builtins.keys() {
native_builtins.entry(builtin_name).or_default();
}
native_builtins
};
for (builtin_name, native_counter) in native_builtins {
let vm_counter = vm_builtins.get(builtin_name).cloned().unwrap_or_default();
if native_counter != vm_counter {
return Ok((
name,
Some(TestResult {
status: TestStatus::Mismatch(format!(
"{} builtin mismatch: expected {}, got {}",
builtin_name, vm_counter, native_counter
)),
gas_usage,
}),
));
}
}
}
Ok((
name,
Some(TestResult {
status: match &run_result {
RunResultValue::Success(_) => match test.expectation {
TestExpectation::Success => TestStatus::Success,
TestExpectation::Panics(_) => TestStatus::Fail(run_result),
},
RunResultValue::Panic(value) => match test.expectation {
TestExpectation::Success => TestStatus::Fail(run_result),
TestExpectation::Panics(panic_expectation) => {
match panic_expectation {
PanicExpectation::Exact(expected) if value != &expected => {
TestStatus::Fail(run_result)
}
_ => TestStatus::Success,
}
}
},
},
gas_usage,
}),
))
},
)
.for_each(|r| {
let mut wrapped_summary = wrapped_summary.lock().unwrap();
if wrapped_summary.is_err() {
return;
}
let (name, status) = match r {
Ok((name, status)) => (name, status),
Err(err) => {
*wrapped_summary = Err(err);
return;
}
};
let summary = wrapped_summary.as_mut().unwrap();
let (res_type, status_str, gas_usage) = match status {
Some(TestResult {
status: TestStatus::Success,
gas_usage,
}) => (&mut summary.passed, "ok".bright_green(), gas_usage),
Some(TestResult {
status: TestStatus::Fail(run_result),
gas_usage,
}) => {
summary.failed_run_results.push(run_result);
(&mut summary.failed, "fail".bright_red(), gas_usage)
}
Some(TestResult {
status: TestStatus::Mismatch(reason),
gas_usage,
}) => {
summary.mismatch_reason.push(reason);
(&mut summary.mismatch, "mismatch".bright_red(), gas_usage)
}
None => (&mut summary.ignored, "ignored".bright_yellow(), None),
};
if let Some(gas_usage) = gas_usage {
println!("test {name} ... {status_str} (gas usage est.: {gas_usage})");
} else {
println!("test {name} ... {status_str}");
}
res_type.push(name);
});
wrapped_summary.into_inner().unwrap()
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/cairo-native-bin-utils/src/lib.rs | binaries/cairo-native-bin-utils/src/lib.rs | #![allow(dead_code)]
use anyhow::bail;
use cairo_lang_runner::{casm_run::format_next_item, RunResultValue};
use cairo_lang_sierra::program::{Function, Program};
use cairo_native::{
execution_result::ExecutionResult,
starknet::{Secp256k1Point, Secp256r1Point},
Value,
};
use itertools::Itertools;
use starknet_types_core::felt::Felt;
use std::vec::IntoIter;
pub mod test;
pub struct RunArgs {
pub opt_level: u8,
pub compare_with_vm: bool,
}
/// Find the function ending with `name_suffix` in the program.
pub fn find_function<'a>(
sierra_program: &'a Program,
name_suffix: &str,
) -> anyhow::Result<&'a Function> {
if let Some(x) = sierra_program.funcs.iter().find(|f| {
if let Some(name) = &f.id.debug_name {
name.ends_with(name_suffix)
} else {
false
}
}) {
Ok(x)
} else {
bail!("test function not found")
}
}
/// Formats the given felts as a panic string.
pub fn format_for_panic(mut felts: IntoIter<Felt>) -> String {
let mut items = Vec::new();
while let Some(item) = format_next_item(&mut felts) {
items.push(item.quote_if_string());
}
let panic_values_string = if let [item] = &items[..] {
item.clone()
} else {
format!("({})", items.join(", "))
};
format!("Panicked with {panic_values_string}.")
}
/// Convert the execution result to a run result.
pub fn result_to_runresult(result: &ExecutionResult) -> anyhow::Result<RunResultValue> {
let is_success;
let mut felts: Vec<Felt> = Vec::new();
match &result.return_value {
outer_value @ Value::Enum {
tag,
value,
debug_name,
} => {
let debug_name = debug_name.as_ref().expect("missing debug name");
if debug_name.starts_with("core::panics::PanicResult::")
|| debug_name.starts_with("Enum<ut@core::panics::PanicResult::")
{
is_success = *tag == 0;
if !is_success {
match &**value {
Value::Struct { fields, .. } => {
for field in fields {
let felt = jitvalue_to_felt(field);
felts.extend(felt);
}
}
_ => bail!("unsuported return value in cairo-native"),
}
} else {
felts.extend(jitvalue_to_felt(value));
}
} else {
is_success = true;
felts.extend(jitvalue_to_felt(outer_value));
}
}
x => {
is_success = true;
felts.extend(jitvalue_to_felt(x));
}
}
let return_values = felts
.into_iter()
.map(|x| x.to_bigint().into())
.collect_vec();
Ok(match is_success {
true => RunResultValue::Success(return_values),
false => RunResultValue::Panic(return_values),
})
}
/// Convert a JIT value to a felt.
fn jitvalue_to_felt(value: &Value) -> Vec<Felt> {
let mut felts = Vec::new();
match value {
Value::Felt252(felt) => vec![*felt],
Value::BoundedInt { value, .. } => vec![*value],
Value::Array(fields) | Value::Struct { fields, .. } => {
fields.iter().flat_map(jitvalue_to_felt).collect()
}
Value::Enum {
value,
tag,
debug_name,
} => {
if let Some(debug_name) = debug_name {
if debug_name == "core::bool" {
vec![(*tag == 1).into()]
} else {
let mut felts = vec![(*tag).into()];
felts.extend(jitvalue_to_felt(value));
felts
}
} else {
// Assume its a regular enum.
let mut felts = vec![(*tag).into()];
felts.extend(jitvalue_to_felt(value));
felts
}
}
Value::Felt252Dict { value, .. } => {
for (key, value) in value {
felts.push(*key);
let felt = jitvalue_to_felt(value);
felts.extend(felt);
}
felts
}
Value::Uint8(x) => vec![(*x).into()],
Value::Uint16(x) => vec![(*x).into()],
Value::Uint32(x) => vec![(*x).into()],
Value::Uint64(x) => vec![(*x).into()],
Value::Uint128(x) => vec![(*x).into()],
Value::Sint8(x) => vec![(*x).into()],
Value::Sint16(x) => vec![(*x).into()],
Value::Sint32(x) => vec![(*x).into()],
Value::Sint64(x) => vec![(*x).into()],
Value::Sint128(x) => vec![(*x).into()],
Value::Bytes31(bytes) => vec![Felt::from_bytes_le_slice(bytes)],
Value::EcPoint(x, y) => {
vec![*x, *y]
}
Value::EcState(a, b, c, d) => {
vec![*a, *b, *c, *d]
}
Value::Secp256K1Point(Secp256k1Point {
x,
y,
is_infinity: _,
}) => {
vec![x.lo.into(), x.hi.into(), y.lo.into(), y.hi.into()]
}
Value::Secp256R1Point(Secp256r1Point {
x,
y,
is_infinity: _,
}) => {
vec![x.lo.into(), x.hi.into(), y.lo.into(), y.hi.into()]
}
Value::Null => vec![0.into()],
Value::IntRange { x, y } => [jitvalue_to_felt(x), jitvalue_to_felt(y)].concat(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use cairo_lang_sierra::ProgramParser;
use std::collections::HashMap;
/// Check if subsequence is present in sequence
fn is_subsequence<T: PartialEq>(subsequence: &[T], mut sequence: &[T]) -> bool {
for search in subsequence {
if let Some(index) = sequence.iter().position(|element| search == element) {
sequence = &sequence[index + 1..];
} else {
return false;
}
}
true
}
#[test]
fn test_find_function() {
// Parse a simple program containing a function named "Func2"
let program = ProgramParser::new().parse("Func2@6() -> ();").unwrap();
// Assert that the function "Func2" is found and returned correctly
assert_eq!(
find_function(&program, "Func2").unwrap(),
program.funcs.first().unwrap()
);
// Assert that an error is returned when trying to find a non-existing function "Func3"
assert!(find_function(&program, "Func3").is_err());
// Assert that an error is returned when trying to find a function in an empty program
assert!(find_function(&ProgramParser::new().parse("").unwrap(), "Func2").is_err());
}
#[test]
fn test_result_to_runresult_enum_nonpanic() {
// Tests the conversion of a non-panic enum result to a `RunResultValue::Success`.
assert_eq!(
result_to_runresult(&ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 34,
value: Value::Array(vec![
Value::Felt252(42.into()),
Value::Uint8(100),
Value::Uint128(1000),
])
.into(),
debug_name: Some("debug_name".into()),
},
builtin_stats: Default::default(),
})
.unwrap(),
RunResultValue::Success(vec![
Felt::from(34),
Felt::from(42),
Felt::from(100),
Felt::from(1000)
])
);
}
#[test]
fn test_result_to_runresult_success() {
// Tests the conversion of a success enum result to a `RunResultValue::Success`.
assert_eq!(
result_to_runresult(&ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 0,
value: Value::Uint64(24).into(),
debug_name: Some("core::panics::PanicResult::Test".into()),
},
builtin_stats: Default::default(),
})
.unwrap(),
RunResultValue::Success(vec![Felt::from(24)])
);
}
#[test]
#[should_panic(expected = "unsuported return value in cairo-native")]
fn test_result_to_runresult_panic() {
// Tests the conversion with unsuported return value.
let _ = result_to_runresult(&ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 10,
value: Value::Uint64(24).into(),
debug_name: Some("core::panics::PanicResult::Test".into()),
},
builtin_stats: Default::default(),
})
.unwrap();
}
#[test]
#[should_panic(expected = "missing debug name")]
fn test_result_to_runresult_missing_debug_name() {
// Tests the conversion with no debug name.
let _ = result_to_runresult(&ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 10,
value: Value::Uint64(24).into(),
debug_name: None,
},
builtin_stats: Default::default(),
})
.unwrap();
}
#[test]
fn test_result_to_runresult_return() {
// Tests the conversion of a panic enum result with non-zero tag to a `RunResultValue::Panic`.
assert_eq!(
result_to_runresult(&ExecutionResult {
remaining_gas: None,
return_value: Value::Enum {
tag: 10,
value: Value::Struct {
fields: vec![
Value::Felt252(42.into()),
Value::Uint8(100),
Value::Uint128(1000),
],
debug_name: Some("debug_name".into()),
}
.into(),
debug_name: Some("core::panics::PanicResult::Test".into()),
},
builtin_stats: Default::default(),
})
.unwrap(),
RunResultValue::Panic(vec![Felt::from(42), Felt::from(100), Felt::from(1000)])
);
}
#[test]
fn test_result_to_runresult_non_enum() {
// Tests the conversion of a non-enum result to a `RunResultValue::Success`.
assert_eq!(
result_to_runresult(&ExecutionResult {
remaining_gas: None,
return_value: Value::Uint8(10),
builtin_stats: Default::default(),
})
.unwrap(),
RunResultValue::Success(vec![Felt::from(10)])
);
}
#[test]
fn test_jitvalue_to_felt_felt252() {
let felt_value: Felt = 42.into();
assert_eq!(
jitvalue_to_felt(&Value::Felt252(felt_value)),
vec![felt_value]
);
}
#[test]
fn test_jitvalue_to_felt_array() {
assert_eq!(
jitvalue_to_felt(&Value::Array(vec![
Value::Felt252(42.into()),
Value::Uint8(100),
Value::Uint128(1000),
])),
vec![Felt::from(42), Felt::from(100), Felt::from(1000)]
);
}
#[test]
fn test_jitvalue_to_felt_struct() {
assert_eq!(
jitvalue_to_felt(&Value::Struct {
fields: vec![
Value::Felt252(42.into()),
Value::Uint8(100),
Value::Uint128(1000)
],
debug_name: Some("debug_name".into())
}),
vec![Felt::from(42), Felt::from(100), Felt::from(1000)]
);
}
#[test]
fn test_jitvalue_to_felt_enum() {
// With debug name
assert_eq!(
jitvalue_to_felt(&Value::Enum {
tag: 34,
value: Value::Array(vec![
Value::Felt252(42.into()),
Value::Uint8(100),
Value::Uint128(1000),
])
.into(),
debug_name: Some("debug_name".into())
}),
vec![
Felt::from(34),
Felt::from(42),
Felt::from(100),
Felt::from(1000)
]
);
// With core::bool debug name and tag 1
assert_eq!(
jitvalue_to_felt(&Value::Enum {
tag: 1,
value: Value::Uint128(1000).into(),
debug_name: Some("core::bool".into())
}),
vec![Felt::ONE]
);
// With core::bool debug name and tag not 1
assert_eq!(
jitvalue_to_felt(&Value::Enum {
tag: 10,
value: Value::Uint128(1000).into(),
debug_name: Some("core::bool".into())
}),
vec![Felt::ZERO]
);
}
#[test]
fn test_jitvalue_to_felt_u8() {
assert_eq!(jitvalue_to_felt(&Value::Uint8(10)), vec![Felt::from(10)]);
}
#[test]
fn test_jitvalue_to_felt_u16() {
assert_eq!(jitvalue_to_felt(&Value::Uint16(100)), vec![Felt::from(100)]);
}
#[test]
fn test_jitvalue_to_felt_u32() {
assert_eq!(
jitvalue_to_felt(&Value::Uint32(1000)),
vec![Felt::from(1000)]
);
}
#[test]
fn test_jitvalue_to_felt_u64() {
assert_eq!(
jitvalue_to_felt(&Value::Uint64(10000)),
vec![Felt::from(10000)]
);
}
#[test]
fn test_jitvalue_to_felt_u128() {
assert_eq!(
jitvalue_to_felt(&Value::Uint128(100000)),
vec![Felt::from(100000)]
);
}
#[test]
fn test_jitvalue_to_felt_sint8() {
assert_eq!(jitvalue_to_felt(&Value::Sint8(-10)), vec![Felt::from(-10)]);
}
#[test]
fn test_jitvalue_to_felt_sint16() {
assert_eq!(
jitvalue_to_felt(&Value::Sint16(-100)),
vec![Felt::from(-100)]
);
}
#[test]
fn test_jitvalue_to_felt_sint32() {
assert_eq!(
jitvalue_to_felt(&Value::Sint32(-1000)),
vec![Felt::from(-1000)]
);
}
#[test]
fn test_jitvalue_to_felt_sint64() {
assert_eq!(
jitvalue_to_felt(&Value::Sint64(-10000)),
vec![Felt::from(-10000)]
);
}
#[test]
fn test_jitvalue_to_felt_sint128() {
assert_eq!(
jitvalue_to_felt(&Value::Sint128(-100000)),
vec![Felt::from(-100000)]
);
}
#[test]
fn test_jitvalue_to_felt_null() {
assert_eq!(jitvalue_to_felt(&Value::Null), vec![Felt::ZERO]);
}
#[test]
fn test_jitvalue_to_felt_felt252_dict() {
let result = jitvalue_to_felt(&Value::Felt252Dict {
value: HashMap::from([
(Felt::ONE, Value::Felt252(Felt::from(101))),
(Felt::TWO, Value::Felt252(Felt::from(102))),
]),
debug_name: None,
});
let first_dict_entry = vec![Felt::from(1), Felt::from(101)];
let second_dict_entry = vec![Felt::from(2), Felt::from(102)];
// Check that the two Key, value pairs are in the result
assert!(is_subsequence(&first_dict_entry, &result));
assert!(is_subsequence(&second_dict_entry, &result));
}
#[test]
fn test_jitvalue_to_felt_felt252_dict_with_array() {
let result = jitvalue_to_felt(&Value::Felt252Dict {
value: HashMap::from([
(
Felt::ONE,
Value::Array(Vec::from([
Value::Felt252(Felt::from(101)),
Value::Felt252(Felt::from(102)),
])),
),
(
Felt::TWO,
Value::Array(Vec::from([
Value::Felt252(Felt::from(201)),
Value::Felt252(Felt::from(202)),
])),
),
]),
debug_name: None,
});
let first_dict_entry = vec![Felt::from(1), Felt::from(101), Felt::from(102)];
let second_dict_entry = vec![Felt::from(2), Felt::from(201), Felt::from(202)];
// Check that the two Key, value pairs are in the result
assert!(is_subsequence(&first_dict_entry, &result));
assert!(is_subsequence(&second_dict_entry, &result));
}
#[test]
fn test_jitvalue_to_felt_ec_point() {
assert_eq!(
jitvalue_to_felt(&Value::EcPoint(Felt::ONE, Felt::TWO,)),
vec![Felt::ONE, Felt::TWO,]
);
}
#[test]
fn test_jitvalue_to_felt_ec_state() {
assert_eq!(
jitvalue_to_felt(&Value::EcState(
Felt::ONE,
Felt::TWO,
Felt::THREE,
Felt::from(4)
)),
vec![Felt::ONE, Felt::TWO, Felt::THREE, Felt::from(4)]
);
}
#[test]
fn test_jitvalue_to_felt_secp256_k1_point() {
assert_eq!(
jitvalue_to_felt(&Value::Secp256K1Point(Secp256k1Point::new(
1, 2, 3, 4, false
))),
vec![Felt::ONE, Felt::TWO, Felt::THREE, Felt::from(4)]
);
}
#[test]
fn test_jitvalue_to_felt_secp256_r1_point() {
assert_eq!(
jitvalue_to_felt(&Value::Secp256R1Point(Secp256r1Point::new(
1, 2, 3, 4, false
))),
vec![Felt::ONE, Felt::TWO, Felt::THREE, Felt::from(4)]
);
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/cairo-native-dump/src/main.rs | binaries/cairo-native-dump/src/main.rs | use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
};
use cairo_lang_defs::plugin::NamedPlugin;
use cairo_lang_filesystem::ids::CrateInput;
use cairo_lang_semantic::plugin::PluginSuite;
use cairo_lang_sierra::{program::Program, ProgramParser};
use cairo_lang_starknet::{
compile::compile_contract_in_prepared_db, inline_macros::selector::SelectorMacro,
plugin::StarknetPlugin,
};
use cairo_native::context::NativeContext;
use clap::Parser;
use melior::ir::operation::OperationPrintingFlags;
use std::{
ffi::OsStr,
fs,
path::{Path, PathBuf},
sync::Arc,
};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Parse command-line arguments.
let args = CmdLine::parse();
// Configure logging and error handling.
tracing::subscriber::set_global_default(
FmtSubscriber::builder()
.with_env_filter(EnvFilter::from_default_env())
.finish(),
)?;
// Load the program.
let context = NativeContext::new();
let program = load_program(Path::new(&args.input), args.starknet)?;
// Compile the program.
let module = context.compile(&program, false, Some(Default::default()), None)?;
// Write the output.
let output_str = module
.module()
.as_operation()
.to_string_with_flags(OperationPrintingFlags::new().enable_debug_info(true, false))?;
match args.output {
CompilerOutput::Stdout => println!("{output_str}"),
CompilerOutput::Path(path) => fs::write(path, &output_str)?,
}
Ok(())
}
fn load_program(path: &Path, is_contract: bool) -> Result<Program, Box<dyn std::error::Error>> {
Ok(match path.extension().and_then(OsStr::to_str) {
Some("cairo") if !is_contract => {
let mut db = RootDatabase::builder().detect_corelib().build()?;
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, path).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
compile_prepared_db(
&db,
main_crate_ids,
CompilerConfig {
replace_ids: true,
..Default::default()
},
)?
.program
}
Some("cairo") if is_contract => {
// mimics cairo_lang_starknet::contract_class::compile_path
let mut plugins = PluginSuite::default();
plugins
.add_plugin::<StarknetPlugin>()
.add_inline_macro_plugin_ex(SelectorMacro::NAME, Arc::new(SelectorMacro));
let mut db = RootDatabase::builder()
.detect_corelib()
.with_default_plugin_suite(plugins)
.build()?;
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, path).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let contract = compile_contract_in_prepared_db(
&db,
None,
main_crate_ids,
CompilerConfig {
replace_ids: true,
..Default::default()
},
)?;
contract.extract_sierra_program()?
}
Some("sierra") => {
let program_src = fs::read_to_string(path)?;
let program_parser = ProgramParser::new();
program_parser
.parse(&program_src)
.map_err(|e| e.map_token(|t| t.to_string()))?
}
_ => unreachable!(),
})
}
#[derive(Clone, Debug, Parser)]
struct CmdLine {
#[clap(value_parser = parse_input)]
input: PathBuf,
#[clap(short = 'o', long = "output", value_parser = parse_output, default_value = "-")]
output: CompilerOutput,
/// Compile a starknet contract
#[clap(long)]
starknet: bool,
}
#[derive(Clone, Debug)]
enum CompilerOutput {
Stdout,
Path(PathBuf),
}
fn parse_input(input: &str) -> Result<PathBuf, String> {
Ok(match Path::new(input).extension().and_then(OsStr::to_str) {
Some("cairo" | "sierra") => input.into(),
_ => {
return Err(
"Input path expected to have either `cairo` or `sierra` as its extension."
.to_string(),
)
}
})
}
fn parse_output(input: &str) -> Result<CompilerOutput, String> {
Ok(if input == "-" {
CompilerOutput::Stdout
} else {
CompilerOutput::Path(match Path::new(input).extension().and_then(OsStr::to_str) {
Some("mlir") => input.into(),
_ => {
return Err(
"Output path expected to be `-` for stdout or have `mlir` as its extension."
.to_string(),
)
}
})
})
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/starknet-native-compile/src/main.rs | binaries/starknet-native-compile/src/main.rs | use anyhow::{anyhow, bail, Context};
use cairo_native::statistics::Statistics;
use std::fs;
use std::path::PathBuf;
use cairo_lang_sierra::program::Program;
use cairo_lang_starknet_classes::compiler_version::VersionId;
use cairo_lang_starknet_classes::contract_class::ContractClass;
use cairo_native::executor::AotContractExecutor;
use clap::Parser;
/// Given a Sierra file (as saved in Starknet's contract tree), extracts the sierra_program from
/// felts into readable Sierra code, compiles it to native, and saves the result to the given output
/// path.
#[derive(Parser, Debug)]
#[clap(version, verbatim_doc_comment)]
struct Args {
/// The path of the Sierra file to compile.
path: PathBuf,
/// Optimization level, Valid: 0, 1, 2, 3. Values higher than 3 are considered as 3.
#[arg(short = 'O', long, default_value_t = 0)]
opt_level: u8,
/// The output file path.
output: PathBuf,
#[arg(long)]
/// Output path for compilation statistics
stats: Option<PathBuf>,
}
fn main() -> anyhow::Result<()> {
let args = Args::parse();
let (contract_class, sierra_program, sierra_version) =
load_sierra_program_from_file(&args.path)?;
let mut stats_with_path = args.stats.map(|path| (Statistics::default(), path));
let stats = stats_with_path.as_mut().map(|v| &mut v.0);
AotContractExecutor::new_into(
&sierra_program,
&contract_class.entry_points_by_type,
sierra_version,
args.output.clone(),
args.opt_level.into(),
stats,
)
.context("Error compiling Sierra program.")?
.with_context(|| format!("Failed to take lock on path {}", args.output.display()))?;
if let Some((stats, path)) = stats_with_path {
fs::write(path.with_extension("json"), serde_json::to_string(&stats)?)?;
}
Ok(())
}
/// Extracts the first 3 felts from the Sierra program and parses them into a VersionId.
fn get_sierra_version_from_program<F>(sierra_program: &[F]) -> anyhow::Result<VersionId>
where
F: TryInto<usize> + std::fmt::Display + Clone,
<F as TryInto<usize>>::Error: std::fmt::Display,
{
if sierra_program.len() < 3 {
bail!("Sierra program length must be at least 3 Felts.");
}
let version_components: Vec<usize> = sierra_program
.iter()
.take(3)
.enumerate()
.map(|(index, felt)| {
felt.clone().try_into().map_err(|err| {
anyhow!(
"Failed to parse Sierra program to Sierra version. Index: {}, Felt: {}, \
Error: {}",
index,
felt,
err
)
})
})
.collect::<Result<_, _>>()?;
Ok(VersionId {
major: version_components[0],
minor: version_components[1],
patch: version_components[2],
})
}
/// Given a Sierra file path, loads the contract class from it, extracts the sierra version from the
/// first 3 felts of the compressed sierra_program, and extracts the compressed sierra_program into
/// readable sierra code.
fn load_sierra_program_from_file(
path: &PathBuf,
) -> anyhow::Result<(ContractClass, Program, VersionId)> {
let raw_contract_class = std::fs::read_to_string(path).context("Error reading Sierra file.")?;
let contract_class: ContractClass = serde_json::from_str(&raw_contract_class)
.context("Error deserializing Sierra file into contract class.")?;
let raw_sierra_program: Vec<_> = contract_class
.sierra_program
.iter()
.map(|big_uint_as_hex| big_uint_as_hex.value.clone())
.collect();
let sierra_version = get_sierra_version_from_program(&raw_sierra_program)?;
Ok((
contract_class.clone(),
contract_class
.extract_sierra_program()
.context("Error extracting Sierra program from contract class.")?,
sierra_version,
))
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/cairo-native-compile/src/main.rs | binaries/cairo-native-compile/src/main.rs | use anyhow::Context;
use cairo_lang_compiler::project::check_compiler_path;
use cairo_native::{
clone_option_mut, context::NativeContext, module_to_object, object_to_shared_lib,
statistics::Statistics, utils::testing::cairo_to_sierra,
};
use clap::Parser;
use std::{
fs::{self, File},
path::PathBuf,
sync::Arc,
time::Instant,
};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
/// Compiles Cairo/Sierra to Native machine code.
/// Outputs the generated MLIR, and the final shared library.
///
/// Supports different types of inputs:
/// - Cairo project (default)
/// - Standalone Cairo file (with the --single-file option).
/// - Standalone Sierra JSON file (with the --sierra-json option).
///
/// There is no easy way of executing the compiled shared library, so this
/// binary is mostly used for debugging compilation.
///
/// Exits with 1 if the compilation or run fails, otherwise 0.
#[derive(Parser, Debug)]
#[clap(version, verbatim_doc_comment)]
struct Args {
/// The input path to compile.
/// By default, it is intrepreted as a Cairo project.
path: PathBuf,
/// Whether path is a single Cairo file.
#[arg(short, long, group = "input")]
single_file: bool,
/// Whether path is a single Sierra JSON file.
#[arg(long, group = "input")]
sierra_json: bool,
/// Optimization level (Valid: 0, 1, 2, 3).
/// Values higher than 3 are considered as 3.
#[arg(short = 'O', long, default_value_t = 0)]
opt_level: u8,
/// The output path for the generated MLIR.
#[arg(default_value = "out.mlir")]
output_mlir: PathBuf,
/// The output path for the shared library.
#[cfg_attr(target_os = "macos", arg(default_value = "out.dylib"))]
#[cfg_attr(not(target_os = "macos"), arg(default_value = "out.so"))]
output_library: PathBuf,
/// The compilation statistics path.
#[arg(long)]
stats_path: Option<PathBuf>,
}
fn main() -> anyhow::Result<()> {
// Configure logging and error handling.
tracing::subscriber::set_global_default(
FmtSubscriber::builder()
.with_env_filter(EnvFilter::from_default_env())
.finish(),
)?;
let args = Args::parse();
// First, we obtain the sierra program. If the --sierra-json file was
// given, we read the input as Sierra directly. Otherwise, we compile Cairo
// to Sierra.
let sierra_program = if args.sierra_json {
let sierra_file = File::open(&args.path)?;
let program =
serde_json::from_reader(sierra_file).context("Failed to read Sierra JSON file.")?;
Arc::new(program)
} else {
// Check if args.path is a file or a directory.
check_compiler_path(args.single_file, &args.path)?;
cairo_to_sierra(&args.path).context("Failed to compile Cairo to Sierra.")?
};
let mut stats_with_path = args.stats_path.map(|path| (Statistics::default(), path));
let stats = stats_with_path.as_mut().map(|v| &mut v.0);
let pre_compilation_instant = Instant::now();
// Compile the sierra program into a MLIR module.
let native_context = NativeContext::new();
let native_module = native_context
.compile(
&sierra_program,
false,
Some(Default::default()),
clone_option_mut!(stats),
)
.context("Failed to compile to MLIR.")?;
std::fs::write(
args.output_mlir,
native_module.module().as_operation().to_string(),
)
.context("Failed to write MLIR output.")?;
let object_data = module_to_object(
native_module.module(),
args.opt_level.into(),
clone_option_mut!(stats),
)
.context("Failed to convert MLIR to object.")?;
object_to_shared_lib(&object_data, &args.output_library, clone_option_mut!(stats))
.context("Failed to write shared library.")?;
let compilation_time = pre_compilation_instant.elapsed().as_millis();
if let Some(&mut ref mut stats) = stats {
stats.compilation_total_time_ms = Some(compilation_time);
}
if let Some((stats, stats_path)) = stats_with_path {
fs::write(stats_path, serde_json::to_string_pretty(&stats)?)?;
}
Ok(())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/cairo-native-run/src/main.rs | binaries/cairo-native-run/src/main.rs | use anyhow::Context;
use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
};
use cairo_lang_filesystem::ids::CrateInput;
use cairo_lang_runner::short_string::as_cairo_short_string;
#[cfg(feature = "with-libfunc-profiling")]
use cairo_lang_sierra::ids::ConcreteLibfuncId;
use cairo_lang_sierra_to_casm::metadata::MetadataComputationConfig;
use cairo_lang_sierra_type_size::ProgramRegistryInfo;
#[cfg(feature = "with-libfunc-profiling")]
use cairo_native::metadata::profiler::LibfuncProfileData;
use cairo_native::{
context::NativeContext,
executor::{AotNativeExecutor, JitNativeExecutor},
metadata::gas::GasMetadata,
starknet_stub::StubSyscallHandler,
};
use cairo_native_bin_utils::{find_function, result_to_runresult};
use clap::{Parser, ValueEnum};
#[cfg(feature = "with-libfunc-profiling")]
use std::collections::HashMap;
use std::path::PathBuf;
use tracing_subscriber::{EnvFilter, FmtSubscriber};
#[derive(Clone, Debug, ValueEnum)]
enum RunMode {
Aot,
Jit,
}
/// Command line args parser.
/// Exits with 1 if the compilation or run fails, otherwise 0.
#[derive(Parser, Debug)]
#[clap(version, verbatim_doc_comment)]
struct Args {
/// The Cairo project path to compile and run its tests.
path: PathBuf,
/// Whether path is a single file.
#[arg(short, long)]
single_file: bool,
/// Allows the compilation to succeed with warnings.
#[arg(long)]
allow_warnings: bool,
/// In cases where gas is available, the amount of provided gas.
#[arg(long)]
available_gas: Option<u64>,
/// Run with JIT or AOT (compiled).
#[arg(long, value_enum, default_value_t = RunMode::Jit)]
run_mode: RunMode,
/// Optimization level, Valid: 0, 1, 2, 3. Values higher than 3 are considered as 3.
#[arg(short = 'O', long, default_value_t = 0)]
opt_level: u8,
#[cfg(feature = "with-libfunc-profiling")]
#[arg(long)]
/// The output path for the libfunc profilling results
profiler_output: Option<PathBuf>,
#[cfg(feature = "with-trace-dump")]
#[arg(long)]
/// The output path for the execution trace
trace_output: Option<PathBuf>,
#[cfg(feature = "with-trace-dump")]
#[arg(long)]
/// The output path for the compiled sierra code
sierra_output: Option<PathBuf>,
}
fn main() -> anyhow::Result<()> {
// Configure logging and error handling.
tracing::subscriber::set_global_default(
FmtSubscriber::builder()
.with_env_filter(EnvFilter::from_default_env())
.finish(),
)?;
let args = Args::parse();
let mut db = RootDatabase::builder().detect_corelib().build()?;
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, &args.path).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let sierra_program = compile_prepared_db(
&db,
main_crate_ids,
CompilerConfig {
replace_ids: true,
..Default::default()
},
)?
.program;
#[cfg(feature = "with-trace-dump")]
if let Some(sierra_output) = args.sierra_output {
use std::fs::File;
use std::io::Write;
let mut file = File::create(sierra_output).unwrap();
write!(file, "{}", &sierra_program).unwrap();
}
let native_context = NativeContext::new();
// Compile the sierra program into a MLIR module.
let native_module = native_context
.compile(&sierra_program, false, Some(Default::default()), None)
.unwrap();
let native_executor: Box<dyn Fn(_, _, _, &mut StubSyscallHandler) -> _> = match args.run_mode {
RunMode::Aot => {
let executor =
AotNativeExecutor::from_native_module(native_module, args.opt_level.into())?;
#[cfg(feature = "with-trace-dump")]
{
use cairo_native::metadata::trace_dump::TraceBinding;
if let Some(trace_id) = executor.find_symbol_ptr(TraceBinding::TraceId.symbol()) {
let trace_id = trace_id.cast::<u64>();
unsafe { *trace_id = 0 };
}
}
Box::new(move |function_id, args, gas, syscall_handler| {
executor.invoke_dynamic_with_syscall_handler(
function_id,
args,
gas,
syscall_handler,
)
})
}
RunMode::Jit => {
let executor =
JitNativeExecutor::from_native_module(native_module, args.opt_level.into())?;
#[cfg(feature = "with-trace-dump")]
{
use cairo_native::metadata::trace_dump::TraceBinding;
if let Some(trace_id) = executor.find_symbol_ptr(TraceBinding::TraceId.symbol()) {
let trace_id = trace_id.cast::<u64>();
unsafe { *trace_id = 0 };
}
}
#[cfg(feature = "with-libfunc-profiling")]
{
use cairo_native::metadata::profiler::ProfilerBinding;
if let Some(trace_id) =
executor.find_symbol_ptr(ProfilerBinding::ProfileId.symbol())
{
let trace_id = trace_id.cast::<u64>();
unsafe { *trace_id = 0 };
}
}
Box::new(move |function_id, args, gas, syscall_handler| {
executor.invoke_dynamic_with_syscall_handler(
function_id,
args,
gas,
syscall_handler,
)
})
}
};
#[cfg(feature = "with-trace-dump")]
{
use cairo_lang_sierra::program_registry::ProgramRegistry;
use cairo_native::metadata::trace_dump::trace_dump_runtime::{TraceDump, TRACE_DUMP};
TRACE_DUMP.lock().unwrap().insert(
0,
TraceDump::new(ProgramRegistry::new(&sierra_program).unwrap()),
);
}
#[cfg(feature = "with-libfunc-profiling")]
{
use cairo_native::metadata::profiler::{ProfilerImpl, LIBFUNC_PROFILE};
LIBFUNC_PROFILE
.lock()
.unwrap()
.insert(0, ProfilerImpl::new());
}
let gas_metadata = GasMetadata::new(
&sierra_program,
&ProgramRegistryInfo::new(&sierra_program)?,
Some(MetadataComputationConfig::default()),
)
.unwrap();
let func = find_function(&sierra_program, "::main")?;
let initial_gas = gas_metadata
.get_initial_available_gas(&func.id, args.available_gas)
.with_context(|| "not enough gas to run")?;
let mut syscall_handler = StubSyscallHandler::default();
let result = native_executor(&func.id, &[], Some(initial_gas), &mut syscall_handler)
.with_context(|| "Failed to run the function.")?;
let run_result = result_to_runresult(&result)?;
match run_result {
cairo_lang_runner::RunResultValue::Success(values) => {
println!("Run completed successfully, returning {values:?}")
}
cairo_lang_runner::RunResultValue::Panic(values) => {
print!("Run panicked with [");
for value in &values {
match as_cairo_short_string(value) {
Some(as_string) => print!("{value} ('{as_string}'), "),
None => print!("{value}, "),
}
}
println!("].")
}
}
if let Some(gas) = result.remaining_gas {
println!("Remaining gas: {gas}");
}
#[cfg(feature = "with-libfunc-profiling")]
{
use std::{fs::File, io::Write};
let profile = cairo_native::metadata::profiler::LIBFUNC_PROFILE
.lock()
.unwrap();
assert_eq!(profile.values().len(), 1);
let profile = profile.values().next().unwrap();
if let Some(profiler_output_path) = args.profiler_output {
let mut output = File::create(profiler_output_path)?;
let raw_profile = profile.get_profile(&sierra_program);
let mut processed_profile = process_profile(raw_profile);
processed_profile.sort_by_key(|LibfuncProfileSummary { libfunc_idx, .. }| {
sierra_program
.libfunc_declarations
.iter()
.enumerate()
.find_map(|(i, x)| (x.id == *libfunc_idx).then_some(i))
.unwrap()
});
for LibfuncProfileSummary {
libfunc_idx,
samples,
total_time,
average_time,
std_deviation,
quartiles,
} in processed_profile
{
writeln!(output, "{libfunc_idx}")?;
writeln!(output, " Total Samples: {samples}")?;
let (Some(total_time), Some(average_time), Some(std_deviation), Some(quartiles)) =
(total_time, average_time, std_deviation, quartiles)
else {
writeln!(output, " Total Execution Time: none")?;
writeln!(output, " Average Execution Time: none")?;
writeln!(output, " Standard Deviation: none")?;
writeln!(output, " Quartiles: none")?;
writeln!(output)?;
continue;
};
writeln!(output, " Total Execution Time: {total_time}")?;
writeln!(output, " Average Execution Time: {average_time}")?;
writeln!(output, " Standard Deviation: {std_deviation}")?;
writeln!(output, " Quartiles: {quartiles:?}")?;
writeln!(output)?;
}
}
}
#[cfg(feature = "with-trace-dump")]
if let Some(trace_output) = args.trace_output {
let traces = cairo_native::metadata::trace_dump::trace_dump_runtime::TRACE_DUMP
.lock()
.unwrap();
assert_eq!(traces.len(), 1);
let trace_dump = traces.values().next().unwrap();
serde_json::to_writer_pretty(
std::fs::File::create(trace_output).unwrap(),
&trace_dump.trace,
)
.unwrap();
}
Ok(())
}
#[cfg(feature = "with-libfunc-profiling")]
struct LibfuncProfileSummary {
pub libfunc_idx: ConcreteLibfuncId,
pub samples: u64,
pub total_time: Option<u64>,
pub average_time: Option<f64>,
pub std_deviation: Option<f64>,
pub quartiles: Option<[u64; 5]>,
}
#[cfg(feature = "with-libfunc-profiling")]
fn process_profile(
profiles: HashMap<ConcreteLibfuncId, LibfuncProfileData>,
) -> Vec<LibfuncProfileSummary> {
profiles
.into_iter()
.map(
|(
libfunc_idx,
LibfuncProfileData {
mut deltas,
extra_counts,
},
)| {
// if no deltas were registered, we only return the libfunc's calls amount
if deltas.is_empty() {
return LibfuncProfileSummary {
libfunc_idx,
samples: extra_counts,
total_time: None,
average_time: None,
std_deviation: None,
quartiles: None,
};
}
deltas.sort();
// Drop outliers.
{
let q1 = deltas[deltas.len() / 4];
let q3 = deltas[3 * deltas.len() / 4];
let iqr = q3 - q1;
let q1_thr = q1.saturating_sub(iqr + iqr / 2);
let q3_thr = q3 + (iqr + iqr / 2);
deltas.retain(|x| *x >= q1_thr && *x <= q3_thr);
}
// Compute the quartiles.
let quartiles = [
*deltas.first().unwrap(),
deltas[deltas.len() / 4],
deltas[deltas.len() / 2],
deltas[3 * deltas.len() / 4],
*deltas.last().unwrap(),
];
// Compute the average.
let average = deltas.iter().copied().sum::<u64>() as f64 / deltas.len() as f64;
// Compute the standard deviation.
let std_dev = {
let sum = deltas
.iter()
.copied()
.map(|x| x as f64)
.map(|x| (x - average))
.map(|x| x * x)
.sum::<f64>();
sum / (deltas.len() as u64 + extra_counts) as f64
};
LibfuncProfileSummary {
libfunc_idx,
samples: deltas.len() as u64 + extra_counts,
total_time: Some(
deltas.iter().sum::<u64>() + (extra_counts as f64 * average).round() as u64,
),
average_time: Some(average),
std_deviation: Some(std_dev),
quartiles: Some(quartiles),
}
},
)
.collect::<Vec<_>>()
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/binaries/scarb-native-dump/src/main.rs | binaries/scarb-native-dump/src/main.rs | use anyhow::Context;
use cairo_lang_sierra::program::VersionedProgram;
use cairo_native::context::NativeContext;
use melior::ir::operation::OperationPrintingFlags;
use scarb_metadata::{MetadataCommand, ScarbCommand};
use std::{env, fs};
/// Compiles all packages from a Scarb project on the current directory.
fn main() -> anyhow::Result<()> {
let metadata = MetadataCommand::new().inherit_stderr().exec()?;
// Build only the filtered packages.
ScarbCommand::new().arg("build").run()?;
// Get `target` directory.
let profile = env::var("SCARB_PROFILE").unwrap_or("dev".into());
let default_target_dir = metadata.runtime_manifest.join("target");
let target_dir = metadata
.target_dir
.clone()
.unwrap_or(default_target_dir)
.join(profile);
let native_context = NativeContext::new();
for package in metadata.packages.iter() {
for target in &package.targets {
let file_path = target_dir.join(format!("{}.sierra.json", target.name.clone()));
if file_path.exists() {
let compiled = serde_json::from_str::<VersionedProgram>(
&fs::read_to_string(file_path.clone())
.with_context(|| format!("failed to read file: {file_path}"))?,
)
.with_context(|| format!("failed to deserialize compiled file: {file_path}"))?;
// Compile the sierra program into a MLIR module.
let native_module = native_context
.compile(
&compiled.into_v1().unwrap().program,
false,
Some(Default::default()),
None,
)
.unwrap();
// Write the output.
let output_str = native_module.module().as_operation().to_string_with_flags(
OperationPrintingFlags::new().enable_debug_info(true, false),
)?;
fs::write(
target_dir.join(format!("{}.mlir", target.name.clone())),
&output_str,
)?;
}
}
}
Ok(())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/benches/compile_time.rs | benches/compile_time.rs | use cairo_native::{context::NativeContext, module_to_object, OptLevel};
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
use util::prepare_programs;
mod util;
pub fn bench_compile_time(c: &mut Criterion) {
let programs = prepare_programs("programs/compile_benches");
{
let mut c = c.benchmark_group("Compilation With Independent Context");
for (program, filename) in &programs {
c.bench_with_input(BenchmarkId::new(filename, 1), &program, |b, program| {
b.iter(|| {
let native_context = NativeContext::new();
native_context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// pass manager internally verifies the MLIR output is correct.
})
});
}
}
{
let mut c = c.benchmark_group("Compilation With Shared Context");
let native_context = NativeContext::new();
for (program, filename) in &programs {
c.bench_with_input(BenchmarkId::new(filename, 1), &program, |b, program| {
b.iter(|| {
native_context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// pass manager internally verifies the MLIR output is correct.
})
});
}
}
{
let mut c = c.benchmark_group("Compilation With Independent Context To Object Code");
for (program, filename) in &programs {
c.bench_with_input(BenchmarkId::new(filename, 1), &program, |b, program| {
b.iter(|| {
let native_context = NativeContext::new();
let module = native_context
.compile(black_box(program), false, Some(Default::default()), None)
.unwrap();
let object = module_to_object(module.module(), OptLevel::None, None)
.expect("to compile correctly to a object file");
black_box(object)
})
});
}
}
{
let mut c = c.benchmark_group("Compilation With Shared Context To Object Code");
let native_context = NativeContext::new();
for (program, filename) in &programs {
c.bench_with_input(BenchmarkId::new(filename, 1), &program, |b, program| {
b.iter(|| {
let module = native_context
.compile(black_box(program), false, Some(Default::default()), None)
.unwrap();
let object = module_to_object(module.module(), OptLevel::None, None)
.expect("to compile correctly to a object file");
black_box(object)
})
});
}
}
{
let mut c = c.benchmark_group("Compilation With Shared Context To Object Code With -O3");
let native_context = NativeContext::new();
for (program, filename) in &programs {
c.bench_with_input(BenchmarkId::new(filename, 1), &program, |b, program| {
b.iter(|| {
let module = native_context
.compile(black_box(program), false, Some(Default::default()), None)
.unwrap();
let object = module_to_object(module.module(), OptLevel::Aggressive, None)
.expect("to compile correctly to a object file");
black_box(object)
})
});
}
}
}
criterion_group!(benches, bench_compile_time);
criterion_main!(benches);
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/benches/util.rs | benches/util.rs | #![cfg(feature = "testing")]
use cairo_lang_runner::SierraCasmRunner;
use cairo_lang_sierra::program::Program;
use std::sync::Arc;
use walkdir::WalkDir;
pub fn prepare_programs(path: &str) -> Vec<(Arc<Program>, String)> {
WalkDir::new(path)
.into_iter()
.filter_map(|entry| {
let e = entry.unwrap();
let path = e.path();
match path.extension().map(|x| x.to_str().unwrap()) {
Some("cairo") => Some((
cairo_native::utils::testing::cairo_to_sierra(path).unwrap(),
path.display().to_string(),
)),
_ => None,
}
})
.collect::<Vec<_>>()
}
#[allow(unused)] // its used but clippy doesn't detect it well
pub fn create_vm_runner(program: &Program) -> SierraCasmRunner {
SierraCasmRunner::new(
program.clone(),
Some(Default::default()),
Default::default(),
None,
)
.unwrap()
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/benches/libfuncs.rs | benches/libfuncs.rs | use cairo_lang_runner::StarknetState;
use cairo_native::{
context::NativeContext,
executor::{AotNativeExecutor, JitNativeExecutor},
OptLevel,
};
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
use util::{create_vm_runner, prepare_programs};
mod util;
pub fn bench_libfuncs(c: &mut Criterion) {
let programs = prepare_programs("tests/cases");
{
let mut c = c.benchmark_group("Libfunc Execution Time");
for (program, filename) in &programs {
let entry = program
.funcs
.iter()
.find(|f| {
if let Some(name) = &f.id.debug_name {
name.ends_with("main")
} else {
false
}
})
.expect("failed to find entry point");
let vm_runner = create_vm_runner(program);
c.bench_with_input(
BenchmarkId::new(filename, "SierraCasmRunner"),
&program,
|b, _program| {
b.iter(|| {
let res = vm_runner
.run_function_with_starknet_context(
entry,
vec![],
Some(usize::MAX),
StarknetState::default(),
)
.expect("should run correctly");
black_box(res)
})
},
);
c.bench_with_input(
BenchmarkId::new(filename, "jit-cold"),
&program,
|b, program| {
let native_context = NativeContext::new();
b.iter(|| {
let module = native_context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// pass manager internally verifies the MLIR output is correct.
let native_executor =
JitNativeExecutor::from_native_module(module, OptLevel::Aggressive)
.unwrap();
// Execute the program.
let result = native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX))
.unwrap();
black_box(result)
})
},
);
c.bench_with_input(
BenchmarkId::new(filename, "jit-hot"),
program,
|b, program| {
let native_context = NativeContext::new();
let module = native_context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// pass manager internally verifies the MLIR output is correct.
let native_executor =
JitNativeExecutor::from_native_module(module, OptLevel::Aggressive)
.unwrap();
// warmup
for _ in 0..5 {
native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX))
.unwrap();
}
b.iter(|| {
// Execute the program.
let result = native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX))
.unwrap();
black_box(result)
})
},
);
c.bench_with_input(
BenchmarkId::new(filename, "aot-with-compile"),
&program,
|b, program| {
let native_context = NativeContext::new();
b.iter(|| {
let module = native_context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// pass manager internally verifies the MLIR output is correct.
let native_executor =
AotNativeExecutor::from_native_module(module, OptLevel::Aggressive)
.unwrap();
// Execute the program.
let result = native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX))
.unwrap();
black_box(result)
})
},
);
c.bench_with_input(
BenchmarkId::new(filename, "aot-without-compile"),
program,
|b, program| {
let native_context = NativeContext::new();
let module = native_context
.compile(program, false, Some(Default::default()), None)
.unwrap();
// pass manager internally verifies the MLIR output is correct.
let native_executor =
AotNativeExecutor::from_native_module(module, OptLevel::Aggressive)
.unwrap();
// warmup
for _ in 0..5 {
native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX))
.unwrap();
}
b.iter(|| {
// Execute the program.
let result = native_executor
.invoke_dynamic(&entry.id, &[], Some(u64::MAX))
.unwrap();
black_box(result)
})
},
);
}
}
}
criterion_group!(benches, bench_libfuncs);
criterion_main!(benches);
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/benches/benches.rs | benches/benches.rs | use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
};
use cairo_lang_filesystem::ids::CrateInput;
use cairo_lang_runner::{RunResultValue, SierraCasmRunner, StarknetState};
use cairo_lang_sierra::program::Program;
use cairo_lang_sierra_generator::replace_ids::DebugReplacer;
use cairo_lang_starknet::contract::{find_contracts, get_contracts_info};
use cairo_native::{
cache::{AotProgramCache, JitProgramCache},
context::NativeContext,
utils::find_function_id,
OptLevel, Value,
};
use criterion::{criterion_group, criterion_main, Criterion};
use starknet_types_core::felt::Felt;
use std::path::Path;
fn compare(c: &mut Criterion, path: impl AsRef<Path>) {
let context = NativeContext::new();
let mut aot_cache = AotProgramCache::new(&context);
let mut jit_cache = JitProgramCache::new(&context);
let stem = path
.as_ref()
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_string();
let program = load_contract(&path);
let aot_executor = aot_cache
.compile_and_insert(Felt::ZERO, &program, OptLevel::Aggressive)
.unwrap();
let jit_executor = jit_cache
.compile_and_insert(Felt::ZERO, &program, OptLevel::Aggressive)
.unwrap();
let main_name = format!("{stem}::{stem}::main");
let main_id = find_function_id(&program, &main_name).unwrap();
let vm_runner = load_contract_for_vm(&path);
let vm_main_id = vm_runner
.find_function("main")
.expect("failed to find main function");
let mut group = c.benchmark_group(stem);
group.bench_function("Cached JIT", |b| {
b.iter(|| {
let result = jit_executor
.invoke_dynamic(main_id, &[], Some(u64::MAX))
.unwrap();
let value = result.return_value;
assert!(matches!(value, Value::Enum { tag: 0, .. }))
});
});
group.bench_function("Cached AOT", |b| {
b.iter(|| {
let result = aot_executor
.invoke_dynamic(main_id, &[], Some(u64::MAX))
.unwrap();
let value = result.return_value;
assert!(matches!(value, Value::Enum { tag: 0, .. }))
});
});
group.bench_function("VM", |b| {
b.iter(|| {
let result = vm_runner
.run_function_with_starknet_context(
vm_main_id,
vec![],
Some(usize::MAX),
StarknetState::default(),
)
.unwrap();
let value = result.value;
assert!(matches!(value, RunResultValue::Success(_)))
});
});
group.finish();
}
fn criterion_benchmark(c: &mut Criterion) {
// compare(c, "programs/benches/heavy_circuit.cairo");
compare(c, "programs/benches/dict_snapshot.cairo");
compare(c, "programs/benches/dict_insert.cairo");
compare(c, "programs/benches/factorial_2M.cairo");
compare(c, "programs/benches/fib_2M.cairo");
compare(c, "programs/benches/linear_search.cairo");
compare(c, "programs/benches/logistic_map.cairo");
}
fn load_contract(path: impl AsRef<Path>) -> Program {
let mut db = RootDatabase::builder().detect_corelib().build().unwrap();
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, path.as_ref()).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let sirrra_program = compile_prepared_db(
&db,
main_crate_ids,
CompilerConfig {
replace_ids: true,
..Default::default()
},
)
.unwrap();
sirrra_program.program
}
fn load_contract_for_vm(path: impl AsRef<Path>) -> SierraCasmRunner {
let mut db = RootDatabase::builder()
.detect_corelib()
.build()
.expect("failed to build database");
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, path.as_ref()).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let program = compile_prepared_db(
&db,
main_crate_ids.clone(),
CompilerConfig {
replace_ids: true,
..Default::default()
},
)
.expect("failed to compile program");
let replacer = DebugReplacer { db: &db };
let contracts = find_contracts(&db, &main_crate_ids);
let contracts_info =
get_contracts_info(&db, contracts, &replacer).expect("failed to get contracts info");
SierraCasmRunner::new(
program.program.clone(),
Some(Default::default()),
contracts_info,
None,
)
.expect("failed to create runner")
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/src/bin/contract-to-sierra.rs | debug_utils/src/bin/contract-to-sierra.rs | use std::fs::File;
use cairo_lang_starknet_classes::contract_class::ContractClass;
use clap::{command, Parser};
/// Extracts sierra program from contract
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
// Path to cairo contract
contract_path: String,
}
fn main() {
let args = Args::parse();
let contract_file = File::open(args.contract_path).expect("failed to open contract file");
let contract: ContractClass =
serde_json::from_reader(contract_file).expect("failed to parse contract");
let sierra = contract
.extract_sierra_program()
.expect("failed to extract sierra program");
print!("{}", sierra);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/lib.rs | debug_utils/casm-data-flow/src/lib.rs | pub use self::{
mappings::GraphMappings, memory::Memory, program::decode_instruction,
search::run_search_algorithm, trace::Trace,
};
mod mappings;
mod memory;
mod program;
pub mod search;
mod trace;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct StepId(pub usize);
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct ValueId(pub usize);
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/program.rs | debug_utils/casm-data-flow/src/program.rs | use crate::Memory;
use cairo_lang_casm::{
instructions::{
AddApInstruction, AssertEqInstruction, CallInstruction, Instruction, InstructionBody,
JnzInstruction, JumpInstruction, RetInstruction,
},
operand::{BinOpOperand, CellRef, DerefOrImmediate, Operation, ResOperand},
};
use cairo_lang_utils::bigint::BigIntAsHex;
use cairo_vm::{
types::instruction::{
ApUpdate, FpUpdate, Instruction as InstructionRepr, Op1Addr, Opcode, PcUpdate, Register,
Res,
},
vm::decoding::decoder,
};
use starknet_types_core::felt::Felt;
/// Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-casm/src/assembler.rs
pub fn decode_instruction(memory: &Memory, offset: usize) -> Instruction {
let instr_repr =
decoder::decode_instruction(memory[offset].unwrap().try_into().unwrap()).unwrap();
match instr_repr {
InstructionRepr {
off0: -1,
off1,
off2,
dst_register: Register::FP,
op0_register,
op1_addr,
res,
pc_update: PcUpdate::Regular,
ap_update: ApUpdate::Add,
fp_update: FpUpdate::Regular,
opcode: Opcode::NOp,
opcode_extension: _,
} => Instruction {
body: InstructionBody::AddAp(AddApInstruction {
operand: decode_res_operand(ResDescription {
off1,
off2,
imm: memory.get(offset + 1).copied().flatten(),
op0_register,
op1_addr,
res,
}),
}),
inc_ap: false,
hints: Vec::new(),
},
InstructionRepr {
off0,
off1,
off2,
dst_register,
op0_register,
op1_addr,
res,
pc_update: PcUpdate::Regular,
ap_update: ap_update @ (ApUpdate::Add1 | ApUpdate::Regular),
fp_update: FpUpdate::Regular,
opcode: Opcode::AssertEq,
opcode_extension: _,
} => Instruction {
body: InstructionBody::AssertEq(AssertEqInstruction {
a: CellRef {
register: match dst_register {
Register::AP => cairo_lang_casm::operand::Register::AP,
Register::FP => cairo_lang_casm::operand::Register::FP,
},
offset: off0 as i16,
},
b: decode_res_operand(ResDescription {
off1,
off2,
imm: memory.get(offset + 1).copied().flatten(),
op0_register,
op1_addr,
res,
}),
}),
inc_ap: match ap_update {
ApUpdate::Regular => false,
ApUpdate::Add1 => true,
_ => unreachable!(),
},
hints: Vec::new(),
},
InstructionRepr {
off0: 0,
off1: 1,
off2,
dst_register: Register::AP,
op0_register: Register::AP,
op1_addr: op1_addr @ (Op1Addr::AP | Op1Addr::FP | Op1Addr::Imm),
res: Res::Op1,
pc_update: pc_update @ (PcUpdate::JumpRel | PcUpdate::Jump),
ap_update: ApUpdate::Add2,
fp_update: FpUpdate::APPlus2,
opcode: Opcode::Call,
opcode_extension: _,
} => Instruction {
body: InstructionBody::Call(CallInstruction {
target: match op1_addr {
Op1Addr::Imm => {
assert_eq!(off2, 1);
DerefOrImmediate::Immediate(BigIntAsHex {
value: memory[offset + 1].unwrap().to_bigint(),
})
}
Op1Addr::AP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::AP,
offset: off2 as i16,
}),
Op1Addr::FP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::FP,
offset: off2 as i16,
}),
_ => unreachable!(),
},
relative: match pc_update {
PcUpdate::Jump => false,
PcUpdate::JumpRel => true,
_ => unreachable!(),
},
}),
inc_ap: false,
hints: Vec::new(),
},
InstructionRepr {
off0: -1,
off1: -1,
off2,
dst_register: Register::FP,
op0_register: Register::FP,
op1_addr: op1_addr @ (Op1Addr::AP | Op1Addr::FP | Op1Addr::Imm),
res: Res::Op1,
pc_update: pc_update @ (PcUpdate::JumpRel | PcUpdate::Jump),
ap_update: ap_update @ (ApUpdate::Add1 | ApUpdate::Regular),
fp_update: FpUpdate::Regular,
opcode: Opcode::NOp,
opcode_extension: _,
} => Instruction {
body: InstructionBody::Jump(JumpInstruction {
target: match op1_addr {
Op1Addr::Imm => {
assert_eq!(off2, 1);
DerefOrImmediate::Immediate(BigIntAsHex {
value: memory[offset + 1].unwrap().to_bigint(),
})
}
Op1Addr::AP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::AP,
offset: off2 as i16,
}),
Op1Addr::FP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::FP,
offset: off2 as i16,
}),
_ => unreachable!(),
},
relative: match pc_update {
PcUpdate::Jump => false,
PcUpdate::JumpRel => true,
_ => unreachable!(),
},
}),
inc_ap: match ap_update {
ApUpdate::Regular => false,
ApUpdate::Add1 => true,
_ => unreachable!(),
},
hints: Vec::new(),
},
InstructionRepr {
off0,
off1: -1,
off2,
dst_register,
op0_register: Register::FP,
op1_addr: op1_addr @ (Op1Addr::AP | Op1Addr::FP | Op1Addr::Imm),
res: Res::Unconstrained,
pc_update: PcUpdate::Jnz,
ap_update: ap_update @ (ApUpdate::Add1 | ApUpdate::Regular),
fp_update: FpUpdate::Regular,
opcode: Opcode::NOp,
opcode_extension: _,
} => Instruction {
body: InstructionBody::Jnz(JnzInstruction {
jump_offset: match op1_addr {
Op1Addr::Imm => {
assert_eq!(off2, 1);
DerefOrImmediate::Immediate(BigIntAsHex {
value: memory[offset + 1].unwrap().to_bigint(),
})
}
Op1Addr::AP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::AP,
offset: off2 as i16,
}),
Op1Addr::FP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::FP,
offset: off2 as i16,
}),
_ => unreachable!(),
},
condition: CellRef {
register: match dst_register {
Register::AP => cairo_lang_casm::operand::Register::AP,
Register::FP => cairo_lang_casm::operand::Register::FP,
},
offset: off0 as i16,
},
}),
inc_ap: match ap_update {
ApUpdate::Regular => false,
ApUpdate::Add1 => true,
_ => unreachable!(),
},
hints: Vec::new(),
},
InstructionRepr {
off0: -2,
off1: -1,
off2: -1,
dst_register: Register::FP,
op0_register: Register::FP,
op1_addr: Op1Addr::FP,
res: Res::Op1,
pc_update: PcUpdate::Jump,
ap_update: ApUpdate::Regular,
fp_update: FpUpdate::Dst,
opcode: Opcode::Ret,
opcode_extension: _,
} => Instruction {
body: InstructionBody::Ret(RetInstruction {}),
inc_ap: false,
hints: Vec::new(),
},
_ => panic!(),
}
}
struct ResDescription {
off1: isize,
off2: isize,
imm: Option<Felt>,
op0_register: Register,
op1_addr: Op1Addr,
res: Res,
}
fn decode_res_operand(desc: ResDescription) -> ResOperand {
match desc {
ResDescription {
off1: -1,
off2,
imm: _,
op0_register: Register::FP,
op1_addr: op1_addr @ (Op1Addr::AP | Op1Addr::FP),
res: Res::Op1,
} => ResOperand::Deref(CellRef {
register: match op1_addr {
Op1Addr::AP => cairo_lang_casm::operand::Register::AP,
Op1Addr::FP => cairo_lang_casm::operand::Register::FP,
_ => unreachable!(),
},
offset: off2 as i16,
}),
ResDescription {
off1,
off2,
imm: _,
op0_register,
op1_addr: Op1Addr::Op0,
res: Res::Op1,
} => ResOperand::DoubleDeref(
CellRef {
register: match op0_register {
Register::AP => cairo_lang_casm::operand::Register::AP,
Register::FP => cairo_lang_casm::operand::Register::FP,
},
offset: off1 as i16,
},
off2 as i16,
),
ResDescription {
off1: -1,
off2: 1,
imm: Some(imm),
op0_register: Register::FP,
op1_addr: Op1Addr::Imm,
res: Res::Op1,
} => ResOperand::Immediate(BigIntAsHex {
value: imm.to_bigint(),
}),
ResDescription {
off1,
off2,
imm,
op0_register,
op1_addr: op1_addr @ (Op1Addr::AP | Op1Addr::FP | Op1Addr::Imm),
res: res @ (Res::Add | Res::Mul),
} => ResOperand::BinOp(BinOpOperand {
op: match res {
Res::Add => Operation::Add,
Res::Mul => Operation::Mul,
_ => unreachable!(),
},
a: CellRef {
register: match op0_register {
Register::AP => cairo_lang_casm::operand::Register::AP,
Register::FP => cairo_lang_casm::operand::Register::FP,
},
offset: off1 as i16,
},
b: match op1_addr {
Op1Addr::Imm => {
assert_eq!(off2, 1);
DerefOrImmediate::Immediate(BigIntAsHex {
value: imm.unwrap().to_bigint(),
})
}
Op1Addr::AP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::AP,
offset: off2 as i16,
}),
Op1Addr::FP => DerefOrImmediate::Deref(CellRef {
register: cairo_lang_casm::operand::Register::FP,
offset: off2 as i16,
}),
_ => unreachable!(),
},
}),
_ => panic!(),
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/trace.rs | debug_utils/casm-data-flow/src/trace.rs | use bincode::{de::read::Reader, error::DecodeError};
use cairo_vm::vm::trace::trace_entry::RelocatedTraceEntry;
use std::ops::Deref;
#[derive(Debug)]
pub struct Trace(Vec<RelocatedTraceEntry>);
impl Trace {
pub fn decode(mut data: impl Reader) -> Self {
let mut trace = Vec::new();
let mut buf = [0u8; 8];
loop {
match data.read(&mut buf) {
Ok(_) => {}
Err(DecodeError::UnexpectedEnd { additional: 8 }) => break,
e @ Err(_) => e.unwrap(),
}
let ap = u64::from_le_bytes(buf) as usize;
data.read(&mut buf).unwrap();
let fp = u64::from_le_bytes(buf) as usize;
data.read(&mut buf).unwrap();
let pc = u64::from_le_bytes(buf) as usize;
trace.push(RelocatedTraceEntry { pc, ap, fp });
}
Self(trace)
}
}
impl Deref for Trace {
type Target = [RelocatedTraceEntry];
fn deref(&self) -> &Self::Target {
&self.0
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/memory.rs | debug_utils/casm-data-flow/src/memory.rs | use bincode::{de::read::Reader, error::DecodeError};
use starknet_types_core::felt::Felt;
use std::ops::Deref;
#[derive(Debug)]
pub struct Memory(Vec<Option<Felt>>);
impl Memory {
pub fn decode(mut data: impl Reader) -> Self {
let mut memory = Vec::new();
let mut addr_data = [0u8; 8];
let mut value_data = [0u8; 32];
loop {
match data.read(&mut addr_data) {
Ok(_) => {}
Err(DecodeError::UnexpectedEnd { additional: 8 }) => break,
e @ Err(_) => e.unwrap(),
}
data.read(&mut value_data).unwrap();
let addr = u64::from_le_bytes(addr_data);
let value = Felt::from_bytes_le(&value_data);
if addr >= memory.len() as u64 {
memory.resize(addr as usize + 1, None);
}
match &mut memory[addr as usize] {
Some(_) => panic!("duplicated memory cell"),
x @ None => *x = Some(value),
}
}
Self(memory)
}
}
impl Deref for Memory {
type Target = [Option<Felt>];
fn deref(&self) -> &Self::Target {
&self.0
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/search.rs | debug_utils/casm-data-flow/src/search.rs | use crate::{GraphMappings, Memory, StepId, ValueId};
use std::collections::VecDeque;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum NodeId {
Step(StepId),
Value(ValueId),
}
pub trait QueueContainer<T> {
fn new(init: T) -> Self;
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>;
fn pop(&mut self) -> Option<T>;
}
pub struct BfsQueue<T> {
queue: VecDeque<T>,
step: usize,
}
impl<T> BfsQueue<T> {
pub fn current_step(&self) -> usize {
self.step
}
}
impl<T> QueueContainer<T> for BfsQueue<T> {
fn new(init: T) -> Self {
Self {
queue: VecDeque::from([init]),
step: 0,
}
}
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
self.queue.extend(iter);
}
fn pop(&mut self) -> Option<T> {
self.queue.pop_front().inspect(|_| self.step += 1)
}
}
pub struct DfsQueue<T> {
queue: Vec<T>,
step: usize,
}
impl<T> DfsQueue<T> {
pub fn current_step(&self) -> usize {
self.step
}
}
impl<T> QueueContainer<T> for DfsQueue<T> {
fn new(init: T) -> Self {
Self {
queue: Vec::from([init]),
step: 0,
}
}
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
self.queue.extend(iter);
}
fn pop(&mut self) -> Option<T> {
self.queue.pop().inspect(|_| self.step += 1)
}
}
pub struct SearchAlgorithmIter<'a, Q>
where
Q: QueueContainer<Vec<NodeId>>,
{
memory: &'a Memory,
mappings: &'a GraphMappings,
// visited: HashSet<NodeId>,
queue: Q,
target: ValueId,
}
impl<Q> SearchAlgorithmIter<'_, Q>
where
Q: QueueContainer<Vec<NodeId>>,
{
pub fn queue(&self) -> &Q {
&self.queue
}
pub fn into_queue(self) -> Q {
self.queue
}
}
impl<Q> Iterator for SearchAlgorithmIter<'_, Q>
where
Q: QueueContainer<Vec<NodeId>>,
{
type Item = Vec<NodeId>;
fn next(&mut self) -> Option<Self::Item> {
while let Some(path) = self.queue.pop() {
if *path.last().unwrap() == NodeId::Value(self.target) {
return Some(path);
}
match *path.last().unwrap() {
NodeId::Step(id) => {
self.queue.extend(
self.mappings[id]
.iter()
.copied()
.filter(|x| {
// self.visited.insert(NodeId::Value(*x))
!path.contains(&NodeId::Value(*x))
})
.filter(|curr_id| {
// // When searching for gas paths, the gas should not increase.
// let prev_id = path
// .split_last()
// .unwrap()
// .1
// .iter()
// .rev()
// .find_map(|x| match x {
// NodeId::Step(_) => None,
// NodeId::Value(id) => Some(id),
// })
// .unwrap();
// self.memory[curr_id.0]
// .is_some_and(|value| self.memory[prev_id.0].unwrap() >= value)
self.memory[curr_id.0].is_some_and(|value| {
let min_value = 9919468708u64;
let _max_value = 9997035710u64;
// Use half the min value to give some leeway for redeposited
// gas.
value >= (min_value >> 1).into()
// && (value <= (max_value << 1).into())
})
})
.map(|x| {
let mut new_path = path.clone();
new_path.push(NodeId::Value(x));
new_path
}),
);
}
NodeId::Value(id) => {
self.queue.extend(
self.mappings[id]
.iter()
.copied()
.filter(|x| {
// self.visited.insert(NodeId::Step(*x))
!path.contains(&NodeId::Step(*x))
})
.filter(|curr_id| {
// StepId should only increase.
let prev_id = path.iter().rev().find_map(|x| match x {
NodeId::Step(id) => Some(id),
NodeId::Value(_) => None,
});
match prev_id {
Some(prev_id) => curr_id.0 > prev_id.0,
None => true,
}
})
.map(|x| {
let mut new_path = path.clone();
new_path.push(NodeId::Step(x));
new_path
}),
);
}
}
}
None
}
}
pub fn run_search_algorithm<'a, Q>(
memory: &'a Memory,
mappings: &'a GraphMappings,
source: ValueId,
target: ValueId,
) -> SearchAlgorithmIter<'a, Q>
where
Q: QueueContainer<Vec<NodeId>>,
{
SearchAlgorithmIter {
memory,
mappings,
// visited: HashSet::from([NodeId::Value(source)]),
queue: Q::new(vec![NodeId::Value(source)]),
target,
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/mappings.rs | debug_utils/casm-data-flow/src/mappings.rs | use crate::{decode_instruction, Memory, StepId, Trace, ValueId};
use cairo_lang_casm::{
hints::{CoreHint, CoreHintBase, DeprecatedHint, ExternalHint, Hint, StarknetHint},
instructions::InstructionBody,
operand::{CellRef, DerefOrImmediate, Register, ResOperand},
};
use cairo_vm::vm::trace::trace_entry::RelocatedTraceEntry;
use std::{
collections::{HashMap, HashSet},
ops::Index,
};
#[derive(Debug)]
pub struct GraphMappings {
step2value: HashMap<StepId, HashSet<ValueId>>,
value2step: HashMap<ValueId, HashSet<StepId>>,
}
impl GraphMappings {
pub fn new(memory: &Memory, trace: &Trace, hints: &HashMap<usize, Vec<Hint>>) -> Self {
let mut step2value = HashMap::<StepId, HashSet<ValueId>>::new();
let mut value2step = HashMap::<ValueId, HashSet<StepId>>::new();
for (step, trace) in trace.iter().enumerate() {
let mut add_mapping = |value| {
step2value
.entry(StepId(step))
.or_default()
.insert(ValueId(value));
value2step
.entry(ValueId(value))
.or_default()
.insert(StepId(step));
};
Self::iter_memory_references(memory, trace, &mut add_mapping);
if let Some(hints) = hints.get(&step) {
for hint in hints {
Self::iter_hint_references(memory, trace, hint, &mut add_mapping);
}
}
}
Self {
step2value,
value2step,
}
}
pub fn step2value(&self) -> &HashMap<StepId, HashSet<ValueId>> {
&self.step2value
}
pub fn value2step(&self) -> &HashMap<ValueId, HashSet<StepId>> {
&self.value2step
}
fn iter_memory_references(
memory: &Memory,
trace: &RelocatedTraceEntry,
mut callback: impl FnMut(usize),
) {
let instr = decode_instruction(memory, trace.pc);
let mut process_cell_ref = |x: CellRef| {
let offset = match x.register {
Register::AP => trace.ap.wrapping_add_signed(x.offset as isize),
Register::FP => trace.fp.wrapping_add_signed(x.offset as isize),
};
callback(offset);
offset
};
match instr.body {
InstructionBody::AddAp(add_ap_instruction) => match add_ap_instruction.operand {
ResOperand::Deref(_) => todo!(),
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
},
InstructionBody::AssertEq(assert_eq_instruction) => {
process_cell_ref(assert_eq_instruction.a);
match assert_eq_instruction.b {
ResOperand::Deref(cell_ref) => {
process_cell_ref(cell_ref);
}
ResOperand::DoubleDeref(cell_ref, _) => {
let offset = process_cell_ref(cell_ref);
callback(memory[offset].unwrap().try_into().unwrap());
}
ResOperand::Immediate(_) => {}
ResOperand::BinOp(bin_op_operand) => {
process_cell_ref(bin_op_operand.a);
match bin_op_operand.b {
DerefOrImmediate::Deref(cell_ref) => {
process_cell_ref(cell_ref);
}
DerefOrImmediate::Immediate(_) => {}
}
}
}
}
InstructionBody::Call(call_instruction) => match call_instruction.target {
DerefOrImmediate::Deref(_) => todo!(),
DerefOrImmediate::Immediate(_) => {}
},
InstructionBody::Jnz(jnz_instruction) => {
process_cell_ref(jnz_instruction.condition);
match jnz_instruction.jump_offset {
DerefOrImmediate::Deref(_) => todo!(),
DerefOrImmediate::Immediate(_) => {}
}
}
InstructionBody::Jump(jump_instruction) => match jump_instruction.target {
DerefOrImmediate::Deref(cell_ref) => {
process_cell_ref(cell_ref);
}
DerefOrImmediate::Immediate(_) => {}
},
InstructionBody::Ret(_) => {}
InstructionBody::QM31AssertEq(_) => todo!(),
InstructionBody::Blake2sCompress(_) => todo!(),
}
}
fn iter_hint_references(
_memory: &Memory,
trace: &RelocatedTraceEntry,
hint: &Hint,
mut callback: impl FnMut(usize),
) {
let mut process_cell_ref = |x: CellRef| {
let offset = match x.register {
Register::AP => trace.ap.wrapping_add_signed(x.offset as isize),
Register::FP => trace.fp.wrapping_add_signed(x.offset as isize),
};
callback(offset);
offset
};
match hint {
Hint::Core(core_hint_base) => match core_hint_base {
CoreHintBase::Core(core_hint) => match core_hint {
CoreHint::AllocSegment { dst } => {
process_cell_ref(*dst);
}
CoreHint::TestLessThan { lhs, rhs, dst } => {
match lhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(bin_op_operand) => {
process_cell_ref(bin_op_operand.a);
match bin_op_operand.b {
DerefOrImmediate::Deref(cell_ref) => {
process_cell_ref(cell_ref);
}
DerefOrImmediate::Immediate(_) => {}
}
}
}
match rhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
process_cell_ref(*dst);
}
CoreHint::TestLessThanOrEqual { lhs, rhs, dst } => {
match lhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match rhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
process_cell_ref(*dst);
}
CoreHint::TestLessThanOrEqualAddress { .. } => todo!(),
CoreHint::WideMul128 {
lhs,
rhs,
high,
low,
} => {
match lhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match rhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
process_cell_ref(*high);
process_cell_ref(*low);
}
CoreHint::DivMod {
lhs,
rhs,
quotient,
remainder,
} => {
match lhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match rhs {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
process_cell_ref(*quotient);
process_cell_ref(*remainder);
}
CoreHint::Uint256DivMod {
dividend0,
dividend1,
divisor0,
divisor1,
quotient0,
quotient1,
remainder0,
remainder1,
} => {
match dividend0 {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match dividend1 {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match divisor0 {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match divisor1 {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
process_cell_ref(*quotient0);
process_cell_ref(*quotient1);
process_cell_ref(*remainder0);
process_cell_ref(*remainder1);
}
CoreHint::Uint512DivModByUint256 { .. } => todo!(),
CoreHint::SquareRoot { .. } => todo!(),
CoreHint::Uint256SquareRoot { .. } => todo!(),
CoreHint::LinearSplit {
value,
scalar,
max_x,
x,
y,
} => {
match value {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match scalar {
ResOperand::Deref(_) => todo!(),
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
match max_x {
ResOperand::Deref(_) => todo!(),
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(_) => todo!(),
}
process_cell_ref(*x);
process_cell_ref(*y);
}
CoreHint::AllocFelt252Dict { .. } => todo!(),
CoreHint::Felt252DictEntryInit { .. } => todo!(),
CoreHint::Felt252DictEntryUpdate { .. } => todo!(),
CoreHint::GetSegmentArenaIndex { .. } => todo!(),
CoreHint::InitSquashData { .. } => todo!(),
CoreHint::GetCurrentAccessIndex { .. } => todo!(),
CoreHint::ShouldSkipSquashLoop { .. } => todo!(),
CoreHint::GetCurrentAccessDelta { .. } => todo!(),
CoreHint::ShouldContinueSquashLoop { .. } => todo!(),
CoreHint::GetNextDictKey { .. } => todo!(),
CoreHint::AssertLeFindSmallArcs { .. } => todo!(),
CoreHint::AssertLeIsFirstArcExcluded { .. } => todo!(),
CoreHint::AssertLeIsSecondArcExcluded { .. } => todo!(),
CoreHint::RandomEcPoint { .. } => todo!(),
CoreHint::FieldSqrt { .. } => todo!(),
CoreHint::DebugPrint { .. } => todo!(),
CoreHint::AllocConstantSize { .. } => todo!(),
CoreHint::U256InvModN { .. } => todo!(),
CoreHint::EvalCircuit { .. } => todo!(),
},
CoreHintBase::Deprecated(deprecated_hint) => match deprecated_hint {
DeprecatedHint::AssertCurrentAccessIndicesIsEmpty => todo!(),
DeprecatedHint::AssertAllAccessesUsed { .. } => {
todo!()
}
DeprecatedHint::AssertAllKeysUsed => todo!(),
DeprecatedHint::AssertLeAssertThirdArcExcluded => todo!(),
DeprecatedHint::AssertLtAssertValidInput { .. } => todo!(),
DeprecatedHint::Felt252DictRead { .. } => todo!(),
DeprecatedHint::Felt252DictWrite { .. } => todo!(),
},
},
Hint::Starknet(starknet_hint) => match starknet_hint {
StarknetHint::SystemCall { system } => match system {
ResOperand::Deref(cell_ref) => {
process_cell_ref(*cell_ref);
}
ResOperand::DoubleDeref(_, _) => todo!(),
ResOperand::Immediate(_) => {}
ResOperand::BinOp(bin_op_operand) => {
process_cell_ref(bin_op_operand.a);
match bin_op_operand.b {
DerefOrImmediate::Deref(_) => todo!(),
DerefOrImmediate::Immediate(_) => {}
}
}
},
StarknetHint::Cheatcode { .. } => todo!(),
},
Hint::External(external_hint) => match external_hint {
ExternalHint::AddRelocationRule { .. } => todo!(),
ExternalHint::WriteRunParam { .. } => todo!(),
ExternalHint::AddMarker { .. } => todo!(),
ExternalHint::AddTrace { .. } => todo!(),
},
}
}
}
impl Index<StepId> for GraphMappings {
type Output = HashSet<ValueId>;
fn index(&self, index: StepId) -> &Self::Output {
self.step2value.get(&index).unwrap()
}
}
impl Index<ValueId> for GraphMappings {
type Output = HashSet<StepId>;
fn index(&self, index: ValueId) -> &Self::Output {
self.value2step.get(&index).unwrap()
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/src/main.rs | debug_utils/casm-data-flow/src/main.rs | use bincode::de::read::SliceReader;
use cairo_lang_casm::hints::Hint;
use casm_data_flow::{
run_search_algorithm,
search::{DfsQueue, NodeId},
GraphMappings, Memory, Trace,
};
use clap::Parser;
use serde_json::Value;
use starknet_types_core::felt::Felt;
use std::{collections::HashMap, fs, path::PathBuf, str::FromStr};
#[derive(Debug, Parser)]
struct CmdArgs {
#[clap(long)]
memory_path: PathBuf,
#[clap(long)]
trace_path: PathBuf,
#[clap(long)]
program_path: Option<PathBuf>,
#[clap(short, long, value_parser = parse_felt252)]
source_value: Felt,
#[clap(short, long, value_parser = parse_felt252)]
target_value: Felt,
}
fn parse_felt252(input: &str) -> Result<Felt, String> {
Felt::from_str(input).map_err(|e| e.to_string())
}
fn main() {
let args = CmdArgs::parse();
//
// Load data from disk.
//
println!("Loading memory and trace.");
let memory = Memory::decode(SliceReader::new(&fs::read(args.memory_path).unwrap()));
let trace = Trace::decode(SliceReader::new(&fs::read(args.trace_path).unwrap()));
println!(" {:?}", trace.first().unwrap());
println!(" {:?}", trace.last().unwrap());
let hints = match args.program_path {
None => HashMap::default(),
Some(program_path) => {
println!("Loading hints from provided program JSON.");
let mut program_json: Value =
serde_json::from_slice(&fs::read(program_path).unwrap()).unwrap();
let hints = program_json
.as_object_mut()
.unwrap()
.remove("hints")
.unwrap();
let hints: Vec<(usize, Vec<Hint>)> = serde_json::from_value(hints).unwrap();
hints.into_iter().collect()
}
};
//
// Generate graph mappings.
//
println!("Generating graph mappings.");
let mappings = GraphMappings::new(&memory, &trace, &hints);
//
// Find initial and final values.
//
println!("Finding initial and final values within the data.");
let source_value = mappings
.value2step()
.keys()
.copied()
.filter(|x| memory[x.0] == Some(args.source_value))
.min()
.expect("Source value not found within accessed memory.");
let target_value = mappings
.value2step()
.keys()
.copied()
.filter(|x| memory[x.0] == Some(args.target_value))
.max()
.expect("Target value not found within accessed memory.");
println!(" Source value found at {}.", source_value.0);
println!(" Target value found at {}.", target_value.0);
println!();
//
// Find a path between the source and target nodes.
//
// Queue containers:
// - BfsQueue: Will find the shortest path using the BFS algorithm.
// - DfsQueue: Will find the left-most path using the DFS algorithm.
//
println!("Starting search algorithm.");
let mut iter =
run_search_algorithm::<DfsQueue<_>>(&memory, &mappings, source_value, target_value);
println!();
println!();
let mut num_solutions = 0;
while let Some(path) = iter.next() {
num_solutions += 1;
println!("Found solution at step {}.", iter.queue().current_step());
// println!("Connecting path (spans {} steps):", path.len() >> 1);
// for id in path {
// match id {
// NodeId::Step(offset) => {
// if let Some(hints) = hints.get(&offset.0) {
// for hint in hints {
// println!("; {}", hint.representing_string());
// }
// }
// println!("{}", decode_instruction(&memory, trace[offset.0].pc));
// println!(" {:?}", trace[offset.0]);
// }
// NodeId::Value(offset) => {
// println!(" [{}] = {}", offset.0, memory[offset.0].unwrap());
// println!();
// }
// }
// }
// println!();
let mut prev_value: Option<Felt> = None;
for id in path.into_iter().filter_map(|x| match x {
NodeId::Step(_) => None,
NodeId::Value(id) => Some(id),
}) {
let curr_value = memory[id.0].unwrap();
match prev_value {
Some(prev_value) if curr_value != prev_value => println!(
" [{}] = {curr_value} (Δ{})",
id.0,
curr_value.to_bigint() - prev_value.to_bigint()
),
None => println!(" [{}] = {curr_value}", id.0),
_ => {}
}
prev_value = Some(curr_value);
}
println!();
println!();
}
println!("Done! Found {num_solutions} solutions.");
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/examples/run-contract.rs | debug_utils/casm-data-flow/examples/run-contract.rs | use std::{fs::File, io::Write, path::PathBuf};
use bincode::enc::write::Writer;
use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass;
use cairo_vm::{
cairo_run::{write_encoded_memory, write_encoded_trace},
hint_processor::cairo_1_hint_processor::hint_processor::Cairo1HintProcessor,
types::{
builtin_name::BuiltinName, layout_name::LayoutName, program::Program,
relocatable::MaybeRelocatable,
},
vm::runners::cairo_runner::{CairoArg, CairoRunner, RunResources},
};
use clap::Parser;
use starknet_types_core::felt::Felt;
#[derive(Debug, Parser)]
struct Args {
contract_path: PathBuf,
memory_path: PathBuf,
trace_path: PathBuf,
}
pub fn main() {
let cli_args = Args::parse();
let calldata_args = [MaybeRelocatable::from(10)];
let expected_retdata = [Felt::from(89)];
let contract_file = File::open(cli_args.contract_path).expect("failed to open contract path");
let contract: CasmContractClass =
serde_json::from_reader(contract_file).expect("failed to parse contract file");
let program = Program::try_from(contract.clone())
.expect("failed to build vm program from contract class");
let mut runner =
CairoRunner::new(&program, LayoutName::all_cairo, None, false, true, false).unwrap();
let program_builtins = contract
.entry_points_by_type
.external
.iter()
.find(|e| e.offset == 0)
.unwrap()
.builtins
.iter()
.map(|s| BuiltinName::from_str(s).expect("Invalid builtin name"))
.collect::<Vec<_>>();
runner
.initialize_function_runner_cairo_1(&program_builtins)
.unwrap();
let syscall_segment = MaybeRelocatable::from(runner.vm.add_memory_segment());
let builtins = runner.get_program_builtins();
let builtin_segment: Vec<MaybeRelocatable> = runner
.vm
.get_builtin_runners()
.iter()
.filter(|b| builtins.contains(&b.name()))
.flat_map(|b| b.initial_stack())
.collect();
let initial_gas = MaybeRelocatable::from(usize::MAX);
println!("Starting Gas: {}", &initial_gas);
let mut implicit_args = builtin_segment;
implicit_args.extend([initial_gas]);
implicit_args.extend([syscall_segment]);
let builtin_costs: Vec<MaybeRelocatable> =
vec![0.into(), 0.into(), 0.into(), 0.into(), 0.into()];
let builtin_costs_ptr = runner.vm.add_memory_segment();
runner
.vm
.load_data(builtin_costs_ptr, &builtin_costs)
.unwrap();
let core_program_end_ptr =
(runner.program_base.unwrap() + runner.get_program().data_len()).unwrap();
let program_extra_data: Vec<MaybeRelocatable> =
vec![0x208B7FFF7FFF7FFE.into(), builtin_costs_ptr.into()];
runner
.vm
.load_data(core_program_end_ptr, &program_extra_data)
.unwrap();
let calldata_start = runner.vm.add_memory_segment();
let calldata_end = runner.vm.load_data(calldata_start, &calldata_args).unwrap();
let mut entrypoint_args: Vec<CairoArg> = implicit_args
.iter()
.map(|m| CairoArg::from(m.clone()))
.collect();
entrypoint_args.extend([
MaybeRelocatable::from(calldata_start).into(),
MaybeRelocatable::from(calldata_end).into(),
]);
let entrypoint_args: Vec<&CairoArg> = entrypoint_args.iter().collect();
let mut hint_processor =
Cairo1HintProcessor::new(&contract.hints, RunResources::new(621), false);
runner
.run_from_entrypoint(
0,
&entrypoint_args,
true,
Some(runner.get_program().data_len() + program_extra_data.len()),
&mut hint_processor,
)
.expect("failed to execute contract");
let return_values = runner.vm.get_return_values(5).unwrap();
let final_gas = return_values[0].get_int().unwrap();
let retdata_start = return_values[3].get_relocatable().unwrap();
let retdata_end = return_values[4].get_relocatable().unwrap();
let retdata: Vec<Felt> = runner
.vm
.get_integer_range(retdata_start, (retdata_end - retdata_start).unwrap())
.unwrap()
.iter()
.map(|c| c.clone().into_owned())
.collect();
println!("Final Gas: {}", final_gas);
assert_eq!(retdata, expected_retdata);
runner
.relocate(true, true)
.expect("failed to relocate trace");
let trace_file = File::create(cli_args.trace_path).expect("failed to create trace file");
let mut trace_writer = FileWriter::new(trace_file);
write_encoded_trace(
&runner.relocated_trace.expect("trace should exist"),
&mut trace_writer,
)
.expect("failed to write trace");
let memory_file = File::create(cli_args.memory_path).expect("failed to create memory file");
let mut memory_writer = FileWriter::new(memory_file);
write_encoded_memory(&runner.relocated_memory, &mut memory_writer)
.expect("failed to write memory");
}
struct FileWriter {
buf_writer: File,
bytes_written: usize,
}
impl Writer for FileWriter {
fn write(&mut self, bytes: &[u8]) -> Result<(), bincode::error::EncodeError> {
self.buf_writer
.write_all(bytes)
.map_err(|e| bincode::error::EncodeError::Io {
inner: e,
index: self.bytes_written,
})?;
self.bytes_written += bytes.len();
Ok(())
}
}
impl FileWriter {
fn new(buf_writer: File) -> Self {
Self {
buf_writer,
bytes_written: 0,
}
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/casm-data-flow/examples/basic.rs | debug_utils/casm-data-flow/examples/basic.rs | use bincode::de::read::SliceReader;
use casm_data_flow::{decode_instruction, GraphMappings, Memory, Trace, ValueId};
use std::{collections::HashMap, fs};
fn main() {
let memory = Memory::decode(SliceReader::new(&fs::read("memory-2.bin").unwrap()));
let trace = Trace::decode(SliceReader::new(&fs::read("trace-2.bin").unwrap()));
let mappings = GraphMappings::new(&memory, &trace, &HashMap::new());
// let value_idx = memory
// .iter()
// .copied()
// .enumerate()
// .filter_map(|(idx, val)| {
// (val == Some(Felt::from_str("9980669810").unwrap())).then_some(idx)
// })
// .collect::<Vec<_>>();
let value_idx = ValueId(93139);
println!("Memory offset: {value_idx:?}");
for id in &mappings[value_idx] {
println!(
"{id:?} => {} [{:?}]",
decode_instruction(&memory, trace[id.0].pc),
trace[id.0]
);
}
println!("[93139] = {}", memory[93139].unwrap());
println!("[93140] = {}", memory[93140].unwrap());
println!("[93142] = {}", memory[93142].unwrap());
// dbg!(memory[25386].unwrap().to_string());
// dbg!(value_idx);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm.rs | debug_utils/sierra-emu/src/vm.rs | use crate::{
debug::libfunc_to_name,
gas::{BuiltinCosts, GasMetadata},
starknet::StarknetSyscallHandler,
ContractExecutionResult, ProgramTrace, StateDump, Value,
};
use cairo_lang_sierra::{
edit_state,
extensions::{
circuit::CircuitTypeConcrete,
core::{CoreConcreteLibfunc, CoreLibfunc, CoreType, CoreTypeConcrete},
gas::CostTokenType,
starknet::StarknetTypeConcrete,
ConcreteLibfunc, ConcreteType,
},
ids::{ConcreteLibfuncId, FunctionId, VarId},
program::{GenFunction, GenStatement, Invocation, Program, StatementIdx},
program_registry::ProgramRegistry,
};
use cairo_lang_sierra_to_casm::metadata::MetadataComputationConfig;
use cairo_lang_sierra_type_size::ProgramRegistryInfo;
use cairo_lang_starknet_classes::{
casm_contract_class::ENTRY_POINT_COST, compiler_version::VersionId,
contract_class::ContractEntryPoints,
};
use cairo_lang_utils::{ordered_hash_map::OrderedHashMap, small_ordered_map::SmallOrderedMap};
use smallvec::{smallvec, SmallVec};
use starknet_types_core::felt::Felt;
use std::{cmp::Ordering, fmt::Debug, sync::Arc};
use tracing::{debug, trace};
mod ap_tracking;
mod array;
mod bool;
mod bounded_int;
mod r#box;
mod branch_align;
mod bytes31;
mod cast;
mod circuit;
mod r#const;
mod coupon;
mod drop;
mod dup;
mod ec;
mod r#enum;
mod felt252;
mod felt252_dict;
mod felt252_dict_entry;
mod function_call;
mod gas;
mod gas_reserve;
mod int;
mod int_range;
mod jump;
mod mem;
mod nullable;
mod pedersen;
mod poseidon;
mod snapshot_take;
mod starknet;
mod r#struct;
mod uint256;
mod uint512;
#[derive(Clone)]
pub struct VirtualMachine {
pub program: Arc<Program>,
pub registry: Arc<ProgramRegistry<CoreType, CoreLibfunc>>,
frames: Vec<SierraFrame>,
pub gas: GasMetadata,
entry_points: Option<ContractEntryPoints>,
builtin_costs: BuiltinCosts,
}
impl Debug for VirtualMachine {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VirtualMachine")
.field("frames", &self.frames)
.field("gas", &self.gas)
.finish_non_exhaustive()
}
}
impl VirtualMachine {
pub fn new(program: Arc<Program>) -> Self {
let registry = ProgramRegistry::new(&program).unwrap();
let program_info = ProgramRegistryInfo::new(&program).unwrap();
Self {
gas: GasMetadata::new(
&program,
&program_info,
Some(MetadataComputationConfig::default()),
)
.unwrap(),
program,
registry: Arc::new(registry),
frames: Vec::new(),
entry_points: None,
builtin_costs: Default::default(),
}
}
}
impl VirtualMachine {
pub fn new_starknet(
program: Arc<Program>,
entry_points: &ContractEntryPoints,
sierra_version: VersionId,
) -> Self {
let no_eq_solver = match sierra_version.major.cmp(&1) {
Ordering::Less => false,
Ordering::Equal => sierra_version.minor >= 4,
Ordering::Greater => true,
};
let registry = ProgramRegistry::new(&program).unwrap();
let program_info = ProgramRegistryInfo::new(&program).unwrap();
Self {
gas: GasMetadata::new(
&program,
&program_info,
Some(MetadataComputationConfig {
function_set_costs: entry_points
.constructor
.iter()
.chain(entry_points.external.iter())
.chain(entry_points.l1_handler.iter())
.map(|x| {
(
FunctionId::new(x.function_idx as u64),
SmallOrderedMap::from_iter([(
CostTokenType::Const,
ENTRY_POINT_COST,
)]),
)
})
.collect(),
linear_gas_solver: no_eq_solver,
linear_ap_change_solver: no_eq_solver,
skip_non_linear_solver_comparisons: false,
compute_runtime_costs: false,
}),
)
.unwrap(),
program,
registry: Arc::new(registry),
frames: Vec::new(),
entry_points: Some(entry_points.clone()),
builtin_costs: Default::default(),
}
}
pub fn registry(&self) -> &ProgramRegistry<CoreType, CoreLibfunc> {
&self.registry
}
/// Utility to call a contract.
pub fn call_contract<I>(
&mut self,
selector: Felt,
initial_gas: u64,
calldata: I,
builtin_costs: Option<BuiltinCosts>,
) where
I: IntoIterator<Item = Felt>,
I::IntoIter: ExactSizeIterator,
{
self.builtin_costs = builtin_costs.unwrap_or_default();
let args: Vec<_> = calldata.into_iter().map(Value::Felt).collect();
let entry_points = self.entry_points.as_ref().expect("contract should have");
let selector_uint = selector.to_biguint();
let function_idx = entry_points
.constructor
.iter()
.chain(entry_points.external.iter())
.chain(entry_points.l1_handler.iter())
.find(|x| x.selector == selector_uint)
.map(|x| x.function_idx)
.expect("function id not found");
let function = &self.program.funcs[function_idx];
self.push_frame(
function.id.clone(),
function
.signature
.param_types
.iter()
.map(|type_id| {
let type_info = self.registry().get_type(type_id).unwrap();
match type_info {
CoreTypeConcrete::GasBuiltin(_) => Value::U64(initial_gas),
// Add the calldata structure
CoreTypeConcrete::Struct(inner) => {
let member = self.registry().get_type(&inner.members[0]).unwrap();
match member {
CoreTypeConcrete::Snapshot(inner) => {
let inner = self.registry().get_type(&inner.ty).unwrap();
match inner {
CoreTypeConcrete::Array(inner) => {
let felt_ty = &inner.ty;
Value::Struct(vec![Value::Array {
ty: felt_ty.clone(),
data: args.clone(),
}])
}
_ => unreachable!(),
}
}
_ => unreachable!(),
}
}
CoreTypeConcrete::BuiltinCosts(_) => {
Value::BuiltinCosts(builtin_costs.unwrap_or_default())
}
CoreTypeConcrete::Starknet(StarknetTypeConcrete::System(_)) => Value::Unit,
CoreTypeConcrete::RangeCheck(_)
| CoreTypeConcrete::RangeCheck96(_)
| CoreTypeConcrete::Circuit(
CircuitTypeConcrete::MulMod(_) | CircuitTypeConcrete::AddMod(_),
)
| CoreTypeConcrete::Pedersen(_)
| CoreTypeConcrete::Poseidon(_)
| CoreTypeConcrete::Bitwise(_)
| CoreTypeConcrete::EcOp(_)
| CoreTypeConcrete::SegmentArena(_) => Value::Unit,
x => {
todo!("{:?}", x.info())
}
}
})
.collect::<Vec<_>>(),
);
}
/// Utility to call a contract.
pub fn call_program<I>(
&mut self,
function: &GenFunction<StatementIdx>,
initial_gas: u64,
args: I,
) where
I: IntoIterator<Item = Value>,
I::IntoIter: ExactSizeIterator,
{
let required_gas = self.gas.initial_required_gas(&function.id).unwrap();
let initial_gas = initial_gas.checked_sub(required_gas).unwrap();
let mut iter = args.into_iter();
self.push_frame(
function.id.clone(),
function
.signature
.param_types
.iter()
.map(|type_id| {
let type_info = self.registry().get_type(type_id).unwrap();
match type_info {
CoreTypeConcrete::GasBuiltin(_) => Value::U64(initial_gas),
CoreTypeConcrete::RangeCheck(_)
| CoreTypeConcrete::RangeCheck96(_)
| CoreTypeConcrete::Bitwise(_)
| CoreTypeConcrete::Pedersen(_)
| CoreTypeConcrete::Poseidon(_)
| CoreTypeConcrete::SegmentArena(_)
| CoreTypeConcrete::Circuit(
CircuitTypeConcrete::AddMod(_) | CircuitTypeConcrete::MulMod(_),
) => Value::Unit,
CoreTypeConcrete::Starknet(inner) => match inner {
StarknetTypeConcrete::System(_) => Value::Unit,
_ => todo!(),
},
_ => iter.next().unwrap(),
}
})
.collect::<Vec<_>>(),
);
}
/// Effectively a function call (for entry points).
pub fn push_frame<I>(&mut self, function_id: FunctionId, args: I)
where
I: IntoIterator<Item = Value>,
I::IntoIter: ExactSizeIterator,
{
let function = self.registry.get_function(&function_id).unwrap();
let args = args.into_iter();
assert_eq!(args.len(), function.params.len());
self.frames.push(SierraFrame {
_function_id: function_id,
state: function
.params
.iter()
.zip(args)
.map(|(param, value)| {
assert!(value.is(&self.registry, ¶m.ty));
(param.id.clone(), value)
})
.collect(),
pc: function.entry_point,
})
}
/// Run a single statement and return the state before its execution.
pub fn step(
&mut self,
syscall_handler: &mut impl StarknetSyscallHandler,
) -> Option<(StatementIdx, OrderedHashMap<VarId, Value>)> {
let frame = self.frames.last_mut()?;
let pc_snapshot = frame.pc;
let state_snapshot = frame.state.clone();
debug!(
"Evaluating statement {} ({})",
frame.pc.0, &self.program.statements[frame.pc.0],
);
trace!("values: \n{:#?}\n", state_snapshot);
match &self.program.statements[frame.pc.0] {
GenStatement::Invocation(invocation) => {
let libfunc = self.registry.get_libfunc(&invocation.libfunc_id).unwrap();
debug!(
"Executing invocation of libfunc: {}",
libfunc_to_name(libfunc)
);
let (state, values) =
edit_state::take_args(std::mem::take(&mut frame.state), invocation.args.iter())
.unwrap();
match eval(
&self.registry,
&invocation.libfunc_id,
values,
syscall_handler,
&self.gas,
&frame.pc,
self.builtin_costs,
) {
EvalAction::NormalBranch(branch_idx, results) => {
assert_eq!(
results.len(),
invocation.branches[branch_idx].results.len(),
"invocation of {invocation} returned the wrong number of values"
);
assert!(
results
.iter()
.zip(
&self
.registry
.get_libfunc(&invocation.libfunc_id)
.unwrap()
.branch_signatures()[branch_idx]
.vars
)
.all(|(value, ret)| value.is(&self.registry, &ret.ty)),
"invocation of {} returned an invalid argument",
libfunc_to_name(
self.registry.get_libfunc(&invocation.libfunc_id).unwrap()
)
);
frame.pc = frame.pc.next(&invocation.branches[branch_idx].target);
frame.state = edit_state::put_results(
state,
invocation.branches[branch_idx].results.iter().zip(results),
)
.unwrap();
}
EvalAction::FunctionCall(function_id, args) => {
let function = self.registry.get_function(&function_id).unwrap();
frame.state = state;
self.frames.push(SierraFrame {
_function_id: function_id,
state: function
.params
.iter()
.map(|param| param.id.clone())
.zip(args.iter().cloned())
.collect(),
pc: function.entry_point,
});
}
}
}
GenStatement::Return(ids) => {
let mut curr_frame = self.frames.pop().unwrap();
if let Some(prev_frame) = self.frames.last_mut() {
let (state, values) =
edit_state::take_args(std::mem::take(&mut curr_frame.state), ids.iter())
.unwrap();
assert!(state.is_empty());
let target_branch = match &self.program.statements[prev_frame.pc.0] {
GenStatement::Invocation(Invocation { branches, .. }) => {
assert_eq!(branches.len(), 1);
&branches[0]
}
_ => unreachable!(),
};
assert_eq!(target_branch.results.len(), values.len());
prev_frame.pc = prev_frame.pc.next(&target_branch.target);
prev_frame.state = edit_state::put_results(
std::mem::take(&mut prev_frame.state),
target_branch.results.iter().zip(values),
)
.unwrap();
}
}
}
Some((pc_snapshot, state_snapshot))
}
/// Run all the statement and return the trace.
pub fn run_with_trace(
&mut self,
syscall_handler: &mut impl StarknetSyscallHandler,
) -> ProgramTrace {
let mut trace = ProgramTrace::new();
while let Some((statement_idx, state)) = self.step(syscall_handler) {
trace.push(StateDump::new(statement_idx, state));
}
trace
}
/// Run all the statement and return the trace.
pub fn run(
&mut self,
syscall_handler: &mut impl StarknetSyscallHandler,
) -> Option<ContractExecutionResult> {
let mut last = None;
while let Some((statement_idx, state)) = self.step(syscall_handler) {
last = Some(StateDump::new(statement_idx, state));
}
ContractExecutionResult::from_state(&last?)
}
}
#[derive(Clone, Debug)]
struct SierraFrame {
_function_id: FunctionId,
state: OrderedHashMap<VarId, Value>,
pc: StatementIdx,
}
enum EvalAction {
NormalBranch(usize, SmallVec<[Value; 2]>),
FunctionCall(FunctionId, SmallVec<[Value; 2]>),
}
fn eval<'a>(
registry: &'a ProgramRegistry<CoreType, CoreLibfunc>,
id: &'a ConcreteLibfuncId,
args: Vec<Value>,
syscall_handler: &mut impl StarknetSyscallHandler,
gas: &GasMetadata,
statement_idx: &StatementIdx,
builtin_costs: BuiltinCosts,
) -> EvalAction {
match registry.get_libfunc(id).unwrap() {
CoreConcreteLibfunc::ApTracking(selector) => {
self::ap_tracking::eval(registry, selector, args)
}
CoreConcreteLibfunc::Array(selector) => self::array::eval(registry, selector, args),
CoreConcreteLibfunc::Bool(selector) => self::bool::eval(registry, selector, args),
CoreConcreteLibfunc::BoundedInt(selector) => {
self::bounded_int::eval(registry, selector, args)
}
CoreConcreteLibfunc::Box(selector) => self::r#box::eval(registry, selector, args),
CoreConcreteLibfunc::BranchAlign(info) => self::branch_align::eval(registry, info, args),
CoreConcreteLibfunc::Bytes31(selector) => self::bytes31::eval(registry, selector, args),
CoreConcreteLibfunc::Cast(selector) => self::cast::eval(registry, selector, args),
CoreConcreteLibfunc::Circuit(selector) => self::circuit::eval(registry, selector, args),
CoreConcreteLibfunc::Const(selector) => self::r#const::eval(registry, selector, args),
CoreConcreteLibfunc::Coupon(selector) => self::coupon::eval(registry, selector, args),
CoreConcreteLibfunc::Debug(_) => todo!(),
CoreConcreteLibfunc::Drop(info) => self::drop::eval(registry, info, args),
CoreConcreteLibfunc::Dup(info) => self::dup::eval(registry, info, args),
CoreConcreteLibfunc::Ec(selector) => self::ec::eval(registry, selector, args),
CoreConcreteLibfunc::Enum(selector) => self::r#enum::eval(registry, selector, args),
CoreConcreteLibfunc::Felt252(selector) => self::felt252::eval(registry, selector, args),
CoreConcreteLibfunc::Felt252Dict(selector) => {
self::felt252_dict::eval(registry, selector, args)
}
CoreConcreteLibfunc::Felt252DictEntry(selector) => {
self::felt252_dict_entry::eval(registry, selector, args)
}
CoreConcreteLibfunc::FunctionCall(info) => {
self::function_call::eval_function_call(registry, info, args)
}
CoreConcreteLibfunc::CouponCall(info) => {
self::function_call::eval_coupon_call(registry, info, args)
}
CoreConcreteLibfunc::Gas(selector) => {
self::gas::eval(registry, selector, args, gas, *statement_idx, builtin_costs)
}
CoreConcreteLibfunc::Mem(selector) => self::mem::eval(registry, selector, args),
CoreConcreteLibfunc::Nullable(selector) => self::nullable::eval(registry, selector, args),
CoreConcreteLibfunc::Pedersen(selector) => self::pedersen::eval(registry, selector, args),
CoreConcreteLibfunc::Poseidon(selector) => self::poseidon::eval(registry, selector, args),
CoreConcreteLibfunc::Sint8(selector) => self::int::eval_signed(registry, selector, args),
CoreConcreteLibfunc::Sint16(selector) => self::int::eval_signed(registry, selector, args),
CoreConcreteLibfunc::Sint32(selector) => self::int::eval_signed(registry, selector, args),
CoreConcreteLibfunc::Sint64(selector) => self::int::eval_signed(registry, selector, args),
CoreConcreteLibfunc::Sint128(selector) => self::int::eval_i128(registry, selector, args),
CoreConcreteLibfunc::Uint8(selector) => self::int::eval_unsigned(registry, selector, args),
CoreConcreteLibfunc::Uint16(selector) => self::int::eval_unsigned(registry, selector, args),
CoreConcreteLibfunc::Uint32(selector) => self::int::eval_unsigned(registry, selector, args),
CoreConcreteLibfunc::Uint64(selector) => self::int::eval_unsigned(registry, selector, args),
CoreConcreteLibfunc::Uint128(selector) => self::int::eval_uint128(registry, selector, args),
CoreConcreteLibfunc::Uint256(selector) => self::uint256::eval(registry, selector, args),
CoreConcreteLibfunc::Uint512(selector) => self::uint512::eval(registry, selector, args),
CoreConcreteLibfunc::Struct(selector) => self::r#struct::eval(registry, selector, args),
CoreConcreteLibfunc::SnapshotTake(info) => self::snapshot_take::eval(registry, info, args),
CoreConcreteLibfunc::Starknet(selector) => {
self::starknet::eval(registry, selector, args, syscall_handler)
}
CoreConcreteLibfunc::UnconditionalJump(info) => self::jump::eval(registry, info, args),
CoreConcreteLibfunc::UnwrapNonZero(_info) => {
let [value] = args.try_into().unwrap();
EvalAction::NormalBranch(0, smallvec![value])
}
CoreConcreteLibfunc::IntRange(selector) => self::int_range::eval(registry, selector, args),
CoreConcreteLibfunc::GasReserve(selector) => self::gas_reserve::eval(selector, args),
CoreConcreteLibfunc::Blake(_) => todo!(),
CoreConcreteLibfunc::QM31(_) => todo!(),
CoreConcreteLibfunc::Felt252SquashedDict(_) => todo!(),
CoreConcreteLibfunc::Trace(_) => todo!(),
CoreConcreteLibfunc::UnsafePanic(_) => todo!(),
CoreConcreteLibfunc::DummyFunctionCall(_) => todo!(),
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/lib.rs | debug_utils/sierra-emu/src/lib.rs | use std::{num::ParseIntError, str::FromStr, sync::Arc};
use cairo_lang_sierra::{
extensions::{
circuit::CircuitTypeConcrete,
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
starknet::StarknetTypeConcrete,
},
ids::ConcreteTypeId,
program::{GenFunction, Program, StatementIdx},
program_registry::ProgramRegistry,
};
use debug::type_to_name;
use starknet::StubSyscallHandler;
pub use self::{dump::*, gas::BuiltinCosts, value::*, vm::VirtualMachine};
mod debug;
mod dump;
mod gas;
pub mod starknet;
mod test_utils;
mod utils;
mod value;
mod vm;
#[derive(Clone, Debug)]
pub enum EntryPoint {
Number(u64),
String(String),
}
impl FromStr for EntryPoint {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s.chars().next() {
Some(x) if x.is_numeric() => Self::Number(s.parse()?),
_ => Self::String(s.to_string()),
})
}
}
pub fn find_entry_point_by_idx(
program: &Program,
entry_point_idx: usize,
) -> Option<&GenFunction<StatementIdx>> {
program
.funcs
.iter()
.find(|x| x.id.id == entry_point_idx as u64)
}
pub fn find_entry_point_by_name<'a>(
program: &'a Program,
name: &str,
) -> Option<&'a GenFunction<StatementIdx>> {
program
.funcs
.iter()
.find(|x| x.id.debug_name.as_ref().map(|x| x.as_str()) == Some(name))
}
// If type is invisible to sierra (i.e. a single element container),
// finds it's actual concrete type recursively.
// If not, returns the current type
pub fn find_real_type(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
ty: &ConcreteTypeId,
) -> ConcreteTypeId {
match registry.get_type(ty).unwrap() {
cairo_lang_sierra::extensions::core::CoreTypeConcrete::Box(info) => {
find_real_type(registry, &info.ty)
}
cairo_lang_sierra::extensions::core::CoreTypeConcrete::Uninitialized(info) => {
find_real_type(registry, &info.ty)
}
cairo_lang_sierra::extensions::core::CoreTypeConcrete::Span(info) => {
find_real_type(registry, &info.ty)
}
cairo_lang_sierra::extensions::core::CoreTypeConcrete::Snapshot(info) => {
find_real_type(registry, &info.ty)
}
_ => ty.clone(),
}
}
pub fn run_program(
program: Arc<Program>,
entry_point: EntryPoint,
args: Vec<String>,
available_gas: u64,
) -> ProgramTrace {
let mut vm = VirtualMachine::new(program.clone());
let function = program
.funcs
.iter()
.find(|f| match &entry_point {
EntryPoint::Number(x) => f.id.id == *x,
EntryPoint::String(x) => f.id.debug_name.as_deref() == Some(x.as_str()),
})
.unwrap();
let mut iter = args.into_iter();
vm.push_frame(
function.id.clone(),
function
.signature
.param_types
.iter()
.map(|type_id| {
let type_info = vm.registry().get_type(type_id).unwrap();
match type_info {
CoreTypeConcrete::Felt252(_) => Value::parse_felt(&iter.next().unwrap()),
CoreTypeConcrete::GasBuiltin(_) => Value::U64(available_gas),
CoreTypeConcrete::RangeCheck(_)
| CoreTypeConcrete::RangeCheck96(_)
| CoreTypeConcrete::Bitwise(_)
| CoreTypeConcrete::Pedersen(_)
| CoreTypeConcrete::Poseidon(_)
| CoreTypeConcrete::SegmentArena(_)
| CoreTypeConcrete::Circuit(
CircuitTypeConcrete::AddMod(_) | CircuitTypeConcrete::MulMod(_),
) => Value::Unit,
CoreTypeConcrete::Starknet(inner) => match inner {
StarknetTypeConcrete::System(_) => Value::Unit,
StarknetTypeConcrete::ClassHash(_)
| StarknetTypeConcrete::ContractAddress(_)
| StarknetTypeConcrete::StorageBaseAddress(_)
| StarknetTypeConcrete::StorageAddress(_) => {
Value::parse_felt(&iter.next().unwrap())
}
_ => todo!(),
},
CoreTypeConcrete::EcOp(_) => Value::Unit,
_ => todo!("{}", type_to_name(type_id, vm.registry())),
}
})
.collect::<Vec<_>>(),
);
let syscall_handler = &mut StubSyscallHandler::default();
vm.run_with_trace(syscall_handler)
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/value.rs | debug_utils/sierra-emu/src/value.rs | use cairo_lang_sierra::{
extensions::{
circuit::CircuitTypeConcrete,
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
starknet::StarknetTypeConcrete,
ConcreteType,
},
ids::ConcreteTypeId,
program_registry::ProgramRegistry,
};
use num_bigint::{BigInt, BigUint};
use serde::Serialize;
use starknet_types_core::felt::Felt;
use std::{collections::HashMap, ops::Range};
use crate::{debug::type_to_name, gas::BuiltinCosts};
/// TODO: Can we reuse `cairo_native::Value::from_ptr`?
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub enum Value {
Array {
ty: ConcreteTypeId,
data: Vec<Self>,
},
BoundedInt {
range: Range<BigInt>,
value: BigInt,
},
Circuit(Vec<BigUint>),
CircuitOutputs {
circuits: Vec<BigUint>,
modulus: BigUint,
},
CircuitModulus(BigUint),
Enum {
self_ty: ConcreteTypeId,
index: usize,
payload: Box<Self>,
},
Felt(Felt),
Bytes31(Felt),
FeltDict {
ty: ConcreteTypeId,
data: HashMap<Felt, Self>,
count: u64,
},
FeltDictEntry {
ty: ConcreteTypeId,
data: HashMap<Felt, Self>,
count: u64,
key: Felt,
},
EcPoint {
x: Felt,
y: Felt,
},
EcState {
x0: Felt,
y0: Felt,
x1: Felt,
y1: Felt,
},
I128(i128),
I64(i64),
I32(i32),
I16(i16),
I8(i8),
Struct(Vec<Self>),
U256(u128, u128),
U128(u128),
U16(u16),
U32(u32),
U64(u64),
U8(u8),
IntRange {
x: Box<Value>,
y: Box<Value>,
},
Uninitialized {
ty: ConcreteTypeId,
},
BuiltinCosts(BuiltinCosts),
Null,
Unit,
}
impl Value {
pub fn default_for_type(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
type_id: &ConcreteTypeId,
) -> Self {
match registry.get_type(type_id).unwrap() {
CoreTypeConcrete::Uint8(_) => Value::U8(0),
CoreTypeConcrete::Uint32(_) => Value::U32(0),
CoreTypeConcrete::Uint64(_) => Value::U64(0),
CoreTypeConcrete::Uint16(_) => Value::U16(0),
CoreTypeConcrete::Uint128(_) => Value::U128(0),
CoreTypeConcrete::Felt252(_) => Value::Felt(0.into()),
CoreTypeConcrete::Enum(info) => Value::Enum {
self_ty: type_id.clone(),
index: 0,
payload: Box::new(Value::default_for_type(registry, &info.variants[0])),
},
CoreTypeConcrete::Array(info) => Value::Array {
ty: info.ty.clone(),
data: vec![],
},
CoreTypeConcrete::Struct(info) => Value::Struct(
info.members
.iter()
.map(|member| Value::default_for_type(registry, member))
.collect(),
),
CoreTypeConcrete::Nullable(_) => Value::Null,
x => panic!("type {:?} has no default value implementation", x.info()),
}
}
pub fn is(
&self,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
type_id: &ConcreteTypeId,
) -> bool {
let ty = registry.get_type(type_id).unwrap();
let res = match ty {
CoreTypeConcrete::Array(info) => {
matches!(self, Self::Array { ty, .. } if *ty == info.ty)
}
CoreTypeConcrete::BoundedInt(info) => {
matches!(self, Self::BoundedInt { range, .. } if range.start == info.range.lower && range.end == info.range.upper)
}
CoreTypeConcrete::Enum(_) => {
matches!(self, Self::Enum { self_ty, .. } if self_ty == type_id)
}
CoreTypeConcrete::Felt252(_) => matches!(self, Self::Felt(_)),
CoreTypeConcrete::Bytes31(_) => matches!(self, Self::Bytes31(_)),
CoreTypeConcrete::Felt252Dict(info) => {
matches!(self, Self::FeltDict { ty, .. } if *ty == info.ty)
}
CoreTypeConcrete::GasBuiltin(_) => matches!(self, Self::U64(_)),
CoreTypeConcrete::NonZero(info) => self.is(registry, &info.ty),
CoreTypeConcrete::Sint128(_) => matches!(self, Self::I128(_)),
CoreTypeConcrete::Sint32(_) => matches!(self, Self::I32(_)),
CoreTypeConcrete::Sint8(_) => matches!(self, Self::I8(_)),
CoreTypeConcrete::Snapshot(info) => self.is(registry, &info.ty),
CoreTypeConcrete::Starknet(
StarknetTypeConcrete::ClassHash(_)
| StarknetTypeConcrete::ContractAddress(_)
| StarknetTypeConcrete::StorageBaseAddress(_)
| StarknetTypeConcrete::StorageAddress(_),
) => matches!(self, Self::Felt(_)),
CoreTypeConcrete::Struct(info) => {
matches!(self, Self::Struct(members)
if members.len() == info.members.len()
&& members
.iter()
.zip(&info.members)
.all(|(value, ty)| value.is(registry, ty))
)
}
CoreTypeConcrete::Span(info) => self.is(registry, &info.ty),
CoreTypeConcrete::Uint8(_) => matches!(self, Self::U8(_)),
CoreTypeConcrete::Uint32(_) => matches!(self, Self::U32(_)),
CoreTypeConcrete::Uint128(_) => {
matches!(self, Self::U128(_))
}
// Unused builtins (mapped to `Value::Unit`).
CoreTypeConcrete::RangeCheck(_)
| CoreTypeConcrete::SegmentArena(_)
| CoreTypeConcrete::RangeCheck96(_)
| CoreTypeConcrete::Starknet(StarknetTypeConcrete::System(_)) => {
matches!(self, Self::Unit)
}
// To do:
CoreTypeConcrete::Coupon(_) => matches!(self, Self::Unit),
CoreTypeConcrete::Bitwise(_) => matches!(self, Self::Unit),
CoreTypeConcrete::Box(info) => self.is(registry, &info.ty),
// Circuit related types
CoreTypeConcrete::Circuit(selector) => match selector {
CircuitTypeConcrete::Circuit(_)
| CircuitTypeConcrete::CircuitData(_)
| CircuitTypeConcrete::CircuitInputAccumulator(_) => {
matches!(self, Self::Circuit(_))
}
CircuitTypeConcrete::CircuitOutputs(_) => {
matches!(self, Self::CircuitOutputs { .. })
}
CircuitTypeConcrete::CircuitModulus(_) => matches!(self, Self::CircuitModulus(_)),
CircuitTypeConcrete::U96Guarantee(_) => matches!(self, Self::U128(_)),
CircuitTypeConcrete::CircuitInput(_) => {
matches!(self, Self::Struct(_))
}
CircuitTypeConcrete::U96LimbsLessThanGuarantee(_) => {
matches!(self, Self::Struct(_))
}
CircuitTypeConcrete::AddMod(_)
| CircuitTypeConcrete::MulMod(_)
| CircuitTypeConcrete::CircuitDescriptor(_)
| CircuitTypeConcrete::CircuitFailureGuarantee(_)
| CircuitTypeConcrete::AddModGate(_)
| CircuitTypeConcrete::CircuitPartialOutputs(_)
| CircuitTypeConcrete::InverseGate(_)
| CircuitTypeConcrete::MulModGate(_)
| CircuitTypeConcrete::SubModGate(_) => matches!(self, Self::Unit),
},
CoreTypeConcrete::Const(info) => self.is(registry, &info.inner_ty),
CoreTypeConcrete::EcOp(_) => matches!(self, Self::Unit),
CoreTypeConcrete::EcPoint(_) => matches!(self, Self::EcPoint { .. }),
CoreTypeConcrete::EcState(_) => matches!(self, Self::EcState { .. }),
CoreTypeConcrete::BuiltinCosts(_) => matches!(self, Self::BuiltinCosts(_)),
CoreTypeConcrete::Uint16(_) => matches!(self, Self::U16(_)),
CoreTypeConcrete::Uint64(_) => matches!(self, Self::U64(_)),
CoreTypeConcrete::Uint128MulGuarantee(_) => matches!(self, Self::Unit),
CoreTypeConcrete::Sint16(_) => matches!(self, Self::I16(_)),
CoreTypeConcrete::Sint64(_) => matches!(self, Self::I64(_)),
CoreTypeConcrete::Nullable(info) => {
matches!(self, Value::Null) || self.is(registry, &info.ty)
}
CoreTypeConcrete::Uninitialized(_) => matches!(self, Self::Uninitialized { .. }),
CoreTypeConcrete::Felt252DictEntry(info) => {
matches!(self, Self::FeltDictEntry { ty, .. } if *ty == info.ty)
}
CoreTypeConcrete::SquashedFelt252Dict(info) => {
matches!(self, Self::FeltDict { ty, .. } if *ty == info.ty)
}
CoreTypeConcrete::Pedersen(_) => matches!(self, Self::Unit),
CoreTypeConcrete::Poseidon(_) => matches!(self, Self::Unit),
CoreTypeConcrete::Starknet(inner) => match inner {
StarknetTypeConcrete::ClassHash(_)
| StarknetTypeConcrete::ContractAddress(_)
| StarknetTypeConcrete::StorageBaseAddress(_)
| StarknetTypeConcrete::StorageAddress(_) => matches!(self, Self::Felt(_)),
StarknetTypeConcrete::System(_) => matches!(self, Self::Unit),
StarknetTypeConcrete::Secp256Point(_) => matches!(self, Self::Struct(_)),
StarknetTypeConcrete::Sha256StateHandle(_) => matches!(self, Self::Struct { .. }),
},
CoreTypeConcrete::IntRange(_) => matches!(self, Self::IntRange { .. }),
CoreTypeConcrete::GasReserve(_) => matches!(self, Self::U128(_)),
CoreTypeConcrete::Blake(_) => todo!(),
CoreTypeConcrete::QM31(_) => todo!(),
};
if !res {
dbg!(
"value is mismatch",
ty.info(),
self,
type_to_name(type_id, registry)
);
}
res
}
#[doc(hidden)]
pub fn parse_felt(value: &str) -> Self {
Self::Felt(if value.starts_with("0x") {
Felt::from_hex(value).unwrap()
} else {
Felt::from_dec_str(value).unwrap()
})
}
}
macro_rules! impl_conversions {
( $( $t:ty as $i:ident ; )+ ) => { $(
impl From<$t> for Value {
fn from(value: $t) -> Self {
Self::$i(value)
}
}
impl TryFrom<Value> for $t {
type Error = Value;
fn try_from(value: Value) -> Result<Self, Self::Error> {
match value {
Value::$i(value) => Ok(value),
_ => Err(value),
}
}
}
)+ };
}
impl_conversions! {
Felt as Felt;
u8 as U8;
u16 as U16;
u32 as U32;
u64 as U64;
u128 as U128;
i8 as I8;
i16 as I16;
i32 as I32;
i64 as I64;
i128 as I128;
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/args.rs | debug_utils/sierra-emu/src/args.rs | use clap::Parser;
use sierra_emu::EntryPoint;
use std::path::PathBuf;
#[derive(Debug, Parser)]
pub struct CmdArgs {
pub program: PathBuf,
pub entry_point: EntryPoint,
pub args: Vec<String>,
#[clap(long)]
pub available_gas: Option<u64>,
#[clap(long, short)]
pub output: Option<PathBuf>,
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/test_utils.rs | debug_utils/sierra-emu/src/test_utils.rs | #![cfg(test)]
use std::{fs, path::Path, sync::Arc};
use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, diagnostics::DiagnosticsReporter,
project::setup_project, CompilerConfig,
};
use cairo_lang_filesystem::{db::init_dev_corelib, ids::CrateInput};
use cairo_lang_sierra::program::Program;
use crate::{starknet::StubSyscallHandler, Value, VirtualMachine};
#[macro_export]
macro_rules! load_cairo {
( $( $program:tt )+ ) => {
$crate::test_utils::load_cairo_from_str(stringify!($($program)+))
};
}
pub(crate) fn load_cairo_from_str(cairo_str: &str) -> (String, Program) {
let mut file = tempfile::Builder::new()
.prefix("test_")
.suffix(".cairo")
.tempfile()
.unwrap();
let mut db = RootDatabase::default();
fs::write(&mut file, cairo_str).unwrap();
init_dev_corelib(
&mut db,
Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("corelib/src"),
);
let main_crate_ids = {
let crate_inputs = setup_project(&mut db, file.path()).unwrap();
CrateInput::into_crate_ids(&db, crate_inputs)
};
let sierra_with_dbg = compile_prepared_db(
&db,
main_crate_ids,
CompilerConfig {
diagnostics_reporter: DiagnosticsReporter::stderr(),
replace_ids: true,
..Default::default()
},
)
.unwrap();
let module_name = file.path().with_extension("");
let module_name = module_name.file_name().unwrap().to_str().unwrap();
(module_name.to_string(), sierra_with_dbg.program)
}
pub fn run_test_program(sierra_program: Program) -> Vec<Value> {
let function = sierra_program
.funcs
.iter()
.find(|f| {
f.id.debug_name
.as_ref()
.map(|name| name.as_str().contains("main"))
.unwrap_or_default()
})
.unwrap();
let mut vm = VirtualMachine::new(Arc::new(sierra_program.clone()));
let initial_gas = 1000000;
let args: &[Value] = &[];
vm.call_program(function, initial_gas, args.iter().cloned());
let syscall_handler = &mut StubSyscallHandler::default();
let trace = vm.run_with_trace(syscall_handler);
trace
.states
.last()
.unwrap()
.items
.values()
.cloned()
.collect()
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/debug.rs | debug_utils/sierra-emu/src/debug.rs | use cairo_lang_sierra::{
extensions::{
array::ArrayConcreteLibfunc,
boolean::BoolConcreteLibfunc,
bounded_int::BoundedIntConcreteLibfunc,
boxing::BoxConcreteLibfunc,
bytes31::Bytes31ConcreteLibfunc,
casts::CastConcreteLibfunc,
circuit::{CircuitConcreteLibfunc, CircuitTypeConcrete},
const_type::ConstConcreteLibfunc,
core::{CoreConcreteLibfunc, CoreLibfunc, CoreType, CoreTypeConcrete},
coupon::CouponConcreteLibfunc,
debug::DebugConcreteLibfunc,
ec::EcConcreteLibfunc,
enm::EnumConcreteLibfunc,
felt252::{Felt252BinaryOperationConcrete, Felt252BinaryOperator, Felt252Concrete},
felt252_dict::{Felt252DictConcreteLibfunc, Felt252DictEntryConcreteLibfunc},
gas::GasConcreteLibfunc,
gas_reserve::GasReserveConcreteLibfunc,
int::{
signed::SintConcrete, signed128::Sint128Concrete, unsigned::UintConcrete,
unsigned128::Uint128Concrete, unsigned256::Uint256Concrete,
unsigned512::Uint512Concrete, IntOperator,
},
lib_func::{BranchSignature, ParamSignature},
mem::MemConcreteLibfunc,
nullable::NullableConcreteLibfunc,
pedersen::PedersenConcreteLibfunc,
poseidon::PoseidonConcreteLibfunc,
range::IntRangeConcreteLibfunc,
starknet::{
secp256::{Secp256ConcreteLibfunc, Secp256OpConcreteLibfunc},
testing::TestingConcreteLibfunc,
StarknetConcreteLibfunc, StarknetTypeConcrete,
},
structure::StructConcreteLibfunc,
},
ids::ConcreteTypeId,
program_registry::ProgramRegistry,
};
use crate::Value;
pub fn libfunc_to_name(value: &CoreConcreteLibfunc) -> &'static str {
match value {
CoreConcreteLibfunc::ApTracking(value) => match value {
cairo_lang_sierra::extensions::ap_tracking::ApTrackingConcreteLibfunc::Revoke(_) => {
"revoke_ap_tracking"
}
cairo_lang_sierra::extensions::ap_tracking::ApTrackingConcreteLibfunc::Enable(_) => {
"enable_ap_tracking"
}
cairo_lang_sierra::extensions::ap_tracking::ApTrackingConcreteLibfunc::Disable(_) => {
"disable_ap_tracking"
}
},
CoreConcreteLibfunc::Array(value) => match value {
ArrayConcreteLibfunc::New(_) => "array_new",
ArrayConcreteLibfunc::SpanFromTuple(_) => "span_from_tuple",
ArrayConcreteLibfunc::Append(_) => "array_append",
ArrayConcreteLibfunc::PopFront(_) => "array_pop_front",
ArrayConcreteLibfunc::PopFrontConsume(_) => "array_pop_front_consume",
ArrayConcreteLibfunc::Get(_) => "array_get",
ArrayConcreteLibfunc::Slice(_) => "array_slice",
ArrayConcreteLibfunc::Len(_) => "array_len",
ArrayConcreteLibfunc::SnapshotPopFront(_) => "array_snapshot_pop_front",
ArrayConcreteLibfunc::SnapshotPopBack(_) => "array_snapshot_pop_back",
ArrayConcreteLibfunc::TupleFromSpan(_) => "array_tuple_from_span",
ArrayConcreteLibfunc::SnapshotMultiPopFront(_) => "array_snapshot_multi_pop_front",
ArrayConcreteLibfunc::SnapshotMultiPopBack(_) => "array_snapshot_multi_pop_back",
},
CoreConcreteLibfunc::BranchAlign(_) => "branch_align",
CoreConcreteLibfunc::Bool(value) => match value {
BoolConcreteLibfunc::And(_) => "bool_and",
BoolConcreteLibfunc::Not(_) => "bool_not",
BoolConcreteLibfunc::Xor(_) => "bool_xor",
BoolConcreteLibfunc::Or(_) => "bool_or",
BoolConcreteLibfunc::ToFelt252(_) => "bool_to_felt252",
},
CoreConcreteLibfunc::Box(value) => match value {
BoxConcreteLibfunc::Into(_) => "box_into",
BoxConcreteLibfunc::Unbox(_) => "box_unbox",
BoxConcreteLibfunc::ForwardSnapshot(_) => "box_forward_snapshot",
BoxConcreteLibfunc::LocalInto(_) => todo!(),
},
CoreConcreteLibfunc::Cast(value) => match value {
CastConcreteLibfunc::Downcast(_) => "downcast",
CastConcreteLibfunc::Upcast(_) => "upcast",
},
CoreConcreteLibfunc::Coupon(value) => match value {
CouponConcreteLibfunc::Buy(_) => "coupon_buy",
CouponConcreteLibfunc::Refund(_) => "coupon_refund",
},
CoreConcreteLibfunc::CouponCall(_) => "coupon_call",
CoreConcreteLibfunc::Drop(_) => "drop",
CoreConcreteLibfunc::Dup(_) => "dup",
CoreConcreteLibfunc::Ec(value) => match value {
EcConcreteLibfunc::IsZero(_) => "ec_is_zero",
EcConcreteLibfunc::Neg(_) => "ec_neg",
EcConcreteLibfunc::StateAdd(_) => "ec_state_add",
EcConcreteLibfunc::TryNew(_) => "ec_try_new",
EcConcreteLibfunc::StateFinalize(_) => "ec_state_finalize",
EcConcreteLibfunc::StateInit(_) => "ec_state_init",
EcConcreteLibfunc::StateAddMul(_) => "ec_state_add_mul",
EcConcreteLibfunc::PointFromX(_) => "ec_point_from_x",
EcConcreteLibfunc::UnwrapPoint(_) => "ec_unwrap_point",
EcConcreteLibfunc::Zero(_) => "ec_zero",
EcConcreteLibfunc::NegNz(_) => todo!(),
},
CoreConcreteLibfunc::Felt252(value) => match value {
Felt252Concrete::BinaryOperation(op) => match op {
Felt252BinaryOperationConcrete::WithVar(op) => match &op.operator {
Felt252BinaryOperator::Add => "felt252_add",
Felt252BinaryOperator::Sub => "felt252_sub",
Felt252BinaryOperator::Mul => "felt252_mul",
Felt252BinaryOperator::Div => "felt252_div",
},
Felt252BinaryOperationConcrete::WithConst(op) => match &op.operator {
Felt252BinaryOperator::Add => "felt252_const_add",
Felt252BinaryOperator::Sub => "felt252_const_sub",
Felt252BinaryOperator::Mul => "felt252_const_mul",
Felt252BinaryOperator::Div => "felt252_const_div",
},
},
Felt252Concrete::Const(_) => "felt252_const",
Felt252Concrete::IsZero(_) => "felt252_is_zero",
},
CoreConcreteLibfunc::Const(value) => match value {
ConstConcreteLibfunc::AsBox(_) => "const_as_box",
ConstConcreteLibfunc::AsImmediate(_) => "const_as_immediate",
},
CoreConcreteLibfunc::FunctionCall(_) => "function_call",
CoreConcreteLibfunc::Gas(value) => match value {
GasConcreteLibfunc::WithdrawGas(_) => "withdraw_gas",
GasConcreteLibfunc::RedepositGas(_) => "redeposit_gas",
GasConcreteLibfunc::GetAvailableGas(_) => "get_available_gas",
GasConcreteLibfunc::BuiltinWithdrawGas(_) => "builtin_withdraw_gas",
GasConcreteLibfunc::GetBuiltinCosts(_) => "get_builtin_costs",
GasConcreteLibfunc::GetUnspentGas(_) => todo!(),
},
CoreConcreteLibfunc::Uint8(value) => match value {
UintConcrete::Const(_) => "u8_const",
UintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "u8_overflowing_add",
IntOperator::OverflowingSub => "u8_overflowing_sub",
},
UintConcrete::SquareRoot(_) => "u8_sqrt",
UintConcrete::Equal(_) => "u8_eq",
UintConcrete::ToFelt252(_) => "u8_to_felt252",
UintConcrete::FromFelt252(_) => "u8_from_felt252",
UintConcrete::IsZero(_) => "u8_is_zero",
UintConcrete::Divmod(_) => "u8_divmod",
UintConcrete::WideMul(_) => "u8_wide_mul",
UintConcrete::Bitwise(_) => "u8_bitwise",
},
CoreConcreteLibfunc::Uint16(value) => match value {
UintConcrete::Const(_) => "u16_const",
UintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "u16_overflowing_add",
IntOperator::OverflowingSub => "u16_overflowing_sub",
},
UintConcrete::SquareRoot(_) => "u16_sqrt",
UintConcrete::Equal(_) => "u16_eq",
UintConcrete::ToFelt252(_) => "u16_to_felt252",
UintConcrete::FromFelt252(_) => "u16_from_felt252",
UintConcrete::IsZero(_) => "u16_is_zero",
UintConcrete::Divmod(_) => "u16_divmod",
UintConcrete::WideMul(_) => "u16_wide_mul",
UintConcrete::Bitwise(_) => "u16_bitwise",
},
CoreConcreteLibfunc::Uint32(value) => match value {
UintConcrete::Const(_) => "u32_const",
UintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "u32_overflowing_add",
IntOperator::OverflowingSub => "u32_overflowing_sub",
},
UintConcrete::SquareRoot(_) => "u32_sqrt",
UintConcrete::Equal(_) => "u32_eq",
UintConcrete::ToFelt252(_) => "u32_to_felt252",
UintConcrete::FromFelt252(_) => "u32_from_felt252",
UintConcrete::IsZero(_) => "u32_is_zero",
UintConcrete::Divmod(_) => "u32_divmod",
UintConcrete::WideMul(_) => "u32_wide_mul",
UintConcrete::Bitwise(_) => "u32_bitwise",
},
CoreConcreteLibfunc::Uint64(value) => match value {
UintConcrete::Const(_) => "u64_const",
UintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "u64_overflowing_add",
IntOperator::OverflowingSub => "u64_overflowing_sub",
},
UintConcrete::SquareRoot(_) => "u64_sqrt",
UintConcrete::Equal(_) => "u64_eq",
UintConcrete::ToFelt252(_) => "u64_to_felt252",
UintConcrete::FromFelt252(_) => "u64_from_felt252",
UintConcrete::IsZero(_) => "u64_is_zero",
UintConcrete::Divmod(_) => "u64_divmod",
UintConcrete::WideMul(_) => "u64_wide_mul",
UintConcrete::Bitwise(_) => "u64_bitwise",
},
CoreConcreteLibfunc::Uint128(value) => match value {
Uint128Concrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "u128_overflowing_add",
IntOperator::OverflowingSub => "u128_overflowing_sub",
},
Uint128Concrete::Divmod(_) => "u128_divmod",
Uint128Concrete::GuaranteeMul(_) => "u128_guarantee_mul",
Uint128Concrete::MulGuaranteeVerify(_) => "u128_mul_guarantee_verify",
Uint128Concrete::Equal(_) => "u128_equal",
Uint128Concrete::SquareRoot(_) => "u128_sqrt",
Uint128Concrete::Const(_) => "u128_const",
Uint128Concrete::FromFelt252(_) => "u128_from_felt",
Uint128Concrete::ToFelt252(_) => "u128_to_felt252",
Uint128Concrete::IsZero(_) => "u128_is_zero",
Uint128Concrete::Bitwise(_) => "u128_bitwise",
Uint128Concrete::ByteReverse(_) => "u128_byte_reverse",
},
CoreConcreteLibfunc::Uint256(value) => match value {
Uint256Concrete::IsZero(_) => "u256_is_zero",
Uint256Concrete::Divmod(_) => "u256_divmod",
Uint256Concrete::SquareRoot(_) => "u256_sqrt",
Uint256Concrete::InvModN(_) => "u256_inv_mod_n",
},
CoreConcreteLibfunc::Uint512(value) => match value {
Uint512Concrete::DivModU256(_) => "u512_divmod_u256",
},
CoreConcreteLibfunc::Sint8(value) => match value {
SintConcrete::Const(_) => "i8_const",
SintConcrete::Equal(_) => "i8_eq",
SintConcrete::ToFelt252(_) => "i8_to_felt252",
SintConcrete::FromFelt252(_) => "i8_from_felt252",
SintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "i8_overflowing_add",
IntOperator::OverflowingSub => "i8_overflowing_sub",
},
SintConcrete::Diff(_) => "i8_diff",
SintConcrete::WideMul(_) => "i8_wide_mul",
},
CoreConcreteLibfunc::Sint16(value) => match value {
SintConcrete::Const(_) => "i16_const",
SintConcrete::Equal(_) => "i16_eq",
SintConcrete::ToFelt252(_) => "i16_to_felt252",
SintConcrete::FromFelt252(_) => "i16_from_felt252",
SintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "i16_overflowing_add",
IntOperator::OverflowingSub => "i16_overflowing_sub",
},
SintConcrete::Diff(_) => "i16_diff",
SintConcrete::WideMul(_) => "i16_wide_mul",
},
CoreConcreteLibfunc::Sint32(value) => match value {
SintConcrete::Const(_) => "i32_const",
SintConcrete::Equal(_) => "i32_eq",
SintConcrete::ToFelt252(_) => "i32_to_felt252",
SintConcrete::FromFelt252(_) => "i32_from_felt252",
SintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "i32_overflowing_add",
IntOperator::OverflowingSub => "i32_overflowing_sub",
},
SintConcrete::Diff(_) => "i32_diff",
SintConcrete::WideMul(_) => "i32_wide_mul",
},
CoreConcreteLibfunc::Sint64(value) => match value {
SintConcrete::Const(_) => "i64_const",
SintConcrete::Equal(_) => "i64_eq",
SintConcrete::ToFelt252(_) => "i64_to_felt252",
SintConcrete::FromFelt252(_) => "i64_from_felt252",
SintConcrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "i64_overflowing_add",
IntOperator::OverflowingSub => "i64_overflowing_sub",
},
SintConcrete::Diff(_) => "i64_diff",
SintConcrete::WideMul(_) => "i64_wide_mul",
},
CoreConcreteLibfunc::Sint128(value) => match value {
Sint128Concrete::Const(_) => "i128_const",
Sint128Concrete::Equal(_) => "i128_eq",
Sint128Concrete::ToFelt252(_) => "i128_to_felt252",
Sint128Concrete::FromFelt252(_) => "i128_from_felt252",
Sint128Concrete::Operation(op) => match &op.operator {
IntOperator::OverflowingAdd => "i128_overflowing_add",
IntOperator::OverflowingSub => "i128_overflowing_sub",
},
Sint128Concrete::Diff(_) => "i128_diff",
},
CoreConcreteLibfunc::Mem(value) => match value {
MemConcreteLibfunc::StoreTemp(_) => "store_temp",
MemConcreteLibfunc::StoreLocal(_) => "store_local",
MemConcreteLibfunc::FinalizeLocals(_) => "finalize_locals",
MemConcreteLibfunc::AllocLocal(_) => "alloc_local",
MemConcreteLibfunc::Rename(_) => "rename",
},
CoreConcreteLibfunc::Nullable(value) => match value {
NullableConcreteLibfunc::Null(_) => "nullable_null",
NullableConcreteLibfunc::NullableFromBox(_) => "nullable_from_box",
NullableConcreteLibfunc::MatchNullable(_) => "match_nullable",
NullableConcreteLibfunc::ForwardSnapshot(_) => "nullable_forward_snapshot",
},
CoreConcreteLibfunc::UnwrapNonZero(_) => "unwrap_non_zero",
CoreConcreteLibfunc::UnconditionalJump(_) => "jump",
CoreConcreteLibfunc::Enum(value) => match value {
EnumConcreteLibfunc::Init(_) => "enum_init",
EnumConcreteLibfunc::FromBoundedInt(_) => "enum_from_bounded_int",
EnumConcreteLibfunc::Match(_) => "enum_match",
EnumConcreteLibfunc::SnapshotMatch(_) => "enum_snapshot_match",
},
CoreConcreteLibfunc::Struct(value) => match value {
StructConcreteLibfunc::Construct(_) => "struct_construct",
StructConcreteLibfunc::Deconstruct(_) => "struct_deconstruct",
StructConcreteLibfunc::SnapshotDeconstruct(_) => "struct_snapshot_deconstruct",
StructConcreteLibfunc::BoxedDeconstruct(_) => "struct_boxed_deconstruct",
},
CoreConcreteLibfunc::Felt252Dict(value) => match value {
Felt252DictConcreteLibfunc::New(_) => "felt252dict_new",
Felt252DictConcreteLibfunc::Squash(_) => "felt252dict_squash",
},
CoreConcreteLibfunc::Felt252DictEntry(value) => match value {
Felt252DictEntryConcreteLibfunc::Get(_) => "felt252dict_get",
Felt252DictEntryConcreteLibfunc::Finalize(_) => "felt252dict_finalize",
},
CoreConcreteLibfunc::Pedersen(value) => match value {
PedersenConcreteLibfunc::PedersenHash(_) => "pedersen_hash",
},
CoreConcreteLibfunc::Poseidon(value) => match value {
PoseidonConcreteLibfunc::HadesPermutation(_) => "hades_permutation",
},
CoreConcreteLibfunc::Starknet(value) => match value {
StarknetConcreteLibfunc::CallContract(_) => "call_contract",
StarknetConcreteLibfunc::ClassHashConst(_) => "class_hash_const",
StarknetConcreteLibfunc::ClassHashTryFromFelt252(_) => "class_hash_try_from_felt252",
StarknetConcreteLibfunc::ClassHashToFelt252(_) => "class_hash_to_felt252",
StarknetConcreteLibfunc::ContractAddressConst(_) => "contract_address_const",
StarknetConcreteLibfunc::ContractAddressTryFromFelt252(_) => {
"contract_address_try_from_felt252"
}
StarknetConcreteLibfunc::ContractAddressToFelt252(_) => "contract_address_to_felt252",
StarknetConcreteLibfunc::StorageRead(_) => "storage_read",
StarknetConcreteLibfunc::StorageWrite(_) => "storage_write",
StarknetConcreteLibfunc::StorageBaseAddressConst(_) => "storage_base_address_const",
StarknetConcreteLibfunc::StorageBaseAddressFromFelt252(_) => {
"storage_base_address_from_felt252"
}
StarknetConcreteLibfunc::StorageAddressFromBase(_) => "storage_address_from_base",
StarknetConcreteLibfunc::StorageAddressFromBaseAndOffset(_) => {
"storage_address_from_base_and_offset"
}
StarknetConcreteLibfunc::StorageAddressToFelt252(_) => "storage_address_to_felt252",
StarknetConcreteLibfunc::StorageAddressTryFromFelt252(_) => {
"storage_address_try_from_felt252"
}
StarknetConcreteLibfunc::EmitEvent(_) => "emit_event",
StarknetConcreteLibfunc::GetBlockHash(_) => "get_block_hash",
StarknetConcreteLibfunc::GetExecutionInfo(_) => "get_exec_info_v1",
StarknetConcreteLibfunc::GetExecutionInfoV2(_) => "get_exec_info_v2",
StarknetConcreteLibfunc::Deploy(_) => "deploy",
StarknetConcreteLibfunc::Keccak(_) => "keccak",
StarknetConcreteLibfunc::LibraryCall(_) => "library_call",
StarknetConcreteLibfunc::ReplaceClass(_) => "replace_class",
StarknetConcreteLibfunc::SendMessageToL1(_) => "send_message_to_l1",
StarknetConcreteLibfunc::Testing(value) => match value {
TestingConcreteLibfunc::Cheatcode(_) => "cheatcode",
},
StarknetConcreteLibfunc::Secp256(value) => match value {
Secp256ConcreteLibfunc::K1(value) => match value {
Secp256OpConcreteLibfunc::New(_) => "secp256k1_new",
Secp256OpConcreteLibfunc::Add(_) => "secp256k1_add",
Secp256OpConcreteLibfunc::Mul(_) => "secp256k1_mul",
Secp256OpConcreteLibfunc::GetPointFromX(_) => "secp256k1_get_point_from_x",
Secp256OpConcreteLibfunc::GetXy(_) => "secp256k1_get_xy",
},
Secp256ConcreteLibfunc::R1(value) => match value {
Secp256OpConcreteLibfunc::New(_) => "secp256r1_new",
Secp256OpConcreteLibfunc::Add(_) => "secp256r1_add",
Secp256OpConcreteLibfunc::Mul(_) => "secp256r1_mul",
Secp256OpConcreteLibfunc::GetPointFromX(_) => "secp256r1_get_point_from_x",
Secp256OpConcreteLibfunc::GetXy(_) => "secp256r1_get_xy",
},
},
StarknetConcreteLibfunc::Sha256ProcessBlock(_) => "sha256_process_block",
StarknetConcreteLibfunc::Sha256StateHandleInit(_) => "sha256_state_handle_init",
StarknetConcreteLibfunc::Sha256StateHandleDigest(_) => "sha256_state_handle_digest",
StarknetConcreteLibfunc::GetClassHashAt(_) => "get_class_hash_at",
StarknetConcreteLibfunc::MetaTxV0(_) => todo!(),
StarknetConcreteLibfunc::GetExecutionInfoV3(_) => todo!(),
},
CoreConcreteLibfunc::Debug(value) => match value {
DebugConcreteLibfunc::Print(_) => "debug_print",
},
CoreConcreteLibfunc::SnapshotTake(_) => "snapshot_take",
CoreConcreteLibfunc::Bytes31(value) => match value {
Bytes31ConcreteLibfunc::Const(_) => "bytes31_const",
Bytes31ConcreteLibfunc::ToFelt252(_) => "bytes31_to_felt252",
Bytes31ConcreteLibfunc::TryFromFelt252(_) => "bytes31_try_from_felt252",
},
CoreConcreteLibfunc::Circuit(selector) => match selector {
CircuitConcreteLibfunc::AddInput(_) => "circuit_add_input",
CircuitConcreteLibfunc::Eval(_) => "circuit_eval",
CircuitConcreteLibfunc::GetDescriptor(_) => "circuit_get_descriptor",
CircuitConcreteLibfunc::InitCircuitData(_) => "circuit_init_circuit_data",
CircuitConcreteLibfunc::GetOutput(_) => "circuit_get_output",
CircuitConcreteLibfunc::TryIntoCircuitModulus(_) => "circuit_try_into_circuit_modulus",
CircuitConcreteLibfunc::FailureGuaranteeVerify(_) => "circuit_failure_guarantee_verify",
CircuitConcreteLibfunc::IntoU96Guarantee(_) => "circuit_into_u96_guarantee",
CircuitConcreteLibfunc::U96GuaranteeVerify(_) => "circuit_u96_guarantee_verify",
CircuitConcreteLibfunc::U96LimbsLessThanGuaranteeVerify(_) => {
"circuit_u96_limbs_less_than_guarantee_verify"
}
CircuitConcreteLibfunc::U96SingleLimbLessThanGuaranteeVerify(_) => {
"circuit_u96_single_limb_less_than_guarantee_verify"
}
},
CoreConcreteLibfunc::BoundedInt(selector) => match selector {
BoundedIntConcreteLibfunc::Add(_) => "bounded_int_add",
BoundedIntConcreteLibfunc::Sub(_) => "bounded_int_sub",
BoundedIntConcreteLibfunc::Mul(_) => "bounded_int_mul",
BoundedIntConcreteLibfunc::DivRem(_) => "bounded_int_div_rem",
BoundedIntConcreteLibfunc::Constrain(_) => "bounded_int_constrain",
BoundedIntConcreteLibfunc::IsZero(_) => "bounded_int_is_zero",
BoundedIntConcreteLibfunc::WrapNonZero(_) => "bounded_int_wrap_non_zero",
BoundedIntConcreteLibfunc::TrimMin(_) => "bounded_int_trim_min",
BoundedIntConcreteLibfunc::TrimMax(_) => "bounded_int_trim_max",
},
CoreConcreteLibfunc::IntRange(selector) => match selector {
IntRangeConcreteLibfunc::TryNew(_) => "int_range_try_new",
IntRangeConcreteLibfunc::PopFront(_) => "int_range_pop_front",
},
CoreConcreteLibfunc::Blake(_) => todo!(),
CoreConcreteLibfunc::Felt252SquashedDict(_) => todo!(),
CoreConcreteLibfunc::Trace(_) => todo!(),
CoreConcreteLibfunc::QM31(_) => todo!(),
CoreConcreteLibfunc::UnsafePanic(_) => todo!(),
CoreConcreteLibfunc::DummyFunctionCall(_) => "dummy_function_call",
CoreConcreteLibfunc::GasReserve(selector) => match selector {
GasReserveConcreteLibfunc::Create(_) => "gas_reserve_create",
GasReserveConcreteLibfunc::Utilize(_) => "gas_reserve_utilize",
},
}
}
pub fn type_to_name(
ty_id: &ConcreteTypeId,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
) -> String {
let ty = registry.get_type(ty_id).unwrap();
match ty {
CoreTypeConcrete::Array(info) => {
format!("Array<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Box(info) => {
format!("Box<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Uninitialized(info) => {
format!("Uninitialized<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::NonZero(info) => {
format!("NonZero<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Nullable(info) => {
format!("Nullable<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Span(info) => {
format!("Span<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Snapshot(info) => {
format!("Snapshot<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Struct(info) => {
let fields = info
.members
.iter()
.map(|ty_id| type_to_name(ty_id, registry))
.collect::<Vec<_>>();
let fields = fields.join(", ");
format!("Struct<{}>", fields)
}
CoreTypeConcrete::Enum(info) => {
let fields = info
.variants
.iter()
.map(|ty_id| type_to_name(ty_id, registry))
.collect::<Vec<_>>();
let fields = fields.join(", ");
format!("Enum<{}>", fields)
}
CoreTypeConcrete::Felt252Dict(_) => String::from("Felt252Dict"),
CoreTypeConcrete::Felt252DictEntry(_) => String::from("Felt252DictEntry"),
CoreTypeConcrete::SquashedFelt252Dict(_) => String::from("SquashedFelt252Dict"),
CoreTypeConcrete::Starknet(selector) => match selector {
StarknetTypeConcrete::ClassHash(_) => String::from("Starknet::ClassHash"),
StarknetTypeConcrete::ContractAddress(_) => String::from("Starknet::ContractAddress"),
StarknetTypeConcrete::StorageBaseAddress(_) => {
String::from("Starknet::StorageBaseAddress")
}
StarknetTypeConcrete::StorageAddress(_) => String::from("Starknet::StorageAddress"),
StarknetTypeConcrete::System(_) => String::from("Starknet::System"),
StarknetTypeConcrete::Secp256Point(_) => String::from("Starknet::Secp256Point"),
StarknetTypeConcrete::Sha256StateHandle(_) => {
String::from("Starknet::Sha256StateHandle")
}
},
CoreTypeConcrete::Bitwise(_) => String::from("Bitwise"),
CoreTypeConcrete::Circuit(selector) => match selector {
CircuitTypeConcrete::AddMod(_) => String::from("AddMod"),
CircuitTypeConcrete::MulMod(_) => String::from("MulMod"),
CircuitTypeConcrete::AddModGate(_) => String::from("AddModGate"),
CircuitTypeConcrete::Circuit(_) => String::from("Circuit"),
CircuitTypeConcrete::CircuitData(_) => String::from("CircuitData"),
CircuitTypeConcrete::CircuitOutputs(_) => String::from("CircuitOutputs"),
CircuitTypeConcrete::CircuitPartialOutputs(_) => String::from("CircuitPartialOutputs"),
CircuitTypeConcrete::CircuitDescriptor(_) => String::from("CircuitDescriptor"),
CircuitTypeConcrete::CircuitFailureGuarantee(_) => {
String::from("CircuitFailureGuarantee")
}
CircuitTypeConcrete::CircuitInput(_) => String::from("CircuitInput"),
CircuitTypeConcrete::CircuitInputAccumulator(_) => {
String::from("CircuitInputAccumulator")
}
CircuitTypeConcrete::CircuitModulus(_) => String::from("CircuitModulus"),
CircuitTypeConcrete::InverseGate(_) => String::from("InverseGate"),
CircuitTypeConcrete::MulModGate(_) => String::from("MulModGate"),
CircuitTypeConcrete::SubModGate(_) => String::from("SubModGate"),
CircuitTypeConcrete::U96Guarantee(_) => String::from("U96Guarantee"),
CircuitTypeConcrete::U96LimbsLessThanGuarantee(_) => {
String::from("U96LimbsLessThanGuarantee")
}
},
CoreTypeConcrete::Const(_) => String::from("Const"),
CoreTypeConcrete::Coupon(_) => String::from("Coupon"),
CoreTypeConcrete::EcOp(_) => String::from("EcOp"),
CoreTypeConcrete::EcPoint(_) => String::from("EcPoint"),
CoreTypeConcrete::EcState(_) => String::from("EcState"),
CoreTypeConcrete::Felt252(_) => String::from("Felt252"),
CoreTypeConcrete::GasBuiltin(_) => String::from("GasBuiltin"),
CoreTypeConcrete::BuiltinCosts(_) => String::from("BuiltinCosts"),
CoreTypeConcrete::Uint8(_) => String::from("Uint8"),
CoreTypeConcrete::Uint16(_) => String::from("Uint16"),
CoreTypeConcrete::Uint32(_) => String::from("Uint32"),
CoreTypeConcrete::Uint64(_) => String::from("Uint64"),
CoreTypeConcrete::Uint128(_) => String::from("Uint128"),
CoreTypeConcrete::Uint128MulGuarantee(_) => String::from("Uint128MulGuarantee"),
CoreTypeConcrete::Sint8(_) => String::from("Sint8"),
CoreTypeConcrete::Sint16(_) => String::from("Sint16"),
CoreTypeConcrete::Sint32(_) => String::from("Sint32"),
CoreTypeConcrete::Sint64(_) => String::from("Sint64"),
CoreTypeConcrete::Sint128(_) => String::from("Sint128"),
CoreTypeConcrete::RangeCheck(_) => String::from("RangeCheck"),
CoreTypeConcrete::RangeCheck96(_) => String::from("RangeCheck96"),
CoreTypeConcrete::Pedersen(_) => String::from("Pedersen"),
CoreTypeConcrete::Poseidon(_) => String::from("Poseidon"),
CoreTypeConcrete::SegmentArena(_) => String::from("SegmentArena"),
CoreTypeConcrete::Bytes31(_) => String::from("Bytes31"),
CoreTypeConcrete::BoundedInt(_) => String::from("BoundedInt"),
CoreTypeConcrete::IntRange(info) => {
format!("IntRange<{}>", type_to_name(&info.ty, registry))
}
CoreTypeConcrete::Blake(_) => todo!(),
CoreTypeConcrete::QM31(_) => todo!(),
CoreTypeConcrete::GasReserve(_) => String::from("GasReserve"),
}
}
/// prints all the signature information, used while debugging to learn
/// how to implement a certain libfunc.
#[allow(dead_code)]
pub fn debug_signature(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
params: &[ParamSignature],
branches: &[BranchSignature],
args: &[Value],
) {
println!(
"Params: {:#?}",
params
.iter()
.map(|p| type_to_name(&p.ty, registry))
.collect::<Vec<_>>()
);
println!(
"Branches: {:#?}",
branches
.iter()
.map(|b| {
b.vars
.iter()
.map(|vars| type_to_name(&vars.ty, registry))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
);
println!("Args: {:#?}", args);
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/dump.rs | debug_utils/sierra-emu/src/dump.rs | use crate::value::Value;
use cairo_lang_sierra::{ids::VarId, program::StatementIdx};
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use serde::{ser::SerializeMap, Serialize};
use starknet_crypto::Felt;
use std::collections::BTreeMap;
#[derive(Clone, Debug, Default, Serialize, Eq, PartialEq)]
pub struct ProgramTrace {
pub states: Vec<StateDump>,
// TODO: Syscall data.
}
impl ProgramTrace {
pub fn new() -> Self {
Self { states: Vec::new() }
}
pub fn push(&mut self, state: StateDump) {
self.states.push(state);
}
pub fn return_value(&self) -> Value {
self.states
.last()
.unwrap()
.items
.values()
.cloned()
.collect::<Vec<_>>()
.last()
.cloned()
.unwrap_or(Value::Unit)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StateDump {
pub statement_idx: StatementIdx,
pub items: BTreeMap<u64, Value>,
}
impl StateDump {
pub fn new(statement_idx: StatementIdx, state: OrderedHashMap<VarId, Value>) -> Self {
Self {
statement_idx,
items: state
.into_iter()
.map(|(id, value)| (id.id, value))
.collect(),
}
}
}
impl Serialize for StateDump {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut s = s.serialize_map(Some(2))?;
s.serialize_entry("statementIdx", &self.statement_idx.0)?;
s.serialize_entry("preStateDump", &self.items)?;
s.end()
}
}
#[derive(Debug, Clone)]
pub struct ContractExecutionResult {
pub remaining_gas: u64,
pub failure_flag: bool,
pub return_values: Vec<Felt>,
pub error_msg: Option<String>,
}
impl ContractExecutionResult {
pub fn from_trace(trace: &ProgramTrace) -> Option<Self> {
let last = trace.states.last()?;
Self::from_state(last)
}
pub fn from_state(state: &StateDump) -> Option<Self> {
let mut remaining_gas = None;
let mut error_msg = None;
let mut failure_flag = false;
let mut return_values = Vec::new();
for value in state.items.values() {
match value {
Value::U64(gas) => remaining_gas = Some(*gas),
Value::Enum {
self_ty: _,
index,
payload,
} => {
failure_flag = (*index) != 0;
if let Value::Struct(inner) = &**payload {
if !failure_flag {
if let Value::Struct(inner) = &inner[0] {
if let Value::Array { ty: _, data } = &inner[0] {
for value in data.iter() {
if let Value::Felt(x) = value {
return_values.push(*x);
}
}
}
}
} else if let Value::Array { ty: _, data } = &inner[1] {
let mut error_felt_vec = Vec::new();
for value in data.iter() {
if let Value::Felt(x) = value {
error_felt_vec.push(*x);
}
}
let bytes_err: Vec<_> = error_felt_vec
.iter()
.flat_map(|felt| felt.to_bytes_be().to_vec())
// remove null chars
.filter(|b| *b != 0)
.collect();
let str_error = String::from_utf8(bytes_err).unwrap().to_owned();
error_msg = Some(str_error);
}
}
}
Value::Unit => {}
_ => None?,
}
}
Some(Self {
remaining_gas: remaining_gas.unwrap_or(0),
return_values,
error_msg,
failure_flag,
})
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet.rs | debug_utils/sierra-emu/src/starknet.rs | use std::{
collections::{BTreeMap, VecDeque},
iter::once,
};
pub use self::{
block_info::BlockInfo, execution_info::ExecutionInfo, execution_info_v2::ExecutionInfoV2,
resource_bounds::ResourceBounds, secp256k1_point::Secp256k1Point,
secp256r1_point::Secp256r1Point, tx_info::TxInfo, tx_v2_info::TxV2Info, u256::U256,
};
use k256::elliptic_curve::{
generic_array::GenericArray,
sec1::{FromEncodedPoint, ToEncodedPoint},
};
use sec1::point::Coordinates;
use serde::Serialize;
use starknet_types_core::felt::Felt;
mod block_info;
mod execution_info;
mod execution_info_v2;
mod resource_bounds;
mod secp256k1_point;
mod secp256r1_point;
mod tx_info;
mod tx_v2_info;
mod u256;
pub type SyscallResult<T> = Result<T, Vec<Felt>>;
pub trait StarknetSyscallHandler {
fn get_block_hash(&mut self, block_number: u64, remaining_gas: &mut u64)
-> SyscallResult<Felt>;
fn get_execution_info(&mut self, remaining_gas: &mut u64) -> SyscallResult<ExecutionInfo>;
fn get_execution_info_v2(&mut self, remaining_gas: &mut u64) -> SyscallResult<ExecutionInfoV2>;
fn deploy(
&mut self,
class_hash: Felt,
contract_address_salt: Felt,
calldata: Vec<Felt>,
deploy_from_zero: bool,
remaining_gas: &mut u64,
) -> SyscallResult<(Felt, Vec<Felt>)>;
fn replace_class(&mut self, class_hash: Felt, remaining_gas: &mut u64) -> SyscallResult<()>;
fn library_call(
&mut self,
class_hash: Felt,
function_selector: Felt,
calldata: Vec<Felt>,
remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>>;
fn call_contract(
&mut self,
address: Felt,
entry_point_selector: Felt,
calldata: Vec<Felt>,
remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>>;
fn storage_read(
&mut self,
address_domain: u32,
address: Felt,
remaining_gas: &mut u64,
) -> SyscallResult<Felt>;
fn storage_write(
&mut self,
address_domain: u32,
address: Felt,
value: Felt,
remaining_gas: &mut u64,
) -> SyscallResult<()>;
fn emit_event(
&mut self,
keys: Vec<Felt>,
data: Vec<Felt>,
remaining_gas: &mut u64,
) -> SyscallResult<()>;
fn send_message_to_l1(
&mut self,
to_address: Felt,
payload: Vec<Felt>,
remaining_gas: &mut u64,
) -> SyscallResult<()>;
fn keccak(&mut self, input: Vec<u64>, remaining_gas: &mut u64) -> SyscallResult<U256>;
fn secp256k1_new(
&mut self,
x: U256,
y: U256,
remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>>;
fn secp256k1_add(
&mut self,
p0: Secp256k1Point,
p1: Secp256k1Point,
remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point>;
fn secp256k1_mul(
&mut self,
p: Secp256k1Point,
m: U256,
remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point>;
fn secp256k1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>>;
fn secp256k1_get_xy(
&mut self,
p: Secp256k1Point,
remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)>;
fn secp256r1_new(
&mut self,
x: U256,
y: U256,
remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>>;
fn secp256r1_add(
&mut self,
p0: Secp256r1Point,
p1: Secp256r1Point,
remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point>;
fn secp256r1_mul(
&mut self,
p: Secp256r1Point,
m: U256,
remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point>;
fn secp256r1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>>;
fn secp256r1_get_xy(
&mut self,
p: Secp256r1Point,
remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)>;
fn sha256_process_block(
&mut self,
prev_state: [u32; 8],
current_block: [u32; 16],
remaining_gas: &mut u64,
) -> SyscallResult<[u32; 8]>;
fn meta_tx_v0(
&mut self,
_address: Felt,
_entry_point_selector: Felt,
_calldata: Vec<Felt>,
_signature: Vec<Felt>,
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
unimplemented!();
}
fn get_class_hash_at(
&mut self,
_contract_address: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
unimplemented!()
}
fn cheatcode(&mut self, _selector: Felt, _input: Vec<Felt>) -> Vec<Felt> {
unimplemented!()
}
}
/// A (somewhat) usable implementation of the starknet syscall handler trait.
///
/// Currently gas is not deducted.
#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
pub struct StubSyscallHandler {
pub storage: BTreeMap<(u32, Felt), Felt>,
pub events: Vec<StubEvent>,
pub execution_info: ExecutionInfoV2,
pub logs: BTreeMap<Felt, ContractLogs>,
}
/// Event emitted by the emit_event syscall.
#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
pub struct StubEvent {
pub keys: Vec<Felt>,
pub data: Vec<Felt>,
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
pub struct ContractLogs {
pub events: VecDeque<StubEvent>,
pub l2_to_l1_messages: VecDeque<L2ToL1Message>,
}
type L2ToL1Message = (Felt, Vec<Felt>);
impl Default for StubSyscallHandler {
fn default() -> Self {
Self {
storage: BTreeMap::new(),
events: Vec::new(),
execution_info: ExecutionInfoV2 {
block_info: BlockInfo {
block_number: 0,
block_timestamp: 0,
sequencer_address: 666.into(),
},
tx_info: TxV2Info {
version: 1.into(),
account_contract_address: 1.into(),
max_fee: 0,
signature: vec![1.into()],
transaction_hash: 1.into(),
chain_id: 1.into(),
nonce: 0.into(),
resource_bounds: vec![],
tip: 0,
paymaster_data: vec![],
nonce_data_availability_mode: 0,
fee_data_availability_mode: 0,
account_deployment_data: vec![],
},
caller_address: 2.into(),
contract_address: 3.into(),
entry_point_selector: 4.into(),
},
logs: BTreeMap::new(),
}
}
}
impl StarknetSyscallHandler for StubSyscallHandler {
fn get_block_hash(
&mut self,
block_number: u64,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
Ok(block_number.into())
}
fn get_execution_info(&mut self, _remaining_gas: &mut u64) -> SyscallResult<ExecutionInfo> {
Ok(ExecutionInfo {
block_info: self.execution_info.block_info,
tx_info: TxInfo {
version: self.execution_info.tx_info.version,
account_contract_address: self.execution_info.tx_info.account_contract_address,
max_fee: self.execution_info.tx_info.max_fee,
signature: self.execution_info.tx_info.signature.clone(),
transaction_hash: self.execution_info.tx_info.transaction_hash,
chain_id: self.execution_info.tx_info.chain_id,
nonce: self.execution_info.tx_info.nonce,
},
caller_address: self.execution_info.caller_address,
contract_address: self.execution_info.contract_address,
entry_point_selector: self.execution_info.entry_point_selector,
})
}
fn get_execution_info_v2(
&mut self,
_remaining_gas: &mut u64,
) -> SyscallResult<ExecutionInfoV2> {
Ok(self.execution_info.clone())
}
fn deploy(
&mut self,
_class_hash: Felt,
_contract_address_salt: Felt,
_calldata: Vec<Felt>,
_deploy_from_zero: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<(Felt, Vec<Felt>)> {
unimplemented!()
}
fn replace_class(&mut self, _class_hash: Felt, _remaining_gas: &mut u64) -> SyscallResult<()> {
unimplemented!()
}
fn library_call(
&mut self,
_class_hash: Felt,
_function_selector: Felt,
_calldata: Vec<Felt>,
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
unimplemented!()
}
fn call_contract(
&mut self,
_address: Felt,
_entry_point_selector: Felt,
_calldata: Vec<Felt>,
_remaining_gas: &mut u64,
) -> SyscallResult<Vec<Felt>> {
unimplemented!()
}
fn storage_read(
&mut self,
address_domain: u32,
address: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<Felt> {
if let Some(value) = self.storage.get(&(address_domain, address)) {
Ok(*value)
} else {
Err(vec![Felt::from_bytes_be_slice(b"address not found")])
}
}
fn storage_write(
&mut self,
address_domain: u32,
address: Felt,
value: Felt,
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
self.storage.insert((address_domain, address), value);
Ok(())
}
fn emit_event(
&mut self,
keys: Vec<Felt>,
data: Vec<Felt>,
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
self.events.push(StubEvent {
keys: keys.to_vec(),
data: data.to_vec(),
});
Ok(())
}
fn send_message_to_l1(
&mut self,
_to_address: Felt,
_payload: Vec<Felt>,
_remaining_gas: &mut u64,
) -> SyscallResult<()> {
unimplemented!()
}
fn keccak(&mut self, input: Vec<u64>, gas: &mut u64) -> SyscallResult<U256> {
let length = input.len();
if length % 17 != 0 {
let error_msg = b"Invalid keccak input size";
let felt_error = Felt::from_bytes_be_slice(error_msg);
return Err(vec![felt_error]);
}
let n_chunks = length / 17;
let mut state = [0u64; 25];
const KECCAK_ROUND_COST: u64 = 180000;
for i in 0..n_chunks {
if *gas < KECCAK_ROUND_COST {
let error_msg = b"Syscall out of gas";
let felt_error = Felt::from_bytes_be_slice(error_msg);
return Err(vec![felt_error]);
}
*gas -= KECCAK_ROUND_COST;
let chunk = &input[i * 17..(i + 1) * 17]; //(request.input_start + i * 17)?;
for (i, val) in chunk.iter().enumerate() {
state[i] ^= val;
}
keccak::f1600(&mut state)
}
// state[0] and state[1] conform the hash_high (u128)
// state[2] and state[3] conform the hash_low (u128)
SyscallResult::Ok(U256 {
lo: state[0] as u128 | ((state[1] as u128) << 64),
hi: state[2] as u128 | ((state[3] as u128) << 64),
})
}
fn secp256k1_new(
&mut self,
x: U256,
y: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>> {
// The following unwraps should be unreachable because the iterator we provide has the
// expected number of bytes.
let point = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
x.hi.to_be_bytes().into_iter().chain(x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
y.hi.to_be_bytes().into_iter().chain(y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
);
if bool::from(point.is_some()) {
Ok(Some(Secp256k1Point { x, y }))
} else {
Ok(None)
}
}
fn secp256k1_add(
&mut self,
p0: Secp256k1Point,
p1: Secp256k1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point> {
// The inner unwraps should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwraps depend on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p0 = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p0.x.hi
.to_be_bytes()
.into_iter()
.chain(p0.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p0.y.hi
.to_be_bytes()
.into_iter()
.chain(p0.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p1 = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p1.x.hi
.to_be_bytes()
.into_iter()
.chain(p1.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p1.y.hi
.to_be_bytes()
.into_iter()
.chain(p1.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p = p0 + p1;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256k1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256k1_mul(
&mut self,
p: Secp256k1Point,
m: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256k1Point> {
// The inner unwrap should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwrap depends on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p.x.hi.to_be_bytes().into_iter().chain(p.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p.y.hi.to_be_bytes().into_iter().chain(p.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let m: k256::Scalar = k256::elliptic_curve::ScalarPrimitive::from_slice(&{
let mut buf = [0u8; 32];
buf[0..16].copy_from_slice(&m.hi.to_be_bytes());
buf[16..32].copy_from_slice(&m.lo.to_be_bytes());
buf
})
.map_err(|_| {
vec![Felt::from_bytes_be(
b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0invalid scalar",
)]
})?
.into();
let p = p * m;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256k1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256k1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256k1Point>> {
// The inner unwrap should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwrap depends on the encoding format, which should be valid
// since it's hardcoded..
let point = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_bytes(
k256::CompressedPoint::from_exact_iter(
once(0x02 | y_parity as u8)
.chain(x.hi.to_be_bytes())
.chain(x.lo.to_be_bytes()),
)
.unwrap(),
)
.unwrap(),
);
if bool::from(point.is_some()) {
// This unwrap has already been checked in the `if` expression's condition.
let p = point.unwrap();
let p = p.to_encoded_point(false);
let y = match p.coordinates() {
Coordinates::Uncompressed { y, .. } => y,
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following unwrap should be safe because the array always has 32 bytes. The other
// two are definitely safe because the slicing guarantees its length to be the right
// one.
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Some(Secp256k1Point {
x,
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
}))
} else {
Ok(None)
}
}
fn secp256k1_get_xy(
&mut self,
p: Secp256k1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)> {
Ok((p.x, p.y))
}
fn secp256r1_new(
&mut self,
x: U256,
y: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>> {
// The following unwraps should be unreachable because the iterator we provide has the
// expected number of bytes.
let point = p256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
x.hi.to_be_bytes().into_iter().chain(x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
y.hi.to_be_bytes().into_iter().chain(y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
);
if bool::from(point.is_some()) {
Ok(Some(Secp256r1Point { x, y }))
} else {
Ok(None)
}
}
fn secp256r1_add(
&mut self,
p0: Secp256r1Point,
p1: Secp256r1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point> {
// The inner unwraps should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwraps depend on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p0 = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p0.x.hi
.to_be_bytes()
.into_iter()
.chain(p0.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p0.y.hi
.to_be_bytes()
.into_iter()
.chain(p0.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p1 = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p1.x.hi
.to_be_bytes()
.into_iter()
.chain(p1.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p1.y.hi
.to_be_bytes()
.into_iter()
.chain(p1.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p = p0 + p1;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256r1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256r1_mul(
&mut self,
p: Secp256r1Point,
m: U256,
_remaining_gas: &mut u64,
) -> SyscallResult<Secp256r1Point> {
// The inner unwrap should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwrap depends on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p.x.hi.to_be_bytes().into_iter().chain(p.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p.y.hi.to_be_bytes().into_iter().chain(p.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let m: p256::Scalar = p256::elliptic_curve::ScalarPrimitive::from_slice(&{
let mut buf = [0u8; 32];
buf[0..16].copy_from_slice(&m.hi.to_be_bytes());
buf[16..32].copy_from_slice(&m.lo.to_be_bytes());
buf
})
.map_err(|_| {
vec![Felt::from_bytes_be(
b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0invalid scalar",
)]
})?
.into();
let p = p * m;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256r1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256r1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
_remaining_gas: &mut u64,
) -> SyscallResult<Option<Secp256r1Point>> {
let point = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_bytes(
p256::CompressedPoint::from_exact_iter(
once(0x02 | y_parity as u8)
.chain(x.hi.to_be_bytes())
.chain(x.lo.to_be_bytes()),
)
.unwrap(),
)
.unwrap(),
);
if bool::from(point.is_some()) {
let p = point.unwrap();
let p = p.to_encoded_point(false);
let y = match p.coordinates() {
Coordinates::Uncompressed { y, .. } => y,
_ => unreachable!(),
};
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Some(Secp256r1Point {
x,
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
}))
} else {
Ok(None)
}
}
fn secp256r1_get_xy(
&mut self,
p: Secp256r1Point,
_remaining_gas: &mut u64,
) -> SyscallResult<(U256, U256)> {
Ok((p.x, p.y))
}
fn sha256_process_block(
&mut self,
prev_state: [u32; 8],
current_block: [u32; 16],
_remaining_gas: &mut u64,
) -> SyscallResult<[u32; 8]> {
let mut state = prev_state;
let data_as_bytes = sha2::digest::generic_array::GenericArray::from_exact_iter(
current_block.iter().flat_map(|x| x.to_be_bytes()),
)
.unwrap();
sha2::compress256(&mut state, &[data_as_bytes]);
Ok(state)
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/utils.rs | debug_utils/sierra-emu/src/utils.rs | use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
utils::Range,
},
ids::ConcreteTypeId,
program_registry::ProgramRegistry,
};
use num_bigint::BigInt;
use num_traits::{Bounded, One, ToPrimitive};
use starknet_types_core::felt::CAIRO_PRIME_BIGINT;
use crate::{debug::type_to_name, Value};
/// Receives a vector of values, filters any which is non numeric and returns a `Vec<BigInt>`
///
/// Useful when a binary operation takes generic values (like with bounded ints).
pub fn get_numeric_args_as_bigints(args: &[Value]) -> Vec<BigInt> {
args.iter()
.map(|v| match v {
Value::BoundedInt { value, .. } => value.to_owned(),
Value::I8(value) => BigInt::from(*value),
Value::I16(value) => BigInt::from(*value),
Value::I32(value) => BigInt::from(*value),
Value::I64(value) => BigInt::from(*value),
Value::I128(value) => BigInt::from(*value),
Value::U8(value) => BigInt::from(*value),
Value::U16(value) => BigInt::from(*value),
Value::U32(value) => BigInt::from(*value),
Value::U64(value) => BigInt::from(*value),
Value::U128(value) => BigInt::from(*value),
Value::Felt(value) => value.to_bigint(),
Value::Bytes31(value) => value.to_bigint(),
value => panic!("Argument should be an integer: {:?}", value),
})
.collect()
}
pub fn get_value_from_integer(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
ty_id: &ConcreteTypeId,
value: BigInt,
) -> Value {
let ty = registry.get_type(ty_id).unwrap();
match ty {
CoreTypeConcrete::NonZero(info) => get_value_from_integer(registry, &info.ty, value),
CoreTypeConcrete::Sint8(_) => Value::I8(value.to_i8().unwrap()),
CoreTypeConcrete::Sint16(_) => Value::I16(value.to_i16().unwrap()),
CoreTypeConcrete::Sint32(_) => Value::I32(value.to_i32().unwrap()),
CoreTypeConcrete::Sint64(_) => Value::I64(value.to_i64().unwrap()),
CoreTypeConcrete::Sint128(_) => Value::I128(value.to_i128().unwrap()),
CoreTypeConcrete::Uint8(_) => Value::U8(value.to_u8().unwrap()),
CoreTypeConcrete::Uint16(_) => Value::U16(value.to_u16().unwrap()),
CoreTypeConcrete::Uint32(_) => Value::U32(value.to_u32().unwrap()),
CoreTypeConcrete::Uint64(_) => Value::U64(value.to_u64().unwrap()),
CoreTypeConcrete::Uint128(_) => Value::U128(value.to_u128().unwrap()),
CoreTypeConcrete::BoundedInt(info) => {
let range = &info.range;
Value::BoundedInt {
range: range.lower.clone()..range.upper.clone(),
value,
}
}
CoreTypeConcrete::Felt252(_) => Value::Felt(value.into()),
_ => panic!(
"Cannot get integer value for a non-integer type: {}",
type_to_name(ty_id, registry)
),
}
}
pub fn integer_range(
ty_id: &ConcreteTypeId,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
) -> Range {
fn range_of<T>() -> Range
where
T: Bounded + Into<BigInt>,
{
Range {
lower: T::min_value().into(),
upper: T::max_value().into() + BigInt::one(),
}
}
let ty = registry.get_type(ty_id).unwrap();
match ty {
CoreTypeConcrete::Uint8(_) => range_of::<u8>(),
CoreTypeConcrete::Uint16(_) => range_of::<u16>(),
CoreTypeConcrete::Uint32(_) => range_of::<u32>(),
CoreTypeConcrete::Uint64(_) => range_of::<u64>(),
CoreTypeConcrete::Uint128(_) => range_of::<u128>(),
CoreTypeConcrete::Felt252(_) => Range {
lower: BigInt::ZERO,
upper: CAIRO_PRIME_BIGINT.clone(),
},
CoreTypeConcrete::Sint8(_) => range_of::<i8>(),
CoreTypeConcrete::Sint16(_) => range_of::<i16>(),
CoreTypeConcrete::Sint32(_) => range_of::<i32>(),
CoreTypeConcrete::Sint64(_) => range_of::<i64>(),
CoreTypeConcrete::Sint128(_) => range_of::<i128>(),
CoreTypeConcrete::BoundedInt(info) => info.range.clone(),
CoreTypeConcrete::Bytes31(_) => Range {
lower: BigInt::ZERO,
upper: BigInt::one() << 248,
},
CoreTypeConcrete::Const(info) => integer_range(&info.inner_ty, registry),
CoreTypeConcrete::NonZero(info) => integer_range(&info.ty, registry),
_ => panic!(
"Cannot get integer range value for a non-integer type {}",
type_to_name(ty_id, registry)
),
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/gas.rs | debug_utils/sierra-emu/src/gas.rs | use std::{fmt::Debug, ops::Deref};
use cairo_lang_runner::token_gas_cost;
use cairo_lang_sierra::{
extensions::gas::CostTokenType,
ids::FunctionId,
program::{Program, StatementIdx},
};
use cairo_lang_sierra_ap_change::{ap_change_info::ApChangeInfo, ApChangeError};
use cairo_lang_sierra_gas::{gas_info::GasInfo, CostError};
use cairo_lang_sierra_to_casm::metadata::{
calc_metadata, calc_metadata_ap_change_only, Metadata as CairoGasMetadata,
MetadataComputationConfig, MetadataError as CairoGasMetadataError,
};
use cairo_lang_sierra_type_size::ProgramRegistryInfo;
use cairo_lang_utils::casts::IntoOrPanic;
use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct BuiltinCosts {
pub r#const: u64,
pub pedersen: u64,
pub bitwise: u64,
pub ecop: u64,
pub poseidon: u64,
pub add_mod: u64,
pub mul_mod: u64,
}
impl Default for BuiltinCosts {
fn default() -> Self {
Self {
r#const: token_gas_cost(CostTokenType::Const) as u64,
pedersen: token_gas_cost(CostTokenType::Pedersen) as u64,
bitwise: token_gas_cost(CostTokenType::Bitwise) as u64,
ecop: token_gas_cost(CostTokenType::EcOp) as u64,
poseidon: token_gas_cost(CostTokenType::Poseidon) as u64,
add_mod: token_gas_cost(CostTokenType::AddMod) as u64,
mul_mod: token_gas_cost(CostTokenType::MulMod) as u64,
}
}
}
impl From<BuiltinCosts> for [u64; 7] {
// Order matters, for the libfunc impl
// https://github.com/starkware-libs/sequencer/blob/1b7252f8a30244d39614d7666aa113b81291808e/crates/blockifier/src/execution/entry_point_execution.rs#L208
fn from(value: BuiltinCosts) -> Self {
[
value.r#const,
value.pedersen,
value.bitwise,
value.ecop,
value.poseidon,
value.add_mod,
value.mul_mod,
]
}
}
/// Holds global gas info.
#[derive(Default)]
pub struct GasMetadata(pub CairoGasMetadata);
/// Error for metadata calculations.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
pub enum GasMetadataError {
#[error(transparent)]
ApChangeError(#[from] ApChangeError),
#[error(transparent)]
CostError(#[from] CostError),
#[error("Not enough gas to run the operation. Required: {:?}, Available: {:?}.", gas.0, gas.1)]
NotEnoughGas { gas: Box<(u64, u64)> },
}
impl From<CairoGasMetadataError> for GasMetadataError {
fn from(value: CairoGasMetadataError) -> Self {
match value {
CairoGasMetadataError::ApChangeError(e) => Self::ApChangeError(e),
CairoGasMetadataError::CostError(e) => Self::CostError(e),
}
}
}
impl Deref for GasMetadata {
type Target = CairoGasMetadata;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Debug for GasMetadata {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GasMetadata")
.field("ap_change_info", &self.ap_change_info)
.field("gas_info", &self.gas_info)
.finish()
}
}
impl GasMetadata {
pub fn new(
sierra_program: &Program,
sierra_program_info: &ProgramRegistryInfo,
config: Option<MetadataComputationConfig>,
) -> Result<GasMetadata, GasMetadataError> {
let metadata = if let Some(metadata_config) = config {
calc_metadata(sierra_program, sierra_program_info, metadata_config)
.map_err(GasMetadataError::from)?
} else {
calc_metadata_ap_change_only(sierra_program, sierra_program_info)
.map_err(GasMetadataError::from)?
};
Ok(Self(metadata))
}
/// Returns the initial value for the gas counter.
/// If `available_gas` is None returns 0.
pub fn get_initial_available_gas(
&self,
func: &FunctionId,
available_gas: Option<u64>,
) -> Result<u64, GasMetadataError> {
let Some(available_gas) = available_gas else {
return Ok(0);
};
// In case we don't have any costs - it means no gas equations were solved (and we are in
// the case of no gas checking enabled) - so the gas builtin is irrelevant, and we
// can return any value.
let Some(required_gas) = self.initial_required_gas(func) else {
return Ok(0);
};
available_gas
.checked_sub(required_gas)
.ok_or(GasMetadataError::NotEnoughGas {
gas: Box::new((required_gas, available_gas)),
})
}
pub fn initial_required_gas(&self, func: &FunctionId) -> Option<u64> {
if self.gas_info.function_costs.is_empty() {
return None;
}
Some(
self.gas_info.function_costs[func]
.iter()
.map(|(token_type, val)| val.into_or_panic::<usize>() * token_gas_cost(*token_type))
.sum::<usize>() as u64,
)
}
pub fn get_gas_costs_for_statement(&self, idx: StatementIdx) -> Vec<(u64, CostTokenType)> {
let mut costs = Vec::new();
for cost_type in CostTokenType::iter_casm_tokens() {
if let Some(cost_count) =
self.get_gas_cost_for_statement_and_cost_token_type(idx, *cost_type)
{
if cost_count > 0 {
costs.push((cost_count, *cost_type));
}
}
}
costs
}
pub fn get_gas_cost_for_statement_and_cost_token_type(
&self,
idx: StatementIdx,
cost_type: CostTokenType,
) -> Option<u64> {
self.gas_info
.variable_values
.get(&(idx, cost_type))
.copied()
.map(|x| {
x.try_into()
.expect("gas cost couldn't be converted to u128, should never happen")
})
}
}
impl Clone for GasMetadata {
fn clone(&self) -> Self {
Self(CairoGasMetadata {
ap_change_info: ApChangeInfo {
variable_values: self.ap_change_info.variable_values.clone(),
function_ap_change: self.ap_change_info.function_ap_change.clone(),
},
gas_info: GasInfo {
variable_values: self.gas_info.variable_values.clone(),
function_costs: self.gas_info.function_costs.clone(),
},
})
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/main.rs | debug_utils/sierra-emu/src/main.rs | use self::args::CmdArgs;
use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
};
use cairo_lang_filesystem::ids::CrateInput;
use clap::Parser;
use sierra_emu::run_program;
use std::{fs::File, io::stdout};
use tracing::{info, Level};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
mod args;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = CmdArgs::parse();
tracing::subscriber::set_global_default(
FmtSubscriber::builder()
.with_env_filter(EnvFilter::from_default_env())
.with_max_level(Level::TRACE)
.finish(),
)?;
let mut db = RootDatabase::builder().detect_corelib().build()?;
let main_crate_ids = {
let main_crate_inputs =
setup_project(&mut db, &args.program).expect("failed to setup project");
CrateInput::into_crate_ids(&db, main_crate_inputs)
};
let program = compile_prepared_db(
&db,
main_crate_ids,
CompilerConfig {
replace_ids: true,
..Default::default()
},
)?
.program;
info!("Running the program.");
let trace = run_program(
program.into(),
args.entry_point,
args.args,
args.available_gas.unwrap_or_default(),
);
match args.output {
Some(path) => serde_json::to_writer(File::create(path)?, &trace)?,
None => serde_json::to_writer(stdout().lock(), &trace)?,
};
Ok(())
}
#[cfg(test)]
mod test {
use std::path::Path;
use cairo_lang_compiler::CompilerConfig;
use cairo_lang_lowering::utils::InliningStrategy;
use cairo_lang_starknet::compile::compile_path;
use cairo_lang_starknet_classes::contract_class::version_id_from_serialized_sierra_program;
use sierra_emu::{starknet::StubSyscallHandler, ContractExecutionResult, VirtualMachine};
#[test]
fn test_contract() {
let path = Path::new("programs/hello_starknet.cairo");
let contract = compile_path(
path,
None,
CompilerConfig {
replace_ids: true,
..Default::default()
},
InliningStrategy::Default,
)
.unwrap();
let sierra_program = contract.extract_sierra_program().unwrap();
let (sierra_version, _) =
version_id_from_serialized_sierra_program(&contract.sierra_program).unwrap();
let entry_point = contract.entry_points_by_type.external.first().unwrap();
let mut vm = VirtualMachine::new_starknet(
sierra_program.clone().into(),
&contract.entry_points_by_type,
sierra_version,
);
let calldata = [2.into()];
let initial_gas = 1000000;
let syscall_handler = &mut StubSyscallHandler::default();
// Set the VM at the contract entrypoint
vm.call_contract(
entry_point.selector.clone().into(),
initial_gas,
calldata,
None,
);
// Run all the steps generating a program execution trace. (Not to be confused with a proof trace)
let _trace = vm.run_with_trace(syscall_handler);
// let trace_str = serde_json::to_string_pretty(&trace).unwrap();
// std::fs::write("contract_trace.json", trace_str).unwrap();
}
#[test]
fn test_contract_constructor() {
let path = Path::new("programs/hello_starknet.cairo");
let contract = compile_path(
path,
None,
CompilerConfig {
replace_ids: true,
..Default::default()
},
InliningStrategy::Default,
)
.unwrap();
let (sierra_version, _) =
version_id_from_serialized_sierra_program(&contract.sierra_program).unwrap();
let sierra_program = contract.extract_sierra_program().unwrap();
let entry_point = contract.entry_points_by_type.constructor.first().unwrap();
let mut vm = VirtualMachine::new_starknet(
sierra_program.clone().into(),
&contract.entry_points_by_type,
sierra_version,
);
let calldata = [2.into()];
let initial_gas = 1000000;
let syscall_handler = &mut StubSyscallHandler::default();
vm.call_contract(
entry_point.selector.clone().into(),
initial_gas,
calldata,
None,
);
let trace = vm.run_with_trace(syscall_handler);
assert!(!syscall_handler.storage.is_empty());
let result = ContractExecutionResult::from_trace(&trace).unwrap();
assert!(!result.failure_flag);
assert_eq!(result.return_values.len(), 0);
assert_eq!(result.error_msg, None);
// let trace_str = serde_json::to_string_pretty(&trace).unwrap();
// std::fs::write("contract_trace.json", trace_str).unwrap();
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/secp256r1_point.rs | debug_utils/sierra-emu/src/starknet/secp256r1_point.rs | use super::U256;
use crate::Value;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Secp256r1Point {
pub x: U256,
pub y: U256,
}
impl Secp256r1Point {
#[allow(unused)]
pub fn into_value(self) -> Value {
Value::Struct(vec![
Value::Struct(vec![Value::U128(self.x.lo), Value::U128(self.x.hi)]),
Value::Struct(vec![Value::U128(self.y.lo), Value::U128(self.y.hi)]),
])
}
pub fn from_value(v: Value) -> Self {
let Value::Struct(mut v) = v else { panic!() };
let y = U256::from_value(v.remove(1));
let x = U256::from_value(v.remove(0));
Self { x, y }
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/tx_info.rs | debug_utils/sierra-emu/src/starknet/tx_info.rs | use crate::Value;
use cairo_lang_sierra::ids::ConcreteTypeId;
use starknet_types_core::felt::Felt;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TxInfo {
pub version: Felt,
pub account_contract_address: Felt,
pub max_fee: u128,
pub signature: Vec<Felt>,
pub transaction_hash: Felt,
pub chain_id: Felt,
pub nonce: Felt,
}
impl TxInfo {
pub(crate) fn into_value(self, felt252_ty: ConcreteTypeId) -> Value {
Value::Struct(vec![
Value::Felt(self.version),
Value::Felt(self.account_contract_address),
Value::U128(self.max_fee),
Value::Struct(vec![Value::Array {
ty: felt252_ty,
data: self.signature.into_iter().map(Value::Felt).collect(),
}]),
Value::Felt(self.transaction_hash),
Value::Felt(self.chain_id),
Value::Felt(self.nonce),
])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/execution_info_v2.rs | debug_utils/sierra-emu/src/starknet/execution_info_v2.rs | use super::{BlockInfo, TxV2Info};
use crate::Value;
use cairo_lang_sierra::ids::ConcreteTypeId;
use serde::Serialize;
use starknet_types_core::felt::Felt;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct ExecutionInfoV2 {
pub block_info: BlockInfo,
pub tx_info: TxV2Info,
pub caller_address: Felt,
pub contract_address: Felt,
pub entry_point_selector: Felt,
}
impl ExecutionInfoV2 {
pub(crate) fn into_value(
self,
felt252_ty: ConcreteTypeId,
resource_bounds_ty: ConcreteTypeId,
) -> Value {
Value::Struct(vec![
self.block_info.into_value(),
self.tx_info.into_value(felt252_ty, resource_bounds_ty),
Value::Felt(self.caller_address),
Value::Felt(self.contract_address),
Value::Felt(self.entry_point_selector),
])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/secp256k1_point.rs | debug_utils/sierra-emu/src/starknet/secp256k1_point.rs | use super::U256;
use crate::Value;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Secp256k1Point {
pub x: U256,
pub y: U256,
}
impl Secp256k1Point {
#[allow(unused)]
pub fn into_value(self) -> Value {
Value::Struct(vec![
Value::Struct(vec![Value::U128(self.x.lo), Value::U128(self.x.hi)]),
Value::Struct(vec![Value::U128(self.y.lo), Value::U128(self.y.hi)]),
])
}
pub fn from_value(v: Value) -> Self {
let Value::Struct(mut v) = v else { panic!() };
let y = U256::from_value(v.remove(1));
let x = U256::from_value(v.remove(0));
Self { x, y }
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/block_info.rs | debug_utils/sierra-emu/src/starknet/block_info.rs | use crate::Value;
use serde::Serialize;
use starknet_types_core::felt::Felt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct BlockInfo {
pub block_number: u64,
pub block_timestamp: u64,
pub sequencer_address: Felt,
}
impl BlockInfo {
pub(crate) fn into_value(self) -> Value {
Value::Struct(vec![
Value::U64(self.block_number),
Value::U64(self.block_timestamp),
Value::Felt(self.sequencer_address),
])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/u256.rs | debug_utils/sierra-emu/src/starknet/u256.rs | use crate::Value;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct U256 {
pub lo: u128,
pub hi: u128,
}
impl U256 {
#[allow(unused)]
pub(crate) fn into_value(self) -> Value {
Value::Struct(vec![Value::U128(self.lo), Value::U128(self.hi)])
}
pub fn from_value(v: Value) -> Self {
let Value::Struct(v) = v else { panic!() };
let Value::U128(lo) = v[0] else { panic!() };
let Value::U128(hi) = v[1] else { panic!() };
Self { lo, hi }
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/resource_bounds.rs | debug_utils/sierra-emu/src/starknet/resource_bounds.rs | use crate::Value;
use serde::Serialize;
use starknet_types_core::felt::Felt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct ResourceBounds {
pub resource: Felt,
pub max_amount: u64,
pub max_price_per_unit: u128,
}
impl ResourceBounds {
pub(crate) fn into_value(self) -> Value {
Value::Struct(vec![
Value::Felt(self.resource),
Value::U64(self.max_amount),
Value::U128(self.max_price_per_unit),
])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/tx_v2_info.rs | debug_utils/sierra-emu/src/starknet/tx_v2_info.rs | use super::ResourceBounds;
use crate::Value;
use cairo_lang_sierra::ids::ConcreteTypeId;
use serde::Serialize;
use starknet_types_core::felt::Felt;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct TxV2Info {
pub version: Felt,
pub account_contract_address: Felt,
pub max_fee: u128,
pub signature: Vec<Felt>,
pub transaction_hash: Felt,
pub chain_id: Felt,
pub nonce: Felt,
pub resource_bounds: Vec<ResourceBounds>,
pub tip: u128,
pub paymaster_data: Vec<Felt>,
pub nonce_data_availability_mode: u32,
pub fee_data_availability_mode: u32,
pub account_deployment_data: Vec<Felt>,
}
impl TxV2Info {
pub(crate) fn into_value(
self,
felt252_ty: ConcreteTypeId,
resource_bounds_ty: ConcreteTypeId,
) -> Value {
Value::Struct(vec![
Value::Felt(self.version),
Value::Felt(self.account_contract_address),
Value::U128(self.max_fee),
Value::Struct(vec![Value::Array {
ty: felt252_ty.clone(),
data: self.signature.into_iter().map(Value::Felt).collect(),
}]),
Value::Felt(self.transaction_hash),
Value::Felt(self.chain_id),
Value::Felt(self.nonce),
Value::Struct(vec![Value::Array {
ty: resource_bounds_ty,
data: self
.resource_bounds
.into_iter()
.map(ResourceBounds::into_value)
.collect(),
}]),
Value::U128(self.tip),
Value::Struct(vec![Value::Array {
ty: felt252_ty.clone(),
data: self.paymaster_data.into_iter().map(Value::Felt).collect(),
}]),
Value::U32(self.nonce_data_availability_mode),
Value::U32(self.fee_data_availability_mode),
Value::Struct(vec![Value::Array {
ty: felt252_ty,
data: self
.account_deployment_data
.into_iter()
.map(Value::Felt)
.collect(),
}]),
])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/starknet/execution_info.rs | debug_utils/sierra-emu/src/starknet/execution_info.rs | use super::{BlockInfo, TxInfo};
use crate::Value;
use cairo_lang_sierra::ids::ConcreteTypeId;
use starknet_types_core::felt::Felt;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExecutionInfo {
pub block_info: BlockInfo,
pub tx_info: TxInfo,
pub caller_address: Felt,
pub contract_address: Felt,
pub entry_point_selector: Felt,
}
impl ExecutionInfo {
pub(crate) fn into_value(self, felt252_ty: ConcreteTypeId) -> Value {
Value::Struct(vec![
self.block_info.into_value(),
self.tx_info.into_value(felt252_ty),
Value::Felt(self.caller_address),
Value::Felt(self.contract_address),
Value::Felt(self.entry_point_selector),
])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/struct.rs | debug_utils/sierra-emu/src/vm/struct.rs | use super::EvalAction;
use crate::Value;
use cairo_lang_sierra::{
extensions::{
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
lib_func::SignatureOnlyConcreteLibfunc,
structure::{StructConcreteLibfunc, StructConcreteType},
},
program_registry::ProgramRegistry,
};
use smallvec::smallvec;
pub fn eval(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
selector: &StructConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
match selector {
StructConcreteLibfunc::Construct(info) => eval_construct(registry, info, args),
StructConcreteLibfunc::Deconstruct(info) => eval_deconstruct(registry, info, args),
StructConcreteLibfunc::SnapshotDeconstruct(info) => {
eval_snapshot_deconstruct(registry, info, args)
}
StructConcreteLibfunc::BoxedDeconstruct(_info) => {
todo!("implement struct_boxed_deconstruct")
}
}
}
pub fn eval_construct(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let CoreTypeConcrete::Struct(StructConcreteType { members, .. }) = registry
.get_type(&info.signature.branch_signatures[0].vars[0].ty)
.unwrap()
else {
panic!()
};
assert_eq!(args.len(), members.len());
assert!(args
.iter()
.zip(members)
.all(|(value, ty)| value.is(registry, ty)));
EvalAction::NormalBranch(0, smallvec![Value::Struct(args)])
}
pub fn eval_deconstruct(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Struct(values)]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let CoreTypeConcrete::Struct(StructConcreteType { members, .. }) = registry
.get_type(&info.signature.param_signatures[0].ty)
.unwrap()
else {
panic!()
};
assert_eq!(values.len(), members.len());
assert!(values
.iter()
.zip(members)
.all(|(value, ty)| value.is(registry, ty)));
EvalAction::NormalBranch(0, values.into())
}
pub fn eval_snapshot_deconstruct(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Struct(values)]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let CoreTypeConcrete::Snapshot(snapshot_ty) = registry
.get_type(&info.signature.param_signatures[0].ty)
.unwrap()
else {
panic!()
};
let CoreTypeConcrete::Struct(StructConcreteType { members, .. }) =
registry.get_type(&snapshot_ty.ty).unwrap()
else {
panic!()
};
assert_eq!(values.len(), members.len());
assert!(values
.iter()
.zip(members)
.all(|(value, ty)| value.is(registry, ty)));
EvalAction::NormalBranch(0, values.into())
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/circuit.rs | debug_utils/sierra-emu/src/vm/circuit.rs | use super::EvalAction;
use crate::Value;
use cairo_lang_sierra::{
extensions::{
circuit::{
CircuitConcreteLibfunc, CircuitTypeConcrete, ConcreteGetOutputLibFunc,
ConcreteU96LimbsLessThanGuaranteeVerifyLibfunc,
},
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
lib_func::{SignatureAndTypeConcreteLibfunc, SignatureOnlyConcreteLibfunc},
},
program_registry::ProgramRegistry,
};
use num_bigint::{BigInt, BigUint, Sign, ToBigInt};
use num_integer::{ExtendedGcd, Integer};
use num_traits::{One, ToPrimitive, Zero};
use smallvec::smallvec;
fn u384_to_struct(num: BigUint) -> Value {
let output_big = num.to_bigint().unwrap();
let mask: BigInt = BigInt::from_bytes_be(Sign::Plus, &[255; 12]);
let l0: BigInt = &output_big & &mask;
let l1: BigInt = (&output_big >> 96) & &mask;
let l2: BigInt = (&output_big >> 192) & &mask;
let l3: BigInt = (output_big >> 288) & &mask;
let range = BigInt::ZERO..(BigInt::from(1) << 96);
Value::Struct(vec![
Value::BoundedInt {
range: range.clone(),
value: l0,
},
Value::BoundedInt {
range: range.clone(),
value: l1,
},
Value::BoundedInt {
range: range.clone(),
value: l2,
},
Value::BoundedInt { range, value: l3 },
])
}
fn struct_to_u384(struct_members: Vec<Value>) -> BigUint {
let [Value::U128(l0), Value::U128(l1), Value::U128(l2), Value::U128(l3)]: [Value; 4] =
struct_members.try_into().unwrap()
else {
panic!()
};
let l0 = l0.to_le_bytes();
let l1 = l1.to_le_bytes();
let l2 = l2.to_le_bytes();
let l3 = l3.to_le_bytes();
BigUint::from_bytes_le(&[
l0[0], l0[1], l0[2], l0[3], l0[4], l0[5], l0[6], l0[7], l0[8], l0[9], l0[10],
l0[11], //
l1[0], l1[1], l1[2], l1[3], l1[4], l1[5], l1[6], l1[7], l1[8], l1[9], l1[10],
l1[11], //
l2[0], l2[1], l2[2], l2[3], l2[4], l2[5], l2[6], l2[7], l2[8], l2[9], l2[10],
l2[11], //
l3[0], l3[1], l3[2], l3[3], l3[4], l3[5], l3[6], l3[7], l3[8], l3[9], l3[10],
l3[11], //
])
}
/// If the value is non-invertible a nullifier is returned instead. A nullifier
/// is value which satisfies this following equation: num * nullifier ≡ 0(modulus).
fn find_nullifier(num: &BigUint, modulus: &BigUint) -> BigUint {
let ExtendedGcd { gcd, .. } = num
.to_bigint()
.unwrap()
.extended_gcd(&modulus.to_bigint().unwrap());
let gcd = gcd.to_biguint().unwrap();
modulus / gcd
}
pub fn eval(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
selector: &CircuitConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
match selector {
CircuitConcreteLibfunc::AddInput(info) => eval_add_input(registry, info, args),
CircuitConcreteLibfunc::Eval(info) => eval_eval(registry, info, args),
CircuitConcreteLibfunc::GetDescriptor(info) => eval_get_descriptor(registry, info, args),
CircuitConcreteLibfunc::InitCircuitData(info) => {
eval_init_circuit_data(registry, info, args)
}
CircuitConcreteLibfunc::GetOutput(info) => eval_get_output(registry, info, args),
CircuitConcreteLibfunc::TryIntoCircuitModulus(info) => {
eval_try_into_circuit_modulus(registry, info, args)
}
CircuitConcreteLibfunc::FailureGuaranteeVerify(info) => {
eval_failure_guarantee_verify(registry, info, args)
}
CircuitConcreteLibfunc::IntoU96Guarantee(info) => {
eval_into_u96_guarantee(registry, info, args)
}
CircuitConcreteLibfunc::U96GuaranteeVerify(info) => {
eval_u96_guarantee_verify(registry, info, args)
}
CircuitConcreteLibfunc::U96LimbsLessThanGuaranteeVerify(info) => {
eval_u96_limbs_less_than_guarantee_verify(registry, info, args)
}
CircuitConcreteLibfunc::U96SingleLimbLessThanGuaranteeVerify(info) => {
eval_u96_single_limb_less_than_guarantee_verify(registry, info, args)
}
}
}
fn eval_add_input(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Circuit(mut values), Value::Struct(members)]: [Value; 2] = args.try_into().unwrap()
else {
panic!()
};
let n_inputs = match registry.get_type(&info.ty).unwrap() {
CoreTypeConcrete::Circuit(CircuitTypeConcrete::Circuit(info)) => info.circuit_info.n_inputs,
_ => panic!(),
};
values.push(struct_to_u384(members));
EvalAction::NormalBranch(
(values.len() != n_inputs) as usize,
smallvec![Value::Circuit(values)],
)
}
fn eval_eval(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
_args: Vec<Value>,
) -> EvalAction {
let [add_mod @ Value::Unit, mul_mod @ Value::Unit, _descripctor @ Value::Unit, Value::Circuit(inputs), Value::CircuitModulus(modulus), _, _]: [Value; 7] = _args.try_into().unwrap()
else {
panic!()
};
let circ_info = match _registry.get_type(&_info.ty).unwrap() {
CoreTypeConcrete::Circuit(CircuitTypeConcrete::Circuit(info)) => &info.circuit_info,
_ => todo!(),
};
let mut outputs = vec![None; 1 + circ_info.n_inputs + circ_info.values.len()];
let mut add_gates = circ_info.add_offsets.iter().peekable();
let mut mul_gates = circ_info.mul_offsets.iter();
outputs[0] = Some(BigUint::from(1_u8));
for (i, input) in inputs.iter().enumerate() {
outputs[i + 1] = Some(input.to_owned());
}
let success = loop {
while let Some(add_gate) = add_gates.peek() {
let lhs = outputs[add_gate.lhs].to_owned();
let rhs = outputs[add_gate.rhs].to_owned();
match (lhs, rhs) {
(Some(l), Some(r)) => {
outputs[add_gate.output] = Some((l + r) % &modulus);
}
(None, Some(r)) => {
let res = match outputs[add_gate.output].to_owned() {
Some(res) => res,
None => break,
};
// if it is a sub_gate the output index is store in lhs
outputs[add_gate.lhs] = Some((res + &modulus - r) % &modulus);
}
// there aren't enough gates computed for add_gate to compute
// the next gate so we need to compute a mul_gate
_ => break,
};
add_gates.next();
}
match mul_gates.next() {
Some(mul_gate) => {
let lhs = outputs[mul_gate.lhs].to_owned();
let rhs = outputs[mul_gate.rhs].to_owned();
match (lhs, rhs) {
(Some(l), Some(r)) => {
outputs[mul_gate.output] = Some((l * r) % &modulus);
}
(None, Some(r)) => {
match r.modinv(&modulus) {
// if it is a inv_gate the output index is store in lhs
Some(r) => outputs[mul_gate.lhs] = Some(r),
// Since we don't calculate CircuitPartialOutputs
// perform an early break
None => {
outputs[mul_gate.lhs] = Some(find_nullifier(&r, &modulus));
break false;
}
}
}
// this state should not be reached since it would mean that
// not all the circuit's inputs where filled
_ => unreachable!(),
}
}
None => break true,
}
};
if success {
let values = outputs
.into_iter()
.skip(1 + circ_info.n_inputs)
.collect::<Option<Vec<BigUint>>>()
.expect("The circuit cannot be calculated");
EvalAction::NormalBranch(
0,
smallvec![
add_mod,
mul_mod,
Value::CircuitOutputs {
circuits: values,
modulus
}
],
)
} else {
EvalAction::NormalBranch(1, smallvec![add_mod, mul_mod, Value::Unit, Value::Unit])
}
}
fn eval_get_output(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &ConcreteGetOutputLibFunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::CircuitOutputs {
circuits: outputs,
modulus,
}]: [Value; 1] = args.try_into().unwrap()
else {
panic!()
};
let circuit_info = match _registry.get_type(&_info.circuit_ty).unwrap() {
CoreTypeConcrete::Circuit(CircuitTypeConcrete::Circuit(info)) => &info.circuit_info,
_ => todo!(),
};
let gate_offset = *circuit_info.values.get(&_info.output_ty).unwrap();
let output_idx = gate_offset - 1 - circuit_info.n_inputs;
let output = outputs[output_idx].to_owned();
let output_struct = u384_to_struct(output);
let modulus = u384_to_struct(modulus);
EvalAction::NormalBranch(
0,
smallvec![
output_struct.clone(),
Value::Struct(vec![output_struct, modulus]),
],
)
}
fn eval_u96_limbs_less_than_guarantee_verify(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &ConcreteU96LimbsLessThanGuaranteeVerifyLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Struct(guarantee)]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let limb_count = info.limb_count;
let Value::Struct(gate) = &guarantee[0] else {
panic!();
};
let Value::Struct(modulus) = &guarantee[1] else {
panic!();
};
let Value::BoundedInt {
value: gate_last_limb,
..
} = &gate[limb_count - 1]
else {
panic!();
};
let Value::BoundedInt {
value: modulus_last_limb,
..
} = &modulus[limb_count - 1]
else {
panic!();
};
let diff = (modulus_last_limb - gate_last_limb).to_u128().unwrap();
if diff != 0 {
EvalAction::NormalBranch(1, smallvec![Value::U128(diff)])
} else {
// if there is no diff, build a new guarantee, skipping the last limb
let new_gate = Value::Struct(gate[0..limb_count].to_vec());
let new_modulus = Value::Struct(modulus[0..limb_count].to_vec());
EvalAction::NormalBranch(0, smallvec![Value::Struct(vec![new_gate, new_modulus])])
}
}
fn eval_u96_single_limb_less_than_guarantee_verify(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [_guarantee]: [Value; 1] = args.try_into().unwrap();
EvalAction::NormalBranch(0, smallvec![Value::U128(0)])
}
fn eval_u96_guarantee_verify(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [range_check_96 @ Value::Unit, _]: [Value; 2] = args.try_into().unwrap() else {
panic!();
};
EvalAction::NormalBranch(0, smallvec![range_check_96])
}
fn eval_failure_guarantee_verify(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureOnlyConcreteLibfunc,
_args: Vec<Value>,
) -> EvalAction {
let [rc96 @ Value::Unit, mul_mod @ Value::Unit, _, _, _]: [Value; 5] =
_args.try_into().unwrap()
else {
panic!()
};
let limbs_count = match registry
.get_type(&info.signature.branch_signatures[0].vars[2].ty)
.unwrap()
{
CoreTypeConcrete::Circuit(CircuitTypeConcrete::U96LimbsLessThanGuarantee(info)) => {
info.limb_count
}
_ => panic!(),
};
let zero_u96 = Value::BoundedInt {
range: BigInt::zero()..BigInt::one() << 96,
value: 0.into(),
};
// This should be changed with it correct value when we implement this libfunc in native
let limbs_struct = Value::Struct(vec![zero_u96; limbs_count]);
EvalAction::NormalBranch(
0,
smallvec![
rc96,
mul_mod,
Value::Struct(vec![limbs_struct.clone(), limbs_struct])
],
)
}
fn eval_get_descriptor(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
_args: Vec<Value>,
) -> EvalAction {
EvalAction::NormalBranch(0, smallvec![Value::Unit])
}
fn eval_init_circuit_data(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [range_check_96 @ Value::Unit]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let num_inputs = match _registry.get_type(&info.ty).unwrap() {
CoreTypeConcrete::Circuit(CircuitTypeConcrete::Circuit(info)) => info.circuit_info.n_inputs,
_ => todo!("{}", info.ty),
};
EvalAction::NormalBranch(
0,
smallvec![
range_check_96,
Value::Circuit(Vec::with_capacity(num_inputs)),
],
)
}
fn eval_try_into_circuit_modulus(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Struct(members)]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let [Value::BoundedInt {
range: r0,
value: l0,
}, Value::BoundedInt {
range: r1,
value: l1,
}, Value::BoundedInt {
range: r2,
value: l2,
}, Value::BoundedInt {
range: r3,
value: l3,
}]: [Value; 4] = members.try_into().unwrap()
else {
panic!()
};
assert_eq!(r0, BigInt::ZERO..(BigInt::from(1) << 96));
assert_eq!(r1, BigInt::ZERO..(BigInt::from(1) << 96));
assert_eq!(r2, BigInt::ZERO..(BigInt::from(1) << 96));
assert_eq!(r3, BigInt::ZERO..(BigInt::from(1) << 96));
let l0 = l0.to_biguint().unwrap();
let l1 = l1.to_biguint().unwrap();
let l2 = l2.to_biguint().unwrap();
let l3 = l3.to_biguint().unwrap();
let value = l0 | (l1 << 96) | (l2 << 192) | (l3 << 288);
if value > BigUint::one() {
EvalAction::NormalBranch(0, smallvec![Value::CircuitModulus(value)])
} else {
EvalAction::NormalBranch(1, smallvec![])
}
}
fn eval_into_u96_guarantee(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::BoundedInt { range, value }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
assert_eq!(range, BigInt::ZERO..(BigInt::from(1) << 96));
EvalAction::NormalBranch(0, smallvec![Value::U128(value.try_into().unwrap())])
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
lambdaclass/cairo_native | https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/array.rs | debug_utils/sierra-emu/src/vm/array.rs | use super::EvalAction;
use crate::{find_real_type, Value};
use cairo_lang_sierra::{
extensions::{
array::ArrayConcreteLibfunc,
core::{CoreLibfunc, CoreType, CoreTypeConcrete},
lib_func::{SignatureAndTypeConcreteLibfunc, SignatureOnlyConcreteLibfunc},
ConcreteLibfunc,
},
program_registry::ProgramRegistry,
};
use smallvec::smallvec;
pub fn eval(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
selector: &ArrayConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
match selector {
ArrayConcreteLibfunc::New(info) => eval_new(registry, info, args),
ArrayConcreteLibfunc::SpanFromTuple(info) => eval_span_from_tuple(registry, info, args),
ArrayConcreteLibfunc::TupleFromSpan(info) => eval_tuple_from_span(registry, info, args),
ArrayConcreteLibfunc::Append(info) => eval_append(registry, info, args),
ArrayConcreteLibfunc::PopFront(info) => eval_pop_front(registry, info, args),
ArrayConcreteLibfunc::PopFrontConsume(info) => eval_pop_front_consume(registry, info, args),
ArrayConcreteLibfunc::Get(info) => eval_get(registry, info, args),
ArrayConcreteLibfunc::Slice(info) => eval_slice(registry, info, args),
ArrayConcreteLibfunc::Len(info) => eval_len(registry, info, args),
ArrayConcreteLibfunc::SnapshotPopFront(info) => {
eval_snapshot_pop_front(registry, info, args)
}
ArrayConcreteLibfunc::SnapshotPopBack(info) => eval_snapshot_pop_back(registry, info, args),
ArrayConcreteLibfunc::SnapshotMultiPopFront(info) => {
eval_snapshot_multi_pop_front(registry, info, args)
}
ArrayConcreteLibfunc::SnapshotMultiPopBack(info) => {
eval_snapshot_multi_pop_back(registry, info, args)
}
}
}
fn eval_span_from_tuple(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Struct(data)]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let ty = &info.branch_signatures()[0].vars[0].ty;
let ty = find_real_type(registry, ty);
let CoreTypeConcrete::Array(info) = registry.get_type(&ty).unwrap() else {
panic!()
};
let value = Value::Array {
ty: info.ty.clone(),
data,
};
EvalAction::NormalBranch(0, smallvec![value])
}
fn eval_tuple_from_span(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { data, .. }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let tuple_len = {
let CoreTypeConcrete::Struct(param) = registry.get_type(&info.ty).unwrap() else {
panic!()
};
param.members.len()
};
if data.len() == tuple_len {
EvalAction::NormalBranch(0, smallvec![Value::Struct(data)])
} else {
EvalAction::NormalBranch(1, smallvec![])
}
}
fn eval_new(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureOnlyConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [] = args.try_into().unwrap();
let type_info = registry
.get_type(&info.signature.branch_signatures[0].vars[0].ty)
.unwrap();
let ty = match type_info {
CoreTypeConcrete::Array(info) => &info.ty,
_ => unreachable!(),
};
EvalAction::NormalBranch(
0,
smallvec![Value::Array {
ty: ty.clone(),
data: Vec::new(),
}],
)
}
fn eval_append(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { ty, mut data }, item]: [Value; 2] = args.try_into().unwrap() else {
panic!()
};
assert_eq!(info.signature.param_signatures[1].ty, ty);
assert!(item.is(registry, &ty));
data.push(item.clone());
EvalAction::NormalBranch(0, smallvec![Value::Array { ty, data }])
}
fn eval_get(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [range_check @ Value::Unit, Value::Array { data, .. }, Value::U32(index)]: [Value; 3] =
args.try_into().unwrap()
else {
panic!()
};
match data.get(index as usize).cloned() {
Some(value) => EvalAction::NormalBranch(0, smallvec![range_check, value]),
None => EvalAction::NormalBranch(1, smallvec![range_check]),
}
}
fn eval_slice(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [range_check @ Value::Unit, Value::Array { data, ty }, Value::U32(start), Value::U32(len)]: [Value; 4] =
args.try_into().unwrap()
else {
panic!()
};
match data.get(start as usize..(start + len) as usize) {
Some(value) => EvalAction::NormalBranch(
0,
smallvec![
range_check,
Value::Array {
data: value.to_vec(),
ty
}
],
),
None => EvalAction::NormalBranch(1, smallvec![range_check]),
}
}
fn eval_len(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { data, .. }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
let array_len = data.len().try_into().unwrap();
EvalAction::NormalBranch(0, smallvec![Value::U32(array_len)])
}
fn eval_pop_front(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { mut data, ty }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
if !data.is_empty() {
let new_data = data.split_off(1);
let value = data[0].clone();
EvalAction::NormalBranch(0, smallvec![Value::Array { data: new_data, ty }, value])
} else {
EvalAction::NormalBranch(1, smallvec![Value::Array { data, ty }])
}
}
fn eval_pop_front_consume(
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
_info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { mut data, ty }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
if !data.is_empty() {
let new_data = data.split_off(1);
let value = data[0].clone();
EvalAction::NormalBranch(0, smallvec![Value::Array { data: new_data, ty }, value])
} else {
EvalAction::NormalBranch(1, smallvec![])
}
}
fn eval_snapshot_pop_front(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { mut data, ty }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
if !data.is_empty() {
let new_data = data.split_off(1);
let value = data[0].clone();
assert!(value.is(registry, &info.ty));
EvalAction::NormalBranch(0, smallvec![Value::Array { data: new_data, ty }, value])
} else {
EvalAction::NormalBranch(1, smallvec![Value::Array { data, ty }])
}
}
fn eval_snapshot_pop_back(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &SignatureAndTypeConcreteLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [Value::Array { mut data, ty }]: [Value; 1] = args.try_into().unwrap() else {
panic!()
};
if !data.is_empty() {
let new_data = data.split_off(data.len() - 1);
let value = new_data[0].clone();
assert!(value.is(registry, &info.ty));
EvalAction::NormalBranch(0, smallvec![Value::Array { data, ty }, value])
} else {
EvalAction::NormalBranch(1, smallvec![Value::Array { data, ty }])
}
}
fn eval_snapshot_multi_pop_front(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &cairo_lang_sierra::extensions::array::ConcreteMultiPopLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [rangecheck, Value::Array { mut data, ty }]: [Value; 2] = args.try_into().unwrap() else {
panic!()
};
let CoreTypeConcrete::Struct(popped_cty) = registry.get_type(&info.popped_ty).unwrap() else {
panic!()
};
if data.len() >= popped_cty.members.len() {
let new_data = data.split_off(popped_cty.members.len());
let value = Value::Struct(data);
assert!(value.is(registry, &info.popped_ty));
EvalAction::NormalBranch(
0,
smallvec![rangecheck, Value::Array { data: new_data, ty }, value],
)
} else {
EvalAction::NormalBranch(1, smallvec![rangecheck, Value::Array { data, ty }])
}
}
fn eval_snapshot_multi_pop_back(
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
info: &cairo_lang_sierra::extensions::array::ConcreteMultiPopLibfunc,
args: Vec<Value>,
) -> EvalAction {
let [rangecheck, Value::Array { mut data, ty }]: [Value; 2] = args.try_into().unwrap() else {
panic!()
};
let CoreTypeConcrete::Struct(popped_cty) = registry.get_type(&info.popped_ty).unwrap() else {
panic!()
};
if data.len() >= popped_cty.members.len() {
let popped_data = data.split_off(data.len() - popped_cty.members.len());
let value = Value::Struct(popped_data);
assert!(value.is(registry, &info.popped_ty));
EvalAction::NormalBranch(0, smallvec![rangecheck, Value::Array { data, ty }, value])
} else {
EvalAction::NormalBranch(1, smallvec![rangecheck, Value::Array { data, ty }])
}
}
| rust | Apache-2.0 | f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce | 2026-01-04T20:20:54.031924Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.