/** * ICS23 Proof Operations * Implements hash, length, and apply operations for ICS23 proof verification * Based on Go ics23 v0.10.0 ops.go */ import { ripemd160, } from "@noble/hashes/legacy.js"; import { sha256, sha512, sha512_256, } from "@noble/hashes/sha2.js"; import type { HashOp, InnerOp, InnerSpec, LeafOp, LengthOp, ProofSpec, } from "../generated/cosmos/ics23/v1/proofs.js"; import { encodeUvarint, } from "../utils/encoding.js"; /** * Apply LeafOp to key and value to compute leaf hash * Based on Go ics23 LeafOp.Apply (ops.go lines 58-79) */ export function applyLeaf( op: LeafOp, key: Uint8Array, value: Uint8Array, ): Uint8Array { if (key.length === 0) { throw new Error("leaf op needs key"); } if (value.length === 0) { throw new Error("leaf op needs value"); } // Prepare key and value (prehash + length prefix) const pkey = prepareLeafData(op.prehashKey, op.length, key); const pvalue = prepareLeafData(op.prehashValue, op.length, value); // Concatenate: prefix + pkey + pvalue const data = new Uint8Array( op.prefix.length + pkey.length + pvalue.length, ); data.set(op.prefix, 0); data.set(pkey, op.prefix.length); data.set(pvalue, op.prefix.length + pkey.length); // Hash the result return doHash(op.hash, data); } /** * Apply InnerOp to child hash to compute parent hash * Based on Go ics23 InnerOp.Apply (ops.go lines 82-90) */ export function applyInner( op: InnerOp, child: Uint8Array, ): Uint8Array { if (child.length === 0) { throw new Error("inner op needs child value"); } // Concatenate: prefix + child + suffix const preimage = new Uint8Array( op.prefix.length + child.length + op.suffix.length, ); preimage.set(op.prefix, 0); preimage.set(child, op.prefix.length); preimage.set(op.suffix, op.prefix.length + child.length); // Hash the result return doHash(op.hash, preimage); } /** * Perform hash operation on data * Based on Go ics23 doHash (ops.go lines 154-178) */ export function doHash(hashOp: HashOp, data: Uint8Array): Uint8Array { switch (hashOp) { case 1: // HashOp.SHA256 return sha256(data); case 2: // HashOp.SHA512 return sha512(data); case 4: // HashOp.RIPEMD160 return ripemd160(data); case 5: // HashOp.BITCOIN (ripemd160(sha256(x))) return ripemd160(sha256(data)); case 6: // HashOp.SHA512_256 return sha512_256(data); default: throw new Error(`unsupported hashop: ${hashOp}`); } } /** * Perform hash operation or return data unchanged if NO_HASH * Based on Go ics23 doHashOrNoop (ops.go lines 245-252) */ export function doHashOrNoop( hashOp: HashOp, data: Uint8Array, ): Uint8Array { if (hashOp === 0) { // HashOp.NO_HASH return data; } return doHash(hashOp, data); } /** * Prepare leaf data by applying hash and length operations * Based on Go ics23 prepareLeafData (ops.go lines 190-198) */ export function prepareLeafData( hashOp: HashOp, lengthOp: LengthOp, data: Uint8Array, ): Uint8Array { // First apply hash (or noop) const hdata = doHashOrNoop(hashOp, data); // Then apply length prefix return doLengthOp(lengthOp, hdata); } /** * Apply length operation to prepend length prefix * Based on Go ics23 doLengthOp (ops.go lines 211-243) */ export function doLengthOp( lengthOp: LengthOp, data: Uint8Array, ): Uint8Array { switch (lengthOp) { case 0: // LengthOp.NO_PREFIX return data; case 1: { // LengthOp.VAR_PROTO - uses UNSIGNED varint for lengths (protobuf standard) const lenBytes = encodeUvarint(BigInt(data.length)); const result = new Uint8Array(lenBytes.length + data.length); result.set(lenBytes, 0); result.set(data, lenBytes.length); return result; } case 2: { // LengthOp.VAR_RLP // RLP encoding for byte strings const len = data.length; if (len === 1 && data[0] < 0x80) { // Single byte < 0x80: encode as itself return data; } else if (len <= 55) { // 0-55 bytes: 0x80 + length, then data const result = new Uint8Array(1 + len); result[0] = 0x80 + len; result.set(data, 1); return result; } else { // > 55 bytes: 0xb7 + length of length, then length, then data const lenLen = len <= 0xff ? 1 : len <= 0xffff ? 2 : len <= 0xffffff ? 3 : 4; const result = new Uint8Array(1 + lenLen + len); result[0] = 0xb7 + lenLen; // Encode length in big-endian for (let i = 0; i < lenLen; i++) { result[1 + i] = (len >> (8 * (lenLen - 1 - i))) & 0xff; } result.set(data, 1 + lenLen); return result; } } case 3: { // LengthOp.FIXED32_BIG const result = new Uint8Array(4 + data.length); const view = new DataView(result.buffer); view.setUint32(0, data.length, false); // false = big endian result.set(data, 4); return result; } case 4: { // LengthOp.FIXED32_LITTLE const result = new Uint8Array(4 + data.length); const view = new DataView(result.buffer); view.setUint32(0, data.length, true); // true = little endian result.set(data, 4); return result; } case 5: { // LengthOp.FIXED64_BIG const result = new Uint8Array(8 + data.length); const view = new DataView(result.buffer); view.setBigUint64(0, BigInt(data.length), false); // false = big endian result.set(data, 8); return result; } case 6: { // LengthOp.FIXED64_LITTLE const result = new Uint8Array(8 + data.length); const view = new DataView(result.buffer); view.setBigUint64(0, BigInt(data.length), true); // true = little endian result.set(data, 8); return result; } case 7: // LengthOp.REQUIRE_32_BYTES if (data.length !== 32) { throw new Error(`data was ${data.length} bytes, not 32`); } return data; case 8: // LengthOp.REQUIRE_64_BYTES if (data.length !== 64) { throw new Error(`data was ${data.length} bytes, not 64`); } return data; default: throw new Error(`unsupported lengthop: ${lengthOp}`); } } /** * Check LeafOp against ProofSpec * Based on Go ics23 LeafOp.CheckAgainstSpec (ops.go lines 92-119) */ export function checkLeafOp(op: LeafOp, spec: ProofSpec): void { const lspec = spec.leafSpec; if (!lspec) { throw new Error("spec missing leaf spec"); } if (op.hash !== lspec.hash) { throw new Error(`unexpected HashOp: ${op.hash}`); } if (op.prehashKey !== lspec.prehashKey) { throw new Error(`unexpected PrehashKey: ${op.prehashKey}`); } if (op.prehashValue !== lspec.prehashValue) { throw new Error(`unexpected PrehashValue: ${op.prehashValue}`); } if (op.length !== lspec.length) { throw new Error(`unexpected LengthOp: ${op.length}`); } // Check prefix starts with expected prefix if (!hasPrefix(op.prefix, lspec.prefix)) { throw new Error( `leaf Prefix doesn't start with ${bytesToHex(lspec.prefix)}`, ); } } /** * Check InnerOp against ProofSpec * Based on Go ics23 InnerOp.CheckAgainstSpec (ops.go lines 121-151) */ export function checkInnerOp( op: InnerOp, spec: ProofSpec, _layer: number, ): void { const ispec = spec.innerSpec; if (!ispec) { throw new Error("spec missing inner spec"); } if (op.hash !== ispec.hash) { throw new Error(`unexpected HashOp: ${op.hash}`); } const leafPrefix = spec.leafSpec?.prefix ?? new Uint8Array(0); if (hasPrefix(op.prefix, leafPrefix)) { throw new Error(`inner Prefix starts with ${bytesToHex(leafPrefix)}`); } if (op.prefix.length < ispec.minPrefixLength) { throw new Error(`innerOp prefix too short (${op.prefix.length})`); } const maxLeftChildBytes = (ispec.childOrder.length - 1) * ispec.childSize; if (op.prefix.length > ispec.maxPrefixLength + maxLeftChildBytes) { throw new Error(`innerOp prefix too long (${op.prefix.length})`); } // Suffix must be multiple of child size if (op.suffix.length % ispec.childSize !== 0) { throw new Error("InnerOp suffix malformed"); } } /** * Helper: Check if data starts with prefix */ function hasPrefix(data: Uint8Array, prefix: Uint8Array): boolean { if (prefix.length > data.length) { return false; } for (let i = 0; i < prefix.length; i++) { if (data[i] !== prefix[i]) { return false; } } return true; } /** * Helper: Convert bytes to hex string for error messages */ function bytesToHex(bytes: Uint8Array): string { return Array.from(bytes) .map(b => b.toString(16).padStart(2, "0")) .join(""); } /** * Get position of branch in child order * Based on Go ics23 getPosition (proof.go lines 426-438) */ export function getPosition(order: number[], branch: number): number { if (branch < 0 || branch >= order.length) { throw new Error(`invalid branch: ${branch}`); } for (let i = 0; i < order.length; i++) { if (order[i] === branch) { return i; } } throw new Error(`branch ${branch} not found in order ${order}`); } /** * Get padding sizes for a branch position * Based on Go ics23 getPadding (proof.go lines 359-371) */ export function getPadding( spec: InnerSpec, branch: number, ): { minPrefix: number maxPrefix: number suffix: number } { const idx = getPosition(spec.childOrder, branch); // Count how many children are in the prefix const prefix = idx * spec.childSize; const minPrefix = prefix + spec.minPrefixLength; const maxPrefix = prefix + spec.maxPrefixLength; // Count how many children are in the suffix const suffix = (spec.childOrder.length - 1 - idx) * spec.childSize; return { minPrefix, maxPrefix, suffix, }; } /** * Check if InnerOp has expected padding * Based on Go ics23 hasPadding (proof.go lines 349-357) */ export function hasPadding( op: InnerOp, minPrefix: number, maxPrefix: number, suffix: number, ): boolean { if (op.prefix.length < minPrefix) { return false; } if (op.prefix.length > maxPrefix) { return false; } return op.suffix.length === suffix; }