Skip to content
This repository has been archived by the owner on Dec 15, 2023. It is now read-only.

Commit

Permalink
hash: Use BytesOrString
Browse files Browse the repository at this point in the history
  • Loading branch information
kvinwang committed Dec 9, 2023
1 parent 1da255e commit a0a64ee
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
8 changes: 8 additions & 0 deletions npm_package/sidevm-env/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ declare global {
* @type {ScaleCodec}
*/
SCALE: ScaleCodec;

/**
* Hashes a message using the specified algorithm.
* @param {string} algrithm - The name of the hash algorithm to use.
* Supported values are "blake2b128", "blake2b256", "blake2b512", "sha256", "keccak256".
* @param {(Uint8Array|string)} message - The message to hash, either as a Uint8Array or a string.
*/
hash(algrithm: string, message: Uint8Array | string): Uint8Array;
};
}
export {};
12 changes: 6 additions & 6 deletions src/host_functions/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ fn do_hash<T: Digest>(data: impl AsRef<[u8]>) -> Vec<u8> {
}

#[js::host_call]
fn hash(algorithm: js::JsString, message: AsBytes<Vec<u8>>) -> Result<AsBytes<Vec<u8>>> {
fn hash(algorithm: js::JsString, message: js::BytesOrString) -> Result<AsBytes<Vec<u8>>> {
let hash = match algorithm.as_str() {
"sha256" => do_hash::<sha2::Sha256>(message.0),
"keccak256" => do_hash::<sha3::Keccak256>(message.0),
"blake2b128" => do_hash::<Blake2b<U16>>(message.0),
"blake2b256" => do_hash::<Blake2b<U32>>(message.0),
"blake2b512" => do_hash::<Blake2b<U64>>(message.0),
"sha256" => do_hash::<sha2::Sha256>(message),
"keccak256" => do_hash::<sha3::Keccak256>(message),
"blake2b128" => do_hash::<Blake2b<U16>>(message),
"blake2b256" => do_hash::<Blake2b<U32>>(message),
"blake2b512" => do_hash::<Blake2b<U64>>(message),
_ => bail!("Unsupported hash algorithm: {}", algorithm.as_str()),
};
Ok(hash.into())
Expand Down

0 comments on commit a0a64ee

Please sign in to comment.