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

Host function generic_hash() with blake2b/blake3 support. #4412

Closed
Closed
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
32 changes: 32 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions execution_engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ license = "Apache-2.0"
anyhow = "1.0.33"
base16 = "0.2.1"
bincode = "1.3.1"
blake3 = "1.5.0"
casper-hashing = { version = "2.0.0", path = "../hashing" }
casper-types = { version = "3.0.0", path = "../types", default-features = false, features = ["datasize", "gens", "json-schema"] }
casper-wasm = { version = "0.46.0", default-features = false }
Expand Down
1 change: 1 addition & 0 deletions execution_engine/src/core/resolvers/v1_function_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub(crate) enum FunctionIndex {
RandomBytes,
DictionaryReadFuncIndex,
EnableContractVersion,
GenericHash,
}

impl From<FunctionIndex> for usize {
Expand Down
4 changes: 4 additions & 0 deletions execution_engine/src/core/resolvers/v1_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ impl ModuleImportResolver for RuntimeModuleImportResolver {
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::EnableContractVersion.into(),
),
"casper_generic_hash" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 5][..], Some(ValueType::I32)),
FunctionIndex::GenericHash.into(),
),
_ => {
return Err(InterpreterError::Function(format!(
"host module doesn't export function with name {}",
Expand Down
15 changes: 15 additions & 0 deletions execution_engine/src/core/runtime/crypto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/// The number of bytes in a Blake3 hash.
/// NOTE: It does not make sense to use different lengths.
const BLAKE3_DIGEST_LENGTH: usize = 32;

#[doc(hidden)]
pub fn blake3<T: AsRef<[u8]>>(data: T) -> [u8; BLAKE3_DIGEST_LENGTH] {
let mut result = [0; BLAKE3_DIGEST_LENGTH];
let mut hasher = blake3::Hasher::new();

hasher.update(data.as_ref());
let hash = hasher.finalize();
let hash_bytes: &[u8; BLAKE3_DIGEST_LENGTH] = hash.as_bytes();
result.copy_from_slice(hash_bytes);
result
}
49 changes: 46 additions & 3 deletions execution_engine/src/core/runtime/externals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ use casper_types::{
contracts::{ContractPackageStatus, EntryPoints, NamedKeys},
crypto,
system::auction::EraInfo,
ApiError, ContractHash, ContractPackageHash, ContractVersion, EraId, Gas, Group, Key,
StoredValue, URef, U512, UREF_SERIALIZED_LENGTH,
ApiError, ContractHash, ContractPackageHash, ContractVersion, EraId, Gas, Group, HashAlgoType,
Key, StoredValue, URef, U512, UREF_SERIALIZED_LENGTH,
};

use super::{args::Args, Error, Runtime};
use crate::{
core::resolvers::v1_function_index::FunctionIndex,
core::{resolvers::v1_function_index::FunctionIndex, runtime::crypto as core_crypto},
shared::host_function_costs::{Cost, HostFunction, DEFAULT_HOST_FUNCTION_NEW_DICTIONARY},
storage::global_state::StateReader,
};
Expand Down Expand Up @@ -1097,6 +1097,49 @@ where

Ok(Some(RuntimeValue::I32(api_error::i32_from(result))))
}

FunctionIndex::GenericHash => {
// args(0) = pointer to input in Wasm memory
// args(1) = size of input in Wasm memory
// args(2) = integer representation of HashAlgoType enum variant
// args(3) = pointer to output pointer in Wasm memory
// args(4) = size of output
let (in_ptr, in_size, hash_algo_type, out_ptr, out_size) = Args::parse(args)?;
self.charge_host_function_call(
&host_function_costs.generic_hash,
[in_ptr, in_size, hash_algo_type, out_ptr, out_size],
)?;
let hash_algo_type = match HashAlgoType::try_from(hash_algo_type as u8) {
Ok(v) => v,
Err(_e) => {
return Ok(Some(RuntimeValue::I32(api_error::i32_from(Err(
ApiError::InvalidArgument,
)))))
}
};

let digest =
self.checked_memory_slice(in_ptr as usize, in_size as usize, |input| {
match hash_algo_type {
HashAlgoType::Blake2b => crypto::blake2b(input),
HashAlgoType::Blake3 => core_crypto::blake3(input),
}
})?;

let result = if digest.len() > out_size as usize {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something I just noticed - we've done hashing already, but we're checking the size after the fact. Since the output of the hash is constant, we could also move this check above the checked_memory_slice line.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though the output is always expected to be 32 bytes, those hashes use different constants for their digest size:

  • blake2: BLAKE2B_DIGEST_LENGTH
  • blake3: BLAKE3_DIGEST_LENGTH

Unless we implement all the necessary hash functions (e.g., sha256, keccak, poseidon) and generalize it with something like GENERIC_HASH_DIGEST_LENGTH, I would prefer to avoid using hardcoded pre-checks.

Err(ApiError::BufferTooSmall)
} else {
Ok(())
};
if result.is_err() {
return Ok(Some(RuntimeValue::I32(api_error::i32_from(result))));
}

self.try_get_memory()?
.set(out_ptr, &digest)
.map_err(|error| Error::Interpreter(error.into()))?;
Ok(Some(RuntimeValue::I32(0)))
}
}
}
}
1 change: 1 addition & 0 deletions execution_engine/src/core/runtime/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! This module contains executor state of the WASM code.
mod args;
mod auction_internal;
mod crypto;
mod externals;
mod handle_payment_internal;
mod host_function_flag;
Expand Down
10 changes: 10 additions & 0 deletions execution_engine/src/shared/host_function_costs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ pub struct HostFunctionCosts {
pub random_bytes: HostFunction<[Cost; 2]>,
/// Cost of calling the `enable_contract_version` host function.
pub enable_contract_version: HostFunction<[Cost; 4]>,
/// Cost of calling the `generic_hash` host function.
pub generic_hash: HostFunction<[Cost; 5]>,
}

impl Default for HostFunctionCosts {
Expand Down Expand Up @@ -420,6 +422,7 @@ impl Default for HostFunctionCosts {
blake2b: HostFunction::default(),
random_bytes: HostFunction::default(),
enable_contract_version: HostFunction::default(),
generic_hash: HostFunction::default(),
}
}
}
Expand Down Expand Up @@ -471,6 +474,7 @@ impl ToBytes for HostFunctionCosts {
ret.append(&mut self.blake2b.to_bytes()?);
ret.append(&mut self.random_bytes.to_bytes()?);
ret.append(&mut self.enable_contract_version.to_bytes()?);
ret.append(&mut self.generic_hash.to_bytes()?);
Ok(ret)
}

Expand Down Expand Up @@ -519,6 +523,7 @@ impl ToBytes for HostFunctionCosts {
+ self.blake2b.serialized_length()
+ self.random_bytes.serialized_length()
+ self.enable_contract_version.serialized_length()
+ self.generic_hash.serialized_length()
}
}

Expand Down Expand Up @@ -568,6 +573,7 @@ impl FromBytes for HostFunctionCosts {
let (blake2b, rem) = FromBytes::from_bytes(rem)?;
let (random_bytes, rem) = FromBytes::from_bytes(rem)?;
let (enable_contract_version, rem) = FromBytes::from_bytes(rem)?;
let (generic_hash, rem) = FromBytes::from_bytes(rem)?;
Ok((
HostFunctionCosts {
read_value,
Expand Down Expand Up @@ -614,6 +620,7 @@ impl FromBytes for HostFunctionCosts {
blake2b,
random_bytes,
enable_contract_version,
generic_hash,
},
rem,
))
Expand Down Expand Up @@ -667,6 +674,7 @@ impl Distribution<HostFunctionCosts> for Standard {
blake2b: rng.gen(),
random_bytes: rng.gen(),
enable_contract_version: rng.gen(),
generic_hash: rng.gen(),
}
}
}
Expand Down Expand Up @@ -728,6 +736,7 @@ pub mod gens {
blake2b in host_function_cost_arb(),
random_bytes in host_function_cost_arb(),
enable_contract_version in host_function_cost_arb(),
generic_hash in host_function_cost_arb(),
) -> HostFunctionCosts {
HostFunctionCosts {
read_value,
Expand Down Expand Up @@ -774,6 +783,7 @@ pub mod gens {
blake2b,
random_bytes,
enable_contract_version,
generic_hash,
}
}
}
Expand Down
1 change: 1 addition & 0 deletions execution_engine_testing/tests/src/test/storage_costs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ static NEW_HOST_FUNCTION_COSTS: Lazy<HostFunctionCosts> = Lazy::new(|| HostFunct
blake2b: HostFunction::fixed(0),
random_bytes: HostFunction::fixed(0),
enable_contract_version: HostFunction::fixed(0),
generic_hash: HostFunction::fixed(0),
});
static STORAGE_COSTS_ONLY: Lazy<WasmConfig> = Lazy::new(|| {
WasmConfig::new(
Expand Down
1 change: 1 addition & 0 deletions execution_engine_testing/tests/src/test/system_costs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -979,6 +979,7 @@ fn should_verify_wasm_add_bid_wasm_cost_is_not_recursive() {
blake2b: HostFunction::fixed(0),
random_bytes: HostFunction::fixed(0),
enable_contract_version: HostFunction::fixed(0),
generic_hash: HostFunction::fixed(0),
};

let new_wasm_config = WasmConfig::new(
Expand Down
1 change: 1 addition & 0 deletions node/src/types/chainspec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ mod tests {
blake2b: HostFunction::new(133, [0, 1, 2, 3]),
random_bytes: HostFunction::new(123, [0, 1]),
enable_contract_version: HostFunction::new(142, [0, 1, 2, 3]),
generic_hash: HostFunction::new(152, [0, 1, 2, 3, 4]),
});
static EXPECTED_GENESIS_WASM_COSTS: Lazy<WasmConfig> = Lazy::new(|| {
WasmConfig::new(
Expand Down
1 change: 1 addition & 0 deletions resources/local/chainspec.toml.in
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ transfer_to_account = { cost = 2_500_000_000, arguments = [0, 0, 0, 0, 0, 0, 0]
update_associated_key = { cost = 4_200, arguments = [0, 0, 0] }
write = { cost = 14_000, arguments = [0, 0, 0, 980] }
dictionary_put = { cost = 9_500, arguments = [0, 1_800, 0, 520] }
generic_hash = { cost = 200, arguments = [0, 0, 0, 0, 0] }

[system_costs]
wasmless_transfer_cost = 100_000_000
Expand Down
1 change: 1 addition & 0 deletions resources/production/chainspec.toml
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ update_associated_key = { cost = 4_200, arguments = [0, 0, 0] }
write = { cost = 14_000, arguments = [0, 0, 0, 980] }
dictionary_put = { cost = 9_500, arguments = [0, 1_800, 0, 520] }
enable_contract_version = { cost = 200, arguments = [0, 0, 0, 0] }
generic_hash = { cost = 200, arguments = [0, 0, 0, 0, 0] }

[system_costs]
wasmless_transfer_cost = 100_000_000
Expand Down
1 change: 1 addition & 0 deletions resources/test/valid/0_9_0/chainspec.toml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ update_associated_key = { cost = 139, arguments = [0, 1, 2] }
write = { cost = 140, arguments = [0, 1, 0, 2] }
dictionary_put = { cost = 141, arguments = [0, 1, 2, 3] }
enable_contract_version = { cost = 142, arguments = [0, 1, 2, 3] }
generic_hash = { cost = 152, arguments = [0, 1, 2, 3, 4] }

[system_costs]
wasmless_transfer_cost = 100_000_000
Expand Down
1 change: 1 addition & 0 deletions resources/test/valid/0_9_0_unordered/chainspec.toml
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ update_associated_key = { cost = 139, arguments = [0, 1, 2] }
write = { cost = 140, arguments = [0, 1, 0, 2] }
dictionary_put = { cost = 141, arguments = [0, 1, 2, 3] }
enable_contract_version = { cost = 142, arguments = [0, 1, 2, 3] }
generic_hash = { cost = 152, arguments = [0, 1, 2, 3, 4] }

[system_costs]
wasmless_transfer_cost = 100_000_000
Expand Down
1 change: 1 addition & 0 deletions resources/test/valid/1_0_0/chainspec.toml
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ update_associated_key = { cost = 139, arguments = [0, 1, 2] }
write = { cost = 140, arguments = [0, 1, 0, 2] }
dictionary_put = { cost = 141, arguments = [0, 1, 2, 3] }
enable_contract_version = { cost = 142, arguments = [0, 1, 2, 3] }
generic_hash = { cost = 152, arguments = [0, 1, 2, 3, 4] }

[system_costs]
wasmless_transfer_cost = 100_000_000
Expand Down
1 change: 1 addition & 0 deletions smart_contracts/contract/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ All notable changes to this project will be documented in this file. The format

### Added
* Add `storage::enable_contract_version` for enabling a specific version of a contract.
* Add `crypto::generic_hash` with blake2b and blake3 support.



Expand Down
22 changes: 22 additions & 0 deletions smart_contracts/contract/src/contract_api/crypto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Functions with cryptographic utils.

use casper_types::{api_error, HashAlgoType, BLAKE2B_DIGEST_LENGTH};

use crate::{ext_ffi, unwrap_or_revert::UnwrapOrRevert};

/// Computes digest hash, using provided algorithm type.
pub fn generic_hash<T: AsRef<[u8]>>(input: T, algo: HashAlgoType) -> [u8; 32] {
let mut ret = [0; 32];

let result = unsafe {
ext_ffi::casper_generic_hash(
input.as_ref().as_ptr(),
input.as_ref().len(),
algo as u8,
ret.as_mut_ptr(),
BLAKE2B_DIGEST_LENGTH,
)
};
api_error::result_from(result).unwrap_or_revert();
ret
}
1 change: 1 addition & 0 deletions smart_contracts/contract/src/contract_api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Contains support for writing smart contracts.

pub mod account;
pub mod crypto;
pub mod runtime;
pub mod storage;
pub mod system;
Expand Down
16 changes: 16 additions & 0 deletions smart_contracts/contract/src/ext_ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -805,4 +805,20 @@ extern "C" {
contract_hash_ptr: *const u8,
contract_hash_size: usize,
) -> i32;
/// Computes digest hash, using provided algorithm type.
///
/// # Arguments
///
/// * `in_ptr` - pointer to the location where argument bytes will be copied from the host side
/// * `in_size` - size of output pointer
/// * `hash_algo_type` - integer representation of HashAlgoType enum variant
/// * `out_ptr` - pointer to the location where argument bytes will be copied to the host side
/// * `out_size` - size of output pointer
pub fn casper_generic_hash(
in_ptr: *const u8,
in_size: usize,
hash_algo_type: u8,
out_ptr: *const u8,
out_size: usize,
) -> i32;
}
Loading
Loading