/** * Hashing utilities for IAVL tree. * Uses SHA-256 for computing node hashes, compatible with Go's crypto/sha256. */ import { sha256, } from "@noble/hashes/sha2.js"; /** * Computes SHA-256 hash of the input bytes. * * @param data - Data to hash * @returns 32-byte hash */ export function hash(data: Uint8Array): Uint8Array { return sha256(data); } /** * Computes SHA-256 hash of multiple byte arrays concatenated together. * This is more efficient than manually concatenating first. * * @param arrays - Arrays to hash * @returns 32-byte hash */ export function hashConcat(...arrays: Uint8Array[]): Uint8Array { // Calculate total length const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); // Concatenate and hash const combined = new Uint8Array(totalLength); let offset = 0; for (const arr of arrays) { combined.set(arr, offset); offset += arr.length; } return sha256(combined); } /** * Computes SHA-256 hash of a UTF-8 string. * * @param str - String to hash * @returns 32-byte hash */ export function hashString(str: string): Uint8Array { const encoder = new TextEncoder(); return sha256(encoder.encode(str)); } /** * Size of SHA-256 hash in bytes. */ export const HASH_SIZE = 32; /** * Creates an empty hash (all zeros). * Used as placeholder in some contexts. * * @returns 32-byte array of zeros */ export function emptyHash(): Uint8Array { return new Uint8Array(HASH_SIZE); }