/** * Key formatting utilities for IAVL storage. * * Provides a fixed-width lexicographically sortable byte key format. * Based on Go IAVL keyformat/key_format.go */ /** * Provides a fixed-width lexicographically sortable byte key format. * * Create a byte key format based on a single byte prefix and fixed width key segments * each of whose length is specified by the corresponding element of layout. * * For example, to store keys that could index some objects by a version number and * their SHA256 hash using the form: 'c' then you * would define the KeyFormat with: * * ```typescript * const keyFormat = new KeyFormat('c'.charCodeAt(0), 8, 32); * ``` * * Then you can create a key with: * ```typescript * function ObjectKey(version: bigint, objectBytes: Uint8Array): Uint8Array { * const hasher = sha256(objectBytes); * return keyFormat.key(version, hasher); * } * ``` * * If the last term of the layout is 0 it is unbounded, and will accept any length. */ export class KeyFormat { private readonly prefix: number; private readonly layout: number[]; private readonly length: number; private readonly unbounded: boolean; /** * Creates a new key format. * @param prefix - Single byte prefix for the key format * @param layout - Array of segment lengths. Last element can be 0 for unbounded. * @throws If any element except the last is 0 */ constructor(prefix: number, ...layout: number[]) { // Validate prefix is a byte if (prefix < 0 || prefix > 255) { throw new Error("Prefix must be a valid byte value (0-255)"); } // For prefix byte let length = 1; for (let i = 0; i < layout.length; i++) { const l = layout[i]; length += l; if (l === 0 && i !== layout.length - 1) { throw new Error("Only the last item in a key format can be 0"); } } this.prefix = prefix; this.layout = layout; this.length = length; this.unbounded = layout.length > 0 && layout[layout.length - 1] === 0; } /** * Format the byte segments into the key format. * @param segments - Byte arrays to format * @returns Formatted key * @throws If segment lengths do not match layout */ keyBytes(...segments: Uint8Array[]): Uint8Array { let keyLen = this.length; // In case segments length is less than layouts length, // we don't have to allocate the whole length, just // enough space to store the segments. if (segments.length < this.layout.length) { keyLen = 1; for (let i = 0; i < segments.length; i++) { keyLen += this.layout[i]; } } if (this.unbounded && segments.length > 0) { keyLen += segments[segments.length - 1].length; } const key = new Uint8Array(keyLen); key[0] = this.prefix; let n = 1; for (let i = 0; i < segments.length; i++) { const s = segments[i]; const l = this.layout[i]; if (l === 0) { // If the expected segment length is unbounded, increase by string length n += s.length; } else { if (s.length > l) { throw new Error( `Length of segment ${i} (${s.length} bytes) is longer than the ` + `${l} bytes required by layout`, ); } // Otherwise increase n by the segment length n += l; } // Big endian so pad on left if not given the full width for this segment key.set(s, n - s.length); } return key.slice(0, n); } /** * Format the args passed into the key format. * @param args - Arguments to format (number, bigint, or Uint8Array) * @returns Formatted key * @throws If arguments don't match layout */ key(...args: (number | bigint | Uint8Array)[]): Uint8Array { if (args.length > this.layout.length) { throw new Error( `keyFormat.key() is provided with ${args.length} args but format only has ${this.layout.length} segments`, ); } const segments: Uint8Array[] = []; for (const arg of args) { segments.push(this.format(arg)); } return this.keyBytes(...segments); } /** * Reads out the bytes associated with each segment of the key format from key. * @param key - Key to scan * @returns Array of byte segments */ scanBytes(key: Uint8Array): Uint8Array[] { const segments: Uint8Array[] = []; let n = 1; for (let i = 0; i < this.layout.length; i++) { const l = this.layout[i]; // if current section is longer than key, then there are no more subsequent segments. if (n + l > key.length && l !== 0) { break; } // if unbounded, segment is rest of key if (l === 0) { segments.push(key.slice(n)); break; } segments.push(key.slice(n, n + l)); n += l; } return segments; } /** * Extracts the segments into values. * @param key - Key to scan * @param types - Array of types to extract ('bigint', 'uint32', 'int32', 'bytes') * @returns Array of extracted values */ scan(key: Uint8Array, types: Array<"bigint" | "uint32" | "int32" | "bytes">): Array { const segments = this.scanBytes(key); const results: Array = []; for (let i = 0; i < Math.min(types.length, segments.length); i++) { const segment = segments[i]; const type = types[i]; switch (type) { case "bigint": { // Convert big-endian bytes to bigint let value = 0n; for (const byte of segment) { value = (value << 8n) | BigInt(byte); } results.push(value); break; } case "uint32": { // Convert 4 bytes big-endian to uint32 if (segment.length !== 4) { throw new Error(`Expected 4 bytes for uint32, got ${segment.length}`); } const value = (segment[0] << 24) | (segment[1] << 16) | (segment[2] << 8) | segment[3]; results.push(value >>> 0); // Ensure unsigned break; } case "int32": { // Convert 4 bytes big-endian to int32 if (segment.length !== 4) { throw new Error(`Expected 4 bytes for int32, got ${segment.length}`); } const value = (segment[0] << 24) | (segment[1] << 16) | (segment[2] << 8) | segment[3]; results.push(value | 0); // Ensure signed break; } case "bytes": { results.push(segment); break; } default: throw new Error(`Unknown type: ${type}`); } } return results; } /** * Get the total length of the key format. */ getLength(): number { return this.length; } /** * Get the prefix as a string. */ getPrefix(): string { return String.fromCharCode(this.prefix); } /** * Format a value into bytes. */ private format(value: number | bigint | Uint8Array): Uint8Array { if (value instanceof Uint8Array) { return value; } if (typeof value === "bigint") { return this.formatBigInt(value); } if (typeof value === "number") { // Treat numbers as uint32 by default return this.formatUint32(value); } throw new Error(`keyFormat format() does not support formatting value of type ${typeof value}`); } /** * Format a bigint as big-endian bytes (8 bytes for compatibility). */ private formatBigInt(value: bigint): Uint8Array { const bytes = new Uint8Array(8); let v = value; // Handle negative values (two's complement) if (v < 0n) { v = (1n << 64n) + v; // Convert to unsigned representation } // Write big-endian for (let i = 7; i >= 0; i--) { bytes[i] = Number(v & 0xFFn); v = v >> 8n; } return bytes; } /** * Format a uint32 as big-endian bytes. */ private formatUint32(value: number): Uint8Array { const bytes = new Uint8Array(4); const v = value >>> 0; // Ensure unsigned bytes[0] = (v >>> 24) & 0xFF; bytes[1] = (v >>> 16) & 0xFF; bytes[2] = (v >>> 8) & 0xFF; bytes[3] = v & 0xFF; return bytes; } } /** * Fast prefix formatter for simple prefix-based keys. * Used for node keys and other simple formats. */ export class FastPrefixFormatter { private readonly prefix: number; private readonly length: number; constructor(prefix: number, length: number) { if (prefix < 0 || prefix > 255) { throw new Error("Prefix must be a valid byte value (0-255)"); } this.prefix = prefix; this.length = length; } /** * Create a key with the prefix and value. */ key(value: Uint8Array): Uint8Array { if (value.length !== this.length && this.length !== 0) { throw new Error(`Expected value of length ${this.length}, got ${value.length}`); } const key = new Uint8Array(1 + value.length); key[0] = this.prefix; key.set(value, 1); return key; } /** * Extract the value from a prefixed key. */ scan(key: Uint8Array): Uint8Array { if (key.length < 1 || key[0] !== this.prefix) { throw new Error("Invalid key format"); } return key.slice(1); } } // Pre-defined key formats matching Go IAVL const INT64_SIZE = 8; const INT32_SIZE = 4; const HASH_SIZE = 32; /** * Key format for node storage: s */ export const nodeKeyFormat = new FastPrefixFormatter("s".charCodeAt(0), INT64_SIZE + INT32_SIZE); /** * Key format for fast nodes: f */ export const fastKeyFormat = new KeyFormat("f".charCodeAt(0), 0); /** * Key format for metadata: m */ export const metadataKeyFormat = new KeyFormat("m".charCodeAt(0), 0); /** * Legacy key format for nodes: n */ export const legacyNodeKeyFormat = new FastPrefixFormatter("n".charCodeAt(0), HASH_SIZE); /** * Legacy key format for orphans: o */ export const legacyOrphanKeyFormat = new KeyFormat("o".charCodeAt(0), INT64_SIZE, INT64_SIZE, HASH_SIZE); /** * Legacy key format for roots: r */ export const legacyRootKeyFormat = new KeyFormat("r".charCodeAt(0), INT64_SIZE); /** * Create a node key from version and nonce. */ export function formatNodeKey(version: bigint, nonce: number): Uint8Array { const key = new Uint8Array(INT64_SIZE + INT32_SIZE); // Write version (8 bytes, big-endian) let v = version; if (v < 0n) { v = (1n << 64n) + v; // Two's complement for negative } for (let i = 7; i >= 0; i--) { key[i] = Number(v & 0xFFn); v = v >> 8n; } // Write nonce (4 bytes, big-endian) const n = nonce >>> 0; // Ensure unsigned key[8] = (n >>> 24) & 0xFF; key[9] = (n >>> 16) & 0xFF; key[10] = (n >>> 8) & 0xFF; key[11] = n & 0xFF; return nodeKeyFormat.key(key); } /** * Extract version and nonce from a node key. */ export function parseNodeKey(key: Uint8Array): { version: bigint nonce: number } { const value = nodeKeyFormat.scan(key); if (value.length !== INT64_SIZE + INT32_SIZE) { throw new Error("Invalid node key format"); } // Read version (8 bytes, big-endian) let version = 0n; for (let i = 0; i < 8; i++) { version = (version << 8n) | BigInt(value[i]); } // Handle signed conversion if needed if (version >= (1n << 63n)) { version = version - (1n << 64n); } // Read nonce (4 bytes, big-endian) const nonce = (value[8] << 24) | (value[9] << 16) | (value[10] << 8) | value[11]; return { version, nonce: nonce | 0, }; // Ensure signed int32 }