/** * Test utilities for IAVL tree testing * Based on Go IAVL v1.3.5 testutils_test.go */ import type { ImmutableTree, } from "./immutable-tree.js"; import type { MutableTree, } from "./mutable-tree.js"; /** * Generate random bytes of specified length * @param length - Number of bytes to generate * @returns Random byte array */ export function randBytes(length: number): Uint8Array { const bytes = new Uint8Array(length); crypto.getRandomValues(bytes); return bytes; } /** * Generate random string of specified length * @param length - Length of string * @returns Random alphanumeric string */ export function randStr(length: number): string { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const bytes = randBytes(length); return Array.from(bytes) .map(b => chars[b % chars.length]) .join(""); } /** * Convert integer to bytes (varint encoding) * @param i - Integer to encode * @returns Byte array */ export function i2b(i: number): Uint8Array { // Simple varint encoding for testing const arr: number[] = []; let n = i; while (n > 127) { arr.push((n & 0x7F) | 0x80); n >>>= 7; } arr.push(n & 0x7F); return new Uint8Array(arr); } /** * Convert bytes to integer (varint decoding) * @param bz - Byte array to decode * @returns Decoded integer */ export function b2i(bz: Uint8Array): number { let result = 0; let shift = 0; for (let i = 0; i < bz.length; i++) { const byte = bz[i]; result |= (byte & 0x7F) << shift; if ((byte & 0x80) === 0) { return result; } shift += 7; } return result; } /** * Randomize a tree and mirror map with sets, updates, and deletions * * Based on Go IAVL testutils_test.go randomizeTreeAndMirror (lines 175-246) * * @param tree - MutableTree to randomize * @param mirror - Map to keep in sync with tree operations * @param keyValLength - Length of keys/values (default: 5) * @returns The mirror map */ export async function randomizeTreeAndMirror( tree: MutableTree, mirror: Map = new Map(), keyValLength = 5, ): Promise> { let numberOfSets = 1000; let numberOfUpdates = Math.floor(numberOfSets / 4); let numberOfRemovals = Math.floor(numberOfSets / 4); // Initial bulk insert phase - sets only while (numberOfSets > numberOfRemovals * 3) { const key = randBytes(keyValLength); const value = randBytes(keyValLength); const isUpdated = await tree.set(key, value); if (isUpdated) { throw new Error("Should not update during initial insert phase"); } mirror.set(Buffer.from(key).toString("hex"), Buffer.from(value).toString("hex")); numberOfSets--; } // Mixed operations phase while (numberOfSets + numberOfRemovals + numberOfUpdates > 0) { const randOp = Math.floor(Math.random() * 3); switch (randOp) { case 0: // Set if (numberOfSets === 0) { continue; } numberOfSets--; { const key = randBytes(keyValLength); const value = randBytes(keyValLength); const isUpdated = await tree.set(key, value); if (isUpdated) { throw new Error("Should not update during set phase"); } mirror.set(Buffer.from(key).toString("hex"), Buffer.from(value).toString("hex")); } break; case 1: // Update if (numberOfUpdates === 0 || mirror.size === 0) { continue; } numberOfUpdates--; { const keyHex = getRandomKeyFrom(mirror); const value = randBytes(keyValLength); const isUpdated = await tree.set(Buffer.from(keyHex, "hex"), value); if (!isUpdated) { throw new Error("Should update existing key"); } mirror.set(keyHex, Buffer.from(value).toString("hex")); } break; case 2: // Remove if (numberOfRemovals === 0 || mirror.size === 0) { continue; } numberOfRemovals--; { const keyHex = getRandomKeyFrom(mirror); const result = await tree.remove(Buffer.from(keyHex, "hex")); if (!result.removed) { throw new Error("Should remove existing key"); } if (!result.value) { throw new Error("Removed value should not be null"); } mirror.delete(keyHex); } break; default: throw new Error(`Invalid randOp: ${randOp}`); } } return mirror; } /** * Get a random key from a map * @param map - Map to get key from * @returns Random key */ function getRandomKeyFrom(map: Map): string { const keys = Array.from(map.keys()); if (keys.length === 0) { throw new Error("No keys in map"); } const idx = Math.floor(Math.random() * keys.length); return keys[idx]; } /** * Assert that tree iteration matches the mirror map * * Based on Go IAVL testutils_test.go assertMutableMirrorIterate (lines 119-137) * * @param tree - Tree to iterate * @param mirror - Expected key-value map */ export async function assertMutableMirrorIterate( tree: MutableTree, mirror: Map, ): Promise { const sortedMirrorKeys = Array.from(mirror.keys()).sort(); const collected: string[] = []; await tree.iterate((key, value) => { collected.push(Buffer.from(key).toString("hex")); const keyHex = Buffer.from(key).toString("hex"); const expectedValue = mirror.get(keyHex); if (expectedValue === undefined) { throw new Error(`Unexpected key in tree: ${keyHex}`); } const actualValue = Buffer.from(value).toString("hex"); if (actualValue !== expectedValue) { throw new Error(`Value mismatch for key ${keyHex}: expected ${expectedValue}, got ${actualValue}`); } return false; }); if (collected.length !== sortedMirrorKeys.length) { throw new Error(`Key count mismatch: expected ${sortedMirrorKeys.length}, got ${collected.length}`); } for (let i = 0; i < sortedMirrorKeys.length; i++) { if (collected[i] !== sortedMirrorKeys[i]) { throw new Error(`Key order mismatch at index ${i}: expected ${sortedMirrorKeys[i]}, got ${collected[i]}`); } } } /** * Assert that immutable tree iteration matches the mirror map * * Based on Go IAVL testutils_test.go assertImmutableMirrorIterate (lines 139-153) * * @param tree - Tree to iterate * @param mirror - Expected key-value map */ export async function assertImmutableMirrorIterate( tree: ImmutableTree, mirror: Map, ): Promise { const sortedMirrorKeys = Array.from(mirror.keys()).sort(); const collected: string[] = []; await tree.iterate((key, value) => { collected.push(Buffer.from(key).toString("hex")); const keyHex = Buffer.from(key).toString("hex"); const expectedValue = mirror.get(keyHex); if (expectedValue === undefined) { throw new Error(`Unexpected key in tree: ${keyHex}`); } const actualValue = Buffer.from(value).toString("hex"); if (actualValue !== expectedValue) { throw new Error(`Value mismatch for key ${keyHex}: expected ${expectedValue}, got ${actualValue}`); } return false; }); if (collected.length !== sortedMirrorKeys.length) { throw new Error(`Key count mismatch: expected ${sortedMirrorKeys.length}, got ${collected.length}`); } for (let i = 0; i < sortedMirrorKeys.length; i++) { if (collected[i] !== sortedMirrorKeys[i]) { throw new Error(`Key order mismatch at index ${i}: expected ${sortedMirrorKeys[i]}, got ${collected[i]}`); } } } /** * Create a randomized tree and mirror for testing * * Based on Go IAVL testutils_test.go getRandomizedTreeAndMirror (lines 164-173) * * @param tree - MutableTree to randomize * @param keyValLength - Length of keys/values (default: 5) * @returns Mirror map with tree contents */ export async function getRandomizedTreeAndMirror( tree: MutableTree, keyValLength = 5, ): Promise> { const mirror = new Map(); await randomizeTreeAndMirror(tree, mirror, keyValLength); return mirror; }