Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Added support functions for filesha512 and BLAKE-3 hashing. #1697

Merged
merged 3 commits into from
Oct 17, 2024
Merged
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
71 changes: 71 additions & 0 deletions kclvm/runtime/src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,3 +269,74 @@ pub extern "C" fn kclvm_crypto_filesha256(
}
panic!("filesha256() missing 1 required positional argument: 'filepath'");
}

#[no_mangle]
#[runtime_fn]
pub extern "C" fn kclvm_crypto_filesha512(
ctx: *mut kclvm_context_t,
args: *const kclvm_value_ref_t,
kwargs: *const kclvm_value_ref_t,
) -> *const kclvm_value_ref_t {
let args = ptr_as_ref(args);
let kwargs = ptr_as_ref(kwargs);
let ctx = mut_ptr_as_ref(ctx);

if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) {
let mut file = File::open(&filepath)
.unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e));

let mut hasher = Sha512::new();

let mut buffer = [0; 4096];
while let Ok(bytes_read) = file.read(&mut buffer) {
if bytes_read == 0 {
break; // End of file
}
hasher.update(&buffer[..bytes_read]);
}

let hash_result = hasher.finalize();

let hex = hash_result
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();

return ValueRef::str(&hex).into_raw(ctx);
}
panic!("filesha512() missing 1 required positional argument: 'filepath'");
}

// fileblake3
#[no_mangle]
#[runtime_fn]
pub extern "C" fn kclvm_crypto_fileblake3(
ctx: *mut kclvm_context_t,
args: *const kclvm_value_ref_t,
kwargs: *const kclvm_value_ref_t,
) -> *const kclvm_value_ref_t {
let args = ptr_as_ref(args);
let kwargs = ptr_as_ref(kwargs);
let ctx = mut_ptr_as_ref(ctx);

if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) {
let mut file = File::open(&filepath)
.unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e));

let mut buffer = Vec::new();
file.read_to_end(&mut buffer)
.unwrap_or_else(|e| panic!("failed to read file '{}': {}", filepath, e));

let hasher = blake3::hash(&buffer);

let mut hex = String::with_capacity(2 * blake3::OUT_LEN);
use std::fmt::Write;

for byte in hasher.as_bytes() {
let _ = write!(&mut hex, "{byte:02x}");
}

return ValueRef::str(hex.as_str()).into_raw(ctx);
}
panic!("fileblake3() missing 1 required positional argument: 'filepath'");
}
Loading