Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
6f8c152
implement blake libfunc
FrancoGiachetta Mar 31, 2025
94729dc
doc
FrancoGiachetta Mar 31, 2025
df089c7
Merge branch 'main' into impl-blake-libfunc
FrancoGiachetta Apr 1, 2025
e44e96e
merge main
FrancoGiachetta Apr 3, 2025
520e8f5
Merge branch 'impl-blake-libfunc' of github.com:lambdaclass/cairo_nat…
FrancoGiachetta Apr 3, 2025
73d4a52
merge main
FrancoGiachetta Apr 3, 2025
95e6f19
Merge branch 'main' into impl-blake-libfunc
FrancoGiachetta Apr 7, 2025
abfe998
rename runtime function
FrancoGiachetta Apr 7, 2025
40fe8ac
Merge branch 'impl-blake-libfunc' of github.com:lambdaclass/cairo_nat…
FrancoGiachetta Apr 7, 2025
5c774a9
remove blake type and fix runtime blake symbol
FrancoGiachetta Apr 8, 2025
da14c5e
fmt
FrancoGiachetta Apr 8, 2025
ed82cfb
add blake libfuncs' firms to the comments
FrancoGiachetta Apr 15, 2025
3d509f7
Merge branch 'main' into impl-blake-libfunc
FrancoGiachetta Apr 21, 2025
2ed2110
merge main
FrancoGiachetta Apr 30, 2025
5d06af9
Merge branch 'impl-blake-libfunc' of github.com:lambdaclass/cairo_nat…
FrancoGiachetta Apr 30, 2025
b7713dc
Merge branch 'main' into impl-blake-libfunc
FrancoGiachetta Apr 30, 2025
f2cebe3
merge main
FrancoGiachetta Oct 17, 2025
1128ee8
Merge branch 'impl-blake-libfunc' of github.com:lambdaclass/cairo_nat…
FrancoGiachetta Oct 17, 2025
5d5d65c
fmt
FrancoGiachetta Oct 17, 2025
b36248c
post merge fix
FrancoGiachetta Oct 17, 2025
8d6b3f6
post merge fix
FrancoGiachetta Oct 17, 2025
6b7a5ab
add tests
FrancoGiachetta Oct 17, 2025
7ceb9ac
change test
FrancoGiachetta Oct 17, 2025
307d968
Merge branch 'main' into impl-blake-libfunc
FrancoGiachetta Oct 24, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
780 changes: 391 additions & 389 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion src/libfuncs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ use std::{
};

mod array;
mod blake;
mod r#bool;
mod bounded_int;
mod r#box;
Expand Down Expand Up @@ -191,7 +192,9 @@ impl LibfuncBuilder for CoreConcreteLibfunc {
Self::IntRange(selector) => self::int_range::build(
context, registry, entry, location, helper, metadata, selector,
),
Self::Blake(_) => native_panic!("Implement blake libfunc"),
Self::Blake(selector) => self::blake::build(
context, registry, entry, location, helper, metadata, selector,
),
Self::Mem(selector) => self::mem::build(
context, registry, entry, location, helper, metadata, selector,
),
Expand Down
135 changes: 135 additions & 0 deletions src/libfuncs/blake.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use cairo_lang_sierra::{
extensions::{
blake::BlakeConcreteLibfunc,
core::{CoreLibfunc, CoreType},
lib_func::SignatureOnlyConcreteLibfunc,
},
program_registry::ProgramRegistry,
};
use melior::{
helpers::{ArithBlockExt, BuiltinBlockExt},
ir::{Block, Location},
Context,
};

use crate::{
error::{panic::ToNativeAssertError, Result},
metadata::{runtime_bindings::RuntimeBindingsMeta, MetadataStorage},
};

use super::LibfuncHelper;

pub fn build<'ctx, 'this>(
context: &'ctx Context,
registry: &ProgramRegistry<CoreType, CoreLibfunc>,
entry: &'this Block<'ctx>,
location: Location<'ctx>,
helper: &LibfuncHelper<'ctx, 'this>,
metadata: &mut MetadataStorage,
selector: &BlakeConcreteLibfunc,
) -> Result<()> {
match selector {
BlakeConcreteLibfunc::Blake2sCompress(info) => build_blake_operation(
context, registry, entry, location, helper, metadata, info, false,
),
BlakeConcreteLibfunc::Blake2sFinalize(info) => build_blake_operation(
context, registry, entry, location, helper, metadata, info, true,
),
}
}

/// Performs a blake2s compression.
///
/// `bytes_count`: total amount of bytes hashed after hashing the message.
/// `finalize`: wether the libfunc call is a finalize or not.
/// ```cairo
/// pub extern fn blake2s_compress(
/// state: Blake2sState, byte_count: u32, msg: Blake2sInput,
/// ) -> Blake2sState nopanic;
/// ```
///
/// Similar to `blake2s_compress`, but it marks the end of the compression
/// ```cairo
/// pub extern fn blake2s_finalize(
/// state: Blake2sState, byte_count: u32, msg: Blake2sInput,
/// ) -> Blake2sState nopanic;
/// ```
#[allow(clippy::too_many_arguments)]
fn build_blake_operation<'ctx, 'this>(
context: &'ctx Context,
_registry: &ProgramRegistry<CoreType, CoreLibfunc>,
entry: &'this Block<'ctx>,
location: Location<'ctx>,
helper: &LibfuncHelper<'ctx, 'this>,
metadata: &mut MetadataStorage,
_info: &SignatureOnlyConcreteLibfunc,
finalize: bool,
) -> Result<()> {
let state_ptr = entry.arg(0)?;
let bytes_count = entry.arg(1)?;
let message = entry.arg(2)?;
let k_finalize = entry.const_int(context, location, finalize as u8, 1)?;

let runtime_bindings = metadata
.get_mut::<RuntimeBindingsMeta>()
.to_native_assert_error("runtime library should be available")?;

runtime_bindings.libfunc_blake_compress(
context,
helper,
entry,
state_ptr,
message,
bytes_count,
k_finalize,
location,
)?;

helper.br(entry, 0, &[state_ptr], location)?;

Ok(())
}

#[cfg(test)]
mod tests {
use crate::{
utils::test::{jit_struct, load_cairo, run_program},
Value,
};

// This test is taken from the Blake2s-256 implementeation RFC-7693, Appendix B.
// https://www.rfc-editor.org/rfc/rfc7693#appendix-B.
#[test]
fn test_blake_3_bytes_compress() {
let program = load_cairo!(
use core::blake::{blake2s_compress, blake2s_finalize};

fn run_test() -> [u32; 8] nopanic {
let initial_state: Box<[u32; 8]> = BoxTrait::new([
0x6B08E647, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
]);
// This number represents the bytes for "abc" string.
let abc_bytes = 0x00636261;
let msg: Box<[u32; 16]> = BoxTrait::new([abc_bytes, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);

blake2s_finalize(initial_state, 3, msg).unbox()
}
);

let result = run_program(&program, "run_test", &[]).return_value;

assert_eq!(
result,
jit_struct!(
Value::Uint32(0x8C5E8C50),
Value::Uint32(0xE2147C32),
Value::Uint32(0xA32BA7E1),
Value::Uint32(0x2F45EB4E),
Value::Uint32(0x208B4537),
Value::Uint32(0x293AD69E),
Value::Uint32(0x4C9B994D),
Value::Uint32(0x82596786),
)
);
}
}
37 changes: 37 additions & 0 deletions src/metadata/runtime_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ enum RuntimeBinding {
DictDrop,
DictDup,
GetCostsBuiltin,
BlakeCompress,
DebugPrint,
ExtendedEuclideanAlgorithm,
CircuitArithOperation,
Expand Down Expand Up @@ -72,6 +73,7 @@ impl RuntimeBinding {
RuntimeBinding::DictDrop => "cairo_native__dict_drop",
RuntimeBinding::DictDup => "cairo_native__dict_dup",
RuntimeBinding::GetCostsBuiltin => "cairo_native__get_costs_builtin",
RuntimeBinding::BlakeCompress => "cairo_native__libfunc__blake_compress",
RuntimeBinding::ExtendedEuclideanAlgorithm => {
"cairo_native__extended_euclidean_algorithm"
}
Expand Down Expand Up @@ -124,6 +126,9 @@ impl RuntimeBinding {
RuntimeBinding::GetCostsBuiltin => {
crate::runtime::cairo_native__get_costs_builtin as *const ()
}
RuntimeBinding::BlakeCompress => {
crate::runtime::cairo_native__libfunc__blake_compress as *const ()
}
RuntimeBinding::ExtendedEuclideanAlgorithm => return None,
RuntimeBinding::CircuitArithOperation => return None,
#[cfg(feature = "with-cheatcode")]
Expand Down Expand Up @@ -377,6 +382,37 @@ impl RuntimeBindingsMeta {
))
}

#[allow(clippy::too_many_arguments)]
pub fn libfunc_blake_compress<'c, 'a>(
&mut self,
context: &'c Context,
module: &Module,
block: &'a Block<'c>,
state: Value<'c, 'a>,
message: Value<'c, 'a>,
count_bytes: Value<'c, 'a>,
finalize: Value<'c, 'a>,
location: Location<'c>,
) -> Result<OperationRef<'c, 'a>>
where
'c: 'a,
{
let function = self.build_function(
context,
module,
block,
location,
RuntimeBinding::BlakeCompress,
)?;

Ok(block.append_operation(
OperationBuilder::new("llvm.call", location)
.add_operands(&[function])
.add_operands(&[state, message, count_bytes, finalize])
.build()?,
))
}

/// Register if necessary, then invoke the `ec_point_from_x_nz()` function.
pub fn libfunc_ec_point_from_x_nz<'c, 'a>(
&mut self,
Expand Down Expand Up @@ -798,6 +834,7 @@ pub fn setup_runtime(find_symbol_ptr: impl Fn(&str) -> Option<*mut c_void>) {
RuntimeBinding::DictDrop,
RuntimeBinding::DictDup,
RuntimeBinding::GetCostsBuiltin,
RuntimeBinding::BlakeCompress,
RuntimeBinding::DebugPrint,
#[cfg(feature = "with-cheatcode")]
RuntimeBinding::VtableCheatcode,
Expand Down
20 changes: 19 additions & 1 deletion src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(non_snake_case)]

use crate::utils::BuiltinCosts;
use crate::utils::{blake_utils, BuiltinCosts};
use cairo_lang_sierra_gas::core_libfunc_cost::{
DICT_SQUASH_REPEATED_ACCESS_COST, DICT_SQUASH_UNIQUE_KEY_COST,
};
Expand Down Expand Up @@ -144,6 +144,24 @@ pub unsafe extern "C" fn cairo_native__libfunc__hades_permutation(
*op2 = state[2].to_bytes_le();
}

pub unsafe extern "C" fn cairo_native__libfunc__blake_compress(
state: &mut [u32; 8],
message: &[u32; 16],
count_bytes: u32,
finalize: bool,
) {
let new_state = blake_utils::blake2s_compress(
state,
message,
count_bytes,
0,
if finalize { 0xFFFFFFFF } else { 0 },
0,
);

*state = new_state;
}

/// Felt252 type used in cairo native runtime
#[derive(Debug)]
pub struct FeltDict {
Expand Down
11 changes: 6 additions & 5 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,8 @@ impl TypeBuilder for CoreTypeConcrete {
CoreTypeConcrete::Circuit(info) => circuit::is_complex(info),

CoreTypeConcrete::IntRange(_info) => false,
CoreTypeConcrete::Blake(_info) => native_panic!("Implement is_complex for Blake type"),

CoreTypeConcrete::Blake(_) => native_panic!("Implement is_complex for Blake type"),
CoreTypeConcrete::QM31(_info) => native_panic!("Implement is_complex for QM31 type"),
CoreTypeConcrete::GasReserve(_info) => native_panic!("Implement is_complex for GasReserve type"),
})
Expand Down Expand Up @@ -633,7 +634,7 @@ impl TypeBuilder for CoreTypeConcrete {
let type_info = registry.get_type(&info.ty)?;
type_info.is_zst(registry)?
}
CoreTypeConcrete::Blake(_info) => native_panic!("Implement is_zst for Blake type"),
CoreTypeConcrete::Blake(_) => native_panic!("Implement is_zst for Blake type"),
CoreTypeConcrete::QM31(_info) => native_panic!("Implement is_zst for QM31 type"),
CoreTypeConcrete::GasReserve(_info) => {
native_panic!("Implement is_zst for GasReserve type")
Expand Down Expand Up @@ -765,9 +766,6 @@ impl TypeBuilder for CoreTypeConcrete {
// arguments.
Ok(match self {
CoreTypeConcrete::IntRange(_) => false,
CoreTypeConcrete::Blake(_info) => {
native_panic!("Implement is_memory_allocated for Blake type")
}
CoreTypeConcrete::Array(_) => false,
CoreTypeConcrete::Bitwise(_) => false,
CoreTypeConcrete::Box(_) => false,
Expand Down Expand Up @@ -843,6 +841,9 @@ impl TypeBuilder for CoreTypeConcrete {
.is_memory_allocated(registry)?,
CoreTypeConcrete::Coupon(_) => false,
CoreTypeConcrete::Circuit(_) => false,
CoreTypeConcrete::Blake(_) => {
native_panic!("Implement is_memory_allocated for Blake type")
}
CoreTypeConcrete::QM31(_) => native_panic!("Implement is_memory_allocated for QM31"),
CoreTypeConcrete::GasReserve(_) => {
native_panic!("Implement is_memory_allocated for GasReserve")
Expand Down
1 change: 1 addition & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use std::{
};
use thiserror::Error;

pub mod blake_utils;
pub mod mem_tracing;
mod program_registry_ext;
mod range_ext;
Expand Down
Loading
Loading