import type { keccak256 as Keccak256 } from "ethereum-cryptography/keccak"; import type { sha256 as Sha256 } from "ethereum-cryptography/sha256"; // We don't load ethereum-cryptography on startup because it's slow to // initialize and this module is transitively imported from many places. let keccak256Impl: typeof Keccak256 | undefined; let sha256Impl: typeof Sha256 | undefined; /** * Computes the Keccak-256 hash of the input bytes. * * @param bytes The input bytes to hash. * @returns The Keccak-256 hash of the input bytes. */ export async function keccak256(bytes: Uint8Array): Promise { if (keccak256Impl === undefined) { ({ keccak256: keccak256Impl } = await import( "ethereum-cryptography/keccak" )); } return keccak256Impl(bytes); } /** * Computes the SHA-256 hash of the input bytes. * * @param bytes The input bytes to hash. * @returns The SHA-256 hash of the input bytes. */ export async function sha256(bytes: Uint8Array): Promise { if (sha256Impl === undefined) { ({ sha256: sha256Impl } = await import("ethereum-cryptography/sha256")); } return sha256Impl(bytes); } /** * Creates a non-cryptographic hash-based identifier for the given input. * * This function is primarily intended for generating unique identifiers from * a given input string. * It uses the SHA-1 hash algorithm, which is not cryptographically secure, but * is sufficient for this use case as long as the input is not generated by an * attacker. * * Note: The exact algorithm used (SHA-1) is not crucial for the function's * purpose of generating unique identifiers, and could be replaced if needed. * * @param data The input string to be hashed. * @returns The SHA-1 hash of the input string, represented as a * hexadecimal string. */ export async function createNonCryptographicHashId( data: string, ): Promise { const message = new TextEncoder().encode(data); const buffer = await crypto.subtle.digest("SHA-1", message); return Buffer.from(buffer).toString("hex"); }