2022-12-03 05:23:13 +03:00
|
|
|
/**
|
|
|
|
* Cryptographic hashing functions
|
|
|
|
*
|
|
|
|
* @_subsection: api/crypto:Hash Functions [about-crypto-hashing]
|
|
|
|
*/
|
|
|
|
|
2022-09-05 23:14:43 +03:00
|
|
|
import { keccak_256 } from "@noble/hashes/sha3";
|
|
|
|
|
2022-09-09 06:21:08 +03:00
|
|
|
import { getBytes, hexlify } from "../utils/index.js";
|
2022-09-05 23:14:43 +03:00
|
|
|
|
|
|
|
import type { BytesLike } from "../utils/index.js";
|
|
|
|
|
|
|
|
|
|
|
|
let locked = false;
|
|
|
|
|
|
|
|
const _keccak256 = function(data: Uint8Array): Uint8Array {
|
|
|
|
return keccak_256(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
let __keccak256: (data: Uint8Array) => BytesLike = _keccak256;
|
|
|
|
|
2022-11-28 05:53:06 +03:00
|
|
|
/**
|
|
|
|
* Compute the cryptographic KECCAK256 hash of %%data%%.
|
|
|
|
*
|
2022-12-10 02:21:45 +03:00
|
|
|
* The %%data%% **must** be a data representation, to compute the
|
|
|
|
* hash of UTF-8 data use the [[id]] function.
|
|
|
|
*
|
2022-11-28 05:53:06 +03:00
|
|
|
* @returns DataHexstring
|
2022-12-10 02:21:45 +03:00
|
|
|
* @example:
|
|
|
|
* keccak256("0x")
|
|
|
|
* //_result:
|
|
|
|
*
|
|
|
|
* keccak256("0x1337")
|
|
|
|
* //_result:
|
|
|
|
*
|
|
|
|
* keccak256(new Uint8Array([ 0x13, 0x37 ]))
|
|
|
|
* //_result:
|
|
|
|
*
|
2022-11-28 05:53:06 +03:00
|
|
|
*/
|
2022-09-05 23:14:43 +03:00
|
|
|
export function keccak256(_data: BytesLike): string {
|
2022-09-09 06:21:08 +03:00
|
|
|
const data = getBytes(_data, "data");
|
2022-09-05 23:14:43 +03:00
|
|
|
return hexlify(__keccak256(data));
|
|
|
|
}
|
|
|
|
keccak256._ = _keccak256;
|
|
|
|
keccak256.lock = function(): void { locked = true; }
|
|
|
|
keccak256.register = function(func: (data: Uint8Array) => BytesLike) {
|
|
|
|
if (locked) { throw new TypeError("keccak256 is locked"); }
|
|
|
|
__keccak256 = func;
|
|
|
|
}
|
|
|
|
Object.freeze(keccak256);
|