/** * ProofLeafNode represents a leaf node in a proof. * Used internally during proof construction before conversion to ICS23 format. * * Based on Go IAVL v1.3.5 proof.go ProofLeafNode */ import { sha256, } from "@noble/hashes/sha2.js"; import { encodeBytes, encodeVarint, } from "../utils/encoding.js"; export class ProofLeafNode { /** * The key of the leaf node */ readonly key: Uint8Array; /** * The hash of the value (SHA256(value)) * Note: This is the value hash, not the raw value */ readonly valueHash: Uint8Array; /** * Version when this leaf was created */ readonly version: bigint; constructor(key: Uint8Array, valueHash: Uint8Array, version: bigint) { this.key = key; this.valueHash = valueHash; this.version = version; } /** * Compute the hash of this leaf node. * * The hash is computed as: * SHA256(varint(0) || varint(1) || varint(version) || * varint_bytes(key) || varint_bytes(valueHash)) * * Where: * - varint(0) represents the height (leaves have height 0) * - varint(1) represents the size (leaves have size 1) * - varint(version) is the version when the leaf was created * - varint_bytes(key) is the length-prefixed key * - varint_bytes(valueHash) is the length-prefixed value hash * * @returns The computed hash */ hash(): Uint8Array { // Build the data to hash const data: Uint8Array[] = []; // Encode height (0 for leaf nodes) data.push(encodeVarint(0n)); // Encode size (1 for leaf nodes) data.push(encodeVarint(1n)); // Encode version data.push(encodeVarint(this.version)); // Encode key with length prefix data.push(encodeBytes(this.key)); // Encode valueHash with length prefix data.push(encodeBytes(this.valueHash)); // Concatenate all data const totalLength = data.reduce((sum, arr) => sum + arr.length, 0); const combined = new Uint8Array(totalLength); let offset = 0; for (const arr of data) { combined.set(arr, offset); offset += arr.length; } // Return SHA256 hash return sha256(combined); } /** * String representation for debugging */ toString(): string { return `ProofLeafNode{ Key: ${this.toHex(this.key)} ValueHash: ${this.toHex(this.valueHash)} Version: ${this.version} }`; } private toHex(bytes: Uint8Array): string { return Array.from(bytes) .map(b => b.toString(16).padStart(2, "0")) .join("") .toUpperCase(); } }