Skip to content

[2.11.1] Implement blake libfunc #1160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 62 additions & 55 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 @@ -33,6 +33,7 @@ use num_bigint::BigInt;
use std::{cell::Cell, error::Error, ops::Deref};

mod array;
mod blake;
mod r#bool;
mod bounded_int;
mod r#box;
Expand Down Expand Up @@ -179,7 +180,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
132 changes: 132 additions & 0 deletions src/libfuncs/blake.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
use cairo_lang_sierra::{
extensions::{
blake::BlakeConcreteLibfunc,
core::{CoreLibfunc, CoreType},
lib_func::SignatureOnlyConcreteLibfunc,
},
program_registry::ProgramRegistry,
};
use melior::{
ir::{Block, BlockLike, Location},
Context,
};

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

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` is the total amount of bytes hashed after hashing the message.
/// `finalize` is 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, 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,
)?;

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

Ok(())
}

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

#[test]
fn test_blake() {
let program = load_cairo!(
use core::blake::{blake2s_compress, blake2s_finalize};

fn run_test() -> [u32; 8] nopanic {
let state = BoxTrait::new([0_u32; 8]);
let msg = BoxTrait::new([0_u32; 16]);
let byte_count = 64_u32;

let _res = blake2s_compress(state, byte_count, msg).unbox();

blake2s_finalize(state, byte_count, msg).unbox()
}
);

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

assert_eq!(
result,
jit_struct!(
Value::Uint32(128291589),
Value::Uint32(1454945417),
Value::Uint32(3191583614),
Value::Uint32(1491889056),
Value::Uint32(794023379),
Value::Uint32(651000200),
Value::Uint32(3725903680),
Value::Uint32(1044330286),
)
);
}
}
37 changes: 37 additions & 0 deletions src/metadata/runtime_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ enum RuntimeBinding {
DictDrop,
DictDup,
GetCostsBuiltin,
BlakeCompress,
DebugPrint,
#[cfg(feature = "with-cheatcode")]
VtableCheatcode,
Expand All @@ -65,6 +66,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",
#[cfg(feature = "with-cheatcode")]
RuntimeBinding::VtableCheatcode => "cairo_native__vtable_cheatcode",
}
Expand Down Expand Up @@ -109,6 +111,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 ()
}
#[cfg(feature = "with-cheatcode")]
RuntimeBinding::VtableCheatcode => {
crate::starknet::cairo_native__vtable_cheatcode as *const ()
Expand Down Expand Up @@ -257,6 +262,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 @@ -681,6 +717,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 @@ -142,6 +142,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 @@ -544,7 +544,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"),
})
}
Expand Down Expand Up @@ -630,7 +631,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"),
})
}
Expand Down Expand Up @@ -756,9 +757,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 @@ -834,6 +832,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"),
})
}
Expand Down
1 change: 1 addition & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use std::{
};
use thiserror::Error;

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