/** * A function to perform runtime assertions. * * We avoid using `node:assert` to keep compatibility with a browser environment. * Note the checks should not have any side effects, since we might decide * to remove all of them in a post-processing step. */ declare function check(condition: boolean, message?: string): asserts condition is true { if (!condition) { throw new Error(`Assertion failure: ${message ?? ""}`); } } /** * Yet another function to perform runtime assertions. * This function returns a new type to mark in the code that this value was checked and you don't have to do it again. * * In the post-processing step all usages of this functions should be replaced with simple casting. An example: * const x = checkAndType(y); * should be replaced with: * const x = y as CheckedNumber; */ declare function ensure(a: T, condition: boolean, message?: string): U { if (cast(a, condition)) { return a; } throw new Error(`Assertion failure: ${message ?? ""}`); } /** * The function can be used to make sure that a particular type is `never` * at some point in the code. * * Basically that means that all other options are exhaustively handled * earlier and the assertion should make sure that an unhandled case * is not introduced in the future. */ declare function assertNever(value: never): never { throw new Error(`Unexpected value: ${value}`); } /** * The function can be used to make sure that a particular object type * has no keys at a certain point in the code. * * Basically that means that all other possible keys are exhaustively * handled earlier and the assertion should make sure that no unexpected * keys are introduced in the future. */ declare function assertEmpty>(value: T) { const keys = Object.keys(value); if (keys.length > 0) { throw new Error(`Unexpected keys: ${keys.join(", ")}`); } } /** Debug print an object. */ declare function inspect(val: T): string { const nest = (v: string) => v .split("\n") .map((x) => ` ${x}`) .join("\n") .trim(); if (val === null) { return ""; } if (val === undefined) { return ""; } if (Array.isArray(val)) { return `[${val.map((x) => inspect(x))}]`; } if (val instanceof Map) { return inspect(Array.from(val.entries())); } if (typeof val === "number") { return `${val} (0x${val.toString(16)})`; } if (typeof val !== "object") { return `${val}`; } if ( "toString" in val && Object.prototype.toString !== val.toString && WithDebug.prototype.toString !== val.toString ) { return `${val}`; } const name = val.constructor.name; let v = name !== "Object" ? `${name} {` : "{"; const keys = Object.keys(val); const oneLine = keys.length < 3; for (const k of keys) { if (typeof k === "string") { v += oneLine ? "" : "\n "; v += `${k}: ${nest(inspect(val[k as keyof T]))}`; v += oneLine ? "," : ""; } } v += oneLine ? "}" : "\n}"; return v; } /** Utility function to measure time taken for some operation [ms]. */ declare const measure = typeof process === "undefined" ? (id: string) => { const start = performance.now(); return () => `${id} took ${performance.now() - start}ms`; } : (id: string) => { const start = process.hrtime.bigint(); return () => { const tookNano = process.hrtime.bigint() - start; const tookMilli = Number(tookNano / 1_000_000n).toFixed(2); return `${id} took ${tookMilli}ms`; }; }; /** A class that adds `toString` method that prints all properties of an object. */ declare abstract class WithDebug { toString() { return inspect(this); } } /** * @fileoverview `Opaque` constructs a unique type which is a subset of Type with a * specified unique token Token. It means that base type cannot be assigned to unique type by accident. * Good examples of opaque types include: * - JWTs or other tokens - these are special kinds of string used for authorization purposes. * If your app uses multiple types of tokens each should be a separate opaque type to avoid confusion * - Specific currencies - amount of different currencies shouldn't be mixed * - Bitcoin address - special kind of string * * `type GithubAccessToken = Opaque;` * `type USD = Opaque;` * `type PositiveNumber = Opaque; * * More: https://github.com/ts-essentials/ts-essentials/blob/master/lib/opaque/README.md * * Copyright (c) 2018-2019 Chris Kaczor (github.com/krzkaczor) */ // biome-ignore lint/suspicious/noConfusingVoidType: We want the type to be impossible to instantiate. type Uninstantiable = void & { __brand: "uninstantiable" }; type StringLiteral = Type extends string ? (string extends Type ? never : Type) : never; // TODO [MaSi]: it should be "unique symbol" but in debugger adapter we have opaque types from different packages and it is problematic. declare const __OPAQUE_TYPE__ = "__INTERNAL_OPAQUE_ID__"; type WithOpaque = { readonly [__OPAQUE_TYPE__]: Token; }; type TokenOf = OpaqueType extends Opaque ? Token : never; type Opaque = Token extends StringLiteral ? Type & WithOpaque : Uninstantiable; declare function asOpaqueType(v: T): Opaque { return v as Opaque; } declare function seeThrough(v: Opaque): T { return v as T; } type OkResult = { isOk: true; isError: false; ok: Ok; }; type ErrorResult = { isOk: false; isError: true; error: Error; details: string; }; /** * A generic `OK` response to be used instead of some empty/null value. * * NOTE that generic error is not provided to rather have a more * descriptive value. */ declare const OK = Symbol("ok"); type OK = typeof OK; /** * A standardized tagged union for nested error types. */ type TaggedError = { kind: Kind; error: Nested; }; declare function resultToString(res: Result$2) { if (res.isOk) { return `OK: ${typeof res.ok === "symbol" ? res.ok.toString() : res.ok}`; } return `${res.details}\nError: ${maybeTaggedErrorToString(res.error)}`; } /** An indication of two possible outcomes returned from a function. */ type Result$2 = OkResult | ErrorResult; /** An indication of two possible outcomes returned from a function. */ declare const Result$2 = { /** Create new [`Result`] with `Ok` status. */ ok: (ok: Ok): Result => { check(ok !== undefined, "`Ok` type cannot be undefined."); return { isOk: true, isError: false, ok, }; }, /** Create new [`Result`] with `Error` status. */ error: (error: Error, details = ""): Result => { check(error !== undefined, "`Error` type cannot be undefined."); return { isOk: false, isError: true, error, details, }; }, /** Create new [`Result`] with `Error` coming from a nested error type. */ taggedError: ( enumMapping: EnumMapping, kind: Kind, nested: ErrorResult, ): Result> => { return Result.error(new RichTaggedError(kind, nested.error, enumMapping), nested.details); }, }; /** * Utilities for tests. */ /** * If some object has this property set, it can override how it's being compared * using [`deepEqual`]. * The value under that symbol should be a function to be invoked by `deepEqual`. * Returned values will then be further compared recursively. */ declare const TEST_COMPARE_USING: unique symbol = Symbol("compare using"); /** * TODO [ToDr] This should be `unique symbol`, but for some reason * I can't figure out how to build `@typeberry/blocks` package. */ declare const __REPRESENTATION_BYTES__: "REPRESENTATION_BYTES"; type WithBytesRepresentation = { readonly [__REPRESENTATION_BYTES__]: Bytes; }; type FixedSizeNumber = number & WithBytesRepresentation; /** Unsigned integer that can be represented as one byte. */ type U8 = FixedSizeNumber<1>; /** Unsigned integer that can be represented as two bytes. */ type U16 = FixedSizeNumber<2>; /** Unsigned integer that can be represented as 4 bytes. */ type U32 = FixedSizeNumber<4>; /** Unsigned integer that can be represented as 8 bytes. */ type U64 = bigint & WithBytesRepresentation<8>; /** Attempt to cast an input number into U8. */ declare const tryAsU8 = (v: number): U8 => ensure(v, isU8(v), `input must have one-byte representation, got ${v}`); /** Check if given number is a valid U8 number. */ declare const isU8 = (v: number): v is U8 => (v & MAX_VALUE_U8) === v; /** Attempt to cast an input number into U16. */ declare const tryAsU16 = (v: number): U16 => ensure(v, isU16(v), `input must have two-byte representation, got ${v}`); /** Check if given number is a valid U16 number. */ declare const isU16 = (v: number): v is U16 => (v & MAX_VALUE_U16) === v; /** Attempt to cast an input number into U32. */ declare const tryAsU32 = (v: number): U32 => ensure(v, isU32(v), `input must have four-byte representation, got ${v}`); /** Check if given number is a valid U32 number. */ declare const isU32 = (v: number): v is U32 => (v & MAX_VALUE_U32) >>> 0 === v; /** Attempt to cast an input number into U64. */ declare const tryAsU64 = (x: number | bigint): U64 => { const v = BigInt(x); return ensure(v, isU64(v), `input must have eight-byte representation, got ${x}`); }; /** Check if given number is a valid U64 number. */ declare const isU64 = (v: bigint): v is U64 => (v & MAX_VALUE_U64) === v; /** Collate two U32 parts into one U64. */ declare const u64FromParts = ({ lower, upper }: { lower: U32; upper: U32 }): U64 => { const val = (BigInt(upper) << 32n) + BigInt(lower); return asWithBytesRepresentation(val); }; /** Split U64 into lower & upper parts. */ declare const u64IntoParts = (v: U64): { lower: U32; upper: U32 } => { const lower = v & (2n ** 32n - 1n); const upper = v >> 32n; return { lower: asWithBytesRepresentation(Number(lower)), upper: asWithBytesRepresentation(Number(upper)), }; }; /** A result of modulo arithmetic. */ type Result$1 = { /** Was there an overflow/underflow? */ overflow: boolean; /** What's the value after the operation. */ value: T; }; /** * Sum all provided U64 values using modulo arithmetic. * NOTE that the overflow may happen multiple times here! */ declare function sumU64(...values: U64[]) { let sum = 0n; for (const v of values) { sum = sum + v; } const overflow = !isU64(sum); sum = sum & 0xffff_ffff_ffff_ffffn; return { overflow, value: tryAsU64(sum) }; } /** * Sum all provided U32 values using modulo arithmetic. * NOTE that the overflow may happen multiple times here! */ declare function sumU32(...values: U32[]) { let sum = 0; let overflow = false; for (const v of values) { const prev = sum; sum = (sum + v) >>> 0; overflow ||= prev > sum; } return { overflow, value: tryAsU32(sum) }; } /** * Transform provided U32 number to little-endian representation. */ declare function u32AsLeBytes(value: U32): Uint8Array { return new Uint8Array([value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff]); } /** * Interpret 4-byte `Uint8Array` as U32 written as little endian. */ declare function leBytesAsU32(uint8Array: Uint8Array): U32 { check(uint8Array.length === 4, "Input must be a Uint8Array of length 4"); return asWithBytesRepresentation( uint8Array[0] | (uint8Array[1] << 8) | (uint8Array[2] << 16) | (uint8Array[3] << 24), ); } /** Get the smallest value between U64 a and values given as input parameters. */ declare const minU64 = (a: U64, ...values: U64[]): U64 => values.reduce((min, value) => (value > min ? min : value), a); /** Get the biggest value between U64 a and values given as input parameters. */ declare const maxU64 = (a: U64, ...values: U64[]): U64 => values.reduce((max, value) => (value < max ? max : value), a); type index$6_FixedSizeNumber = FixedSizeNumber; type index$6_U16 = U16; type index$6_U32 = U32; type index$6_U64 = U64; type index$6_U8 = U8; declare const index$6_isU16: typeof isU16; declare const index$6_isU32: typeof isU32; declare const index$6_isU64: typeof isU64; declare const index$6_isU8: typeof isU8; declare const index$6_leBytesAsU32: typeof leBytesAsU32; declare const index$6_maxU64: typeof maxU64; declare const index$6_minU64: typeof minU64; declare const index$6_sumU32: typeof sumU32; declare const index$6_sumU64: typeof sumU64; declare const index$6_tryAsU16: typeof tryAsU16; declare const index$6_tryAsU32: typeof tryAsU32; declare const index$6_tryAsU64: typeof tryAsU64; declare const index$6_tryAsU8: typeof tryAsU8; declare const index$6_u32AsLeBytes: typeof u32AsLeBytes; declare const index$6_u64FromParts: typeof u64FromParts; declare const index$6_u64IntoParts: typeof u64IntoParts; declare namespace index$6 { export { type index$6_FixedSizeNumber as FixedSizeNumber, type Result$1 as Result, type index$6_U16 as U16, type index$6_U32 as U32, type index$6_U64 as U64, type index$6_U8 as U8, index$6_isU16 as isU16, index$6_isU32 as isU32, index$6_isU64 as isU64, index$6_isU8 as isU8, index$6_leBytesAsU32 as leBytesAsU32, index$6_maxU64 as maxU64, index$6_minU64 as minU64, index$6_sumU32 as sumU32, index$6_sumU64 as sumU64, index$6_tryAsU16 as tryAsU16, index$6_tryAsU32 as tryAsU32, index$6_tryAsU64 as tryAsU64, index$6_tryAsU8 as tryAsU8, index$6_u32AsLeBytes as u32AsLeBytes, index$6_u64FromParts as u64FromParts, index$6_u64IntoParts as u64IntoParts }; } /** A return value of some comparator. */ declare enum OrderingValue { /** `self < other` */ Less = -1, /** `self === other` */ Equal = 0, /** `self > other` */ Greater = 1, } /** A class that provides utility methods to check the type of ordering. */ declare class Ordering { private constructor(public readonly value: OrderingValue) {} static Less = new Ordering(OrderingValue.Less); static Greater = new Ordering(OrderingValue.Greater); static Equal = new Ordering(OrderingValue.Equal); isLess() { return this.value === OrderingValue.Less; } isGreater() { return this.value === OrderingValue.Greater; } isEqual() { return this.value === OrderingValue.Equal; } isNotEqual() { return !this.isEqual(); } isGreaterOrEqual() { return this.isEqual() || this.isGreater(); } isLessOrEqual() { return this.isEqual() || this.isLess(); } } /** * A type that compares the `self` value to `other` and returns an ordering in respect to `self`. * * e.g. `self < other => Ordering.Less`, `self > other => Ordering.Greater` */ type Comparator = (self: V, other: V) => Ordering; // TODO: [MaSo] Update BytesBlob and Bytes, so they return Result (not throw error) /** * A variable-length blob of bytes with a concise text representation. * * The structure is used as convenience wrapper for [`Uint8Array`], * especially if the data is coming from a hex-encoded string. */ declare class BytesBlob { [TEST_COMPARE_USING]() { return this.toString(); } readonly raw: Uint8Array; readonly length: number = 0; protected constructor(data: Uint8Array) { this.raw = data; this.length = data.byteLength; } /** * Display a hex-encoded version of this byte blob. */ toString() { return bytesToHexString(this.raw); } toJSON() { return this.toString(); } /** Decode contained bytes as string. */ asText() { const decoder = new TextDecoder(); return decoder.decode(this.raw); } /** Compare the sequence to another one. */ isEqualTo(other: BytesBlob): boolean { if (this.length !== other.length) { return false; } return u8ArraySameLengthEqual(this.raw, other.raw); } /** Compare the sequence to another one lexicographically. * Returns `Ordering.Less` if "this" blob is less than (or shorter than) "other", `Ordering.Equal` if blobs are identical and `Ordering.Greater` otherwise. * https://graypaper.fluffylabs.dev/#/5f542d7/07c40007c400 */ public compare(other: BytesBlob) { const min = Math.min(this.length, other.length); const thisRaw = this.raw; const otherRaw = other.raw; for (let i = 0; i < min; i++) { if (thisRaw[i] < otherRaw[i]) { return Ordering.Less; } if (thisRaw[i] > otherRaw[i]) { return Ordering.Greater; } } if (this.length < other.length) { return Ordering.Less; } if (this.length > other.length) { return Ordering.Greater; } return Ordering.Equal; } /** Create a new [`BytesBlob`] with no data. */ static empty(): BytesBlob { return new BytesBlob(new Uint8Array()); } /** Create a new [`BytesBlob'] by converting given UTF-u encoded string into bytes. */ static blobFromString(v: string): BytesBlob { const encoder = new TextEncoder(); return BytesBlob.blobFrom(encoder.encode(v)); } /** Create a new [`BytesBlob`] from existing [`Uint8Array`]. */ static blobFrom(v: Uint8Array): BytesBlob { return new BytesBlob(v); } /** Create a new [`BytesBlob`] by concatenating data from multiple `Uint8Array`s. */ static blobFromParts(v: Uint8Array | Uint8Array[], ...rest: Uint8Array[]) { const vArr = v instanceof Uint8Array ? [v] : v; const totalLength = vArr.reduce((a, v) => a + v.length, 0) + rest.reduce((a, v) => a + v.length, 0); const buffer = new Uint8Array(totalLength); let offset = 0; for (const r of vArr) { buffer.set(r, offset); offset += r.length; } for (const r of rest) { buffer.set(r, offset); offset += r.length; } return new BytesBlob(buffer); } /** Create a new [`BytesBlob`] from an array of bytes. */ static blobFromNumbers(v: number[]): BytesBlob { check(v.find((x) => (x & 0xff) !== x) === undefined, "BytesBlob.blobFromNumbers used with non-byte number array."); const arr = new Uint8Array(v); return new BytesBlob(arr); } /** Parse a hex-encoded bytes blob without `0x` prefix. */ static parseBlobNoPrefix(v: string): BytesBlob { const len = v.length; if (len % 2 === 1) { throw new Error(`Odd number of nibbles. Invalid hex string: ${v}.`); } const buffer = new ArrayBuffer(len / 2); const bytes = new Uint8Array(buffer); for (let i = 0; i < len - 1; i += 2) { const c = v.substring(i, i + 2); bytes[i / 2] = byteFromString(c); } return new BytesBlob(bytes); } /** Parse a hex-encoded bytes blob with `0x` prefix. */ static parseBlob(v: string): BytesBlob { if (!v.startsWith("0x")) { throw new Error(`Missing 0x prefix: ${v}.`); } return BytesBlob.parseBlobNoPrefix(v.substring(2)); } /** * Split `BytesBlob` into chunks of given size. * * Last chunk might be smaller than `size`. */ *chunks(size: number): Generator { for (let i = 0; i < this.length; i += size) { yield BytesBlob.blobFrom(this.raw.subarray(i, i + size)); } } } /** * A convenience wrapper for a fix-length sequence of bytes. */ declare class Bytes extends BytesBlob { /** Length of the bytes array. */ readonly length: T; private constructor(raw: Uint8Array, len: T) { super(raw); check(raw.byteLength === len, `Given buffer has incorrect size ${raw.byteLength} vs expected ${len}`); this.length = len; } /** Create new [`Bytes`] given a backing buffer and it's length. */ static fromBlob(v: Uint8Array, len: X): Bytes { return new Bytes(v, len); } /** Create new [`Bytes`] given an array of bytes and it's length. */ static fromNumbers(v: number[], len: X): Bytes { check(v.find((x) => (x & 0xff) !== x) === undefined, "Bytes.fromNumbers used with non-byte number array."); const x = new Uint8Array(v); return new Bytes(x, len); } /** Create an empty [`Bytes`] of given length. */ static zero(len: X): Bytes { return new Bytes(new Uint8Array(len), len); } // TODO [ToDr] `fill` should have the argments swapped to align with the rest. /** Create a [`Bytes`] with all bytes filled with given input number. */ static fill(len: X, input: number): Bytes { check((input & 0xff) === input, "Input has to be a byte."); const bytes = Bytes.zero(len); bytes.raw.fill(input, 0, len); return bytes; } /** Parse a hex-encoded fixed-length bytes without `0x` prefix. */ static parseBytesNoPrefix(v: string, len: X): Bytes { if (v.length > 2 * len) { throw new Error(`Input string too long. Expected ${len}, got ${v.length / 2}`); } const blob = BytesBlob.parseBlobNoPrefix(v); return new Bytes(blob.raw, len); } /** Parse a hex-encoded fixed-length bytes with `0x` prefix. */ static parseBytes(v: string, len: X): Bytes { if (v.length > 2 * len + 2) { throw new Error(`Input string too long. Expected ${len}, got ${v.length / 2 - 1}`); } const blob = BytesBlob.parseBlob(v); return new Bytes(blob.raw, len); } /** Compare the sequence to another one. */ isEqualTo(other: Bytes): boolean { check(this.length === other.length, "Comparing incorrectly typed bytes!"); return u8ArraySameLengthEqual(this.raw, other.raw); } /** Converts current type into some opaque extension. */ asOpaque(): Opaque, TokenOf>> { return asOpaqueType, TokenOf>>(this); } } declare const bytesBlobComparator: Comparator = (a: T, b: T) => a.compare(b); /** * A sequence of bits with a packed in-memory representation. */ declare class BitVec { /** * Wrap an existing bytes and treat them as [`BitVec`] */ static fromBlob(data: Uint8Array, bitLength: number) { return new BitVec(data, bitLength); } static fromBytes(data: Bytes, bitLength: number) { return new BitVec(data.raw, bitLength); } /** * Create new [`BitVec`] with all values set to `false`. */ static empty(bitLength: number) { const data = new Uint8Array(Math.ceil(bitLength / 8)); return new BitVec(data, bitLength); } public readonly byteLength; private constructor( private readonly data: Uint8Array, public readonly bitLength: number, ) { check( data.length * 8 >= bitLength, `Not enough bytes in the data array. Need ${data.length * 8} has ${bitLength}.`, ); this.byteLength = Math.ceil(bitLength / 8); } /** Return a raw in-memory representation of this [`BitVec`]. */ get raw(): Uint8Array { return this.data.subarray(0, this.byteLength); } /** Perform OR operation on all bits in place. */ sumWith(other: BitVec) { check( other.bitLength === this.bitLength, `Invalid bit length for sumWith: ${other.bitLength} vs ${this.bitLength}`, ); const otherRaw = other.raw; for (let i = 0; i < this.byteLength; i++) { this.data[i] |= otherRaw[i]; } } /** * Set the bit at index `idx` to value `val`. */ setBit(idx: number, val: boolean) { check(idx < this.bitLength, `Index out of bounds. Need ${idx} has ${this.bitLength}.`); const byteIndex = Math.floor(idx / 8); const bitIndexInByte = idx % 8; const mask = 1 << bitIndexInByte; if (val) { this.data[byteIndex] |= mask; } else { this.data[byteIndex] &= ~mask; } } /** * Return `true` if the bit at index `idx` is set. */ isSet(idx: number): boolean { check(idx < this.bitLength, `Index out of bounds. Need ${idx} has ${this.bitLength}.`); const byteIndex = Math.floor(idx / 8); const bitIndexInByte = idx % 8; const mask = 1 << bitIndexInByte; return (this.data[byteIndex] & mask) > 0; } /** * Iterate over indices of bits that are set. */ *indicesOfSetBits() { for (let b = 0; b < this.bitLength; b++) { const byteIndex = b >> 3; const bitIndex = b - (byteIndex << 3); const byte = this.data[byteIndex]; const bitValue = byte >> bitIndex; if ((bitValue & 0b1) === 0b1) { yield b; } } } } type index$5_BitVec = BitVec; declare const index$5_BitVec: typeof BitVec; type index$5_Bytes = Bytes; declare const index$5_Bytes: typeof Bytes; type index$5_BytesBlob = BytesBlob; declare const index$5_BytesBlob: typeof BytesBlob; declare const index$5_bytesBlobComparator: typeof bytesBlobComparator; declare namespace index$5 { export { index$5_BitVec as BitVec, index$5_Bytes as Bytes, index$5_BytesBlob as BytesBlob, index$5_bytesBlobComparator as bytesBlobComparator }; } /** * Mask class is an implementation of skip function defined in GP. * * https://graypaper.fluffylabs.dev/#/5f542d7/237201239801 */ declare class Mask { /** * The lookup table will have `0` at the index which corresponds to an instruction on the same index in the bytecode. * In case the value is non-zero it signifies the offset to the index with next instruction. * * Example: * ``` * 0..1..2..3..4..5..6..7..8..9 # Indices * 0..2..1..0..1..0..3..2..1..0 # lookupTable forward values * ``` * There are instructions at indices `0, 3, 5, 9`. */ private lookupTableForward: Uint8Array; constructor(mask: BitVec) { this.lookupTableForward = this.buildLookupTableForward(mask); } isInstruction(index: number) { return this.lookupTableForward[index] === 0; } getNoOfBytesToNextInstruction(index: number) { check(index >= 0, `index (${index}) cannot be a negative number`); return Math.min(this.lookupTableForward[index] ?? 0, MAX_INSTRUCTION_DISTANCE); } private buildLookupTableForward(mask: BitVec) { const table = new Uint8Array(mask.bitLength); let lastInstructionOffset = 0; for (let i = mask.bitLength - 1; i >= 0; i--) { if (mask.isSet(i)) { lastInstructionOffset = 0; } else { lastInstructionOffset++; } table[i] = lastInstructionOffset; } return table; } static empty() { return new Mask(BitVec.empty(0)); } } declare enum ArgumentType { NO_ARGUMENTS = 0, ONE_IMMEDIATE = 1, TWO_IMMEDIATES = 2, ONE_OFFSET = 3, ONE_REGISTER_ONE_IMMEDIATE = 4, ONE_REGISTER_TWO_IMMEDIATES = 5, ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET = 6, TWO_REGISTERS = 7, TWO_REGISTERS_ONE_IMMEDIATE = 8, TWO_REGISTERS_ONE_OFFSET = 9, TWO_REGISTERS_TWO_IMMEDIATES = 10, THREE_REGISTERS = 11, ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE = 12, } declare class ExtendedWitdthImmediateDecoder { private unsignedImmediate: BigUint64Array; private bytes: Uint8Array; constructor() { const buffer = new ArrayBuffer(IMMEDIATE_SIZE); this.unsignedImmediate = new BigUint64Array(buffer); this.bytes = new Uint8Array(buffer); } setBytes(bytes: Uint8Array) { let i = 0; for (; i < bytes.length; i++) { this.bytes[i] = bytes[i]; } for (; i < IMMEDIATE_SIZE; i++) { this.bytes[i] = 0; } } getValue() { return this.unsignedImmediate[0]; } getBytesAsLittleEndian() { return this.bytes.subarray(0, IMMEDIATE_SIZE); } } declare class ImmediateDecoder { private u32: Uint32Array; private i32: Int32Array; private u64: BigUint64Array; private i64: BigInt64Array; private view: DataView; private bytes: Uint8Array; constructor() { const buffer = new ArrayBuffer(BUFFER_SIZE); this.u32 = new Uint32Array(buffer); this.i32 = new Int32Array(buffer); this.u64 = new BigUint64Array(buffer); this.i64 = new BigInt64Array(buffer); this.view = new DataView(buffer); this.bytes = new Uint8Array(buffer); } setBytes(bytes: Uint8Array) { const n = bytes.length; const msb = n > 0 ? bytes[n - 1] & 0x80 : 0; const noOfBytes = Math.min(n, BUFFER_SIZE); const prefix = msb !== 0 ? 0xff : 0x00; for (let i = 0; i < noOfBytes; i++) { this.view.setUint8(i, bytes[i]); } for (let i = n; i < BUFFER_SIZE; i++) { this.view.setUint8(i, prefix); } } /** * @deprecated Use getU32 instead */ getUnsigned() { return this.u32[U32_INDEX]; } /** * @deprecated Use getI32 instead */ getSigned() { return this.i32[U32_INDEX]; } getU32(): number { return this.u32[U32_INDEX]; } getI32(): number { return this.i32[U32_INDEX]; } getU64(): bigint { return this.u64[U64_INDEX]; } getI64(): bigint { return this.i64[U64_INDEX]; } getBytesAsLittleEndian() { return this.bytes.subarray(0, IMMEDIATE_SIZE); } getExtendedBytesAsLittleEndian() { return this.bytes; } } declare const NO_OF_REGISTERS = 13; declare class Registers { private asSigned: BigInt64Array; private asUnsigned: BigUint64Array; constructor(private readonly bytes = new Uint8Array(NO_OF_REGISTERS << REGISTER_SIZE_SHIFT)) { check(bytes.length === NO_OF_REGISTERS << REGISTER_SIZE_SHIFT, "Invalid size of registers array."); this.asSigned = new BigInt64Array(bytes.buffer, bytes.byteOffset); this.asUnsigned = new BigUint64Array(bytes.buffer, bytes.byteOffset); } static fromBytes(bytes: Uint8Array) { check(bytes.length === NO_OF_REGISTERS << REGISTER_SIZE_SHIFT, "Invalid size of registers array."); return new Registers(bytes); } getBytesAsLittleEndian(index: number, len: number) { const offset = index << REGISTER_SIZE_SHIFT; return this.bytes.subarray(offset, offset + len); } getAllBytesAsLittleEndian() { return this.bytes; } copyFrom(regs: Registers | BigUint64Array) { const array = regs instanceof BigUint64Array ? regs : regs.asUnsigned; this.asUnsigned.set(array); } reset() { for (let i = 0; i < NO_OF_REGISTERS; i++) { this.asUnsigned[i] = 0n; } } getLowerU32(registerIndex: number) { return Number(this.asUnsigned[registerIndex] & 0xff_ff_ff_ffn); } getLowerI32(registerIndex: number) { return Number(this.getLowerU32(registerIndex)) >> 0; } setU32(registerIndex: number, value: number) { this.asUnsigned[registerIndex] = signExtend32To64(value); } setI32(registerIndex: number, value: number) { this.asSigned[registerIndex] = signExtend32To64(value); } getU64(registerIndex: number) { return this.asUnsigned[registerIndex]; } getI64(registerIndex: number) { return this.asSigned[registerIndex]; } setU64(registerIndex: number, value: bigint) { this.asUnsigned[registerIndex] = value; } setI64(registerIndex: number, value: bigint) { this.asSigned[registerIndex] = value; } getAllU64() { return this.asUnsigned; } } declare class NibblesDecoder { private byte = new Int8Array(1); setByte(byte: number) { this.byte[0] = byte; } getHighNibble() { return (this.byte[0] & 0xf0) >>> 4; } getLowNibble() { return this.byte[0] & 0x0f; } getHighNibbleAsRegisterIndex() { return Math.min(this.getHighNibble(), MAX_REGISTER_INDEX); } getLowNibbleAsRegisterIndex() { return Math.min(this.getLowNibble(), MAX_REGISTER_INDEX); } getHighNibbleAsLength() { return Math.min(this.getHighNibble(), MAX_LENGTH); } getLowNibbleAsLength() { return Math.min(this.getLowNibble(), MAX_LENGTH); } } type EmptyArgs = { type: ArgumentType.NO_ARGUMENTS; noOfBytesToSkip: number; }; type OneImmediateArgs = { type: ArgumentType.ONE_IMMEDIATE; noOfBytesToSkip: number; /** V_X */ immediateDecoder: ImmediateDecoder; }; type ThreeRegistersArgs = { type: ArgumentType.THREE_REGISTERS; noOfBytesToSkip: number; /** W_A */ firstRegisterIndex: number; /** W_B */ secondRegisterIndex: number; /** W_D */ thirdRegisterIndex: number; }; type TwoRegistersArgs = { type: ArgumentType.TWO_REGISTERS; noOfBytesToSkip: number; /** W_A */ firstRegisterIndex: number; /** W_D */ secondRegisterIndex: number; }; type TwoRegistersOneImmediateArgs = { type: ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; noOfBytesToSkip: number; /** W_A */ firstRegisterIndex: number; /** W_B */ secondRegisterIndex: number; /** V_X */ immediateDecoder: ImmediateDecoder; }; type OneRegisterOneImmediateArgs = { type: ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; noOfBytesToSkip: number; /** W_A */ registerIndex: number; /** V_X */ immediateDecoder: ImmediateDecoder; }; type OneRegisterOneExtendedWidthImmediateArgs = { type: ArgumentType.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE; noOfBytesToSkip: number; /** W_A */ registerIndex: number; /** V_X */ immediateDecoder: ExtendedWitdthImmediateDecoder; }; type TwoRegistersTwoImmediatesArgs = { type: ArgumentType.TWO_REGISTERS_TWO_IMMEDIATES; noOfBytesToSkip: number; /** W_A */ firstRegisterIndex: number; /** W_B */ secondRegisterIndex: number; /** V_X */ firstImmediateDecoder: ImmediateDecoder; /** V_Y */ secondImmediateDecoder: ImmediateDecoder; }; type TwoImmediatesArgs = { type: ArgumentType.TWO_IMMEDIATES; noOfBytesToSkip: number; /** V_X */ firstImmediateDecoder: ImmediateDecoder; /** V_Y */ secondImmediateDecoder: ImmediateDecoder; }; type TwoRegistersOneOffsetArgs = { type: ArgumentType.TWO_REGISTERS_ONE_OFFSET; noOfBytesToSkip: number; /** W_A */ firstRegisterIndex: number; /** W_B */ secondRegisterIndex: number; nextPc: number; }; type OneRegisterOneImmediateOneOffsetArgs = { type: ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; noOfBytesToSkip: number; /** W_A */ registerIndex: number; /** V_X */ immediateDecoder: ImmediateDecoder; /** V_Y */ nextPc: number; }; type OneRegisterTwoImmediatesArgs = { type: ArgumentType.ONE_REGISTER_TWO_IMMEDIATES; noOfBytesToSkip: number; /** W_A */ registerIndex: number; /** V_X */ firstImmediateDecoder: ImmediateDecoder; /** V_Y */ secondImmediateDecoder: ImmediateDecoder; }; type OneOffsetArgs = { type: ArgumentType.ONE_OFFSET; noOfBytesToSkip: number; /** V_X */ nextPc: number; }; type Args = | EmptyArgs | OneImmediateArgs | TwoRegistersArgs | ThreeRegistersArgs | TwoRegistersOneImmediateArgs | TwoRegistersTwoImmediatesArgs | OneRegisterOneImmediateOneOffsetArgs | TwoRegistersOneOffsetArgs | OneRegisterOneImmediateArgs | OneOffsetArgs | TwoImmediatesArgs | OneRegisterTwoImmediatesArgs | OneRegisterOneExtendedWidthImmediateArgs; declare class ArgsDecoder { private nibblesDecoder = new NibblesDecoder(); private offsetDecoder = new ImmediateDecoder(); private code: Uint8Array = new Uint8Array(); private mask: Mask = Mask.empty(); reset(code: Uint8Array, mask: Mask) { this.code = code; this.mask = mask; } fillArgs(pc: number, result: T): void { const nextInstructionDistance = 1 + this.mask.getNoOfBytesToNextInstruction(pc + 1); result.noOfBytesToSkip = nextInstructionDistance; switch (result.type) { case ArgumentType.NO_ARGUMENTS: break; case ArgumentType.ONE_IMMEDIATE: { const immediateLength = Math.min(IMMEDIATE_AND_OFFSET_MAX_LENGTH, nextInstructionDistance - 1); const argsStartIndex = pc + 1; result.immediateDecoder.setBytes(this.code.subarray(argsStartIndex, argsStartIndex + immediateLength)); break; } case ArgumentType.THREE_REGISTERS: { const firstByte = this.code[pc + 1]; const secondByte = this.code[pc + 2]; this.nibblesDecoder.setByte(firstByte); result.firstRegisterIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); result.secondRegisterIndex = this.nibblesDecoder.getHighNibbleAsRegisterIndex(); this.nibblesDecoder.setByte(secondByte); result.thirdRegisterIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); break; } case ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.firstRegisterIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); result.secondRegisterIndex = this.nibblesDecoder.getHighNibbleAsRegisterIndex(); const immediateLength = Math.min(IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 2)); const immediateStartIndex = pc + 2; const immediateEndIndex = immediateStartIndex + immediateLength; result.immediateDecoder.setBytes(this.code.subarray(immediateStartIndex, immediateEndIndex)); break; } case ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.registerIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); const immediateLength = this.nibblesDecoder.getHighNibbleAsLength(); const immediateStartIndex = pc + 2; const immediateEndIndex = immediateStartIndex + immediateLength; result.immediateDecoder.setBytes(this.code.subarray(immediateStartIndex, immediateEndIndex)); const offsetLength = Math.min( IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 2 - immediateLength), ); const offsetStartIndex = pc + 2 + immediateLength; const offsetEndIndex = offsetStartIndex + offsetLength; this.offsetDecoder.setBytes(this.code.subarray(offsetStartIndex, offsetEndIndex)); result.nextPc = pc + this.offsetDecoder.getSigned(); break; } case ArgumentType.TWO_REGISTERS_ONE_OFFSET: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.firstRegisterIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); result.secondRegisterIndex = this.nibblesDecoder.getHighNibbleAsRegisterIndex(); const offsetLength = Math.min(IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 2)); const offsetStartIndex = pc + 2; const offsetEndIndex = offsetStartIndex + offsetLength; this.offsetDecoder.setBytes(this.code.subarray(offsetStartIndex, offsetEndIndex)); result.nextPc = pc + this.offsetDecoder.getSigned(); break; } case ArgumentType.TWO_REGISTERS: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.firstRegisterIndex = this.nibblesDecoder.getHighNibbleAsRegisterIndex(); result.secondRegisterIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); break; } case ArgumentType.ONE_OFFSET: { const offsetLength = Math.min(IMMEDIATE_AND_OFFSET_MAX_LENGTH, nextInstructionDistance - 1); const offsetStartIndex = pc + 1; const offsetEndIndex = offsetStartIndex + offsetLength; const offsetBytes = this.code.subarray(offsetStartIndex, offsetEndIndex); this.offsetDecoder.setBytes(offsetBytes); const offsetValue = this.offsetDecoder.getSigned(); result.nextPc = pc + offsetValue; break; } case ArgumentType.ONE_REGISTER_ONE_IMMEDIATE: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.registerIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); const immediateLength = Math.min(IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 2)); const immediateStartIndex = pc + 2; const immediateEndIndex = immediateStartIndex + immediateLength; const immediateBytes = this.code.subarray(immediateStartIndex, immediateEndIndex); result.immediateDecoder.setBytes(immediateBytes); break; } case ArgumentType.TWO_IMMEDIATES: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); const firstImmediateLength = this.nibblesDecoder.getLowNibbleAsLength(); const firstImmediateStartIndex = pc + 2; const firstImmediateEndIndex = firstImmediateStartIndex + firstImmediateLength; const firstImmediateBytes = this.code.subarray(firstImmediateStartIndex, firstImmediateEndIndex); result.firstImmediateDecoder.setBytes(firstImmediateBytes); const secondImmediateLength = Math.min( IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 2 - firstImmediateLength), ); const secondImmediateStartIndex = firstImmediateEndIndex; const secondImmediateEndIndex = secondImmediateStartIndex + secondImmediateLength; const secondImmediateBytes = this.code.subarray(secondImmediateStartIndex, secondImmediateEndIndex); result.secondImmediateDecoder.setBytes(secondImmediateBytes); break; } case ArgumentType.ONE_REGISTER_TWO_IMMEDIATES: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.registerIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); const firstImmediateLength = this.nibblesDecoder.getHighNibbleAsLength(); const firstImmediateStartIndex = pc + 2; const firstImmediateEndIndex = firstImmediateStartIndex + firstImmediateLength; const firstImmediateBytes = this.code.subarray(firstImmediateStartIndex, firstImmediateEndIndex); result.firstImmediateDecoder.setBytes(firstImmediateBytes); const secondImmediateLength = Math.min( IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 2 - firstImmediateLength), ); const secondImmediateStartIndex = firstImmediateEndIndex; const secondImmediateEndIndex = secondImmediateStartIndex + secondImmediateLength; const secondImmediateBytes = this.code.subarray(secondImmediateStartIndex, secondImmediateEndIndex); result.secondImmediateDecoder.setBytes(secondImmediateBytes); break; } case ArgumentType.TWO_REGISTERS_TWO_IMMEDIATES: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.firstRegisterIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); result.secondRegisterIndex = this.nibblesDecoder.getHighNibbleAsRegisterIndex(); const secondByte = this.code[pc + 2]; this.nibblesDecoder.setByte(secondByte); const firstImmediateLength = this.nibblesDecoder.getLowNibbleAsLength(); const firstImmediateStartIndex = pc + 3; const firstImmediateEndIndex = firstImmediateStartIndex + firstImmediateLength; const firstImmediateBytes = this.code.subarray(firstImmediateStartIndex, firstImmediateEndIndex); result.firstImmediateDecoder.setBytes(firstImmediateBytes); const secondImmediateLength = Math.min( IMMEDIATE_AND_OFFSET_MAX_LENGTH, Math.max(0, nextInstructionDistance - 3 - firstImmediateLength), ); const secondImmediateStartIndex = firstImmediateEndIndex; const secondImmediateEndIndex = secondImmediateStartIndex + secondImmediateLength; const secondImmediateBytes = this.code.subarray(secondImmediateStartIndex, secondImmediateEndIndex); result.secondImmediateDecoder.setBytes(secondImmediateBytes); break; } case ArgumentType.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE: { const firstByte = this.code[pc + 1]; this.nibblesDecoder.setByte(firstByte); result.registerIndex = this.nibblesDecoder.getLowNibbleAsRegisterIndex(); const immediateStartIndex = pc + 2; const immediateEndIndex = immediateStartIndex + 8; const immediateBytes = this.code.subarray(immediateStartIndex, immediateEndIndex); result.immediateDecoder.setBytes(immediateBytes); break; } } } } declare const createResults = () => { const results = new Array(ARGUMENT_TYPE_LENGTH) as Results; results[ArgumentType.NO_ARGUMENTS] = { type: ArgumentType.NO_ARGUMENTS, noOfBytesToSkip: 1, }; results[ArgumentType.ONE_IMMEDIATE] = { type: ArgumentType.ONE_IMMEDIATE, noOfBytesToSkip: 1, immediateDecoder: new ImmediateDecoder(), }; results[ArgumentType.TWO_REGISTERS] = { type: ArgumentType.TWO_REGISTERS, noOfBytesToSkip: 1, firstRegisterIndex: 0, secondRegisterIndex: 0, }; results[ArgumentType.THREE_REGISTERS] = { type: ArgumentType.THREE_REGISTERS, noOfBytesToSkip: 1, firstRegisterIndex: 0, secondRegisterIndex: 0, thirdRegisterIndex: 0, }; results[ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET] = { type: ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET, noOfBytesToSkip: 1, registerIndex: 0, immediateDecoder: new ImmediateDecoder(), nextPc: 0, }; results[ArgumentType.TWO_REGISTERS_ONE_OFFSET] = { type: ArgumentType.TWO_REGISTERS_ONE_OFFSET, noOfBytesToSkip: 1, firstRegisterIndex: 0, secondRegisterIndex: 0, nextPc: 0, }; results[ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE] = { type: ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE, noOfBytesToSkip: 1, firstRegisterIndex: 0, secondRegisterIndex: 0, immediateDecoder: new ImmediateDecoder(), }; results[ArgumentType.ONE_REGISTER_ONE_IMMEDIATE] = { type: ArgumentType.ONE_REGISTER_ONE_IMMEDIATE, noOfBytesToSkip: 1, registerIndex: 0, immediateDecoder: new ImmediateDecoder(), }; results[ArgumentType.ONE_REGISTER_TWO_IMMEDIATES] = { type: ArgumentType.ONE_REGISTER_TWO_IMMEDIATES, noOfBytesToSkip: 1, registerIndex: 0, firstImmediateDecoder: new ImmediateDecoder(), secondImmediateDecoder: new ImmediateDecoder(), }; results[ArgumentType.ONE_OFFSET] = { type: ArgumentType.ONE_OFFSET, noOfBytesToSkip: 1, nextPc: 0, }; results[ArgumentType.TWO_IMMEDIATES] = { type: ArgumentType.TWO_IMMEDIATES, noOfBytesToSkip: 1, firstImmediateDecoder: new ImmediateDecoder(), secondImmediateDecoder: new ImmediateDecoder(), }; results[ArgumentType.TWO_REGISTERS_TWO_IMMEDIATES] = { type: ArgumentType.TWO_REGISTERS_TWO_IMMEDIATES, noOfBytesToSkip: 1, firstImmediateDecoder: new ImmediateDecoder(), secondImmediateDecoder: new ImmediateDecoder(), firstRegisterIndex: 0, secondRegisterIndex: 0, }; results[ArgumentType.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE] = { type: ArgumentType.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE, noOfBytesToSkip: 9, registerIndex: 0, immediateDecoder: new ExtendedWitdthImmediateDecoder(), }; return results; }; declare enum Instruction { TRAP = 0, FALLTHROUGH = 1, ECALLI = 10, LOAD_IMM_64 = 20, STORE_IMM_U8 = 30, STORE_IMM_U16 = 31, STORE_IMM_U32 = 32, STORE_IMM_U64 = 33, JUMP = 40, JUMP_IND = 50, LOAD_IMM = 51, LOAD_U8 = 52, LOAD_I8 = 53, LOAD_U16 = 54, LOAD_I16 = 55, LOAD_U32 = 56, LOAD_I32 = 57, LOAD_U64 = 58, STORE_U8 = 59, STORE_U16 = 60, STORE_U32 = 61, STORE_U64 = 62, STORE_IMM_IND_U8 = 70, STORE_IMM_IND_U16 = 71, STORE_IMM_IND_U32 = 72, STORE_IMM_IND_U64 = 73, LOAD_IMM_JUMP = 80, BRANCH_EQ_IMM = 81, BRANCH_NE_IMM = 82, BRANCH_LT_U_IMM = 83, BRANCH_LE_U_IMM = 84, BRANCH_GE_U_IMM = 85, BRANCH_GT_U_IMM = 86, BRANCH_LT_S_IMM = 87, BRANCH_LE_S_IMM = 88, BRANCH_GE_S_IMM = 89, BRANCH_GT_S_IMM = 90, MOVE_REG = 100, SBRK = 101, COUNT_SET_BITS_64 = 102, COUNT_SET_BITS_32 = 103, LEADING_ZERO_BITS_64 = 104, LEADING_ZERO_BITS_32 = 105, TRAILING_ZERO_BITS_64 = 106, TRAILING_ZERO_BITS_32 = 107, SIGN_EXTEND_8 = 108, SIGN_EXTEND_16 = 109, ZERO_EXTEND_16 = 110, REVERSE_BYTES = 111, STORE_IND_U8 = 120, STORE_IND_U16 = 121, STORE_IND_U32 = 122, STORE_IND_U64 = 123, LOAD_IND_U8 = 124, LOAD_IND_I8 = 125, LOAD_IND_U16 = 126, LOAD_IND_I16 = 127, LOAD_IND_U32 = 128, LOAD_IND_I32 = 129, LOAD_IND_U64 = 130, ADD_IMM_32 = 131, AND_IMM = 132, XOR_IMM = 133, OR_IMM = 134, MUL_IMM_32 = 135, SET_LT_U_IMM = 136, SET_LT_S_IMM = 137, SHLO_L_IMM_32 = 138, SHLO_R_IMM_32 = 139, SHAR_R_IMM_32 = 140, NEG_ADD_IMM_32 = 141, SET_GT_U_IMM = 142, SET_GT_S_IMM = 143, SHLO_L_IMM_ALT_32 = 144, SHLO_R_IMM_ALT_32 = 145, SHAR_R_IMM_ALT_32 = 146, CMOV_IZ_IMM = 147, CMOV_NZ_IMM = 148, ADD_IMM_64 = 149, MUL_IMM_64 = 150, SHLO_L_IMM_64 = 151, SHLO_R_IMM_64 = 152, SHAR_R_IMM_64 = 153, NEG_ADD_IMM_64 = 154, SHLO_L_IMM_ALT_64 = 155, SHLO_R_IMM_ALT_64 = 156, SHAR_R_IMM_ALT_64 = 157, ROT_R_64_IMM = 158, ROT_R_64_IMM_ALT = 159, ROT_R_32_IMM = 160, ROT_R_32_IMM_ALT = 161, BRANCH_EQ = 170, BRANCH_NE = 171, BRANCH_LT_U = 172, BRANCH_LT_S = 173, BRANCH_GE_U = 174, BRANCH_GE_S = 175, LOAD_IMM_JUMP_IND = 180, ADD_32 = 190, SUB_32 = 191, MUL_32 = 192, DIV_U_32 = 193, DIV_S_32 = 194, REM_U_32 = 195, REM_S_32 = 196, SHLO_L_32 = 197, SHLO_R_32 = 198, SHAR_R_32 = 199, ADD_64 = 200, SUB_64 = 201, MUL_64 = 202, DIV_U_64 = 203, DIV_S_64 = 204, REM_U_64 = 205, REM_S_64 = 206, SHLO_L_64 = 207, SHLO_R_64 = 208, SHAR_R_64 = 209, AND = 210, XOR = 211, OR = 212, MUL_UPPER_S_S = 213, MUL_UPPER_U_U = 214, MUL_UPPER_S_U = 215, SET_LT_U = 216, SET_LT_S = 217, CMOV_IZ = 218, CMOV_NZ = 219, ROT_L_64 = 220, ROT_L_32 = 221, ROT_R_64 = 222, ROT_R_32 = 223, AND_INV = 224, OR_INV = 225, XNOR = 226, MAX = 227, MAX_U = 228, MIN = 229, MIN_U = 230, } declare const instructionArgumentTypeMap = (() => { const instructionArgumentTypeMap = new Array(HIGHEST_INSTRUCTION_NUMBER + 1); instructionArgumentTypeMap[Instruction.TRAP] = ArgumentType.NO_ARGUMENTS; instructionArgumentTypeMap[Instruction.FALLTHROUGH] = ArgumentType.NO_ARGUMENTS; instructionArgumentTypeMap[Instruction.ECALLI] = ArgumentType.ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IMM_64] = ArgumentType.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_IMM_U8] = ArgumentType.TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.STORE_IMM_U16] = ArgumentType.TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.STORE_IMM_U32] = ArgumentType.TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.STORE_IMM_U64] = ArgumentType.TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.JUMP] = ArgumentType.ONE_OFFSET; instructionArgumentTypeMap[Instruction.JUMP_IND] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_U8] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_I8] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_U16] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_I16] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_U32] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_I32] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_U64] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_U8] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_U16] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_U32] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_U64] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_IMM_IND_U8] = ArgumentType.ONE_REGISTER_TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.STORE_IMM_IND_U16] = ArgumentType.ONE_REGISTER_TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.STORE_IMM_IND_U32] = ArgumentType.ONE_REGISTER_TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.STORE_IMM_IND_U64] = ArgumentType.ONE_REGISTER_TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.LOAD_IMM_JUMP] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_EQ_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_NE_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_LT_U_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_LE_U_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_GE_U_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_GT_U_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_LT_S_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_LE_S_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_GE_S_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_GT_S_IMM] = ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET; instructionArgumentTypeMap[Instruction.MOVE_REG] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.SBRK] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.COUNT_SET_BITS_64] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.COUNT_SET_BITS_32] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.LEADING_ZERO_BITS_64] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.LEADING_ZERO_BITS_32] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.TRAILING_ZERO_BITS_64] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.TRAILING_ZERO_BITS_32] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.SIGN_EXTEND_8] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.SIGN_EXTEND_16] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.ZERO_EXTEND_16] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.REVERSE_BYTES] = ArgumentType.TWO_REGISTERS; instructionArgumentTypeMap[Instruction.STORE_IND_U8] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_IND_U16] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_IND_U32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.STORE_IND_U64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_U8] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_I8] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_U16] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_I16] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_U32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_I32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.LOAD_IND_U64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.ADD_IMM_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.ADD_IMM_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.AND_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.XOR_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.OR_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.MUL_IMM_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.MUL_IMM_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SET_LT_U_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SET_LT_S_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_L_IMM_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_R_IMM_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHAR_R_IMM_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.NEG_ADD_IMM_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_L_IMM_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_R_IMM_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHAR_R_IMM_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.NEG_ADD_IMM_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SET_GT_U_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SET_GT_S_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_L_IMM_ALT_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_R_IMM_ALT_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHAR_R_IMM_ALT_32] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_L_IMM_ALT_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHLO_R_IMM_ALT_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.SHAR_R_IMM_ALT_64] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.CMOV_IZ_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.CMOV_NZ_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.ROT_R_64_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.ROT_R_64_IMM_ALT] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.ROT_R_32_IMM] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.ROT_R_32_IMM_ALT] = ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE; instructionArgumentTypeMap[Instruction.BRANCH_EQ] = ArgumentType.TWO_REGISTERS_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_NE] = ArgumentType.TWO_REGISTERS_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_LT_U] = ArgumentType.TWO_REGISTERS_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_LT_S] = ArgumentType.TWO_REGISTERS_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_GE_U] = ArgumentType.TWO_REGISTERS_ONE_OFFSET; instructionArgumentTypeMap[Instruction.BRANCH_GE_S] = ArgumentType.TWO_REGISTERS_ONE_OFFSET; instructionArgumentTypeMap[Instruction.LOAD_IMM_JUMP_IND] = ArgumentType.TWO_REGISTERS_TWO_IMMEDIATES; instructionArgumentTypeMap[Instruction.ADD_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.ADD_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SUB_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SUB_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.AND] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.XOR] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.OR] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MUL_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MUL_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MUL_UPPER_S_S] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MUL_UPPER_U_U] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MUL_UPPER_S_U] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.DIV_U_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.DIV_S_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.REM_U_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.REM_S_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.DIV_U_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.DIV_S_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.REM_U_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.REM_S_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SET_LT_U] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SET_LT_S] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SHLO_L_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SHLO_R_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SHAR_R_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SHLO_L_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SHLO_R_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.SHAR_R_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.CMOV_IZ] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.CMOV_NZ] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.ROT_L_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.ROT_L_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.ROT_R_64] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.ROT_R_32] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.AND_INV] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.OR_INV] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.XNOR] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MAX] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MAX_U] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MIN] = ArgumentType.THREE_REGISTERS; instructionArgumentTypeMap[Instruction.MIN_U] = ArgumentType.THREE_REGISTERS; return instructionArgumentTypeMap; })(); /** Gas measuring type. Can be either U64 or U32 for performance reasons. */ type Gas = BigGas | SmallGas; /** A U64 version of `Gas`. */ type BigGas = Opaque; /** A U32 version of `Gas`. */ type SmallGas = Opaque; /** Attempt to convert given number into U32 gas representation. */ declare const tryAsSmallGas = (v: number): SmallGas => asOpaqueType(tryAsU32(v)); /** Attempt to convert given number into U64 gas representation. */ declare const tryAsBigGas = (v: number | bigint): BigGas => asOpaqueType(tryAsU64(v)); /** Attempt to convert given number into gas. */ declare const tryAsGas = (v: number | bigint): Gas => typeof v === "number" && v < 2 ** 32 ? tryAsSmallGas(v) : tryAsBigGas(v); /** Create a new gas counter instance depending on the gas value. */ declare function gasCounter(gas: Gas): GasCounter { return new GasCounterU64(tryAsU64(gas)); } /** An abstraction over gas counter. * * It can be optimized to use numbers instead of bigint in case of small gas. */ interface GasCounter { /** Return remaining gas. */ get(): Gas; /** Overwrite remaining gas. Prefer sub method instead. */ set(g: Gas): void; /** Returns true if there was an underflow. */ sub(g: Gas): boolean; } declare class BasicBlocks { private basicBlocks: Set = new Set(); reset(code: Uint8Array, mask: Mask) { this.basicBlocks.clear(); this.basicBlocks.add(0); const codeLength = code.length; const isBasicBlockTermination = (index: number) => mask.isInstruction(index) && terminationInstructions[code[index]]; for (let i = 0; i < codeLength; i++) { if (mask.isInstruction(i) && isBasicBlockTermination(i)) { this.basicBlocks.add(i + 1 + mask.getNoOfBytesToNextInstruction(i + 1)); } } } isBeginningOfBasicBlock(index: number) { return this.basicBlocks.has(index); } } declare enum Result { HALT = 0, PANIC = 1, FAULT_ACCESS = 2, FAULT = 3, HOST = 4, } declare class InstructionResult { public nextPc = 0; public status: Result | null = null; /** * A numeric exit parameter of the PVM. * * In case of a `status === Result.FAULT` this will be the memory address * that triggered the fault. * In case of a `status === Result.HOST` this will be the host call index * that should be invoked. * * In any other circumstance the value should be `null`. */ public exitParam: number | null = null; reset() { this.nextPc = 0; this.status = null; this.exitParam = null; } } type MemoryIndex = Opaque; declare const tryAsMemoryIndex = (index: number): MemoryIndex => ensure(index, index >= 0 && index <= MAX_MEMORY_INDEX, `Incorrect memory index: ${index}!`); type SbrkIndex = Opaque; declare const tryAsSbrkIndex = (index: number): SbrkIndex => ensure(index, index >= 0 && index <= MAX_MEMORY_INDEX + 1, `Incorrect sbrk index: ${index}!`); type PageIndex = Opaque; type PageNumber = Opaque; declare class PageFault { private constructor( public address: MemoryIndex, public isAccessFault = true, ) {} static fromPageNumber(maybePageNumber: number, isAccessFault = false) { const pageNumber = tryAsPageNumber(maybePageNumber); const startPageIndex = getStartPageIndexFromPageNumber(pageNumber); return new PageFault(startPageIndex, isAccessFault); } static fromMemoryIndex(maybeMemoryIndex: number, isAccessFault = false) { const memoryIndex = tryAsMemoryIndex(maybeMemoryIndex % MEMORY_SIZE); const startPageIndex = getStartPageIndex(memoryIndex); return new PageFault(startPageIndex, isAccessFault); } } declare class OutOfBounds extends Error { constructor() { super("Out of bounds"); } } /** * A representation of open-ended range of consecutive indices in memory, * possibly empty or wrapping around. * * `[start, start + length)` */ declare class MemoryRange { /** * Exclusive end index of the range. * * NOTE: The index may be wrapped around and smaller than `start`! */ public readonly end: MemoryIndex; /** * Inclusive last index of the range (present unless the range is empty). * * NOTE: the index may be wrapped around and smaller than `start`! */ public readonly lastIndex: MemoryIndex | null = null; private constructor( public readonly start: MemoryIndex, public readonly length: number, ) { this.end = tryAsMemoryIndex((this.start + this.length) % MEMORY_SIZE); if (length > 0) { this.lastIndex = tryAsMemoryIndex((this.end - 1 + MEMORY_SIZE) % MEMORY_SIZE); } } /** Creates a memory range from given starting point and length */ static fromStartAndLength(start: MemoryIndex, length: number) { if (!Number.isInteger(length) || length < 0 || length > MEMORY_SIZE) { throw new TypeError(`length must be a non-negative integer and less than ${MEMORY_SIZE}, got ${length}`); } return new MemoryRange(start, length); } /** Checks if a range is empty (`length === 0`) */ isEmpty() { return this.length === 0; } /** Returns true if the range is wrapped (`start` >= `end`) and is not empty */ isWrapped() { return this.start >= this.end && !this.isEmpty(); } /** Checks if given memory address is within the range */ isInRange(address: MemoryIndex) { if (this.isWrapped()) { return address >= this.start || address < this.end; } return address >= this.start && address < this.end; } /** Checks if this range overlaps with another range */ overlapsWith(other: MemoryRange) { if (this.lastIndex === null || other.lastIndex === null) { return false; } return ( this.isInRange(other.start) || this.isInRange(other.lastIndex) || other.isInRange(this.start) || other.isInRange(this.lastIndex) ); } } declare abstract class MemoryPage { public start: MemoryIndex; constructor(pageNumber: PageNumber) { this.start = getStartPageIndexFromPageNumber(pageNumber); } /** Returns `true` if the page is writeable. */ abstract isWriteable(): boolean; /** * Load exactly `length` bytes from memory page, starting at index `address` * into the `res` array. * * Note that the `res` might be bigger than the number of bytes length, but cannot be smaller. * * Returns `null` if copying was successful and [`PageFault`] otherwise. * NOTE That the `result` might be partially modified in case `PageFault` occurs! */ abstract loadInto(res: Uint8Array, address: PageIndex, length: number): Result$2; /** * Copy all bytes from the `data` into the page at index `address`. * * Returns `null` if copying was successful and [`PageFault`] otherwise. */ abstract storeFrom(address: PageIndex, data: Uint8Array): Result$2; /** * Get dump of the entire page. Should only be used for the debugger-adapter because it * might be inefficient. */ abstract getPageDump(): Uint8Array; abstract setData(pageIndex: PageIndex, data: Uint8Array): void; } /** * I had to extend ArrayBuffer type to use resizable ArrayBuffer. * We will be able to remove it when this is merged: https://github.com/microsoft/TypeScript/pull/58573 * And then a new version of TypeScript is released. */ declare global { interface ArrayBufferConstructor { new (length: number, options?: { maxByteLength: number }): ArrayBuffer; } interface ArrayBuffer { resize(length: number): void; } } type InitialMemoryState = { memory: Map; sbrkIndex: SbrkIndex; endHeapIndex: SbrkIndex; }; declare enum AccessType { READ = 0, WRITE = 1, } declare class Memory { static fromInitialMemory(initialMemoryState: InitialMemoryState) { return new Memory( initialMemoryState?.sbrkIndex, initialMemoryState?.sbrkIndex, initialMemoryState?.endHeapIndex, initialMemoryState?.memory, ); } constructor( private sbrkIndex = tryAsSbrkIndex(RESERVED_MEMORY_RANGE.end), private virtualSbrkIndex = tryAsSbrkIndex(RESERVED_MEMORY_RANGE.end), private endHeapIndex = tryAsSbrkIndex(MAX_MEMORY_INDEX), private memory = new Map(), ) {} reset() { this.sbrkIndex = tryAsSbrkIndex(RESERVED_MEMORY_RANGE.end); this.virtualSbrkIndex = tryAsSbrkIndex(RESERVED_MEMORY_RANGE.end); this.endHeapIndex = tryAsSbrkIndex(MAX_MEMORY_INDEX); this.memory = new Map(); // TODO [MaSi]: We should keep allocated pages somewhere and reuse it when it is possible } copyFrom(memory: Memory) { this.sbrkIndex = memory.sbrkIndex; this.virtualSbrkIndex = memory.virtualSbrkIndex; this.endHeapIndex = memory.endHeapIndex; this.memory = memory.memory; } storeFrom(address: MemoryIndex, bytes: Uint8Array): Result$2 { if (bytes.length === 0) { return Result.ok(OK); } const pagesResult = this.getPages(address, bytes.length, AccessType.WRITE); if (pagesResult.isError) { return Result.error(pagesResult.error); } const pages = pagesResult.ok; let currentPosition: number = address; let bytesLeft = bytes.length; for (const page of pages) { const pageStartIndex = tryAsPageIndex(currentPosition % PAGE_SIZE); const bytesToWrite = Math.min(PAGE_SIZE - pageStartIndex, bytesLeft); const sourceStartIndex = currentPosition - address; const source = bytes.subarray(sourceStartIndex, sourceStartIndex + bytesToWrite); page.storeFrom(pageStartIndex, source); currentPosition += bytesToWrite; bytesLeft -= bytesToWrite; } return Result.ok(OK); } private getPages(startAddress: MemoryIndex, length: number, accessType: AccessType): Result$2 { if (length === 0) { return Result.ok([]); } const memoryRange = MemoryRange.fromStartAndLength(startAddress, length); const pageRange = PageRange.fromMemoryRange(memoryRange); const pages: MemoryPage[] = []; for (const pageNumber of pageRange) { if (pageNumber < RESERVED_NUMBER_OF_PAGES) { return Result.error(PageFault.fromPageNumber(pageNumber, true)); } const page = this.memory.get(pageNumber); if (page === undefined) { return Result.error(PageFault.fromPageNumber(pageNumber)); } if (accessType === AccessType.WRITE && !page.isWriteable()) { return Result.error(PageFault.fromPageNumber(pageNumber, true)); } pages.push(page); } return Result.ok(pages); } /** * Read content of the memory at `[address, address + result.length)` and * write the result into the `result` buffer. * * Returns `null` if the data was read successfully or `PageFault` otherwise. */ loadInto(result: Uint8Array, startAddress: MemoryIndex): Result$2 { if (result.length === 0) { return Result.ok(OK); } const pagesResult = this.getPages(startAddress, result.length, AccessType.READ); if (pagesResult.isError) { return Result.error(pagesResult.error); } const pages = pagesResult.ok; let currentPosition: number = startAddress; let bytesLeft = result.length; for (const page of pages) { const pageStartIndex = tryAsPageIndex(currentPosition % PAGE_SIZE); const bytesToRead = Math.min(PAGE_SIZE - pageStartIndex, bytesLeft); const destinationStartIndex = currentPosition - startAddress; const destination = result.subarray(destinationStartIndex); page.loadInto(destination, pageStartIndex, bytesToRead); currentPosition += bytesToRead; bytesLeft -= bytesToRead; } return Result.ok(OK); } sbrk(length: number): SbrkIndex { const currentSbrkIndex = this.sbrkIndex; const currentVirtualSbrkIndex = this.virtualSbrkIndex; // new sbrk index is bigger than 2 ** 32 or endHeapIndex if (MAX_MEMORY_INDEX < currentVirtualSbrkIndex + length || currentVirtualSbrkIndex + length > this.endHeapIndex) { throw new OutOfMemory(); } const newVirtualSbrkIndex = tryAsSbrkIndex(this.virtualSbrkIndex + length); // no alllocation needed if (newVirtualSbrkIndex <= currentSbrkIndex) { this.virtualSbrkIndex = newVirtualSbrkIndex; return currentVirtualSbrkIndex; } // standard allocation using "Writeable" pages const newSbrkIndex = tryAsSbrkIndex(alignToPageSize(newVirtualSbrkIndex)); // TODO [MaSi]: `getPageNumber` works incorrectly for SbrkIndex. Sbrk index should be changed to MemoryIndex const firstPageNumber = getPageNumber(currentSbrkIndex); const pagesToAllocate = (newSbrkIndex - currentSbrkIndex) / PAGE_SIZE; const rangeToAllocate = PageRange.fromStartAndLength(firstPageNumber, pagesToAllocate); for (const pageNumber of rangeToAllocate) { const page = new WriteablePage(pageNumber); this.memory.set(pageNumber, page); } this.virtualSbrkIndex = newVirtualSbrkIndex; this.sbrkIndex = newSbrkIndex; return currentVirtualSbrkIndex; } getPageDump(pageNumber: PageNumber) { const page = this.memory.get(pageNumber); return page?.getPageDump() ?? null; } getDirtyPages() { return this.memory.keys(); } } declare class MemoryBuilder { private readonly initialMemory: Map = new Map(); private isFinalized = false; private ensureNotFinalized() { if (this.isFinalized) { throw new FinalizedBuilderModification(); } } private ensureNoReservedMemoryUsage(range: MemoryRange) { if (range.overlapsWith(RESERVED_MEMORY_RANGE)) { throw new ReservedMemoryFault(); } } /** * Create entire readable pages to handle the `[start, end)` range. * * Note that both `start` and `end` must be multiple of the `PAGE_SIZE`, i.e. * they need to be the start indices of the pages. * * The data passed will be placed at `start`, but might be shorter than the requested range, * prepend it with zeros if you don't wish to have it at the beginning of the page. */ setReadablePages(start: MemoryIndex, end: MemoryIndex, data: Uint8Array = new Uint8Array()) { this.ensureNotFinalized(); check(start < end, "end has to be bigger than start"); check(start % PAGE_SIZE === 0, `start needs to be a multiple of page size (${PAGE_SIZE})`); check(end % PAGE_SIZE === 0, `end needs to be a multiple of page size (${PAGE_SIZE})`); check(data.length <= end - start, "the initial data is longer than address range"); const length = end - start; const range = MemoryRange.fromStartAndLength(start, length); this.ensureNoReservedMemoryUsage(range); const pages = Array.from(PageRange.fromMemoryRange(range)); const noOfPages = pages.length; for (let i = 0; i < noOfPages; i++) { const pageNumber = pages[i]; const dataChunk = data.subarray(i * PAGE_SIZE, (i + 1) * PAGE_SIZE); const page = new ReadablePage(pageNumber, dataChunk); this.initialMemory.set(pageNumber, page); } return this; } /** * Create entire writeable pages to handle the `[start, end)` range. * * Note that both `start` and `end` must be multiple of the `PAGE_SIZE`, i.e. * they need to be the start indices of the pages. * * The data passed will be placed at `start`, but might be shorter than the requested range, * prepend it with zeros if you don't wish to have it at the beginning of the page. */ setWriteablePages(start: MemoryIndex, end: MemoryIndex, data: Uint8Array = new Uint8Array()) { this.ensureNotFinalized(); check(start < end, "end has to be bigger than start"); check(start % PAGE_SIZE === 0, `start needs to be a multiple of page size (${PAGE_SIZE})`); check(end % PAGE_SIZE === 0, `end needs to be a multiple of page size (${PAGE_SIZE})`); check(data.length <= end - start, "the initial data is longer than address range"); const length = end - start; const range = MemoryRange.fromStartAndLength(start, length); this.ensureNoReservedMemoryUsage(range); const pages = Array.from(PageRange.fromMemoryRange(range)); const noOfPages = pages.length; for (let i = 0; i < noOfPages; i++) { const pageNumber = pages[i]; const dataChunk = data.subarray(i * PAGE_SIZE, (i + 1) * PAGE_SIZE); const page = new WriteablePage(pageNumber, dataChunk); this.initialMemory.set(pageNumber, page); } return this; } /** * This function can be useful when page map and initial memory data are provided separatelly. * You can use setWriteablePages/setReadablePages to create empty pages and then setData to fill them */ setData(start: MemoryIndex, data: Uint8Array) { this.ensureNotFinalized(); const pageOffset = start % PAGE_SIZE; const remainingSpaceOnPage = PAGE_SIZE - pageOffset; check(data.length <= remainingSpaceOnPage, "The data has to fit into a single page."); const length = data.length; const range = MemoryRange.fromStartAndLength(start, length); this.ensureNoReservedMemoryUsage(range); const pageNumber = getPageNumber(start); const page = this.initialMemory.get(pageNumber); if (page === undefined) { throw new PageNotExist(); } const startPageIndex = tryAsPageIndex(start - page.start); page.setData(startPageIndex, data); return this; } finalize(startHeapIndex: MemoryIndex, endHeapIndex: SbrkIndex): Memory { check( startHeapIndex <= endHeapIndex, `startHeapIndex (${startHeapIndex}) has to be less than or equal to endHeapIndex (${endHeapIndex})`, ); this.ensureNotFinalized(); const range = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex); const pages = PageRange.fromMemoryRange(range); for (const pageNumber of pages) { if (this.initialMemory.has(pageNumber)) { throw new IncorrectSbrkIndex(); } } const memory = Memory.fromInitialMemory({ memory: this.initialMemory, sbrkIndex: tryAsSbrkIndex(startHeapIndex), endHeapIndex, }); this.isFinalized = true; return memory; } } declare class BitOps { constructor(private regs: Registers) {} or(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) | this.regs.getU64(secondIndex)); } orImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) | immediate.getU64()); } and(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) & this.regs.getU64(secondIndex)); } andImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) & immediate.getU64()); } xor(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) ^ this.regs.getU64(secondIndex)); } xorImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) ^ immediate.getU64()); } andInv(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) & ~this.regs.getU64(secondIndex)); } orInv(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) | ~this.regs.getU64(secondIndex)); } xnor(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, ~(this.regs.getU64(firstIndex) ^ this.regs.getU64(secondIndex))); } countSetBits64(valueIndex: number, resultIndex: number) { this.regs.setU32(resultIndex, countBits64(this.regs.getU64(valueIndex))); } countSetBits32(valueIndex: number, resultIndex: number) { this.regs.setU32(resultIndex, countBits32(this.regs.getLowerU32(valueIndex))); } leadingZeroBits64(valueIndex: number, resultIndex: number) { this.regs.setU32(resultIndex, clz64(this.regs.getU64(valueIndex))); } leadingZeroBits32(valueIndex: number, resultIndex: number) { this.regs.setU32(resultIndex, Math.clz32(this.regs.getLowerU32(valueIndex))); } trailingZeroBits64(valueIndex: number, resultIndex: number) { this.regs.setU32(resultIndex, ctz64(this.regs.getU64(valueIndex))); } trailingZeroBits32(valueIndex: number, resultIndex: number) { this.regs.setU32(resultIndex, ctz32(this.regs.getLowerU32(valueIndex))); } private signExtend(value: number, length: 8 | 16) { const mask = 2 ** length - 1; const maskedValue = value & mask; const bitSign = 1 << (length - 1); if ((maskedValue & bitSign) > 0) { return ~BigInt(mask) | BigInt(maskedValue); } return BigInt(maskedValue); } signExtend8(valueIndex: number, resultIndex: number) { const extendedValue = this.signExtend(this.regs.getLowerU32(valueIndex), 8); this.regs.setU64(resultIndex, extendedValue); } signExtend16(valueIndex: number, resultIndex: number) { const extendedValue = this.signExtend(this.regs.getLowerU32(valueIndex), 16); this.regs.setU64(resultIndex, extendedValue); } zeroExtend16(valueIndex: number, resultIndex: number) { const extendedValue = this.regs.getU64(valueIndex) & 0x00_00_00_00_00_00_ff_ffn; this.regs.setU64(resultIndex, extendedValue); } } declare class ShiftOps { constructor(private regs: Registers) {} shiftLogicalLeftU32(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU32( resultIndex, this.regs.getLowerU32(firstIndex) << (this.regs.getLowerU32(secondIndex) % MAX_SHIFT_U32), ); } shiftLogicalLeftU64(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) << (this.regs.getU64(secondIndex) % MAX_SHIFT_U64)); } shiftLogicalRightU32(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU32( resultIndex, this.regs.getLowerU32(firstIndex) >>> (this.regs.getLowerU32(secondIndex) % MAX_SHIFT_U32), ); } shiftLogicalRightU64(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64( resultIndex, unsignedRightShiftBigInt(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex) % MAX_SHIFT_U64), ); } shiftArithmeticRightU32(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setI32( resultIndex, this.regs.getLowerI32(firstIndex) >> (this.regs.getLowerU32(secondIndex) % MAX_SHIFT_U32), ); } shiftArithmeticRightU64(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setI64(resultIndex, this.regs.getI64(firstIndex) >> (this.regs.getU64(secondIndex) % MAX_SHIFT_U64)); } shiftLogicalLeftImmediateU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU32(resultIndex, this.regs.getLowerU32(firstIndex) << (immediate.getU32() % MAX_SHIFT_U32)); } shiftLogicalLeftImmediateU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) << (immediate.getU64() % MAX_SHIFT_U64)); } shiftLogicalRightImmediateU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU32(resultIndex, this.regs.getLowerU32(firstIndex) >>> (immediate.getU32() % MAX_SHIFT_U32)); } shiftLogicalRightImmediateU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64( resultIndex, unsignedRightShiftBigInt(this.regs.getU64(firstIndex), immediate.getU64() % MAX_SHIFT_U64), ); } shiftArithmeticRightImmediateU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU32(resultIndex, this.regs.getLowerI32(firstIndex) >> (immediate.getU32() % MAX_SHIFT_U32)); } shiftArithmeticRightImmediateU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getI64(firstIndex) >> (immediate.getU64() % MAX_SHIFT_U64)); } shiftLogicalLeftImmediateAlternativeU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU32(resultIndex, immediate.getU32() << (this.regs.getLowerU32(firstIndex) % MAX_SHIFT_U32)); } shiftLogicalLeftImmediateAlternativeU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, immediate.getU64() << (this.regs.getU64(firstIndex) % MAX_SHIFT_U64)); } shiftLogicalRightImmediateAlternativeU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU32(resultIndex, immediate.getU32() >>> (this.regs.getLowerU32(firstIndex) % MAX_SHIFT_U32)); } shiftLogicalRightImmediateAlternativeU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64( resultIndex, unsignedRightShiftBigInt(immediate.getU64(), this.regs.getU64(firstIndex) % MAX_SHIFT_U64), ); } shiftArithmeticRightImmediateAlternativeU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setI32(resultIndex, immediate.getU32() >> (this.regs.getLowerU32(firstIndex) % MAX_SHIFT_U32)); } shiftArithmeticRightImmediateAlternativeU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setI64(resultIndex, immediate.getI64() >> (this.regs.getU64(firstIndex) % MAX_SHIFT_U64)); } } declare class MathOps { constructor(private regs: Registers) {} addU32(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64( resultIndex, signExtend32To64(addWithOverflowU32(this.regs.getLowerU32(firstIndex), this.regs.getLowerU32(secondIndex))), ); } addU64(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, addWithOverflowU64(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex))); } addImmediateU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64( resultIndex, signExtend32To64(addWithOverflowU32(this.regs.getLowerU32(firstIndex), immediate.getU32())), ); } addImmediateU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, addWithOverflowU64(this.regs.getU64(firstIndex), immediate.getU64())); } mulU32(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64( resultIndex, signExtend32To64(mulLowerUnsignedU32(this.regs.getLowerU32(firstIndex), this.regs.getLowerU32(secondIndex))), ); } mulU64(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, mulU64(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex))); } mulUpperUU(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, mulUpperUU(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex))); } mulUpperSS(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setI64(resultIndex, mulUpperSS(this.regs.getI64(firstIndex), this.regs.getI64(secondIndex))); } mulUpperSU(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setI64(resultIndex, mulUpperSU(this.regs.getI64(firstIndex), this.regs.getU64(secondIndex))); } mulImmediateU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64( resultIndex, signExtend32To64(mulLowerUnsignedU32(this.regs.getLowerU32(firstIndex), immediate.getU32())), ); } mulImmediateU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, mulU64(this.regs.getU64(firstIndex), immediate.getU64())); } mulUpperSSImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setI64(resultIndex, mulUpperSS(this.regs.getI64(firstIndex), immediate.getI64())); } mulUpperUUImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, mulUpperUU(this.regs.getU64(firstIndex), immediate.getU64())); } subU32(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64( resultIndex, signExtend32To64(subU32(this.regs.getLowerU32(firstIndex), this.regs.getLowerU32(secondIndex))), ); } subU64(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, subU64(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex))); } negAddImmediateU32(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, signExtend32To64(subU32(immediate.getU32(), this.regs.getLowerU32(firstIndex)))); } negAddImmediateU64(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, subU64(immediate.getU64(), this.regs.getU64(firstIndex))); } divSignedU32(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getLowerU32(secondIndex) === 0) { this.regs.setU64(resultIndex, 2n ** 64n - 1n); } else if (this.regs.getLowerI32(secondIndex) === -1 && this.regs.getLowerI32(firstIndex) === MIN_VALUE) { this.regs.setU64(resultIndex, signExtend32To64(this.regs.getLowerU32(firstIndex))); } else { this.regs.setI64( resultIndex, signExtend32To64(~~(this.regs.getLowerI32(firstIndex) / this.regs.getLowerI32(secondIndex))), ); } } divSignedU64(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getU64(secondIndex) === 0n) { this.regs.setU64(resultIndex, 2n ** 64n - 1n); } else if (this.regs.getI64(secondIndex) === -1n && this.regs.getI64(firstIndex) === -(2n ** 63n)) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex)); } else { this.regs.setI64(resultIndex, ~~(this.regs.getI64(firstIndex) / this.regs.getI64(secondIndex))); } } divUnsignedU32(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getLowerU32(secondIndex) === 0) { this.regs.setU64(resultIndex, 2n ** 64n - 1n); } else { this.regs.setU64( resultIndex, signExtend32To64(~~(this.regs.getLowerU32(firstIndex) / this.regs.getLowerU32(secondIndex))), ); } } divUnsignedU64(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getU64(secondIndex) === 0n) { this.regs.setU64(resultIndex, 2n ** 64n - 1n); } else { this.regs.setU64(resultIndex, ~~(this.regs.getU64(firstIndex) / this.regs.getU64(secondIndex))); } } remSignedU32(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getLowerU32(secondIndex) === 0) { this.regs.setU64(resultIndex, BigInt(this.regs.getLowerI32(firstIndex))); } else if (this.regs.getLowerI32(secondIndex) === -1 && this.regs.getLowerI32(firstIndex) === MIN_VALUE) { this.regs.setU64(resultIndex, 0n); } else { this.regs.setI64( resultIndex, signExtend32To64(this.regs.getLowerI32(firstIndex) % this.regs.getLowerI32(secondIndex)), ); } } remSignedU64(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getU64(secondIndex) === 0n) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex)); } else if (this.regs.getI64(secondIndex) === -1n && this.regs.getI64(firstIndex) === -(2n ** 63n)) { this.regs.setU64(resultIndex, 0n); } else { this.regs.setI64(resultIndex, this.regs.getI64(firstIndex) % this.regs.getI64(secondIndex)); } } remUnsignedU32(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getLowerU32(secondIndex) === 0) { this.regs.setU64(resultIndex, signExtend32To64(this.regs.getLowerU32(firstIndex))); } else { this.regs.setU64( resultIndex, signExtend32To64(this.regs.getLowerU32(firstIndex) % this.regs.getLowerU32(secondIndex)), ); } } remUnsignedU64(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getU64(secondIndex) === 0n) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex)); } else { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) % this.regs.getU64(secondIndex)); } } max(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setI64(resultIndex, maxBigInt(this.regs.getI64(firstIndex), this.regs.getI64(secondIndex))); } maxU(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, maxBigInt(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex))); } min(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setI64(resultIndex, minBigInt(this.regs.getI64(firstIndex), this.regs.getI64(secondIndex))); } minU(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, minBigInt(this.regs.getU64(firstIndex), this.regs.getU64(secondIndex))); } } declare class BooleanOps { constructor(private regs: Registers) {} setLessThanSignedImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getI64(firstIndex) < immediate.getI64() ? 1n : 0n); } setLessThanUnsignedImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) < immediate.getU64() ? 1n : 0n); } setLessThanSigned(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getI64(firstIndex) < this.regs.getI64(secondIndex) ? 1n : 0n); } setLessThanUnsigned(firstIndex: number, secondIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) < this.regs.getU64(secondIndex) ? 1n : 0n); } setGreaterThanSignedImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getI64(firstIndex) > immediate.getI64() ? 1n : 0n); } setGreaterThanUnsignedImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex) > immediate.getU64() ? 1n : 0n); } } declare class MoveOps { constructor(private regs: Registers) {} cmovIfZeroImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { if (this.regs.getU64(firstIndex) === 0n) { this.regs.setU64(resultIndex, immediate.getU64()); } } cmovIfNotZeroImmediate(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { if (this.regs.getU64(firstIndex) !== 0n) { this.regs.setU64(resultIndex, immediate.getU64()); } } cmovIfZero(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getU64(secondIndex) === 0n) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex)); } } cmovIfNotZero(firstIndex: number, secondIndex: number, resultIndex: number) { if (this.regs.getU64(secondIndex) !== 0n) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex)); } } moveRegister(firstIndex: number, resultIndex: number) { this.regs.setU64(resultIndex, this.regs.getU64(firstIndex)); } } declare class BranchOps { constructor( private regs: Registers, private instructionResult: InstructionResult, private basicBlocks: BasicBlocks, ) {} setBasicBlocks(basicBlocks: BasicBlocks) { this.basicBlocks = basicBlocks; } private branch(nextPc: number, condition: boolean) { if (!condition) { return; } if (!this.basicBlocks.isBeginningOfBasicBlock(nextPc)) { this.instructionResult.status = Result.PANIC; return; } this.instructionResult.nextPc = nextPc; } jump(nextPc: number) { this.branch(nextPc, true); } branchEqImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getU64(registerIndex) === immediate.getU64()); } branchEq(firstIndex: number, secondIndex: number, nextPc: number) { this.branch(nextPc, this.regs.getU64(firstIndex) === this.regs.getU64(secondIndex)); } branchNeImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getU64(registerIndex) !== immediate.getU64()); } branchNe(firstIndex: number, secondIndex: number, nextPc: number) { this.branch(nextPc, this.regs.getU64(firstIndex) !== this.regs.getU64(secondIndex)); } branchLtUnsignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getU64(registerIndex) < immediate.getU64()); } branchLtUnsigned(firstIndex: number, secondIndex: number, nextPc: number) { this.branch(nextPc, this.regs.getU64(firstIndex) < this.regs.getU64(secondIndex)); } branchLeUnsignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getU64(registerIndex) <= immediate.getU64()); } branchGtUnsignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getU64(registerIndex) > immediate.getU64()); } branchGeUnsignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getU64(registerIndex) >= immediate.getU64()); } branchGeUnsigned(firstIndex: number, secondIndex: number, nextPc: number) { this.branch(nextPc, this.regs.getU64(firstIndex) >= this.regs.getU64(secondIndex)); } branchLtSignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getI64(registerIndex) < immediate.getI64()); } branchLtSigned(firstIndex: number, secondIndex: number, nextPc: number) { this.branch(nextPc, this.regs.getI64(firstIndex) < this.regs.getI64(secondIndex)); } branchLeSignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getI64(registerIndex) <= immediate.getI64()); } branchGtSignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getI64(registerIndex) > immediate.getI64()); } branchGeSignedImmediate(registerIndex: number, immediate: ImmediateDecoder, nextPc: number) { this.branch(nextPc, this.regs.getI64(registerIndex) >= immediate.getI64()); } branchGeSigned(firstIndex: number, secondIndex: number, nextPc: number) { this.branch(nextPc, this.regs.getI64(firstIndex) >= this.regs.getI64(secondIndex)); } } declare class LoadOps { constructor( private regs: Registers, private memory: Memory, private instructionResult: InstructionResult, ) {} loadImmediate(registerIndex: number, immediate: ImmediateDecoder) { this.regs.setU64(registerIndex, immediate.getU64()); } loadImmediateU64(registerIndex: number, immediate: ExtendedWitdthImmediateDecoder) { this.regs.setU64(registerIndex, immediate.getValue()); } private loadNumber(address: number, registerIndex: number, numberLength: 1 | 2 | 4 | 8) { const registerBytes = this.regs.getBytesAsLittleEndian(registerIndex, REG_SIZE_BYTES); const loadResult = this.memory.loadInto(registerBytes.subarray(0, numberLength), tryAsMemoryIndex(address)); if (loadResult.isError) { if (loadResult.error.isAccessFault) { this.instructionResult.status = Result.FAULT_ACCESS; } else { this.instructionResult.status = Result.FAULT; this.instructionResult.exitParam = address; } return; } registerBytes.fill(0, numberLength); } private loadSignedNumber(address: number, registerIndex: number, numberLength: 1 | 2 | 4) { // load all bytes from register to correctly handle the sign. const registerBytes = this.regs.getBytesAsLittleEndian(registerIndex, REG_SIZE_BYTES); const loadResult = this.memory.loadInto(registerBytes.subarray(0, numberLength), tryAsMemoryIndex(address)); if (loadResult.isError) { if (loadResult.error.isAccessFault) { this.instructionResult.status = Result.FAULT_ACCESS; } else { this.instructionResult.status = Result.FAULT; this.instructionResult.exitParam = address; } return; } const msb = registerBytes[numberLength - 1] & 0x80; if (msb > 0) { registerBytes.fill(0xff, numberLength); } else { registerBytes.fill(0x00, numberLength); } } loadU8(address: number, registerIndex: number) { this.loadNumber(address, registerIndex, 1); } loadU16(address: number, registerIndex: number) { this.loadNumber(address, registerIndex, 2); } loadU32(address: number, registerIndex: number) { this.loadNumber(address, registerIndex, 4); } loadU64(address: number, registerIndex: number) { this.loadNumber(address, registerIndex, 8); } loadI8(address: number, registerIndex: number) { this.loadSignedNumber(address, registerIndex, 1); } loadI16(address: number, registerIndex: number) { this.loadSignedNumber(address, registerIndex, 2); } loadI32(address: number, registerIndex: number) { this.loadSignedNumber(address, registerIndex, 4); } loadIndU8(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadNumber(address, firstRegisterIndex, 1); } loadIndU16(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadNumber(address, firstRegisterIndex, 2); } loadIndU32(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadNumber(address, firstRegisterIndex, 4); } loadIndU64(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadNumber(address, firstRegisterIndex, 8); } loadIndI8(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadSignedNumber(address, firstRegisterIndex, 1); } loadIndI16(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadSignedNumber(address, firstRegisterIndex, 2); } loadIndI32(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getU32()); this.loadSignedNumber(address, firstRegisterIndex, 4); } } declare class StoreOps { constructor( private regs: Registers, private memory: Memory, private instructionResult: InstructionResult, ) {} storeU8(address: number, registerIndex: number) { this.store(address, this.regs.getBytesAsLittleEndian(registerIndex, 1)); } storeU16(address: number, registerIndex: number) { this.store(address, this.regs.getBytesAsLittleEndian(registerIndex, 2)); } storeU32(address: number, registerIndex: number) { this.store(address, this.regs.getBytesAsLittleEndian(registerIndex, 4)); } storeU64(address: number, registerIndex: number) { this.store(address, this.regs.getBytesAsLittleEndian(registerIndex, 8)); } storeIndU8(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getUnsigned()); this.store(address, this.regs.getBytesAsLittleEndian(firstRegisterIndex, 1)); } storeIndU16(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getUnsigned()); this.store(address, this.regs.getBytesAsLittleEndian(firstRegisterIndex, 2)); } storeIndU32(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getUnsigned()); this.store(address, this.regs.getBytesAsLittleEndian(firstRegisterIndex, 4)); } storeIndU64(firstRegisterIndex: number, secondRegisterIndex: number, immediateDecoder: ImmediateDecoder) { const address = addWithOverflowU32(this.regs.getLowerU32(secondRegisterIndex), immediateDecoder.getUnsigned()); this.store(address, this.regs.getBytesAsLittleEndian(firstRegisterIndex, 8)); } storeImmediateU8(address: number, immediateDecoder: ImmediateDecoder) { this.store(address, immediateDecoder.getBytesAsLittleEndian().subarray(0, 1)); } storeImmediateU16(address: number, immediateDecoder: ImmediateDecoder) { this.store(address, immediateDecoder.getBytesAsLittleEndian().subarray(0, 2)); } storeImmediateU32(address: number, immediateDecoder: ImmediateDecoder) { this.store(address, immediateDecoder.getBytesAsLittleEndian().subarray(0, 4)); } storeImmediateU64(address: number, immediateDecoder: ImmediateDecoder) { this.store(address, immediateDecoder.getExtendedBytesAsLittleEndian()); } storeImmediateIndU8( registerIndex: number, firstImmediateDecoder: ImmediateDecoder, secondImmediateDecoder: ImmediateDecoder, ) { const address = addWithOverflowU32(this.regs.getLowerU32(registerIndex), firstImmediateDecoder.getUnsigned()); this.store(address, secondImmediateDecoder.getBytesAsLittleEndian().subarray(0, 1)); } storeImmediateIndU16( registerIndex: number, firstImmediateDecoder: ImmediateDecoder, secondImmediateDecoder: ImmediateDecoder, ) { const address = addWithOverflowU32(this.regs.getLowerU32(registerIndex), firstImmediateDecoder.getUnsigned()); this.store(address, secondImmediateDecoder.getBytesAsLittleEndian().subarray(0, 2)); } storeImmediateIndU32( registerIndex: number, firstImmediateDecoder: ImmediateDecoder, secondImmediateDecoder: ImmediateDecoder, ) { const address = addWithOverflowU32(this.regs.getLowerU32(registerIndex), firstImmediateDecoder.getUnsigned()); this.store(address, secondImmediateDecoder.getBytesAsLittleEndian().subarray(0, 4)); } storeImmediateIndU64( registerIndex: number, firstImmediateDecoder: ImmediateDecoder, secondImmediateDecoder: ImmediateDecoder, ) { const address = addWithOverflowU32(this.regs.getLowerU32(registerIndex), firstImmediateDecoder.getUnsigned()); this.store(address, secondImmediateDecoder.getExtendedBytesAsLittleEndian()); } private store(address: number, bytes: Uint8Array) { const storeResult = this.memory.storeFrom(tryAsMemoryIndex(address), bytes); if (storeResult.isOk) { return; } if (storeResult.error.isAccessFault) { this.instructionResult.status = Result.FAULT_ACCESS; } else { this.instructionResult.status = Result.FAULT; this.instructionResult.exitParam = getStartPageIndex(storeResult.error.address); } } } declare class NoArgsOps { constructor(private instructionResult: InstructionResult) {} trap() { this.instructionResult.status = Result.PANIC; } fallthrough() { // noop } } declare class JumpTable { private indices: Uint32Array; constructor(itemByteLength: number, bytes: Uint8Array) { check( itemByteLength === 0 || bytes.length % itemByteLength === 0, `Length of jump table (${bytes.length}) should be a multiple of item lenght (${itemByteLength})!`, ); const length = itemByteLength === 0 ? 0 : bytes.length / itemByteLength; this.indices = new Uint32Array(length); for (let i = 0; i < length; i++) { this.indices[i] = this.decodeNext(bytes.subarray(i * itemByteLength, (i + 1) * itemByteLength)); } } private decodeNext(bytes: Uint8Array): number { const itemByteLength = bytes.length; let value = 0; for (let i = 0; i < itemByteLength; i++) { if ((value & 0xff00_0000) > 0) { // the value is going to exceed u32 so we can clamp it return 2 ** 32 - 1; } value <<= 8; value |= bytes[itemByteLength - i - 1]; } return value; } hasIndex(index: number) { return index < this.indices.length && index >= 0; } getDestination(index: number) { return this.indices[index]; } static empty() { return new JumpTable(0, new Uint8Array()); } copyFrom(jt: JumpTable) { this.indices = jt.indices; } } declare class DynamicJumpOps { constructor( private regs: Registers, private jumpTable: JumpTable, private instructionResult: InstructionResult, private basicBlocks: BasicBlocks, ) {} private djump(dynamicAddress: number) { if (dynamicAddress === EXIT) { this.instructionResult.status = Result.HALT; return; } if (dynamicAddress === 0 || dynamicAddress % JUMP_ALIGMENT_FACTOR !== 0) { this.instructionResult.status = Result.PANIC; return; } const jumpTableIndex = dynamicAddress / JUMP_ALIGMENT_FACTOR - 1; if (!this.jumpTable.hasIndex(jumpTableIndex)) { this.instructionResult.status = Result.PANIC; return; } const destination = this.jumpTable.getDestination(jumpTableIndex); if (!this.basicBlocks.isBeginningOfBasicBlock(destination)) { this.instructionResult.status = Result.PANIC; return; } this.instructionResult.nextPc = destination; } caluclateJumpAddress(immediate: ImmediateDecoder, registerIndex: number) { const registerValue = this.regs.getLowerU32(registerIndex); return addWithOverflowU32(registerValue, immediate.getU32()); } jumpInd(address: number) { this.djump(address); } } declare class HostCallOps { constructor(private instructionResult: InstructionResult) {} hostCall(immediateDecoder: ImmediateDecoder) { this.instructionResult.status = Result.HOST; this.instructionResult.exitParam = immediateDecoder.getUnsigned(); } } declare class MemoryOps { constructor( private regs: Registers, private memory: Memory, private instructionResult: InstructionResult, ) {} sbrk(firstIndex: number, resultIndex: number) { try { this.regs.setU32(resultIndex, this.memory.sbrk(this.regs.getLowerU32(firstIndex))); } catch { this.instructionResult.status = Result.FAULT; } } } declare class BitRotationOps { constructor(private regs: Registers) {} reverseBytes(valueIndex: number, resultIndex: number) { const value = this.regs.getU64(valueIndex); let reversedValue = 0n; for (let i = 0; i < 8; i++) { const byte = (value >> BigInt(i * 8)) & 0xffn; reversedValue = (reversedValue << 8n) | byte; } this.regs.setU64(resultIndex, reversedValue); } private rotate32Left(value: number, shift: number) { const shiftNormalized = shift % 32; const mask = 2 ** 32 - 1; const rotated = (((value << shiftNormalized) & mask) | (value >>> (32 - shiftNormalized))) >>> 0; return rotated & mask; } private rotate64Left(value: bigint, shift: number) { const shiftNormalized = shift % 64; const mask = (1n << 64n) - 1n; const rotated = ((value << BigInt(shiftNormalized)) & mask) | unsignedRightShiftBigInt(value, BigInt(64 - shiftNormalized)); return rotated & mask; } private rotate32Right(value: number, shift: number) { const shiftNormalized = shift % 32; const mask = 2 ** 32 - 1; const rotated = (value >>> shiftNormalized) | ((value << (32 - shiftNormalized)) & mask); return rotated & mask; } private rotate64Right(value: bigint, shift: number) { const shiftNormalized = shift % 64; const mask = (1n << 64n) - 1n; const rotated = unsignedRightShiftBigInt(value, BigInt(shiftNormalized)) | ((value << BigInt(64 - shiftNormalized)) & mask); return rotated & mask; } rotR64Imm(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { const shift = immediate.getU32(); const value = this.regs.getU64(firstIndex); this.regs.setU64(resultIndex, this.rotate64Right(value, shift)); } rotR64ImmAlt(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { const shift = this.regs.getLowerU32(firstIndex); const value = immediate.getU64(); this.regs.setU64(resultIndex, this.rotate64Right(value, shift)); } rotR32Imm(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { const shift = immediate.getU32(); const value = this.regs.getLowerU32(firstIndex); this.regs.setU32(resultIndex, this.rotate32Right(value, shift)); } rotR32ImmAlt(firstIndex: number, immediate: ImmediateDecoder, resultIndex: number) { const shift = this.regs.getLowerU32(firstIndex); const value = immediate.getU32(); this.regs.setU32(resultIndex, this.rotate32Right(value, shift)); } rotL64(firstIndex: number, secondIndex: number, resultIndex: number) { const value = this.regs.getU64(firstIndex); const shift = this.regs.getLowerU32(secondIndex); this.regs.setU64(resultIndex, this.rotate64Left(value, shift)); } rotL32(firstIndex: number, secondIndex: number, resultIndex: number) { const value = this.regs.getLowerU32(firstIndex); const shift = this.regs.getLowerU32(secondIndex); this.regs.setU32(resultIndex, this.rotate32Left(value, shift)); } rotR64(firstIndex: number, secondIndex: number, resultIndex: number) { const value = this.regs.getU64(firstIndex); const shift = this.regs.getLowerU32(secondIndex); this.regs.setU64(resultIndex, this.rotate64Right(value, shift)); } rotR32(firstIndex: number, secondIndex: number, resultIndex: number) { const value = this.regs.getLowerU32(firstIndex); const shift = this.regs.getLowerU32(secondIndex); this.regs.setU32(resultIndex, this.rotate32Right(value, shift)); } } declare class ThreeRegsDispatcher { constructor( private mathOps: MathOps, private shiftOps: ShiftOps, private bitOps: BitOps, private booleanOps: BooleanOps, private moveOps: MoveOps, private bitRotationOps: BitRotationOps, ) {} dispatch(instruction: Instruction, args: ThreeRegistersArgs) { switch (instruction) { case Instruction.ADD_32: this.mathOps.addU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.ADD_64: this.mathOps.addU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MUL_32: this.mathOps.mulU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MUL_64: this.mathOps.mulU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MUL_UPPER_U_U: this.mathOps.mulUpperUU(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MUL_UPPER_S_S: this.mathOps.mulUpperSS(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MUL_UPPER_S_U: this.mathOps.mulUpperSU(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SUB_32: this.mathOps.subU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SUB_64: this.mathOps.subU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.DIV_S_32: this.mathOps.divSignedU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.DIV_S_64: this.mathOps.divSignedU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.DIV_U_32: this.mathOps.divUnsignedU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.DIV_U_64: this.mathOps.divUnsignedU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.REM_S_32: this.mathOps.remSignedU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.REM_S_64: this.mathOps.remSignedU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.REM_U_32: this.mathOps.remUnsignedU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.REM_U_64: this.mathOps.remUnsignedU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SHLO_L_32: this.shiftOps.shiftLogicalLeftU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SHLO_L_64: this.shiftOps.shiftLogicalLeftU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SHLO_R_32: this.shiftOps.shiftLogicalRightU32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SHLO_R_64: this.shiftOps.shiftLogicalRightU64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SHAR_R_32: this.shiftOps.shiftArithmeticRightU32( args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex, ); break; case Instruction.SHAR_R_64: this.shiftOps.shiftArithmeticRightU64( args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex, ); break; case Instruction.OR: this.bitOps.or(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.AND: this.bitOps.and(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.XOR: this.bitOps.xor(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SET_LT_S: this.booleanOps.setLessThanSigned(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.SET_LT_U: this.booleanOps.setLessThanUnsigned(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.CMOV_IZ: this.moveOps.cmovIfZero(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.CMOV_NZ: this.moveOps.cmovIfNotZero(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.ROT_L_64: this.bitRotationOps.rotL64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.ROT_L_32: this.bitRotationOps.rotL32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.ROT_R_64: this.bitRotationOps.rotR64(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.ROT_R_32: this.bitRotationOps.rotR32(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.AND_INV: this.bitOps.andInv(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.OR_INV: this.bitOps.orInv(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.XNOR: this.bitOps.xnor(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MAX: this.mathOps.max(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MAX_U: this.mathOps.maxU(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MIN: this.mathOps.min(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; case Instruction.MIN_U: this.mathOps.minU(args.firstRegisterIndex, args.secondRegisterIndex, args.thirdRegisterIndex); break; } } } declare class TwoRegsOneImmDispatcher { constructor( private mathOps: MathOps, private shiftOps: ShiftOps, private bitOps: BitOps, private booleanOps: BooleanOps, private moveOps: MoveOps, private storeOps: StoreOps, private loadOps: LoadOps, private bitRotationOps: BitRotationOps, ) {} dispatch(instruction: Instruction, args: TwoRegistersOneImmediateArgs) { switch (instruction) { case Instruction.ADD_IMM_32: this.mathOps.addImmediateU32(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.ADD_IMM_64: this.mathOps.addImmediateU64(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.MUL_IMM_32: this.mathOps.mulImmediateU32(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.MUL_IMM_64: this.mathOps.mulImmediateU64(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.NEG_ADD_IMM_32: this.mathOps.negAddImmediateU32(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.NEG_ADD_IMM_64: this.mathOps.negAddImmediateU64(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.SHLO_L_IMM_32: this.shiftOps.shiftLogicalLeftImmediateU32( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_L_IMM_64: this.shiftOps.shiftLogicalLeftImmediateU64( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_L_IMM_ALT_32: this.shiftOps.shiftLogicalLeftImmediateAlternativeU32( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_L_IMM_ALT_64: this.shiftOps.shiftLogicalLeftImmediateAlternativeU64( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_R_IMM_32: this.shiftOps.shiftLogicalRightImmediateU32( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_R_IMM_64: this.shiftOps.shiftLogicalRightImmediateU64( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_R_IMM_ALT_32: this.shiftOps.shiftLogicalRightImmediateAlternativeU32( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHLO_R_IMM_ALT_64: this.shiftOps.shiftLogicalRightImmediateAlternativeU64( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHAR_R_IMM_32: this.shiftOps.shiftArithmeticRightImmediateU32( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHAR_R_IMM_64: this.shiftOps.shiftArithmeticRightImmediateU64( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHAR_R_IMM_ALT_32: this.shiftOps.shiftArithmeticRightImmediateAlternativeU32( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SHAR_R_IMM_ALT_64: this.shiftOps.shiftArithmeticRightImmediateAlternativeU64( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.OR_IMM: this.bitOps.orImmediate(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.AND_IMM: this.bitOps.andImmediate(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.XOR_IMM: this.bitOps.xorImmediate(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.SET_LT_S_IMM: this.booleanOps.setLessThanSignedImmediate( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SET_LT_U_IMM: this.booleanOps.setLessThanUnsignedImmediate( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SET_GT_S_IMM: this.booleanOps.setGreaterThanSignedImmediate( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.SET_GT_U_IMM: this.booleanOps.setGreaterThanUnsignedImmediate( args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex, ); break; case Instruction.CMOV_IZ_IMM: this.moveOps.cmovIfZeroImmediate(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.CMOV_NZ_IMM: this.moveOps.cmovIfNotZeroImmediate(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.STORE_IND_U8: this.storeOps.storeIndU8(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.STORE_IND_U16: this.storeOps.storeIndU16(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.STORE_IND_U32: this.storeOps.storeIndU32(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.STORE_IND_U64: this.storeOps.storeIndU64(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_U8: this.loadOps.loadIndU8(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_U16: this.loadOps.loadIndU16(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_U32: this.loadOps.loadIndU32(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_U64: this.loadOps.loadIndU64(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_I8: this.loadOps.loadIndI8(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_I16: this.loadOps.loadIndI16(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.LOAD_IND_I32: this.loadOps.loadIndI32(args.firstRegisterIndex, args.secondRegisterIndex, args.immediateDecoder); break; case Instruction.ROT_R_64_IMM: this.bitRotationOps.rotR64Imm(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.ROT_R_64_IMM_ALT: this.bitRotationOps.rotR64ImmAlt(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.ROT_R_32_IMM: this.bitRotationOps.rotR32Imm(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; case Instruction.ROT_R_32_IMM_ALT: this.bitRotationOps.rotR32ImmAlt(args.secondRegisterIndex, args.immediateDecoder, args.firstRegisterIndex); break; } } } declare class TwoRegsDispatcher { constructor( private moveOps: MoveOps, private memoryOps: MemoryOps, private bitOps: BitOps, private bitRotationOps: BitRotationOps, ) {} dispatch(instruction: Instruction, args: TwoRegistersArgs) { switch (instruction) { case Instruction.MOVE_REG: this.moveOps.moveRegister(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.SBRK: this.memoryOps.sbrk(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.COUNT_SET_BITS_64: this.bitOps.countSetBits64(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.COUNT_SET_BITS_32: this.bitOps.countSetBits32(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.LEADING_ZERO_BITS_64: this.bitOps.leadingZeroBits64(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.LEADING_ZERO_BITS_32: this.bitOps.leadingZeroBits32(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.TRAILING_ZERO_BITS_64: this.bitOps.trailingZeroBits64(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.TRAILING_ZERO_BITS_32: this.bitOps.trailingZeroBits32(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.SIGN_EXTEND_8: this.bitOps.signExtend8(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.SIGN_EXTEND_16: this.bitOps.signExtend16(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.ZERO_EXTEND_16: this.bitOps.zeroExtend16(args.firstRegisterIndex, args.secondRegisterIndex); break; case Instruction.REVERSE_BYTES: this.bitRotationOps.reverseBytes(args.firstRegisterIndex, args.secondRegisterIndex); break; } } } declare class OneRegOneImmOneOffsetDispatcher { constructor( private branchOps: BranchOps, private loadOps: LoadOps, ) {} dispatch(instruction: Instruction, args: OneRegisterOneImmediateOneOffsetArgs) { switch (instruction) { case Instruction.LOAD_IMM_JUMP: this.loadOps.loadImmediate(args.registerIndex, args.immediateDecoder); this.branchOps.jump(args.nextPc); break; case Instruction.BRANCH_EQ_IMM: this.branchOps.branchEqImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_NE_IMM: this.branchOps.branchNeImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_LT_U_IMM: this.branchOps.branchLtUnsignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_LE_U_IMM: this.branchOps.branchLeUnsignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_GE_U_IMM: this.branchOps.branchGeUnsignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_GT_U_IMM: this.branchOps.branchGtUnsignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_LT_S_IMM: this.branchOps.branchLtSignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_LE_S_IMM: this.branchOps.branchLeSignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_GE_S_IMM: this.branchOps.branchGeSignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; case Instruction.BRANCH_GT_S_IMM: this.branchOps.branchGtSignedImmediate(args.registerIndex, args.immediateDecoder, args.nextPc); break; } } } declare class TwoRegsOneOffsetDispatcher { constructor(private branchOps: BranchOps) {} dispatch(instruction: Instruction, args: TwoRegistersOneOffsetArgs) { switch (instruction) { case Instruction.BRANCH_EQ: this.branchOps.branchEq(args.firstRegisterIndex, args.secondRegisterIndex, args.nextPc); break; case Instruction.BRANCH_NE: this.branchOps.branchNe(args.firstRegisterIndex, args.secondRegisterIndex, args.nextPc); break; case Instruction.BRANCH_LT_U: this.branchOps.branchLtUnsigned(args.firstRegisterIndex, args.secondRegisterIndex, args.nextPc); break; case Instruction.BRANCH_LT_S: this.branchOps.branchLtSigned(args.firstRegisterIndex, args.secondRegisterIndex, args.nextPc); break; case Instruction.BRANCH_GE_U: this.branchOps.branchGeUnsigned(args.firstRegisterIndex, args.secondRegisterIndex, args.nextPc); break; case Instruction.BRANCH_GE_S: this.branchOps.branchGeSigned(args.firstRegisterIndex, args.secondRegisterIndex, args.nextPc); break; } } } declare class OneOffsetDispatcher { constructor(private branchOps: BranchOps) {} dispatch(instruction: Instruction, args: OneOffsetArgs) { switch (instruction) { case Instruction.JUMP: this.branchOps.jump(args.nextPc); break; } } } declare class OneRegOneImmDispatcher { constructor( private loadOps: LoadOps, private storeOps: StoreOps, private dynamicJumpOps: DynamicJumpOps, ) {} dispatch(instruction: Instruction, args: OneRegisterOneImmediateArgs) { switch (instruction) { case Instruction.LOAD_IMM: this.loadOps.loadImmediate(args.registerIndex, args.immediateDecoder); break; case Instruction.STORE_U8: this.storeOps.storeU8(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.STORE_U16: this.storeOps.storeU16(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.STORE_U32: this.storeOps.storeU32(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.STORE_U64: this.storeOps.storeU64(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_U8: this.loadOps.loadU8(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_U16: this.loadOps.loadU16(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_U32: this.loadOps.loadU32(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_U64: this.loadOps.loadU64(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_I8: this.loadOps.loadI8(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_I16: this.loadOps.loadI16(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.LOAD_I32: this.loadOps.loadI32(args.immediateDecoder.getUnsigned(), args.registerIndex); break; case Instruction.JUMP_IND: { const address = this.dynamicJumpOps.caluclateJumpAddress(args.immediateDecoder, args.registerIndex); this.dynamicJumpOps.jumpInd(address); break; } } } } declare class OneRegTwoImmsDispatcher { constructor(private storeOps: StoreOps) {} dispatch(instruction: Instruction, args: OneRegisterTwoImmediatesArgs) { switch (instruction) { case Instruction.STORE_IMM_IND_U8: this.storeOps.storeImmediateIndU8(args.registerIndex, args.firstImmediateDecoder, args.secondImmediateDecoder); break; case Instruction.STORE_IMM_IND_U16: this.storeOps.storeImmediateIndU16(args.registerIndex, args.firstImmediateDecoder, args.secondImmediateDecoder); break; case Instruction.STORE_IMM_IND_U32: this.storeOps.storeImmediateIndU32(args.registerIndex, args.firstImmediateDecoder, args.secondImmediateDecoder); break; case Instruction.STORE_IMM_IND_U64: this.storeOps.storeImmediateIndU64(args.registerIndex, args.firstImmediateDecoder, args.secondImmediateDecoder); break; } } } declare class TwoImmsDispatcher { constructor(private storeOps: StoreOps) {} dispatch(instruction: Instruction, args: TwoImmediatesArgs) { switch (instruction) { case Instruction.STORE_IMM_U8: this.storeOps.storeImmediateU8(args.firstImmediateDecoder.getUnsigned(), args.secondImmediateDecoder); break; case Instruction.STORE_IMM_U16: this.storeOps.storeImmediateU16(args.firstImmediateDecoder.getUnsigned(), args.secondImmediateDecoder); break; case Instruction.STORE_IMM_U32: this.storeOps.storeImmediateU32(args.firstImmediateDecoder.getUnsigned(), args.secondImmediateDecoder); break; case Instruction.STORE_IMM_U64: this.storeOps.storeImmediateU64(args.firstImmediateDecoder.getUnsigned(), args.secondImmediateDecoder); break; } } } declare class NoArgsDispatcher { constructor(private noArgsOps: NoArgsOps) {} dispatch(instruction: Instruction) { switch (instruction) { case Instruction.TRAP: this.noArgsOps.trap(); break; case Instruction.FALLTHROUGH: this.noArgsOps.fallthrough(); break; } } } declare class TwoRegsTwoImmsDispatcher { constructor( private loadOps: LoadOps, private dynamicJumpOps: DynamicJumpOps, ) {} dispatch(instruction: Instruction, args: TwoRegistersTwoImmediatesArgs) { switch (instruction) { case Instruction.LOAD_IMM_JUMP_IND: { const address = this.dynamicJumpOps.caluclateJumpAddress(args.secondImmediateDecoder, args.secondRegisterIndex); this.loadOps.loadImmediate(args.firstRegisterIndex, args.firstImmediateDecoder); this.dynamicJumpOps.jumpInd(address); break; } } } } declare class OneImmDispatcher { constructor(private hostCallOps: HostCallOps) {} dispatch(instruction: Instruction, args: OneImmediateArgs) { switch (instruction) { case Instruction.ECALLI: this.hostCallOps.hostCall(args.immediateDecoder); break; } } } declare class OneRegOneExtImmDispatcher { constructor(private loadOps: LoadOps) {} dispatch(instruction: Instruction, args: OneRegisterOneExtendedWidthImmediateArgs) { switch (instruction) { case Instruction.LOAD_IMM_64: this.loadOps.loadImmediateU64(args.registerIndex, args.immediateDecoder); break; } } } /** A decoder for some specific type `T` */ type Decode = { /** Decode object of type `T`. */ decode: (d: Decoder) => T; }; /** Primitives decoder for JAM codec. */ declare class Decoder { /** * Create a new [`Decoder`] instance from given bytes blob and starting offset. */ static fromBytesBlob(source: BytesBlob, offset?: number) { return new Decoder(source.raw, offset); } /** * Create a new [`Decoder`] instance given a raw array of bytes as a source. */ static fromBlob(source: Uint8Array) { return new Decoder(source); } /** * Decode a single object from all of the source bytes. * * NOTE that if you need to decode multiple objects, it might be better * to create a [`Decoder`] instance intstead of slicing the data. */ static decodeObject(decode: Decode, source: BytesBlob | Uint8Array, context?: unknown): T { const decoder = source instanceof BytesBlob ? Decoder.fromBytesBlob(source) : Decoder.fromBlob(source); decoder.attachContext(context); const obj = decoder.object(decode); decoder.finish(); return obj; } /** * Decode a sequence of objects from all of the source bytes. */ static decodeSequence(decode: Decode, source: BytesBlob | Uint8Array, context?: unknown): T[] { const decoder = source instanceof BytesBlob ? Decoder.fromBytesBlob(source) : Decoder.fromBlob(source); decoder.attachContext(context); const seq = [] as T[]; while (decoder.bytesRead() < decoder.source.length) { seq.push(decoder.object(decode)); } decoder.finish(); return seq; } private readonly dataView: DataView; private constructor( public readonly source: Uint8Array, private offset = 0, private context?: unknown, ) { this.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength); } /** * Attach context to the decoder. * * The context object can be used to pass some "global" parameters * down to custom decoders. */ attachContext(context?: unknown) { this.context = context; } /** * Get the decoding context object. */ getContext(): unknown { return this.context; } /** * Return a copy of this decoder. * * The copy will maintain it's own `offset` within the source. */ clone(): Decoder { return new Decoder(this.source, this.offset, this.context); } /** * Return the number of bytes read from the source * (i.e. current offset within the source). */ bytesRead(): number { return this.offset; } /** * Return all remaining bytes as BytesBlob and move offset to the end. */ remainingBytes(): BytesBlob { const bytes = this.source.subarray(this.offset); const length = bytes.length; this.offset += length; return Bytes.fromBlob(bytes, length); } /** Decode single byte as a signed number. */ i8(): number { return this.getNum(1, () => this.dataView.getInt8(this.offset)); } /** Decode single byte as an unsigned number. */ u8(): U8 { return this.getNum(1, () => this.dataView.getUint8(this.offset)) as U8; } /** Decode two bytes as a signed number. */ i16(): number { return this.getNum(2, () => this.dataView.getInt16(this.offset, true)); } /** Decode two bytes as an unsigned number. */ u16(): U16 { return this.getNum(2, () => this.dataView.getUint16(this.offset, true)) as U16; } /** Decode three bytes as a signed number. */ i24(): number { const num = this.u24(); return num >= 2 ** 23 ? num - 2 ** 24 : num; } /** Decode three bytes as an unsigned number. */ u24(): number { return this.getNum(3, () => { let num = this.dataView.getUint8(this.offset); num |= this.dataView.getUint16(this.offset + 1, true) << 8; return num; }); } /** Decode 4 bytes as a signed number. */ i32(): number { return this.getNum(4, () => this.dataView.getInt32(this.offset, true)); } /** Decode 4 bytes as an unsigned number. */ u32(): U32 { return this.getNum(4, () => this.dataView.getUint32(this.offset, true)) as U32; } /** Decode 8 bytes as a signed number. */ i64(): bigint { return this.getNum(8, () => this.dataView.getBigInt64(this.offset, true)); } /** Decode 8 bytes as a unsigned number. */ u64(): U64 { return this.getNum(8, () => this.dataView.getBigUint64(this.offset, true)) as U64; } /** * Decode a boolean discriminator. * * NOTE: this method will throw an exception in case the encoded * byte is neither 0 nor 1. */ bool(): boolean { const num = this.u8(); if (num === 0) { return false; } if (num === 1) { return true; } throw new Error(`Unexpected number when decoding a boolean: ${num}`); } /** * Decode a variable-length encoding of natural numbers (up to 2**32). * * NOTE: this method will panic in case a larger number is found * in the source. */ varU32(): U32 { this.ensureHasBytes(1); const firstByte = this.source[this.offset]; const l = decodeVariableLengthExtraBytes(firstByte); this.offset += 1; if (l === 0) { return firstByte as U32; } if (l > 4) { throw new Error(`Unexpectedly large value for u32. l=${l}`); } this.ensureHasBytes(l); const mostSignificantByte = (firstByte + 2 ** (8 - l) - 2 ** 8) << (l * 8); if (l === 1) { return (mostSignificantByte + this.u8()) as U32; } if (l === 2) { return (mostSignificantByte + this.u16()) as U32; } if (l === 3) { return (mostSignificantByte + this.u24()) as U32; } if (mostSignificantByte === 0) { return this.u32(); } throw new Error(`Unexpectedly large value for u32. l=${l}, mostSignificantByte=${mostSignificantByte}`); } /** Decode a variable-length encoding of natural numbers (up to 2**64). */ varU64(): U64 { this.ensureHasBytes(1); const firstByte = this.source[this.offset]; const l = decodeVariableLengthExtraBytes(firstByte); this.offset += 1; if (l === 0) { return tryAsU64(firstByte); } this.ensureHasBytes(l); this.offset += l; if (l === 8) { return tryAsU64(this.dataView.getBigUint64(this.offset - l, true)); } let num = BigInt(firstByte + 2 ** (8 - l) - 2 ** 8) << BigInt(8 * l); for (let i = 0; i < l; i += 1) { num |= BigInt(this.source[this.offset - l + i]) << BigInt(8 * i); } return tryAsU64(num); } /** Decode a fixed-length sequence of bytes. */ bytes(len: N): Bytes { if (len === 0) { return Bytes.zero(len); } this.ensureHasBytes(len); const bytes = this.source.subarray(this.offset, this.offset + len); this.offset += len; return Bytes.fromBlob(bytes, len); } /** Decode a variable-length sequence of bytes. */ bytesBlob(): BytesBlob { const len = this.varU32(); this.ensureHasBytes(len); const bytes = this.source.subarray(this.offset, this.offset + len); this.offset += len; return BytesBlob.blobFrom(bytes); } /** Decode a fixed-length sequence of bits of given length. */ bitVecFixLen(bitLength: number): BitVec { if (bitLength === 0) { return BitVec.empty(0); } const byteLength = Math.ceil(bitLength / 8); const bytes = this.bytes(byteLength); // verify that the remaining bits are zero const emptyBitsStart = bitLength % 8; if (emptyBitsStart > 0) { const lastByte = bytes.raw[byteLength - 1]; const emptyBits = lastByte >> emptyBitsStart; if (emptyBits > 0) { throw new Error("Non-zero bits found in the last byte of bitvec encoding."); } } return BitVec.fromBytes(bytes, bitLength); } /** Decode a variable-length sequence of bits. */ bitVecVarLen(): BitVec { const bitLength = this.varU32(); return this.bitVecFixLen(bitLength); } /** Decode a composite object. */ object(decode: Decode): T { return decode.decode(this); } /** Decode a possibly optional value. */ optional(decode: Decode): T | null { const isSet = this.bool(); if (!isSet) { return null; } return decode.decode(this); } /** Decode a known-length sequence of elements. */ sequenceFixLen(decode: Decode, len: number): T[] { const result = Array(len); for (let i = 0; i < len; i += 1) { result[i] = decode.decode(this); } return result; } /** Decode a variable-length sequence of elements. */ sequenceVarLen(decode: Decode): T[] { const len = this.varU32(); return this.sequenceFixLen(decode, len); } /** * Move the decoding cursor to given offset. * * Note the offset can actually be smaller than the current offset * (i.e. one can go back). */ resetTo(newOffset: number) { if (this.offset < newOffset) { this.skip(newOffset - this.offset); } else { check(newOffset >= 0, "The offset has to be positive"); this.offset = newOffset; } } /** Skip given number of bytes for decoding. */ skip(bytes: number) { this.ensureHasBytes(bytes); this.offset += bytes; } /** * Finish decoding `source` object and make sure there is no data left. * * This method can be called when the entire object that was meant to be * stored in the `source` is now fully decoded and we want to ensure * that there is no extra bytes contained in the `source`. */ finish() { if (this.offset < this.source.length) { throw new Error(`Expecting end of input, yet there are still ${this.source.length - this.offset} bytes left.`); } } private getNum(bytes: number, f: () => T) { this.ensureHasBytes(bytes); const num = f(); this.offset += bytes; return num; } private ensureHasBytes(bytes: number) { check(bytes >= 0, "Negative number of bytes given."); if (this.offset + bytes > this.source.length) { throw new Error( `Attempting to decode more data than there is left. Need ${bytes}, left: ${this.source.length - this.offset}.`, ); } } } declare function decodeVariableLengthExtraBytes(firstByte: number) { check(firstByte >= 0 && firstByte < 256, `Incorrect byte value: ${firstByte}`); for (let i = 0; i < MASKS.length; i++) { if (firstByte >= MASKS[i]) { return 8 - i; } } return 0; } /** Hint for how big the encoded object will be. */ type SizeHint = { /** Number of bytes in the encoding. */ bytes: number; /** Is `bytes` the exact number of bytes that will be used or just a hint? */ isExact: boolean; }; declare function tryAsExactBytes(a: SizeHint): number { check(a.isExact, "The value is not exact size estimation!"); return a.bytes; } declare function addSizeHints(a: SizeHint, b: SizeHint): SizeHint { return { bytes: a.bytes + b.bytes, isExact: a.isExact && b.isExact, }; } /** An encoder for some specific type `T`. */ type Encode = { /** Encode given element of type `T`. */ encode: (encoder: Encoder, elem: T) => void; /** * A hint about size of that type. * * Can be used as an optimization for how many bytes should be allocated for that type. */ sizeHint: SizeHint; }; /** * I had to extend ArrayBuffer type to use resizable ArrayBuffer. * We will be able to remove it when this is merged: https://github.com/microsoft/TypeScript/pull/58573 * And then a new version of TypeScript is released. */ declare global { interface ArrayBufferConstructor { new (length: number, options?: { maxByteLength: number }): ArrayBuffer; } interface ArrayBuffer { resize(length: number): void; } } /** * New encoder options. * * Either provide a destination (needs to be able to fit all the data!) * or hint the expected length of the encoding to avoid re-allocations. */ type Options = | { expectedLength: number; } | { destination: Uint8Array; }; // 10MB /** * JAM encoder. */ declare class Encoder { /** * Create a new encoder either to fill up given `destination` * or with a minimal expected size. */ static create(options?: Options) { if (options !== undefined && "destination" in options) { return new Encoder(options.destination); } const startLength = options?.expectedLength ?? DEFAULT_START_LENGTH; const buffer = new ArrayBuffer(Math.min(MAX_LENGTH, startLength), { maxByteLength: MAX_LENGTH }); const destination = new Uint8Array(buffer); return new Encoder(destination, buffer); } /** * Encode just a single object. * * NOTE that if you need to encode a tuple glueing together outputs * of that function is going to be sub-optimal! * * This is only for one-shot encodings. */ static encodeObject(encode: Encode, object: T, context?: unknown): BytesBlob { const encoder = Encoder.create({ expectedLength: encode.sizeHint.bytes || DEFAULT_START_LENGTH, }); encoder.attachContext(context); encoder.object(encode, object); return encoder.viewResult(); } private offset = 0; private context?: unknown; private readonly dataView: DataView; private constructor( private readonly destination: Uint8Array, private readonly buffer?: ArrayBuffer, ) { if (buffer !== undefined) { this.dataView = new DataView(buffer); } else { this.dataView = new DataView(destination.buffer, destination.byteOffset, destination.byteLength); } } /** * Attach context to the encoder. * * The context object can be used to pass some "global" parameters * down to custom encoders. */ attachContext(context?: unknown) { this.context = context; } /** * Get the encoding context object. */ getContext(): unknown { return this.context; } /** * View the current encoding result. * * Note that the resulting array here, might be shorter than the * underlying `destination`. */ viewResult() { return BytesBlob.blobFrom(this.destination.subarray(0, this.offset)); } /** * Encode a 32-bit integer. * * The encoding will always occupy 4 bytes in little-endian ordering. * Negative numbers are represented as a two-complement. */ i32(num: number) { this.prepareIntegerN(num, 4); this.dataView.setInt32(this.offset, num, true); this.offset += 4; } /** * Encode a 64-bit integer. * * The encoding will always occupy 8 bytes in little-endian ordering. * Negative numbers are represented as a two-complement. */ i64(num: bigint) { const maxNum = 2n ** 64n; // note that despite the actual range of values being within: // `[ - maxNum / 2, maxNum / 2)` // we still allow positive numbers from `[maxNum / 2, maxNum)`. // So it does not matter if the argument is a negative value, // OR if someone just gave us two-complement already. check(num < maxNum, "Only for numbers up to 2**64 - 1"); check(-num <= maxNum / 2n, "Only for numbers down to -2**63"); this.ensureBigEnough(8); this.dataView.setBigInt64(this.offset, num, true); this.offset += 8; } /** * Encode a 24-bit integer. * * The encoding will always occupy 3 bytes in little-endian ordering. * Negative numbers are represented as a two-complement. */ i24(num: number) { this.prepareIntegerN(num, 3); this.dataView.setInt8(this.offset, num & 0xff); this.dataView.setInt16(this.offset + 1, num >> 8, true); this.offset += 3; } /** * Encode a 16-bit integer. * * The encoding will always occupy 2 bytes in little-endian ordering. * Negative numbers are represented as a two-complement. */ i16(num: number) { this.prepareIntegerN(num, 2); this.dataView.setInt16(this.offset, num, true); this.offset += 2; } /** * Encode a 8-bit integer. * * The encoding will always occupy 1 byte in little-endian ordering. * Negative numbers are represented as a two-complement. */ i8(num: number) { this.prepareIntegerN(num, 1); this.dataView.setInt8(this.offset, num); this.offset += 1; } /** * Encode a single boolean discriminator using variable encoding. * * https://graypaper.fluffylabs.dev/#/579bd12/375300375300 */ bool(bool: boolean) { this.varU32(tryAsU32(bool ? 1 : 0)); } /** * Prepare for encoding of a fixed-bytes number. * * * The encoding will always occupy N bytes in little-endian ordering. * Negative numbers are represented as a two-complement. * * https://graypaper.fluffylabs.dev/#/579bd12/36fc0136fc01 */ private prepareIntegerN(num: number, bytesToEncode: 1 | 2 | 3 | 4) { const BITS = 8; const maxNum = 2 ** (BITS * bytesToEncode); // note that despite the actual range of values being within: // `[ - maxNum / 2, maxNum / 2)` // we still allow positive numbers from `[maxNum / 2, maxNum)`. // So it does not matter if the argument is a negative value, // OR if someone just gave us two-complement already. check(num < maxNum, `Only for numbers up to 2**${BITS * bytesToEncode} - 1`); check(-num <= maxNum / 2, `Only for numbers down to -2**${BITS * bytesToEncode - 1}`); this.ensureBigEnough(bytesToEncode); } /** * Encode a 32-bit natural number (compact). * * The encoding can take variable amount of bytes depending on the actual value. * * https://graypaper.fluffylabs.dev/#/579bd12/365202365202 */ varU32(num: U32) { check(num >= 0, "Only for natural numbers."); check(num < 2 ** 32, "Only for numbers up to 2**32"); this.varU64(BigInt(num)); } /** * Encode a 64-bit natural number (compact). * * The encoding can take variable amount of bytes depending on the actual value. * * https://graypaper.fluffylabs.dev/#/579bd12/365202365202 */ varU64(value: bigint) { const num = BigInt(value); // this should be a no-op, but fixes incorrect usage in JS if (num === 0n) { this.ensureBigEnough(1); this.destination[this.offset] = 0; this.offset += 1; return; } // handle the biggest case let maxEncoded = 2n ** (7n * 8n); if (num >= maxEncoded) { this.ensureBigEnough(9); this.destination[this.offset] = 0xff; this.dataView.setBigUint64(this.offset + 1, num, true); this.offset += 9; return; } // let's look for the correct range let minEncoded = maxEncoded >> 7n; for (let l = 7; l >= 0; l -= 1) { if (num >= minEncoded) { this.ensureBigEnough(l + 1); // encode the first byte const maxVal = 2n ** BigInt(8 * l); const byte = BigInt(2 ** 8 - 2 ** (8 - l)) + num / maxVal; this.destination[this.offset] = Number(byte) & 0xff; this.offset += 1; // now encode the rest of bytes of len `l` let rest = num % maxVal; for (let i = this.offset; i < this.offset + l; i += 1) { this.destination[i] = Number(rest & 0xffn); rest >>= 8n; } this.offset += l; return; } // move one power down maxEncoded = minEncoded; minEncoded >>= 7n; } throw new Error(`Unhandled number encoding: ${num}`); } /** * Encode a variable-length sequence of bytes given as [`BytesBlob`]. * * That's just a convenience wrapper for [`blob`] function. */ bytesBlob(blob: BytesBlob) { this.blob(blob.raw); } /** * Encode a variable-length sequence of bytes. * * The data is placed in the destination, but with an * extra length-discriminator (see [`u32`]) encoded in a compact form. * * https://graypaper.fluffylabs.dev/#/579bd12/372600372600 */ blob(blob: Uint8Array) { // first encode the length this.varU32(tryAsU32(blob.length)); // now encode the bytes this.ensureBigEnough(blob.length); this.destination.set(blob, this.offset); this.offset += blob.length; } /** * Encode a fixed-length sequence of bytes. * * The data is simply copied to the destination * without any discriminator (i.e. no length prefix). * * https://graypaper.fluffylabs.dev/#/579bd12/371100371100 * */ bytes(bytes: Bytes) { this.ensureBigEnough(bytes.length); this.destination.set(bytes.raw, this.offset); this.offset += bytes.length; } /** * Encode a bit vector with known length. * * The bits are packed into bytes and just placed as-is in the destination. * https://graypaper.fluffylabs.dev/#/579bd12/378000378000 */ bitVecFixLen(bitvec: BitVec) { const bytes = bitvec.raw; this.bytes(Bytes.fromBlob(bytes, bytes.length)); } /** * Encode a bit vector with variable length. * * A bit-length discriminator (varU32) is placed before the packed bit content. * https://graypaper.fluffylabs.dev/#/579bd12/378200378200 */ bitVecVarLen(bitvec: BitVec) { const len = bitvec.bitLength; this.varU32(tryAsU32(len)); this.bitVecFixLen(bitvec); } /** * Encode a composite object. */ object(encode: Encode, element: T) { this.applySizeHint(encode); encode.encode(this, element); } /** * Encode a potentially empty value. * * A 0 or 1 is placed before the element to indicate it's presence. * https://graypaper.fluffylabs.dev/#/579bd12/375f00375f00 */ optional(encode: Encode, element?: T | null) { const isSet = element !== null && element !== undefined; this.bool(isSet); if (isSet) { this.applySizeHint(encode); encode.encode(this, element); } } /** * Encode a fixed-length sequence of elements of some type. * * https://graypaper.fluffylabs.dev/#/579bd12/371100371100 */ sequenceFixLen(encode: Encode, elements: readonly T[]) { this.applySizeHint(encode, elements.length); for (const e of elements) { encode.encode(this, e); } } /** * Encode a variable-length sequence of elements of some type. * * A length discriminator is placed before the concatentation of encodings of all the elements. * * https://graypaper.fluffylabs.dev/#/579bd12/374400374400 */ sequenceVarLen(encode: Encode, elements: readonly T[]) { check(elements.length <= 2 ** 32, "Wow, that's a nice long sequence you've got here."); this.varU32(tryAsU32(elements.length)); this.sequenceFixLen(encode, elements); } private applySizeHint(encode: Encode, multiply = 1) { const sizeHint = encode.sizeHint.bytes; if (sizeHint > 0 && multiply > 0) { this.ensureBigEnough(sizeHint * multiply, { silent: true }); } } /** * Expand the destination to fit given length. * * The `silent` flag can be set when we are just giving a size hint about * a composite type being encoded. * In such case we are not sure if we are going to use all of the bytes from the hint, * so going over `MAX_LENGTH` or destination is not an error here. * When subsequent fields of a composite object will be encode they call this function * anyway, so if we really should throw we will. */ private ensureBigEnough(length: number, options: { silent: boolean } = { silent: false }) { check(length >= 0, "Negative length given"); const newLength = this.offset + length; if (newLength > MAX_LENGTH) { if (options.silent) { return; } throw new Error(`The encoded size would reach the maximum of ${MAX_LENGTH}.`); } if (newLength > this.destination.length) { // we can try to resize the underlying buffer if (this.buffer !== undefined) { // make sure we at least double the size of the buffer every time. const minExtend = Math.max(newLength, this.buffer.byteLength << 1); // but we must never exceed the max length. this.buffer.resize(Math.min(MAX_LENGTH, minExtend)); } // and then check again if (newLength > this.destination.length) { if (options.silent) { return; } throw new Error( `Not enough space in the destination array. Needs ${newLength}, has ${this.destination.length}.`, ); } } } } /** An extension of a codec that can skip given value. */ type Skip = { /** Skip all bytes occupied by the value. */ skip: (s: Skipper) => void; }; /** Wrapper for `Decoder` that can skip bytes of fields in the data buffer instead of decoding them. */ declare class Skipper { constructor(public readonly decoder: Decoder) {} /** Skip U64/I64. */ u64 = () => this.decoder.skip(8); /** Skip U32/I32. */ u32 = () => this.decoder.skip(4); /** Skip U24/I24. */ u24 = () => this.decoder.skip(3); /** Skip U16/I16. */ u16 = () => this.decoder.skip(2); /** Skip U8/I8. */ u8 = () => this.decoder.skip(1); /** Skip boolean. */ bool = () => this.decoder.skip(1); /** Skip variable-length U32. */ varU32 = () => this.varU64(); /** Skip variable-length U64. */ varU64() { const firstByte = this.decoder.u8(); const l = decodeVariableLengthExtraBytes(firstByte); this.decoder.skip(l); } /** Skip fixed-length bytes. */ bytes(len: N) { this.decoder.skip(len); } /** Skip variable-length bytes blob. */ bytesBlob() { const len = this.decoder.varU32(); this.decoder.skip(len); } /** Skip fixed-length bit vector. */ bitVecFixLen(bitLength: number) { this.decoder.skip(Math.ceil(bitLength / 8)); } /** Skip variable-length bit vector. */ bitVecVarLen() { const len = this.decoder.varU32(); this.bitVecFixLen(len); } /** Skip a composite object. */ object(decode: Skip) { decode.skip(this); } /** Skip a potentially optional value. */ optional(decode: Skip) { const isSet = this.decoder.bool(); if (isSet) { decode.skip(this); } } /** Skip fixed-length sequence. */ sequenceFixLen(decode: Skip, len: number) { for (let i = 0; i < len; i += 1) { decode.skip(this); } } /** Skip variable-length sequence. */ sequenceVarLen(decode: Skip) { const len = this.decoder.varU32(); return this.sequenceFixLen(decode, len); } } type LengthRange = { /** Inclusive value of minimal length of the sequence. */ minLength: number; /** Inclusive value of maximal length of the sequence. */ maxLength: number; }; /** Validate that given sequence length is within expected range. */ declare function validateLength(range: LengthRange, length: number, context: string) { if (length < range.minLength) { throw new Error(`${context}: length is below minimal. ${length} < ${range.minLength}`); } if (length > range.maxLength) { throw new Error(`${context}: length is above maximal. ${length} > ${range.maxLength}`); } } /** A caching wrapper for either object or sequence item. */ declare class ViewField implements ViewField { private cachedValue: T | undefined; private cachedView: V | undefined; private cachedBlob: BytesBlob | undefined; constructor( private readonly getView: () => V, private readonly getValue: () => T, private readonly getEncoded: () => BytesBlob, ) {} /** Fully decode the underlying data. */ materialize(): T { if (this.cachedValue === undefined) { this.cachedValue = this.getValue(); } return this.cachedValue; } /** Decode just the view of the underlying data. */ view(): V { if (this.cachedView === undefined) { this.cachedView = this.getView(); } return this.cachedView; } /** Return an encoded value of that object. */ encoded(): BytesBlob { if (this.cachedBlob === undefined) { this.cachedBlob = this.getEncoded(); } return this.cachedBlob; } } /** * A base class for all the lazy views. */ declare abstract class ObjectView { /** Keys of all descriptors. */ private readonly descriptorsKeys: (keyof T)[]; /** Already decoded items. */ private readonly cache = new Map>(); /** Initial decoder state. */ private readonly initialDecoderOffset; /** Last decoded index that we have in the cache already. */ private lastDecodedFieldIdx = -1; constructor( private readonly decoder: Decoder, protected readonly materializedConstructor: ClassConstructor, protected readonly descriptors: DescriptorRecord, ) { this.descriptorsKeys = Object.keys(descriptors) as (keyof T)[]; this.initialDecoderOffset = decoder.bytesRead(); } /** * Create a concrete instance of `T` by decoding all of the remaining * fields that are not yet there in the cache. */ materialize(): T { const fields = this.descriptorsKeys; const constructorParams = Object.fromEntries(fields.map((key) => [key, this.get(key).materialize()])); return this.materializedConstructor.create(constructorParams as CodecRecord); } /** Return an encoded value of that object. */ encoded(): BytesBlob { const fields = this.descriptorsKeys; // edge case? if (fields.length === 0) { return BytesBlob.blobFromNumbers([]); } if (this.lastDecodedFieldIdx < fields.length - 1) { const lastField = fields[fields.length - 1]; this.decodeUpTo(lastField); } // now our `this.d` points to the end of the object, so we can use // it to determine where is the end of the encoded data. return BytesBlob.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset, this.decoder.bytesRead())); } /** * Get the value of the field from cache or decode it. */ protected get(field: K): ViewField { const cached: ViewField | undefined = this.cache.get(field); if (cached !== undefined) { return cached as ViewField; } return this.decodeUpTo(field); } private decodeUpTo(field: K): ViewField { const index = this.descriptorsKeys.indexOf(field); const lastField = this.descriptorsKeys[this.lastDecodedFieldIdx]; check( this.lastDecodedFieldIdx < index, `Unjustified call to 'decodeUpTo' - the index ($Blobindex}, ${String(field)}) is already decoded (${this.lastDecodedFieldIdx}, ${String(lastField)}). `, ); let lastItem = this.cache.get(lastField); const skipper = new Skipper(this.decoder); // now skip all of the fields and further populate the cache. for (let i = this.lastDecodedFieldIdx + 1; i <= index; i++) { // create new cached prop const fieldDecoder = skipper.decoder.clone(); const field = this.descriptorsKeys[i]; const type = this.descriptors[field as keyof DescriptorRecord]; lastItem = new ViewField( () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()), ); // skip the field type.skip(skipper); // cache data this.cache.set(field, lastItem); this.lastDecodedFieldIdx = i; } const last: ViewField = ensure( lastItem, lastItem !== undefined, "Last item must be set, since the loop turns at least once.", ); return last; } } /** * A lazy-evaluated decoder of a sequence. * * Instead of decoding/allocating the whole collection at once, * you can wrap the decoder into `SequenceView` to do it lazily. * * Collection items can be decoded fully (materialized) or can * just be requested as views. */ declare class SequenceView { /** Length of the sequence (either already decoded or given if fixed). */ public readonly length: number; /** Already decoded items. */ private readonly cache = new Map>(); /** Initial decoder state. */ private readonly initialDecoderOffset; /** Last decoded index that we have in the cache already. */ private lastDecodedIdx = -1; constructor( private readonly decoder: Decoder, private readonly descriptor: Descriptor, fixedLength?: number, ) { this.initialDecoderOffset = this.decoder.bytesRead(); this.length = fixedLength ?? decoder.varU32(); } /** Iterate over field elements of the view. */ *[Symbol.iterator]() { for (let i = 0; i < this.length; i++) { const val = this.get(i); const v: ViewField = ensure( val, val !== undefined, "We are within 0..this.length so all items are defined.", ); yield v; } } /** Create an array of all views mapped to some particular value. */ map(cb: (v: ViewField) => R): R[] { const res = new Array(this.length); let i = 0; for (const v of this) { res[i] = cb(v); i++; } return res; } /** * Retrieve item at given index. * * The item can be either materialized or it's view can be requested. */ get(index: number): ViewField | undefined { if (index >= this.length) { return undefined; } const v = this.cache.get(index); if (v !== undefined) { return v; } // populate the cache return this.decodeUpTo(index); } /** Return an encoded value of that object. */ encoded(): BytesBlob { // edge case? if (this.length === 0) { return BytesBlob.blobFromNumbers([]); } if (this.lastDecodedIdx < this.length - 1) { this.decodeUpTo(this.length - 1); } // now our `this.decoder` points to the end of the object, so we can use // it to determine where is the end of the encoded data. return BytesBlob.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset, this.decoder.bytesRead())); } private decodeUpTo(index: number): ViewField { check( this.lastDecodedIdx < index, `Unjustified call to 'decodeUpTo' - the index (${index}) is already decoded (${this.lastDecodedIdx}).`, ); let lastItem = this.cache.get(this.lastDecodedIdx); const skipper = new Skipper(this.decoder); // now skip all of the fields and further populate the cache. for (let i = this.lastDecodedIdx + 1; i <= index; i++) { // create new cached prop const fieldDecoder = skipper.decoder.clone(); const type = this.descriptor; lastItem = new ViewField( () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()), ); // skip the field type.skip(skipper); // cache data this.cache.set(i, lastItem); this.lastDecodedIdx = i; } const last: ViewField = ensure( lastItem, lastItem !== undefined, "Last item must be set, since the loop turns at least once.", ); return last; } } /** * For the size hint for encoding typical dictionaries. * TODO [ToDr] [opti] This value should be updated when we run some real-data bechmarks. */ declare const TYPICAL_DICTIONARY_LENGTH = 32; /** * A full codec type, i.e. the `Encode` and `Decode`. */ type Codec = Encode & Decode; /** * Type descriptor definition. * * The type descriptor can encode & decode given type `T`, but * also have a `name` and a byte-size hint. * * Descriptors can be composed to form more complex typings. */ declare class Descriptor implements Codec, Skip { /** A "lightweight" version of the object. */ public readonly View: Descriptor; /** New descriptor with specialized `View`. */ public static withView( name: string, sizeHint: SizeHint, encode: Descriptor["encode"], decode: Descriptor["decode"], skip: Descriptor["skip"], view: Descriptor, ) { return new Descriptor(name, sizeHint, encode, decode, skip, view); } /** Create a new descriptor without a specialized `View`. */ public static new( name: string, sizeHint: SizeHint, encode: Descriptor["encode"], decode: Descriptor["decode"], skip: Descriptor["skip"], ) { return new Descriptor(name, sizeHint, encode, decode, skip, null); } private constructor( /** Descriptive name of the coded data. */ public readonly name: string, /** A byte size hint for encoded data. */ public readonly sizeHint: SizeHint, /** Encoding function. */ public readonly encode: (e: Encoder, elem: T) => void, /** Decoding function. */ public readonly decode: (d: Decoder) => T, /** Skipping function. */ public readonly skip: (s: Skipper) => void, /** view object. It can be `null` iff T===V. */ view: Descriptor | null, ) { // We cast here to make sure that the field is always set. this.View = view ?? (this as unknown as Descriptor); } /** * Extract an encoded version of this type from the decoder. * * This function skips the object instead of decoding it, * allowing to retrieve the encoded portion of the object from `Decoder`. */ public skipEncoded(decoder: Decoder) { const initBytes = decoder.bytesRead(); this.skip(new Skipper(decoder)); const endBytes = decoder.bytesRead(); return BytesBlob.blobFrom(decoder.source.subarray(initBytes, endBytes)); } /** Return a new descriptor that converts data into some other type. */ public convert(input: (i: F) => T, output: (i: T) => F): Descriptor { return new Descriptor( this.name, this.sizeHint, (e: Encoder, elem: F) => this.encode(e, input(elem)), (d: Decoder) => output(this.decode(d)), this.skip, this.View, ); } /** Safely cast the descriptor value to a opaque type. */ public asOpaque(): Descriptor>, V> { return this.convert( (i) => seeThrough(i), (o) => asOpaqueType>(o), ); } } /** * Convert a descriptor for regular array into readonly one. * * NOTE: for performance reasons we assume that every `readonly T[]` is `T[]`, * and the `readonly` annotation is there just to prevent altering it. * It's not true in a general case, but should be good enough for us. * */ declare function readonlyArray(desc: Descriptor): Descriptor { return desc.convert( (x) => { check(Array.isArray(x), `Non-arrays are not supported as 'readonly': got ${typeof x}, ${x}`); // NOTE [ToDr] This assumption is incorrect in general, but it's documented // in the general note. We avoid `.slice()` the array for performance reasons. return x as T[]; }, (x) => x, ); } /** Infer the type that is described by given descriptor `T` */ type DescribedBy = T extends Descriptor ? V : never; /** * Converts a class `T` into an object with the same fields as the class. */ type CodecRecord = { [K in PropertyKeys]: T[K]; }; /** * `Descriptor` of a complex type of some class with a bunch of public fields. */ type DescriptorRecord = { [K in PropertyKeys]: Descriptor; }; /** Only keys that contain properties, not methods. */ type PropertyKeys = { // biome-ignore lint/complexity/noBannedTypes: We want to skip any function-like types here. [K in Extract]: T[K] extends Function ? never : K; }[Extract]; /** A constructor of basic data object that takes a `Record`. */ type ClassConstructor = { name: string; create: (o: CodecRecord) => T; }; /** Descriptors for data types that can be read/written from/to codec. */ declare namespace codec$1 { /** Fixed-length bytes sequence. */ export const bytes = (() => { const cache = new Map(); return (len: N): Descriptor> => { let ret = cache.get(len) as Descriptor>; if (ret === undefined) { ret = Descriptor.new>( `Bytes<${len}>`, exactHint(len), (e, v) => e.bytes(v), (d) => d.bytes(len), (s) => s.bytes(len), ); cache.set(len, ret); } return ret; }; })(); /** Variable-length U32. */ export const varU32 = Descriptor.new( "var_u32", { bytes: 4, isExact: false }, (e, v) => e.varU32(v), (d) => d.varU32(), (d) => d.varU32(), ); /** Variable-length U64. */ export const varU64 = Descriptor.new( "var_u64", { bytes: 8, isExact: false }, (e, v) => e.varU64(v), (d) => d.varU64(), (d) => d.varU64(), ); /** Unsigned 64-bit number. */ export const u64 = Descriptor.withView>( "u64", exactHint(8), (e, v) => e.i64(v), (d) => d.u64(), (d) => d.u64(), codec.bytes(8), ); /** Unsigned 32-bit number. */ export const u32 = Descriptor.withView>( "u32", exactHint(4), (e, v) => e.i32(v), (d) => d.u32(), (d) => d.u32(), codec.bytes(4), ); /** Unsigned 24-bit number. */ export const u24 = Descriptor.withView>( "u24", exactHint(3), (e, v) => e.i24(v), (d) => d.u24(), (d) => d.u24(), codec.bytes(3), ); /** Unsigned 16-bit number. */ export const u16 = Descriptor.withView>( "u16", exactHint(2), (e, v) => e.i16(v), (d) => d.u16(), (d) => d.u16(), codec.bytes(2), ); /** Unsigned 8-bit number. */ export const u8 = Descriptor.new( "u8", exactHint(1), (e, v) => e.i8(v), (d) => d.u8(), (d) => d.u8(), ); /** Signed 64-bit number. */ export const i64 = Descriptor.withView>( "u64", exactHint(8), (e, v) => e.i64(v), (d) => d.i64(), (s) => s.u64(), codec.bytes(8), ); /** Signed 32-bit number. */ export const i32 = Descriptor.withView>( "i32", exactHint(4), (e, v) => e.i32(v), (d) => d.i32(), (s) => s.u32(), codec.bytes(4), ); /** Signed 24-bit number. */ export const i24 = Descriptor.withView>( "i24", exactHint(3), (e, v) => e.i24(v), (d) => d.i24(), (s) => s.u24(), codec.bytes(3), ); /** Signed 16-bit number. */ export const i16 = Descriptor.withView>( "i16", exactHint(2), (e, v) => e.i16(v), (d) => d.i16(), (s) => s.u16(), codec.bytes(2), ); /** Signed 8-bit number. */ export const i8 = Descriptor.new( "i8", exactHint(1), (e, v) => e.i8(v), (d) => d.i8(), (s) => s.u8(), ); /** 1-byte boolean value. */ export const bool = Descriptor.new( "bool", exactHint(1), (e, v) => e.bool(v), (d) => d.bool(), (s) => s.bool(), ); /** Variable-length bytes blob. */ export const blob = Descriptor.new( "BytesBlob", { bytes: TYPICAL_SEQUENCE_LENGTH, isExact: false }, (e, v) => e.bytesBlob(v), (d) => d.bytesBlob(), (s) => s.bytesBlob(), ); /** String encoded as variable-length bytes blob. */ export const string = Descriptor.withView( "string", { bytes: TYPICAL_SEQUENCE_LENGTH, isExact: false }, (e, v) => e.bytesBlob(BytesBlob.blobFrom(new TextEncoder().encode(v))), (d) => new TextDecoder("utf8", { fatal: true }).decode(d.bytesBlob().raw), (s) => s.bytesBlob(), codec.blob, ); /** Variable-length bit vector. */ export const bitVecVarLen = Descriptor.new( "BitVec[?]", { bytes: TYPICAL_SEQUENCE_LENGTH >>> 3, isExact: false }, (e, v) => e.bitVecVarLen(v), (d) => d.bitVecVarLen(), (s) => s.bitVecVarLen(), ); /** Fixed-length bit vector. */ export const bitVecFixLen = (bitLen: number) => Descriptor.new( `BitVec[${bitLen}]`, exactHint(bitLen >>> 3), (e, v) => e.bitVecFixLen(v), (d) => d.bitVecFixLen(bitLen), (s) => s.bitVecFixLen(bitLen), ); /** Optionality wrapper for given type. */ export const optional = (type: Descriptor): Descriptor => { const self = Descriptor.new( `Optional<${type.name}>`, addSizeHints({ bytes: 1, isExact: false }, type.sizeHint), (e, v) => e.optional(type, v), (d) => d.optional(type), (s) => s.optional(type), ); if (hasUniqueView(type)) { return Descriptor.withView( self.name, self.sizeHint, self.encode, self.decode, self.skip, codec.optional(type.View), ); } return self; }; export type SequenceVarLenOptions = LengthRange & { typicalLength?: number; }; /** Variable-length sequence of given type. */ export const sequenceVarLen = ( type: Descriptor, options: SequenceVarLenOptions = { minLength: 0, maxLength: 2 ** 32 - 1, }, ) => { const name = `Sequence<${type.name}>[?]`; const typicalLength = options.typicalLength ?? TYPICAL_SEQUENCE_LENGTH; return Descriptor.withView>( name, { bytes: typicalLength * type.sizeHint.bytes, isExact: false }, (e, v) => { validateLength(options, v.length, name); e.sequenceVarLen(type, v); }, (d) => { const len = d.varU32(); validateLength(options, len, name); return d.sequenceFixLen(type, len); }, (s) => { const len = s.decoder.varU32(); validateLength(options, len, name); return s.sequenceFixLen(type, len); }, sequenceViewVarLen(type, options), ); }; /** Fixed-length sequence of given type. */ export const sequenceFixLen = (type: Descriptor, len: number) => Descriptor.withView>( `Sequence<${type.name}>[${len}]`, { bytes: len * type.sizeHint.bytes, isExact: type.sizeHint.isExact }, (e, v) => e.sequenceFixLen(type, v), (d) => d.sequenceFixLen(type, len), (s) => s.sequenceFixLen(type, len), sequenceViewFixLen(type, { fixedLength: len }), ); /** Small dictionary codec. */ export const dictionary = ( key: Descriptor, value: Descriptor, { sortKeys, fixedLength, }: { sortKeys: (a: K, b: K) => number; fixedLength?: number; }, ): Descriptor, Map> => { const self = Descriptor.new>( `Dictionary<${key.name}, ${value.name}>[${fixedLength ?? "?"}]`, { bytes: fixedLength !== undefined ? fixedLength * addSizeHints(key.sizeHint, value.sizeHint).bytes : TYPICAL_DICTIONARY_LENGTH * (addSizeHints(key.sizeHint, value.sizeHint).bytes ?? 0), isExact: fixedLength !== undefined ? key.sizeHint.isExact && value.sizeHint.isExact : false, }, (e, v) => { const data = Array.from(v.entries()); data.sort((a, b) => sortKeys(a[0], b[0])); // length prefix if (fixedLength === undefined || fixedLength === 0) { e.varU32(tryAsU32(data.length)); } for (const [k, v] of data) { key.encode(e, k); value.encode(e, v); } }, (d) => { const map = new Map(); const len = fixedLength ?? d.varU32(); let prevKey = null as null | K; for (let i = 0; i < len; i += 1) { const k = key.decode(d); const v = value.decode(d); if (map.has(k)) { throw new Error(`Duplicate item in the dictionary encoding: "${k}"!`); } if (prevKey !== null && sortKeys(prevKey, k) >= 0) { throw new Error(`The keys in dictionary encoding are not sorted "${prevKey}" >= "${k}"!`); } map.set(k, v); prevKey = k; } return map; }, (s) => { const len = fixedLength ?? s.decoder.varU32(); s.sequenceFixLen(key, len); s.sequenceFixLen(value, len); }, ); if (hasUniqueView(value)) { return Descriptor.withView( self.name, self.sizeHint, self.encode, self.decode, self.skip, codec.dictionary(key, value.View, { sortKeys, fixedLength }), ); } return self; }; /** Custom encoding / decoding logic. */ export const custom = ( { name, sizeHint = { bytes: 0, isExact: false }, }: { name: string; sizeHint: SizeHint; }, encode: (e: Encoder, x: T) => void, decode: (d: Decoder) => T, skip: (s: Skipper) => void, ): Descriptor => Descriptor.new(name, sizeHint, encode, decode, skip); /** Choose a descriptor depending on the encoding/decoding context. */ export const select = ( { name, sizeHint, }: { name: string; sizeHint: SizeHint; }, chooser: (ctx: unknown | null) => Descriptor, ): Descriptor => Descriptor.withView( name, sizeHint, (e, x) => chooser(e.getContext()).encode(e, x), (d) => chooser(d.getContext()).decode(d), (s) => chooser(s.decoder.getContext()).skip(s), chooser(null).View, ); /** * A descriptor for a more complex POJO. * * This descriptor is very similar to `Class`, but it DOES NOT maintain the * prototype chain of the resulting object - we only care about the shape of * the object here. */ export const object = ( descriptors: SimpleDescriptorRecord, name = "object", create: (o: CodecRecord) => T = (o) => o as T, ) => { return Class({ name, create }, descriptors); }; /** * A descriptor for a more complex class type. * * The resulting descriptor is able to encode & decode all of the public fields of * the class, given the map of descriptors for each one of them. * * The resulting decoded object will be an instance of given `Class` unlike simpler, * shape-based `object` method. */ export const Class = = DescriptorRecord>( Class: ClassConstructor, descriptors: D, ): Descriptor> => { // Calculate a size hint for this class. let sizeHint = exactHint(0); forEachDescriptor(descriptors, (_k, val) => { sizeHint = addSizeHints(sizeHint, val.sizeHint); }); const skipper = (s: Skipper) => { // optimized case for fixed size complex values. if (sizeHint.isExact) { return s.decoder.skip(sizeHint.bytes); } forEachDescriptor(descriptors, (_key, descriptor) => { descriptor.skip(s); }); }; const view = objectView(Class, descriptors, sizeHint, skipper); // and create the descriptor for the entire class. return Descriptor.withView>( Class.name, sizeHint, (e, t) => { forEachDescriptor(descriptors, (key, descriptor) => { const value = t[key]; descriptor.encode(e, value); }); }, (d) => { const constructorParams: OptionalRecord = {}; forEachDescriptor(descriptors, (key, descriptor) => { const value = descriptor.decode(d); constructorParams[key] = value; }); return Class.create(constructorParams as CodecRecord); }, skipper, view, ); }; } /** Typesafe iteration of every descriptor in the record object. */ declare function forEachDescriptor( descriptors: DescriptorRecord, f: >(key: K, val: Descriptor) => void, ) { for (const key in descriptors) { if (typeof key === "string" && key in descriptors) { const k = key as keyof DescriptorRecord; f(k, descriptors[k]); } } } type index$4_ClassConstructor = ClassConstructor; type index$4_Codec = Codec; type index$4_CodecRecord = CodecRecord; type index$4_Decode = Decode; type index$4_Decoder = Decoder; declare const index$4_Decoder: typeof Decoder; type index$4_DescribedBy = DescribedBy; type index$4_Descriptor = Descriptor; declare const index$4_Descriptor: typeof Descriptor; type index$4_DescriptorRecord = DescriptorRecord; type index$4_Encode = Encode; type index$4_Encoder = Encoder; declare const index$4_Encoder: typeof Encoder; type index$4_LengthRange = LengthRange; type index$4_ObjectView = ObjectView; declare const index$4_ObjectView: typeof ObjectView; type index$4_Options = Options; type index$4_PropertyKeys = PropertyKeys; type index$4_SequenceView = SequenceView; declare const index$4_SequenceView: typeof SequenceView; type index$4_SizeHint = SizeHint; declare const index$4_TYPICAL_DICTIONARY_LENGTH: typeof TYPICAL_DICTIONARY_LENGTH; declare const index$4_addSizeHints: typeof addSizeHints; declare const index$4_decodeVariableLengthExtraBytes: typeof decodeVariableLengthExtraBytes; declare const index$4_forEachDescriptor: typeof forEachDescriptor; declare const index$4_readonlyArray: typeof readonlyArray; declare const index$4_tryAsExactBytes: typeof tryAsExactBytes; declare const index$4_validateLength: typeof validateLength; declare namespace index$4 { export { type index$4_ClassConstructor as ClassConstructor, type index$4_Codec as Codec, type index$4_CodecRecord as CodecRecord, type index$4_Decode as Decode, index$4_Decoder as Decoder, type index$4_DescribedBy as DescribedBy, index$4_Descriptor as Descriptor, type index$4_DescriptorRecord as DescriptorRecord, type index$4_Encode as Encode, index$4_Encoder as Encoder, type index$4_LengthRange as LengthRange, index$4_ObjectView as ObjectView, type index$4_Options as Options, type index$4_PropertyKeys as PropertyKeys, index$4_SequenceView as SequenceView, type index$4_SizeHint as SizeHint, index$4_TYPICAL_DICTIONARY_LENGTH as TYPICAL_DICTIONARY_LENGTH, index$4_addSizeHints as addSizeHints, index$5 as bytes, codec$1 as codec, index$4_decodeVariableLengthExtraBytes as decodeVariableLengthExtraBytes, index$4_forEachDescriptor as forEachDescriptor, index$4_readonlyArray as readonlyArray, index$4_tryAsExactBytes as tryAsExactBytes, index$4_validateLength as validateLength }; } declare enum ProgramDecoderError { InvalidProgramError = 0, } declare class ProgramDecoder { private code: Uint8Array; private mask: Mask; private jumpTable: JumpTable; constructor(rawProgram: Uint8Array) { const { code, mask, jumpTable, jumpTableItemLength } = this.decodeProgram(rawProgram); this.code = new Uint8Array(code); this.mask = new Mask(mask); this.jumpTable = new JumpTable(jumpTableItemLength, jumpTable); } private decodeProgram(program: Uint8Array) { const decoder = Decoder.fromBlob(program); // number of items in the jump table const jumpTableLength = decoder.varU32(); // how many bytes are used to encode a single item of the jump table const jumpTableItemLength = decoder.u8(); // the length of the code (in bytes). const codeLength = decoder.varU32(); const jumpTableLengthInBytes = jumpTableLength * jumpTableItemLength; const jumpTable = decoder.bytes(jumpTableLengthInBytes).raw; const code = decoder.bytes(codeLength).raw; const mask = decoder.bitVecFixLen(codeLength); decoder.finish(); return { mask, code, jumpTableItemLength, jumpTable, }; } getMask() { return this.mask; } getCode() { return this.code; } getJumpTable() { return this.jumpTable; } /** https://graypaper.fluffylabs.dev/#/68eaa1f/23f400234701?v=0.6.4 */ static deblob(program: Uint8Array): Result$2 { try { return Result.ok(new ProgramDecoder(program)); } catch (e) { logger.error(`Invalid program: ${e}`); return Result.error(ProgramDecoderError.InvalidProgramError); } } } /** * Inner status codes for the PVM * * https://graypaper.fluffylabs.dev/#/85129da/2cae022cae02?v=0.6.3 */ declare enum Status { OK = 255, HALT = 0, PANIC = 1, FAULT = 2, HOST = 3, OOG = 4, } type InterpreterOptions = { useSbrkGas?: boolean; ignoreInstructionGas?: boolean; }; declare class Interpreter { private readonly useSbrkGas: boolean; private readonly ignoreInstructionGas: boolean; private registers = new Registers(); private code: Uint8Array = new Uint8Array(); private mask = Mask.empty(); private pc = 0; private gas = gasCounter(tryAsGas(0)); private initialGas = gasCounter(tryAsGas(0)); private argsDecoder: ArgsDecoder; private threeRegsDispatcher: ThreeRegsDispatcher; private twoRegsOneImmDispatcher: TwoRegsOneImmDispatcher; private twoRegsDispatcher: TwoRegsDispatcher; private oneRegOneImmOneOffsetDispatcher: OneRegOneImmOneOffsetDispatcher; private twoRegsOneOffsetDispatcher: TwoRegsOneOffsetDispatcher; private oneOffsetDispatcher: OneOffsetDispatcher; private oneRegOneImmDispatcher: OneRegOneImmDispatcher; private instructionResult = new InstructionResult(); private memory = new Memory(); private twoImmsDispatcher: TwoImmsDispatcher; private oneRegTwoImmsDispatcher: OneRegTwoImmsDispatcher; private noArgsDispatcher: NoArgsDispatcher; private twoRegsTwoImmsDispatcher: TwoRegsTwoImmsDispatcher; private oneImmDispatcher: OneImmDispatcher; private oneRegOneExtImmDispatcher: OneRegOneExtImmDispatcher; private status = Status.OK; private argsDecodingResults = createResults(); private basicBlocks: BasicBlocks; private jumpTable = JumpTable.empty(); constructor({ useSbrkGas = false, ignoreInstructionGas = false }: InterpreterOptions = {}) { this.useSbrkGas = useSbrkGas; this.ignoreInstructionGas = ignoreInstructionGas; this.argsDecoder = new ArgsDecoder(); this.basicBlocks = new BasicBlocks(); const mathOps = new MathOps(this.registers); const shiftOps = new ShiftOps(this.registers); const bitOps = new BitOps(this.registers); const booleanOps = new BooleanOps(this.registers); const moveOps = new MoveOps(this.registers); const branchOps = new BranchOps(this.registers, this.instructionResult, this.basicBlocks); const loadOps = new LoadOps(this.registers, this.memory, this.instructionResult); const storeOps = new StoreOps(this.registers, this.memory, this.instructionResult); const noArgsOps = new NoArgsOps(this.instructionResult); const dynamicJumpOps = new DynamicJumpOps(this.registers, this.jumpTable, this.instructionResult, this.basicBlocks); const hostCallOps = new HostCallOps(this.instructionResult); const memoryOps = new MemoryOps(this.registers, this.memory, this.instructionResult); const bitRotationOps = new BitRotationOps(this.registers); this.threeRegsDispatcher = new ThreeRegsDispatcher(mathOps, shiftOps, bitOps, booleanOps, moveOps, bitRotationOps); this.twoRegsOneImmDispatcher = new TwoRegsOneImmDispatcher( mathOps, shiftOps, bitOps, booleanOps, moveOps, storeOps, loadOps, bitRotationOps, ); this.twoRegsDispatcher = new TwoRegsDispatcher(moveOps, memoryOps, bitOps, bitRotationOps); this.oneRegOneImmOneOffsetDispatcher = new OneRegOneImmOneOffsetDispatcher(branchOps, loadOps); this.twoRegsOneOffsetDispatcher = new TwoRegsOneOffsetDispatcher(branchOps); this.oneOffsetDispatcher = new OneOffsetDispatcher(branchOps); this.oneRegOneImmDispatcher = new OneRegOneImmDispatcher(loadOps, storeOps, dynamicJumpOps); this.twoImmsDispatcher = new TwoImmsDispatcher(storeOps); this.oneRegTwoImmsDispatcher = new OneRegTwoImmsDispatcher(storeOps); this.noArgsDispatcher = new NoArgsDispatcher(noArgsOps); this.twoRegsTwoImmsDispatcher = new TwoRegsTwoImmsDispatcher(loadOps, dynamicJumpOps); this.oneImmDispatcher = new OneImmDispatcher(hostCallOps); this.oneRegOneExtImmDispatcher = new OneRegOneExtImmDispatcher(loadOps); } reset(rawProgram: Uint8Array, pc: number, gas: Gas, maybeRegisters?: Registers, maybeMemory?: Memory) { const programDecoder = new ProgramDecoder(rawProgram); this.code = programDecoder.getCode(); this.mask = programDecoder.getMask(); this.jumpTable.copyFrom(programDecoder.getJumpTable()); this.pc = pc; this.gas = gasCounter(gas); this.initialGas = gasCounter(gas); this.status = Status.OK; this.argsDecoder.reset(this.code, this.mask); this.basicBlocks.reset(this.code, this.mask); this.instructionResult.reset(); if (maybeRegisters !== undefined) { this.registers.copyFrom(maybeRegisters); } else { this.registers.reset(); } if (maybeMemory !== undefined) { this.memory.copyFrom(maybeMemory); } else { this.memory.reset(); } } printProgram() { const p = assemblify(this.code, this.mask); console.table(p); return p; } runProgram() { while (this.nextStep() === Status.OK) {} } nextStep() { // we are being resumed from a host call, assume all good. if (this.status === Status.HOST) { this.status = Status.OK; this.pc = this.instructionResult.nextPc; this.instructionResult.reset(); } /** * We have two options to handle an invalid instruction: * - change status to panic and quit program immediately, * - treat the invalid instruction as a regular trap. * The difference is that in the second case we don't need any additional condition and gas will be subtracted automagically so this option is implemented * Reference: https://graypaper.fluffylabs.dev/#/579bd12/251100251200 */ const currentInstruction = this.code[this.pc] ?? Instruction.TRAP; const isValidInstruction = Instruction[currentInstruction] !== undefined; const gasCost = instructionGasMap[currentInstruction] ?? instructionGasMap[Instruction.TRAP]; const underflow = this.ignoreInstructionGas ? false : this.gas.sub(gasCost); if (underflow) { this.status = Status.OOG; return this.status; } const argsType = instructionArgumentTypeMap[currentInstruction] ?? ArgumentType.NO_ARGUMENTS; const argsResult = this.argsDecodingResults[argsType]; this.argsDecoder.fillArgs(this.pc, argsResult); if (!isValidInstruction) { this.instructionResult.status = Result.PANIC; } else { this.instructionResult.nextPc = this.pc + argsResult.noOfBytesToSkip; switch (argsResult.type) { case ArgumentType.NO_ARGUMENTS: this.noArgsDispatcher.dispatch(currentInstruction); break; case ArgumentType.ONE_IMMEDIATE: this.oneImmDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET: this.oneRegOneImmOneOffsetDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.TWO_REGISTERS: if (this.useSbrkGas && currentInstruction === Instruction.SBRK) { const calculateSbrkCost = (length: number) => (alignToPageSize(length) / PAGE_SIZE) * 16; const underflow = this.gas.sub( tryAsGas(calculateSbrkCost(this.registers.getLowerU32(argsResult.firstRegisterIndex))), ); if (underflow) { this.status = Status.OOG; return this.status; } } this.twoRegsDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.THREE_REGISTERS: this.threeRegsDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.TWO_REGISTERS_ONE_IMMEDIATE: this.twoRegsOneImmDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.TWO_REGISTERS_ONE_OFFSET: this.twoRegsOneOffsetDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.ONE_OFFSET: this.oneOffsetDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.ONE_REGISTER_ONE_IMMEDIATE: this.oneRegOneImmDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.TWO_IMMEDIATES: this.twoImmsDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.ONE_REGISTER_TWO_IMMEDIATES: this.oneRegTwoImmsDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.TWO_REGISTERS_TWO_IMMEDIATES: this.twoRegsTwoImmsDispatcher.dispatch(currentInstruction, argsResult); break; case ArgumentType.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE: this.oneRegOneExtImmDispatcher.dispatch(currentInstruction, argsResult); break; } } if (this.instructionResult.status !== null) { // All abnormal terminations should be interpreted as TRAP and we should subtract the gas. In case of FAULT we have to do it manually at the very end. if (this.instructionResult.status === Result.FAULT || this.instructionResult.status === Result.FAULT_ACCESS) { // TODO [ToDr] underflow? this.gas.sub(instructionGasMap[Instruction.TRAP]); } switch (this.instructionResult.status) { case Result.FAULT: this.status = Status.FAULT; break; case Result.HALT: this.status = Status.HALT; break; case Result.PANIC: case Result.FAULT_ACCESS: this.status = Status.PANIC; break; case Result.HOST: this.status = Status.HOST; break; } return this.status; } this.pc = this.instructionResult.nextPc; return this.status; } getRegisters() { return this.registers; } getPC() { return this.pc; } setNextPC(nextPc: number) { this.pc = nextPc; } getGas(): Gas { return this.gas.get(); } getGasConsumed(): Gas { const gasConsumed = tryAsBigGas(this.initialGas.get()) - tryAsBigGas(this.gas.get()); if (gasConsumed < 0) { return this.initialGas.get(); } return tryAsBigGas(gasConsumed); } getGasCounter(): GasCounter { return this.gas; } getStatus() { return this.status; } getExitParam(): null | U32 { const p = this.instructionResult.exitParam; return p !== null ? tryAsU32(p) : p; } getMemory() { return this.memory; } getMemoryPage(pageNumber: number): null | Uint8Array { return this.memory.getPageDump(tryAsPageNumber(pageNumber)); } } type index$3_BigGas = BigGas; type index$3_Gas = Gas; type index$3_GasCounter = GasCounter; type index$3_Interpreter = Interpreter; declare const index$3_Interpreter: typeof Interpreter; type index$3_Memory = Memory; declare const index$3_Memory: typeof Memory; type index$3_MemoryBuilder = MemoryBuilder; declare const index$3_MemoryBuilder: typeof MemoryBuilder; type index$3_MemoryIndex = MemoryIndex; type index$3_Registers = Registers; declare const index$3_Registers: typeof Registers; type index$3_SbrkIndex = SbrkIndex; type index$3_SmallGas = SmallGas; declare const index$3_gasCounter: typeof gasCounter; declare const index$3_tryAsBigGas: typeof tryAsBigGas; declare const index$3_tryAsGas: typeof tryAsGas; declare const index$3_tryAsMemoryIndex: typeof tryAsMemoryIndex; declare const index$3_tryAsSbrkIndex: typeof tryAsSbrkIndex; declare const index$3_tryAsSmallGas: typeof tryAsSmallGas; declare namespace index$3 { export { type index$3_BigGas as BigGas, type index$3_Gas as Gas, type index$3_GasCounter as GasCounter, index$3_Interpreter as Interpreter, index$3_Memory as Memory, index$3_MemoryBuilder as MemoryBuilder, type index$3_MemoryIndex as MemoryIndex, index$3_Registers as Registers, type index$3_SbrkIndex as SbrkIndex, type index$3_SmallGas as SmallGas, index$3_gasCounter as gasCounter, index$3_tryAsBigGas as tryAsBigGas, index$3_tryAsGas as tryAsGas, index$3_tryAsMemoryIndex as tryAsMemoryIndex, index$3_tryAsSbrkIndex as tryAsSbrkIndex, index$3_tryAsSmallGas as tryAsSmallGas }; } declare class MemorySegment extends WithDebug { static from({ start, end, data }: Omit) { return new MemorySegment(start, end, data); } constructor( public readonly start: number, public readonly end: number, public readonly data: Uint8Array | null, ) { super(); } } declare class SpiMemory extends WithDebug { constructor( public readonly readable: MemorySegment[], public readonly writeable: MemorySegment[], public readonly sbrkIndex: number, public readonly heapEnd: number, ) { super(); } } declare class SpiProgram extends WithDebug { constructor( public readonly code: Uint8Array, public readonly memory: SpiMemory, public readonly registers: BigUint64Array, ) { super(); } } declare function decodeStandardProgram(program: Uint8Array, args: Uint8Array) { const decoder = Decoder.fromBlob(program); const oLength = decoder.u24(); const wLength = decoder.u24(); const argsLength = ensure(args.length, args.length <= DATA_LEGNTH, "Incorrect arguments length"); const readOnlyLength = ensure( oLength, oLength <= DATA_LEGNTH, "Incorrect readonly segment length", ); const heapLength = ensure(wLength, wLength <= DATA_LEGNTH, "Incorrect heap segment length"); const noOfHeapZerosPages = decoder.u16(); const stackSize = decoder.u24(); const readOnlyMemory = decoder.bytes(readOnlyLength).raw; const initialHeap = decoder.bytes(heapLength).raw; const codeLength = decoder.u32(); const code = decoder.bytes(codeLength).raw; decoder.finish(); const readonlyDataStart = SEGMENT_SIZE; const readonlyDataEnd = SEGMENT_SIZE + alignToPageSize(readOnlyLength); const heapDataStart = 2 * SEGMENT_SIZE + alignToSegmentSize(readOnlyLength); const heapDataEnd = heapDataStart + alignToPageSize(heapLength); const heapZerosEnd = heapDataStart + alignToPageSize(heapLength) + noOfHeapZerosPages * PAGE_SIZE; const stackStart = STACK_SEGMENT - alignToPageSize(stackSize); const stackEnd = STACK_SEGMENT; const argsStart = ARGS_SEGMENT; const argsEnd = argsStart + alignToPageSize(argsLength); const argsZerosEnd = argsEnd + alignToPageSize(argsLength); function nonEmpty(s: MemorySegment | false): s is MemorySegment { return s !== false; } const readableMemory = [ readOnlyLength > 0 && getMemorySegment(readonlyDataStart, readonlyDataEnd, readOnlyMemory), argsLength > 0 && getMemorySegment(argsStart, argsEnd, args), argsEnd < argsZerosEnd && getMemorySegment(argsEnd, argsZerosEnd), ].filter(nonEmpty); const writeableMemory = [ heapLength > 0 && getMemorySegment(heapDataStart, heapDataEnd, initialHeap), heapDataEnd < heapZerosEnd && getMemorySegment(heapDataEnd, heapZerosEnd), stackStart < stackEnd && getMemorySegment(stackStart, stackEnd), ].filter(nonEmpty); return new SpiProgram( code, new SpiMemory(readableMemory, writeableMemory, heapZerosEnd, stackStart), getRegisters(args.length), ); } declare class Program { static fromSpi(blob: Uint8Array, args: Uint8Array, hasMetadata: boolean) { const { code: spiCode, metadata } = hasMetadata ? extractCodeAndMetadata(blob) : { code: blob }; const { code, memory: rawMemory, registers } = decodeStandardProgram(spiCode, args); const regs = new Registers(); regs.copyFrom(registers); const memoryBuilder = new MemoryBuilder(); for (const { start, end, data } of rawMemory.readable) { const startIndex = tryAsMemoryIndex(start); const endIndex = tryAsMemoryIndex(end); memoryBuilder.setReadablePages(startIndex, endIndex, data ?? new Uint8Array()); } for (const { start, end, data } of rawMemory.writeable) { const startIndex = tryAsMemoryIndex(start); const endIndex = tryAsMemoryIndex(end); memoryBuilder.setWriteablePages(startIndex, endIndex, data ?? new Uint8Array()); } const heapStart = tryAsMemoryIndex(rawMemory.sbrkIndex); const heapEnd = tryAsSbrkIndex(rawMemory.heapEnd); const memory = memoryBuilder.finalize(heapStart, heapEnd); return new Program(code, regs, memory, metadata); } static fromGeneric(blob: Uint8Array, hasMetadata: boolean) { const { code, metadata } = hasMetadata ? extractCodeAndMetadata(blob) : { code: blob }; const regs = new Registers(); const memory = new Memory(); return new Program(code, regs, memory, metadata); } private constructor( public readonly code: Uint8Array, public readonly registers: Registers, public readonly memory: Memory, public metadata: Uint8Array = new Uint8Array(), ) {} } /** * A function that splits preimage into metadata and code. * * https://graypaper.fluffylabs.dev/#/cc517d7/109a01109a01?v=0.6.5 */ declare function extractCodeAndMetadata(blobWithMetadata: Uint8Array) { const decoder = Decoder.fromBlob(blobWithMetadata); const metadata = decoder.bytesBlob().raw; const code = decoder.remainingBytes().raw; return { metadata, code }; } declare class DebuggerAdapter { private readonly pvm: Interpreter; constructor(useSbrkGas = false) { this.pvm = new Interpreter({ useSbrkGas }); } // TODO [MaSi]: a temporary solution that is needed to implement host calls in PVM debugger getInterpreter() { return this.pvm; } resetGeneric(rawProgram: Uint8Array, flatRegisters: Uint8Array, initialGas: bigint) { this.pvm.reset(rawProgram, 0, tryAsGas(initialGas), new Registers(flatRegisters)); } reset(rawProgram: Uint8Array, pc: number, gas: bigint, maybeRegisters?: Registers, maybeMemory?: Memory) { this.pvm.reset(rawProgram, pc, tryAsGas(gas), maybeRegisters, maybeMemory); } getPageDump(pageNumber: number): null | Uint8Array { const page = this.pvm.getMemoryPage(pageNumber); if (page === null) { // page wasn't allocated so we return an empty page return new Uint8Array(PAGE_SIZE); } if (page.length === PAGE_SIZE) { // page was allocated and has a proper size so we can simply return it return page; } // page was allocated but it is shorter than PAGE_SIZE so we have to extend it const fullPage = new Uint8Array(PAGE_SIZE); fullPage.set(page); return fullPage; } setMemory(address: number, value: Uint8Array) { this.pvm.getMemory().storeFrom(tryAsMemoryIndex(address), value); } getExitArg(): number { return this.pvm.getExitParam() ?? 0; } getStatus(): Status { return this.pvm.getStatus(); } nextStep(): boolean { return this.pvm.nextStep() === Status.OK; } nSteps(steps: number): boolean { check(steps >>> 0 > 0, `Expected a positive integer got ${steps}`); for (let i = 0; i < steps; i++) { const isOk = this.nextStep(); if (!isOk) { return false; } } return true; } getRegisters(): BigUint64Array { return this.pvm.getRegisters().getAllU64(); } setRegisters(registers: Uint8Array) { this.pvm.getRegisters().copyFrom(new Registers(registers)); } getProgramCounter(): number { return this.pvm.getPC(); } setNextProgramCounter(nextPc: number) { this.pvm.setNextPC(nextPc); } getGasLeft(): bigint { return BigInt(this.pvm.getGas()); } setGasLeft(gas: bigint) { this.pvm.getGasCounter().set(tryAsGas(gas)); } } /** * Host call result constants. * * https://graypaper.fluffylabs.dev/#/85129da/2c7c022c7c02?v=0.6.3 */ declare const HostCallResult = { /** The return value indicating an item does not exist. */ NONE: tryAsU64(0xffff_ffff_ffff_ffffn), // 2**64 - 1 /** Name unknown. */ WHAT: tryAsU64(0xffff_ffff_ffff_fffen), // 2**64 - 2 /** The inner PVM memory index provided for reading/writing is not accessible. */ OOB: tryAsU64(0xffff_ffff_ffff_fffdn), // 2**64 - 3 /** Index unknown. */ WHO: tryAsU64(0xffff_ffff_ffff_fffcn), // 2**64 - 4 /** Storage full. */ FULL: tryAsU64(0xffff_ffff_ffff_fffbn), // 2**64 - 5 /** Core index unknown. */ CORE: tryAsU64(0xffff_ffff_ffff_fffan), // 2**64 - 6 /** Insufficient funds. */ CASH: tryAsU64(0xffff_ffff_ffff_fff9n), // 2**64 - 7 /** Gas limit too low. */ LOW: tryAsU64(0xffff_ffff_ffff_fff8n), // 2**64 - 8 /** The item is already solicited or cannot be forgotten. */ HUH: tryAsU64(0xffff_ffff_ffff_fff7n), // 2**64 - 9 /** The return value indicating general success. */ OK: tryAsU64(0n), } as const; /** * Size of the output of the hash functions. * * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01 * */ declare const HASH_SIZE = 32; type HASH_SIZE = typeof HASH_SIZE; /** A hash without last byte (useful for trie representation). */ declare const TRUNCATED_HASH_SIZE = 31; type TRUNCATED_HASH_SIZE = typeof TRUNCATED_HASH_SIZE; /** Opaque, unknown hash. */ type OpaqueHash = Bytes; /** Opaque Blake2B. */ type Blake2bHash = Bytes; /** Opaque KeccakHash. */ type KeccakHash = Bytes; /** Truncated hash. */ type TruncatedHash = Bytes; /** * Container for some object with a hash that is related to this object. * * After calculating the hash these two should be passed together to avoid * unnecessary re-hashing of the data. */ declare class WithHash extends WithDebug { constructor( public readonly hash: THash, public readonly data: TData, ) { super(); } } /** * Extension of [`WithHash`] additionally containing an encoded version of the object. */ declare class WithHashAndBytes extends WithHash { constructor( hash: THash, data: TData, public readonly encoded: BytesBlob, ) { super(hash, data); } } /** Allocator interface - returns an empty bytes vector that can be filled with the hash. */ interface HashAllocator { /** Return a new hash destination. */ emptyHash(): OpaqueHash; } /** The simplest allocator returning just a fresh copy of bytes each time. */ declare class SimpleAllocator implements HashAllocator { emptyHash(): OpaqueHash { return Bytes.zero(HASH_SIZE); } } /** An allocator that works by allocating larger (continuous) pages of memory. */ declare class PageAllocator implements HashAllocator { private page: Uint8Array = new Uint8Array(0); private currentHash = 0; // TODO [ToDr] Benchmark the performance! constructor(private readonly hashesPerPage: number) { check(hashesPerPage > 0 && hashesPerPage >>> 0 === hashesPerPage, "Expected a non-zero integer."); this.resetPage(); } private resetPage() { const pageSizeBytes = this.hashesPerPage * HASH_SIZE; this.currentHash = 0; this.page = new Uint8Array(pageSizeBytes); } emptyHash(): OpaqueHash { const startIdx = this.currentHash * HASH_SIZE; const endIdx = startIdx + HASH_SIZE; this.currentHash += 1; if (this.currentHash >= this.hashesPerPage) { this.resetPage(); } return Bytes.fromBlob(this.page.subarray(startIdx, endIdx), HASH_SIZE); } } declare const defaultAllocator = new SimpleAllocator(); /** * Hash given collection of blobs. * * If empty array is given a zero-hash is returned. */ declare function hashBlobs$1( r: (BytesBlob | Uint8Array)[], allocator: HashAllocator = defaultAllocator, ): H { const out = allocator.emptyHash(); if (r.length === 0) { return out.asOpaque(); } const hasher = blake2b(HASH_SIZE); for (const v of r) { hasher?.update(v instanceof BytesBlob ? v.raw : v); } hasher?.digest(out.raw); return out.asOpaque(); } /** Hash given blob of bytes. */ declare function hashBytes(blob: BytesBlob | Uint8Array, allocator: HashAllocator = defaultAllocator): Blake2bHash { const hasher = blake2b(HASH_SIZE); const bytes = blob instanceof BytesBlob ? blob.raw : blob; hasher?.update(bytes); const out = allocator.emptyHash(); hasher?.digest(out.raw); return out; } /** Convert given string into bytes and hash it. */ declare function hashString(str: string, allocator: HashAllocator = defaultAllocator) { return hashBytes(BytesBlob.blobFromString(str), allocator); } declare const blake2b_hashBytes: typeof hashBytes; declare const blake2b_hashString: typeof hashString; declare namespace blake2b { export { hashBlobs$1 as hashBlobs, blake2b_hashBytes as hashBytes, blake2b_hashString as hashString }; } type ITypedArray = Uint8Array | Uint16Array | Uint32Array; type IDataType = string | Buffer | ITypedArray; type IHasher = { /** * Initializes hash state to default value */ init: () => IHasher; /** * Updates the hash content with the given data */ update: (data: IDataType) => IHasher; /** * Calculates the hash of all of the data passed to be hashed with hash.update(). * Defaults to hexadecimal string * @param outputType If outputType is "binary", it returns Uint8Array. Otherwise it * returns hexadecimal string */ digest: { (outputType: "binary"): Uint8Array; (outputType?: "hex"): string; }; /** * Save the current internal state of the hasher for later resumption with load(). * Cannot be called before .init() or after .digest() * * Note that this state can include arbitrary information about the value being hashed (e.g. * could include N plaintext bytes from the value), so needs to be treated as being as * sensitive as the input value itself. */ save: () => Uint8Array; /** * Resume a state that was created by save(). If this state was not created by a * compatible build of hash-wasm, an exception will be thrown. */ load: (state: Uint8Array) => IHasher; /** * Block size in bytes */ blockSize: number; /** * Digest size in bytes */ digestSize: number; }; declare class KeccakHasher { static async create(): Promise { return new KeccakHasher(await createKeccak(256)); } private constructor(public readonly hasher: IHasher) {} } declare function hashBlobs(hasher: KeccakHasher, blobs: BytesBlob[]) { hasher.hasher.init(); for (const blob of blobs) { hasher.hasher.update(blob.raw); } // NOTE we can't use an allocator here because the library does not allow that. return Bytes.fromBlob(hasher.hasher.digest("binary"), HASH_SIZE); } type keccak_KeccakHasher = KeccakHasher; declare const keccak_KeccakHasher: typeof KeccakHasher; declare const keccak_hashBlobs: typeof hashBlobs; declare namespace keccak { export { keccak_KeccakHasher as KeccakHasher, keccak_hashBlobs as hashBlobs }; } type index$2_Blake2bHash = Blake2bHash; type index$2_HASH_SIZE = HASH_SIZE; type index$2_HashAllocator = HashAllocator; type index$2_KeccakHash = KeccakHash; type index$2_OpaqueHash = OpaqueHash; type index$2_PageAllocator = PageAllocator; declare const index$2_PageAllocator: typeof PageAllocator; type index$2_SimpleAllocator = SimpleAllocator; declare const index$2_SimpleAllocator: typeof SimpleAllocator; type index$2_TRUNCATED_HASH_SIZE = TRUNCATED_HASH_SIZE; type index$2_TruncatedHash = TruncatedHash; type index$2_WithHash = WithHash; declare const index$2_WithHash: typeof WithHash; type index$2_WithHashAndBytes = WithHashAndBytes; declare const index$2_WithHashAndBytes: typeof WithHashAndBytes; declare const index$2_blake2b: typeof blake2b; declare const index$2_defaultAllocator: typeof defaultAllocator; declare const index$2_keccak: typeof keccak; declare namespace index$2 { export { type index$2_Blake2bHash as Blake2bHash, type index$2_HASH_SIZE as HASH_SIZE, type index$2_HashAllocator as HashAllocator, type index$2_KeccakHash as KeccakHash, type index$2_OpaqueHash as OpaqueHash, index$2_PageAllocator as PageAllocator, index$2_SimpleAllocator as SimpleAllocator, type index$2_TRUNCATED_HASH_SIZE as TRUNCATED_HASH_SIZE, type index$2_TruncatedHash as TruncatedHash, index$2_WithHash as WithHash, index$2_WithHashAndBytes as WithHashAndBytes, index$2_blake2b as blake2b, index$2_defaultAllocator as defaultAllocator, index$2_keccak as keccak }; } /** A collection that has a known, but not necessarily verified size. */ type KnownSize = Opaque; /** Regular array that has known, but not verified length. */ type KnownSizeArray = KnownSize; /** An array with a known, fixed size. */ declare class FixedSizeArray extends Array { public readonly fixedLength: N; private constructor(len: N); private constructor(...data: T[]) { super(...data); // NOTE [ToDr] we know this is going to be set corrrectly, // because the constructor is private (it has to be for things like `map` // to work correctly) and we only invoke it in the `new` static function. this.fixedLength = this.length as N; } static new(data: readonly T[], len: N): FixedSizeArray { check(data.length === len, `Expected an array of size: ${len}, got: ${data.length}`); const arr = new FixedSizeArray(len); for (let i = 0; i < len; i++) { arr[i] = data[i]; } Object.seal(arr); return arr; } static fill(generator: (idx: number) => T, len: N): FixedSizeArray { const data: T[] = []; for (let i = 0; i < len; i++) { data.push(generator(i)); } return FixedSizeArray.new(data, len); } toString() { return inspect(Array.from(this)); } } /** ED25519 public key size. */ declare const ED25519_KEY_BYTES = 32; type ED25519_KEY_BYTES = typeof ED25519_KEY_BYTES; /** ED25519 signature size. */ declare const ED25519_SIGNATURE_BYTES = 64; type ED25519_SIGNATURE_BYTES = typeof ED25519_SIGNATURE_BYTES; /** * Potentially valid Ed25519 public key. * * https://graypaper.fluffylabs.dev/#/579bd12/081300081a00 */ type Ed25519Key = Opaque, "Ed25519Key">; /** * Potentially valid Ed25519 signature. * * https://graypaper.fluffylabs.dev/#/579bd12/081300081a00 */ type Ed25519Signature = Opaque, "Ed25519Signature">; /** Bandersnatch public key size. */ declare const BANDERSNATCH_KEY_BYTES = 32; type BANDERSNATCH_KEY_BYTES = typeof BANDERSNATCH_KEY_BYTES; /** Bandersnatch VRF signature size */ declare const BANDERSNATCH_VRF_SIGNATURE_BYTES = 96; type BANDERSNATCH_VRF_SIGNATURE_BYTES = typeof BANDERSNATCH_VRF_SIGNATURE_BYTES; /** Bandersnatch proof size */ declare const BANDERSNATCH_PROOF_BYTES = 784; type BANDERSNATCH_PROOF_BYTES = typeof BANDERSNATCH_PROOF_BYTES; /** * Potentially valid Bandersnatch public key. * * https://graypaper.fluffylabs.dev/#/7e6ff6a/082200082200?v=0.6.7 */ type BandersnatchKey = Opaque, "BandersnatchKey">; /** * Potentially valid Bandersnatch signature. * * https://graypaper.fluffylabs.dev/#/7e6ff6a/082300082300?v=0.6.7 */ type BandersnatchVrfSignature = Opaque, "BandersnatchVrfSignature">; /** * Potentially valid Bandersnatch RingVRF proof of knowledge. * * https://graypaper.fluffylabs.dev/#/7e6ff6a/082d00083a00?v=0.6.7 */ type BandersnatchProof = Opaque, "BandersnatchRingSignature">; /** * Estimated number of validators. * * NOTE: Should ONLY be used to pre-allocate some data. * * https://graypaper.fluffylabs.dev/#/5f542d7/418800418800 */ declare const EST_VALIDATORS = 1023; /** * Estimated number of super majority of validators. * * NOTE: Should ONLY be used to pre-allocate some data. */ declare const EST_VALIDATORS_SUPER_MAJORITY = 683; /** * Estimated number of cores. * * NOTE: Should ONLY be used to pre-allocate some data. * * https://graypaper.fluffylabs.dev/#/5f542d7/414200414200 */ declare const EST_CORES = 341; /** * Estimated epoch length (in time slots). * * NOTE: Should ONLY be used to pre-allocate some data. * * https://graypaper.fluffylabs.dev/#/5f542d7/414800414800 */ declare const EST_EPOCH_LENGTH = 600; /** * Additional data that has to be passed to the codec to correctly parse incoming bytes. */ declare class ChainSpec extends WithDebug { /** Number of validators. */ readonly validatorsCount: number; /** 1/3 of number of validators */ readonly thirdOfValidators: number; /** 2/3 of number of validators + 1 */ readonly validatorsSuperMajority: number; /** Number of cores. */ readonly coresCount: number; /** Duration of a timeslot in seconds. */ readonly slotDuration: number; /** Length of the epoch in time slots. */ readonly epochLength: number; /** * `R`: The rotation period of validator-core assignments, in timeslots. * * https://graypaper.fluffylabs.dev/#/5f542d7/417f00417f00 */ readonly rotationPeriod: number; /** Length of the ticket contest in time slots. */ readonly contestLength: number; /** The maximum number of tickets each validator can submit. */ readonly ticketsPerValidator: number; /** The maximum number of tickets that can be included in a single block. */ readonly maxTicketsPerExtrinsic: number; /** Number of erasure coding pieces per segment. */ readonly numberECPiecesPerSegment: number; /** * `D`: Period in timeslots after which an unreferenced preimage may be expunged. * * https://graypaper.fluffylabs.dev/#/9a08063/445800445800?v=0.6.6 */ readonly preimageExpungePeriod: number; constructor(data: Omit) { super(); this.validatorsCount = data.validatorsCount; this.thirdOfValidators = Math.floor(data.validatorsCount / 3); this.validatorsSuperMajority = Math.floor(data.validatorsCount / 3) * 2 + 1; this.coresCount = data.coresCount; this.slotDuration = data.slotDuration; this.epochLength = data.epochLength; this.rotationPeriod = data.rotationPeriod; this.contestLength = data.contestLength; this.ticketsPerValidator = data.ticketsPerValidator; this.maxTicketsPerExtrinsic = data.maxTicketsPerExtrinsic; this.numberECPiecesPerSegment = data.numberECPiecesPerSegment; this.preimageExpungePeriod = data.preimageExpungePeriod; } } /** Set of values for "tiny" chain as defined in JAM test vectors. */ declare const tinyChainSpec = new ChainSpec({ contestLength: 10, coresCount: 2, epochLength: 12, maxTicketsPerExtrinsic: 3, rotationPeriod: 4, slotDuration: 6, ticketsPerValidator: 3, validatorsCount: 6, numberECPiecesPerSegment: 1026, preimageExpungePeriod: 6, }); /** * Set of values for "full" chain as defined in JAM test vectors. * Please note that only validatorsCount and epochLength are "full", the rest is copied from "tiny". */ declare const fullChainSpec = new ChainSpec({ contestLength: 500, coresCount: 341, epochLength: 600, maxTicketsPerExtrinsic: 16, rotationPeriod: 10, slotDuration: 6, ticketsPerValidator: 2, validatorsCount: 1023, numberECPiecesPerSegment: 6, preimageExpungePeriod: 19_200, }); /** * Configuration object for typeberry workers. */ declare class WorkerConfig { /** * Since we loose prototypes when transferring the context, * this function is re-initializing proper types. * * TODO [ToDr] instead of doing this hack, we might prefer to pass data * between workers using JAM codec maybe? */ static reInit(config: unknown) { const { chainSpec, dbPath, omitSealVerification } = config as WorkerConfig; return new WorkerConfig(new ChainSpec(chainSpec), dbPath, omitSealVerification); } constructor( public readonly chainSpec: ChainSpec, public readonly dbPath: string, public readonly omitSealVerification: boolean = false, ) {} } type index$1_ChainSpec = ChainSpec; declare const index$1_ChainSpec: typeof ChainSpec; declare const index$1_EST_CORES: typeof EST_CORES; declare const index$1_EST_EPOCH_LENGTH: typeof EST_EPOCH_LENGTH; declare const index$1_EST_VALIDATORS: typeof EST_VALIDATORS; declare const index$1_EST_VALIDATORS_SUPER_MAJORITY: typeof EST_VALIDATORS_SUPER_MAJORITY; type index$1_WorkerConfig = WorkerConfig; declare const index$1_WorkerConfig: typeof WorkerConfig; declare const index$1_fullChainSpec: typeof fullChainSpec; declare const index$1_tinyChainSpec: typeof tinyChainSpec; declare namespace index$1 { export { index$1_ChainSpec as ChainSpec, index$1_EST_CORES as EST_CORES, index$1_EST_EPOCH_LENGTH as EST_EPOCH_LENGTH, index$1_EST_VALIDATORS as EST_VALIDATORS, index$1_EST_VALIDATORS_SUPER_MAJORITY as EST_VALIDATORS_SUPER_MAJORITY, index$1_WorkerConfig as WorkerConfig, index$1_fullChainSpec as fullChainSpec, index$1_tinyChainSpec as tinyChainSpec }; } /** * Helper function to declare a codec descriptor that depends on the context. * * NOTE: the returned values are cached based on the `ChainSpec` reference. */ declare function codecWithContext(chooser: (ctx: ChainSpec) => Descriptor): Descriptor { const defaultContext = fullChainSpec; const { name, sizeHint } = chooser(defaultContext); const cache = new Map>(); return codec.select( { name, sizeHint: { bytes: sizeHint.bytes, isExact: false }, }, (context: unknown) => { if (context instanceof ChainSpec) { const cached = cache.get(context); if (cached !== undefined) { return cached; } const ret = chooser(context); cache.set(context, ret); return ret; } // resolving with default context. if (context === null) { return chooser(defaultContext); } // invalid context type if (context !== null) { throw new Error(`[${name}] Unexpected context type ${typeof context} while encoding/decoding.`); } throw new Error(`[${name}] Missing context while encoding/decoding!`); }, ); } /** Codec for a known-size array with length validation. */ declare const codecKnownSizeArray = ( val: Descriptor, options: codec.SequenceVarLenOptions | { fixedLength: number }, _id?: F, ): Descriptor, SequenceView> => { if ("fixedLength" in options) { return readonlyArray(codec.sequenceFixLen(val, options.fixedLength)).convert(seeThrough, asKnownSize); } return readonlyArray(codec.sequenceVarLen(val, options)).convert(seeThrough, asKnownSize); }; /** Codec for a fixed-size array with length validation. */ declare const codecFixedSizeArray = ( val: Descriptor, len: N, ): Descriptor, SequenceView> => { const checkLength = (actual: number) => { if (len !== actual) { throw new Error(`[${val.name}] Invalid size of fixed-size array. Got ${actual}, expected: ${len}`); } }; return codec.sequenceFixLen(val, len).convert( (i) => { checkLength(i.length); return i; }, (o) => { checkLength(o.length); return FixedSizeArray.new(o, len); }, ); }; type CodecHashDictionaryOptions = { typicalLength?: number; compare?: Comparator; }; /** Codec for a hash-dictionary. */ declare const codecHashDictionary = ( value: Descriptor, extractKey: (val: T) => K, { typicalLength = TYPICAL_DICTIONARY_LENGTH, compare = (a, b) => extractKey(a).compare(extractKey(b)), }: CodecHashDictionaryOptions = {}, ): Descriptor> => { return Descriptor.new( `HashDictionary<${value.name}>[?]`, { bytes: typicalLength * value.sizeHint.bytes, isExact: false, }, (e, v) => { const data = Array.from(v.values()); data.sort((a, b) => compare(a, b).value); e.varU32(tryAsU32(data.length)); for (const v of data) { value.encode(e, v); } }, (d) => { const map = HashDictionary.new(); const len = d.varU32(); let prevValue = null as null | T; for (let i = 0; i < len; i += 1) { const v = value.decode(d); const k = extractKey(v); if (map.has(k)) { throw new Error(`Duplicate item in the dictionary encoding: "${k}"!`); } if (prevValue !== null && compare(prevValue, v).isGreaterOrEqual()) { throw new Error(`The keys in dictionary encoding are not sorted "${prevValue}" >= "${v}"!`); } map.set(k, v); prevValue = v; } return map; }, (s) => { const len = s.decoder.varU32(); s.sequenceFixLen(value, len); }, ); }; type codec_CodecHashDictionaryOptions = CodecHashDictionaryOptions; declare const codec_codecFixedSizeArray: typeof codecFixedSizeArray; declare const codec_codecHashDictionary: typeof codecHashDictionary; declare const codec_codecKnownSizeArray: typeof codecKnownSizeArray; declare const codec_codecWithContext: typeof codecWithContext; declare namespace codec { export { type codec_CodecHashDictionaryOptions as CodecHashDictionaryOptions, codec_codecFixedSizeArray as codecFixedSizeArray, codec_codecHashDictionary as codecHashDictionary, codec_codecKnownSizeArray as codecKnownSizeArray, codec_codecWithContext as codecWithContext }; } /** * Time slot index. * * "an index of a six-second timeslots from the JAM Common Era" * * https://graypaper.fluffylabs.dev/#/579bd12/0b46000b4a00 */ type TimeSlot = Opaque; /** Attempt to convert a number into `TimeSlot`. */ declare const tryAsTimeSlot = (v: number): TimeSlot => asOpaqueType(tryAsU32(v)); /** Index of the validator in current validators set. */ type ValidatorIndex = Opaque; /** Attempt to convert a number into `ValidatorIndex`. */ declare const tryAsValidatorIndex = (v: number): ValidatorIndex => asOpaqueType(tryAsU16(v)); /** Unique service identifier. */ type ServiceId = Opaque; /** Attempt to convert a number into `ServiceId`. */ declare const tryAsServiceId = (v: number): ServiceId => asOpaqueType(tryAsU32(v)); /** Service gas - a measure of execution time/complexity. */ type ServiceGas = Opaque; declare const tryAsServiceGas = (v: number | bigint): ServiceGas => asOpaqueType(tryAsU64(v)); /** Index of the core on which the execution of the work package is done. */ type CoreIndex = Opaque; /** Attempt to convert a number into `CoreIndex`. */ declare const tryAsCoreIndex = (v: number): CoreIndex => asOpaqueType(tryAsU16(v)); /** `eta`: epoch randomness */ type EntropyHash = Opaque; /** Hash of the merkle root of the state. */ type StateRootHash = Opaque; /** * Index of an epoch. * * https://graypaper.fluffylabs.dev/#/579bd12/0b39000b3c00 */ type Epoch = Opaque; /** Attempt to convert a number into `Epoch`. */ declare const tryAsEpoch = (v: number): Epoch => asOpaqueType(tryAsU32(v)); /** One entry of `T` per one validator. */ type PerValidator = KnownSizeArray; declare function tryAsPerValidator(array: T[], spec: ChainSpec): PerValidator { check( array.length === spec.validatorsCount, `Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}`, ); return asKnownSize(array); } declare const codecPerValidator = (val: Descriptor): Descriptor, SequenceView> => codecWithContext((context) => { return codecKnownSizeArray(val, { fixedLength: context.validatorsCount, }); }); /** One entry of `T` per one block in epoch. */ type PerEpochBlock = KnownSizeArray; declare function tryAsPerEpochBlock(array: T[], spec: ChainSpec): PerEpochBlock { check( array.length === spec.epochLength, `Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}`, ); return asKnownSize(array); } declare const codecPerEpochBlock = (val: Descriptor): Descriptor, SequenceView> => codecWithContext((context) => { return codecKnownSizeArray(val, { fixedLength: context.epochLength }); }); /** * Blake2B hash of JAM-encoding of some header. * * https://graypaper.fluffylabs.dev/#/579bd12/0c7b000c7e00 */ type HeaderHash = Opaque; /** Blake2B hash of JAM-encoding of some work report. */ type WorkReportHash = Opaque; /** * Blake2B merkle commitment to the block's extrinsic data. * * https://graypaper.fluffylabs.dev/#/579bd12/0ca1000ca400 */ type ExtrinsicHash = Opaque; /** Blake2B hash of some service / authorization code. */ type CodeHash = Opaque; /** * * A work-report is said to become available iff there are a clear * 2/3 supermajority of validators who have marked its core as set within * the block's assurance extrinsic. * https://graypaper.fluffylabs.dev/#/579bd12/145800145c00 */ declare class AvailabilityAssurance extends WithDebug { static Codec = codec.Class(AvailabilityAssurance, { anchor: codec.bytes(HASH_SIZE).asOpaque(), bitfield: codecWithContext((context) => { return codec.bitVecFixLen(context.coresCount); }), validatorIndex: codec.u16.asOpaque(), signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(), }); static create({ anchor, bitfield, validatorIndex, signature }: CodecRecord) { return new AvailabilityAssurance(anchor, bitfield, validatorIndex, signature); } private constructor( /** * The assurances must all be anchored on the parent. * https://graypaper.fluffylabs.dev/#/579bd12/145800145c00 */ public readonly anchor: HeaderHash, /** * A series of binary values, one per core. * * Value of `1` implies that the validator assures they are contributing * to that's core validity. */ public readonly bitfield: BitVec, /** Validator index that signed this assurance. */ public readonly validatorIndex: ValidatorIndex, /** Signature over the anchor and the bitfield. */ public readonly signature: Ed25519Signature, ) { super(); } } declare const AssurancesExtrinsicBounds = "[0 .. ValidatorsCount)"; /** * `E_A`: Sequence with at most one item per validator. * * Assurances must be ordered by validator index. * https://graypaper.fluffylabs.dev/#/579bd12/145800145c00 */ type AssurancesExtrinsic = KnownSizeArray; declare const assurancesExtrinsicCodec = codecWithContext((context) => { return codecKnownSizeArray( AvailabilityAssurance.Codec, { minLength: 0, maxLength: context.validatorsCount, typicalLength: context.validatorsCount / 2, }, AssurancesExtrinsicBounds, ); }); type AssurancesExtrinsicView = DescribedBy; type assurances_AssurancesExtrinsic = AssurancesExtrinsic; type assurances_AssurancesExtrinsicView = AssurancesExtrinsicView; type assurances_AvailabilityAssurance = AvailabilityAssurance; declare const assurances_AvailabilityAssurance: typeof AvailabilityAssurance; declare const assurances_assurancesExtrinsicCodec: typeof assurancesExtrinsicCodec; declare namespace assurances { export { type assurances_AssurancesExtrinsic as AssurancesExtrinsic, type assurances_AssurancesExtrinsicView as AssurancesExtrinsicView, assurances_AvailabilityAssurance as AvailabilityAssurance, assurances_assurancesExtrinsicCodec as assurancesExtrinsicCodec }; } /** * Proof of signing a contradictory [`Judgement`] of a work report. */ declare class Fault extends WithDebug { static Codec = codec.Class(Fault, { workReportHash: codec.bytes(HASH_SIZE).asOpaque(), wasConsideredValid: codec.bool, key: codec.bytes(ED25519_KEY_BYTES).asOpaque(), signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(), }); static create({ workReportHash, wasConsideredValid, key, signature }: CodecRecord) { return new Fault(workReportHash, wasConsideredValid, key, signature); } private constructor( /** Hash of the work-report that had conflicting votes. */ public readonly workReportHash: WorkReportHash, /** Did the validator consider this work-report valid in their [`Judgement`]? */ public readonly wasConsideredValid: boolean, /** Validator key that provided the signature. */ public readonly key: Ed25519Key, /** Original signature that was part of the [`Judgement`]. */ public readonly signature: Ed25519Signature, ) { super(); } } /** * Proof of guaranteeing a work-report found to be invalid. */ declare class Culprit extends WithDebug { static Codec = codec.Class(Culprit, { workReportHash: codec.bytes(HASH_SIZE).asOpaque(), key: codec.bytes(ED25519_KEY_BYTES).asOpaque(), signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(), }); static create({ workReportHash, key, signature }: CodecRecord) { return new Culprit(workReportHash, key, signature); } private constructor( /** Hash of the invalid work-report. */ public readonly workReportHash: WorkReportHash, /** Validator key that provided the signature. */ public readonly key: Ed25519Key, /** Original signature that was part of the [`Judgement`]. */ public readonly signature: Ed25519Signature, ) { super(); } } /** * A vote for validity or invalidity of a [`WorkReport`] signed by a particular validator. */ declare class Judgement extends WithDebug { static Codec = codec.Class(Judgement, { isWorkReportValid: codec.bool, index: codec.u16.asOpaque(), signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(), }); static create({ isWorkReportValid, index, signature }: CodecRecord) { return new Judgement(isWorkReportValid, index, signature); } private constructor( /** Whether the work report is considered valid or not. */ public readonly isWorkReportValid: boolean, /** Index of the validator that signed this vote. */ public readonly index: ValidatorIndex, /** The signature. */ public readonly signature: Ed25519Signature, ) { super(); } } /** * Votes by super majority of the validator set * (either using keys from current epoch or previous) * over validity or invalidity of a particular [`WorkReport`]. * * https://graypaper.fluffylabs.dev/#/1c979cb/121c01122f01?v=0.7.1 */ declare class Verdict extends WithDebug { static Codec = codec.Class(Verdict, { workReportHash: codec.bytes(HASH_SIZE).asOpaque(), votesEpoch: codec.u32.asOpaque(), votes: codecWithContext((context) => { return readonlyArray(codec.sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority)).convert< Verdict["votes"] >(seeThrough, asKnownSize); }), }); static create({ workReportHash, votesEpoch, votes }: CodecRecord) { return new Verdict(workReportHash, votesEpoch, votes); } private constructor( /** Hash of the work report the verdict is for. */ public readonly workReportHash: WorkReportHash, /** * The epoch from which the validators signed the votes. * * Must either be the previous epoch or one before that. */ public readonly votesEpoch: Epoch, /** * Votes coming from super majority of validators. * * NOTE: must be ordered by validator index. * https://graypaper.fluffylabs.dev/#/1c979cb/12b10212b202?v=0.7.1 */ public readonly votes: KnownSizeArray, ) { super(); } } /** * A collection of judgements (votes over the validity of a [`WorkReport`]) formes a "verdict". * Together with offences (`culprits` & `faults`) - judgements and guarantees which dissent with an established * "verdict", these form the "disputes" system. * * `E_D = (v, c, f)` * * https://graypaper.fluffylabs.dev/#/1c979cb/125d00125d00?v=0.7.1 */ declare class DisputesExtrinsic extends WithDebug { static Codec = codec.Class(DisputesExtrinsic, { verdicts: codec.sequenceVarLen(Verdict.Codec), culprits: codec.sequenceVarLen(Culprit.Codec), faults: codec.sequenceVarLen(Fault.Codec), }); static create({ verdicts, culprits, faults }: CodecRecord) { return new DisputesExtrinsic(verdicts, culprits, faults); } private constructor( /** * `v`: a collection of verdicts over validity of some [`WorkReport`]s. * * NOTE: must be ordered by report hash. * https://graypaper.fluffylabs.dev/#/1c979cb/123f02123f02?v=0.7.1 */ public readonly verdicts: Verdict[], /** * `c`: proofs of validator misbehavior: gauranteeing an invalid [`WorkReport`]. * * NOTE: must be ordered by the validator's Ed25519Key. * https://graypaper.fluffylabs.dev/#/1c979cb/124102124102?v=0.7.1 */ public readonly culprits: Culprit[], /** * `f`: proofs of validator misbehavior: signing a contradictory judgement of a [`WorkReport`] validity. * * NOTE: must be ordered by the validator's Ed25519Key. * https://graypaper.fluffylabs.dev/#/1c979cb/124102124102?v=0.7.1 */ public readonly faults: Fault[], ) { super(); } } type disputes_Culprit = Culprit; declare const disputes_Culprit: typeof Culprit; type disputes_DisputesExtrinsic = DisputesExtrinsic; declare const disputes_DisputesExtrinsic: typeof DisputesExtrinsic; type disputes_Fault = Fault; declare const disputes_Fault: typeof Fault; type disputes_Judgement = Judgement; declare const disputes_Judgement: typeof Judgement; type disputes_Verdict = Verdict; declare const disputes_Verdict: typeof Verdict; declare namespace disputes { export { disputes_Culprit as Culprit, disputes_DisputesExtrinsic as DisputesExtrinsic, disputes_Fault as Fault, disputes_Judgement as Judgement, disputes_Verdict as Verdict }; } /** * Keccak-256 hash of the BEEFY MMR root. * * https://graypaper.fluffylabs.dev/#/579bd12/1e4f011e5201 */ type BeefyHash = Opaque; /** * `X`: Refinement Context - state of the chain at the point * that the report's corresponding work-package was evaluated. * * https://graypaper.fluffylabs.dev/#/579bd12/13b80013bb00 */ declare class RefineContext extends WithDebug { static Codec = codec.Class(RefineContext, { anchor: codec.bytes(HASH_SIZE).asOpaque(), stateRoot: codec.bytes(HASH_SIZE).asOpaque(), beefyRoot: codec.bytes(HASH_SIZE).asOpaque(), lookupAnchor: codec.bytes(HASH_SIZE).asOpaque(), lookupAnchorSlot: codec.u32.asOpaque(), prerequisites: codec.sequenceVarLen(codec.bytes(HASH_SIZE).asOpaque()), }); static create({ anchor, stateRoot, beefyRoot, lookupAnchor, lookupAnchorSlot, prerequisites, }: CodecRecord) { return new RefineContext(anchor, stateRoot, beefyRoot, lookupAnchor, lookupAnchorSlot, prerequisites); } private constructor( /** `a`: Header hash at which the work-package was evaluated. */ public readonly anchor: HeaderHash, /** `s`: **Posterior** state root of the anchor. */ public readonly stateRoot: StateRootHash, /** `b`: **Posterior** BEEFY root. */ public readonly beefyRoot: BeefyHash, /** `l`: Preimage lookup anchor. */ public readonly lookupAnchor: HeaderHash, /** `t`: Lookup anchor time slot. */ public readonly lookupAnchorSlot: TimeSlot, /** `p`: List of hashes of the prerequisite work-packages. */ public readonly prerequisites: WorkPackageHash[] = [], ) { super(); } } type refineContext_BeefyHash = BeefyHash; type refineContext_RefineContext = RefineContext; declare const refineContext_RefineContext: typeof RefineContext; declare namespace refineContext { export { type refineContext_BeefyHash as BeefyHash, refineContext_RefineContext as RefineContext }; } /** `W_M`: The maximum number of entries in a work-package manifest. */ declare const MAX_NUMBER_OF_SEGMENTS = 2048; // 2**11 /** `W_E * W_S`: Exported segment size in bytes. */ declare const SEGMENT_BYTES = W_E * W_S; type SEGMENT_BYTES = typeof SEGMENT_BYTES; /** Exported segment data. */ type Segment = Bytes; /** Index of an segment. */ type SegmentIndex = Opaque; /** Attempt to convert a number into `SegmentIndex`. */ declare const tryAsSegmentIndex = (v: number): SegmentIndex => asOpaqueType(tryAsU16(v)); type WorkItemExtrinsicHash = Opaque; /** * Definition of data segment that was exported by some work package earlier * and now is being imported by another work-item. */ declare class ImportSpec extends WithDebug { static Codec = codec.Class(ImportSpec, { treeRoot: codec.bytes(HASH_SIZE), index: codec.u16.asOpaque(), }); static create({ treeRoot, index }: CodecRecord) { return new ImportSpec(treeRoot, index); } private constructor( /** * ??: TODO [ToDr] GP seems to mention a identity of a work-package: * https://graypaper.fluffylabs.dev/#/579bd12/199300199300 */ public readonly treeRoot: OpaqueHash, /** Index of the prior exported segment. */ public readonly index: SegmentIndex, ) { super(); } } /** Introduced blob hashes and their lengths. */ declare class WorkItemExtrinsicSpec extends WithDebug { static Codec = codec.Class(WorkItemExtrinsicSpec, { hash: codec.bytes(HASH_SIZE).asOpaque(), len: codec.u32, }); static create({ hash, len }: CodecRecord) { return new WorkItemExtrinsicSpec(hash, len); } private constructor( /** The pre-image to this hash should be passed to the guarantor alongisde the work-package. */ public readonly hash: WorkItemExtrinsicHash, /** Length of the preimage identified by the hash above. */ public readonly len: U32, ) { super(); } } /** * Extrinsics that are needed by [`WorkItem`]s and are specified via [`WorkItemExtrinsicSpec`]. */ type WorkItemExtrinsics = KnownSizeArray< Bytes, "Count of all extrinsics within work items in a work package" >; /** * To encode/decode extrinsics that are specified via [`WorkItemExtrinsicSpec`] * we need to know their lenghts. Hence this is created dynamically. */ declare function workItemExtrinsicsCodec(workItems: WorkItem[]) { const extrinsicLengths = Array(); for (const item of workItems) { for (const extrinsic of item.extrinsic) { extrinsicLengths.push(extrinsic.len); } } const sum = sumU32(...extrinsicLengths); if (sum.overflow) { throw new Error("Unable to create a decoder, because the length of extrinsics overflows!"); } return codec.custom( { name: "WorkItemExtrinsics", sizeHint: { bytes: sum.value, isExact: true }, }, (e, val) => { for (const bytes of val) { e.bytes(bytes); } }, (d) => { const extrinsics = Array>(); for (const len of extrinsicLengths) { const bytes = d.bytes(len); extrinsics.push(bytes); } return asKnownSize(extrinsics); }, (s) => s.decoder.skip(sum.value), ); } /** * Work Item which is a part of some work package. * * https://graypaper.fluffylabs.dev/#/579bd12/198b00199600 */ declare class WorkItem extends WithDebug { static Codec = codec.Class(WorkItem, { service: codec.u32.asOpaque(), codeHash: codec.bytes(HASH_SIZE).asOpaque(), payload: codec.blob, refineGasLimit: codec.u64.asOpaque(), accumulateGasLimit: codec.u64.asOpaque(), importSegments: codecKnownSizeArray(ImportSpec.Codec, { minLength: 0, maxLength: MAX_NUMBER_OF_SEGMENTS, typicalLength: MAX_NUMBER_OF_SEGMENTS, }), extrinsic: codec.sequenceVarLen(WorkItemExtrinsicSpec.Codec), exportCount: codec.u16, }); static create({ service, codeHash, payload, refineGasLimit, accumulateGasLimit, importSegments, extrinsic, exportCount, }: CodecRecord) { return new WorkItem( service, codeHash, payload, refineGasLimit, accumulateGasLimit, importSegments, extrinsic, exportCount, ); } private constructor( /** `s`: related service */ public readonly service: ServiceId, /** * `c`: code hash of the service at the time of reporting. * * preimage of that hash must be available from the perspective of the lookup * anchor block. */ public readonly codeHash: CodeHash, /** `y`: payload blob */ public readonly payload: BytesBlob, /** `g`: refine execution gas limit */ public readonly refineGasLimit: ServiceGas, /** `a`: accumulate execution gas limit */ public readonly accumulateGasLimit: ServiceGas, /** `i`: sequence of imported data segments, which identify a prior exported segment. */ public readonly importSegments: KnownSizeArray, /** `x`: sequence of blob hashes and lengths to be introduced in this block */ public readonly extrinsic: WorkItemExtrinsicSpec[], /** `e`: number of data segments exported by this work item. */ public readonly exportCount: U16, ) { super(); } } type workItem_ImportSpec = ImportSpec; declare const workItem_ImportSpec: typeof ImportSpec; type workItem_WorkItem = WorkItem; declare const workItem_WorkItem: typeof WorkItem; type workItem_WorkItemExtrinsicSpec = WorkItemExtrinsicSpec; declare const workItem_WorkItemExtrinsicSpec: typeof WorkItemExtrinsicSpec; type workItem_WorkItemExtrinsics = WorkItemExtrinsics; declare const workItem_workItemExtrinsicsCodec: typeof workItemExtrinsicsCodec; declare namespace workItem { export { workItem_ImportSpec as ImportSpec, workItem_WorkItem as WorkItem, workItem_WorkItemExtrinsicSpec as WorkItemExtrinsicSpec, type workItem_WorkItemExtrinsics as WorkItemExtrinsics, workItem_workItemExtrinsicsCodec as workItemExtrinsicsCodec }; } /** Possible number of work items in the package or results in the report. */ /** Constrained by I=16 https://graypaper.fluffylabs.dev/#/68eaa1f/417a00417a00?v=0.6.4 */ type WorkItemsCount = U8; /** Verify the value is within the `WorkItemsCount` bounds. */ declare function tryAsWorkItemsCount(len: number): WorkItemsCount { return ensure( len, len >= MIN_NUMBER_OF_WORK_ITEMS && len <= MAX_NUMBER_OF_WORK_ITEMS, `WorkItemsCount: Expected '${MIN_NUMBER_OF_WORK_ITEMS} <= count <= ${MAX_NUMBER_OF_WORK_ITEMS}' got ${len}`, ); } /** Minimal number of work items in the work package or results in work report. */ declare const MIN_NUMBER_OF_WORK_ITEMS = 1; /** `I`: Maximal number of work items in the work package or results in work report. */ declare const MAX_NUMBER_OF_WORK_ITEMS = 16; /** * A piece of work done within a core. * * `P = (j ∈ Y, h ∈ NS, u ∈ H, p ∈ Y, x ∈ X, w ∈ ⟦I⟧1∶I) * * https://graypaper.fluffylabs.dev/#/579bd12/197000197200 */ declare class WorkPackage extends WithDebug { static Codec = codec.Class(WorkPackage, { authorization: codec.blob, authCodeHost: codec.u32.asOpaque(), authCodeHash: codec.bytes(HASH_SIZE).asOpaque(), parametrization: codec.blob, context: RefineContext.Codec, items: codec.sequenceVarLen(WorkItem.Codec).convert( (x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length)), ), }); static create({ authorization, authCodeHost, authCodeHash, parametrization, context, items, }: CodecRecord) { return new WorkPackage(authorization, authCodeHost, authCodeHash, parametrization, context, items); } private constructor( /** `j`: simple blob acting as an authorization token */ public readonly authorization: BytesBlob, /** `h`: index of the service that hosts the authorization code */ public readonly authCodeHost: ServiceId, /** `u`: authorization code hash */ public readonly authCodeHash: CodeHash, /** `p`: authorization parametrization blob */ public readonly parametrization: BytesBlob, /** `x`: context in which the refine function should run */ public readonly context: RefineContext, /** * `w`: sequence of work items. * * Constrained by `I=16`: * https://graypaper.fluffylabs.dev/#/579bd12/416600416800 */ public readonly items: FixedSizeArray, ) { super(); } } type WorkPackageView = DescribedBy; declare const workPackage_MAX_NUMBER_OF_WORK_ITEMS: typeof MAX_NUMBER_OF_WORK_ITEMS; declare const workPackage_MIN_NUMBER_OF_WORK_ITEMS: typeof MIN_NUMBER_OF_WORK_ITEMS; type workPackage_WorkItemsCount = WorkItemsCount; type workPackage_WorkPackage = WorkPackage; declare const workPackage_WorkPackage: typeof WorkPackage; type workPackage_WorkPackageView = WorkPackageView; declare const workPackage_tryAsWorkItemsCount: typeof tryAsWorkItemsCount; declare namespace workPackage { export { workPackage_MAX_NUMBER_OF_WORK_ITEMS as MAX_NUMBER_OF_WORK_ITEMS, workPackage_MIN_NUMBER_OF_WORK_ITEMS as MIN_NUMBER_OF_WORK_ITEMS, type workPackage_WorkItemsCount as WorkItemsCount, workPackage_WorkPackage as WorkPackage, type workPackage_WorkPackageView as WorkPackageView, workPackage_tryAsWorkItemsCount as tryAsWorkItemsCount }; } /** The tag to describe the [`WorkExecResult`] union. */ declare enum WorkExecResultKind { /** Execution succesful. The result will be followed by an octet sequence. */ ok = 0, /** `∞`: the machine went out-of-gas during execution. */ outOfGas = 1, /** `☇`: unexpected program termination. */ panic = 2, /** `BAD`: service code was not available for lookup in state. */ badCode = 3, /** `BIG`: the code was too big (beyond the maximum allowed size `W_C`) */ codeOversize = 4, } /** The execution result of some work-package. */ declare class WorkExecResult extends WithDebug { static Codec = codec.custom( { name: "WorkExecResult", sizeHint: { bytes: 1, isExact: false }, }, (e, x) => { e.varU32(tryAsU32(x.kind)); if (x.kind === WorkExecResultKind.ok && x.okBlob !== null) { e.bytesBlob(x.okBlob); } }, (d) => { const kind = d.varU32(); if (kind === WorkExecResultKind.ok) { const blob = d.bytesBlob(); return new WorkExecResult(kind, blob); } if (kind > WorkExecResultKind.codeOversize) { throw new Error(`Invalid WorkExecResultKind: ${kind}`); } return new WorkExecResult(kind); }, (s) => { const kind = s.decoder.varU32(); if (kind === WorkExecResultKind.ok) { s.bytesBlob(); } }, ); constructor( /** The execution result tag. */ public readonly kind: WorkExecResultKind, /** Optional octet sequence - available only if `kind === ok` */ public readonly okBlob: BytesBlob | null = null, ) { super(); } } /** * Five fields describing the level of activity which this workload * imposed on the core in bringing the output datum to bear. * * https://graypaper.fluffylabs.dev/#/68eaa1f/141300141b00?v=0.6.4 * https://graypaper.fluffylabs.dev/#/68eaa1f/1a50001a5000?v=0.6.4 */ declare class WorkRefineLoad extends WithDebug { static Codec = codec.Class(WorkRefineLoad, { gasUsed: codec.varU64.asOpaque(), importedSegments: codec.varU32, extrinsicCount: codec.varU32, extrinsicSize: codec.varU32, exportedSegments: codec.varU32, }); static create({ gasUsed, importedSegments, extrinsicCount, extrinsicSize, exportedSegments, }: CodecRecord) { return new WorkRefineLoad(gasUsed, importedSegments, extrinsicCount, extrinsicSize, exportedSegments); } private constructor( /** `u`: actual amount of gas used during refinement */ public readonly gasUsed: ServiceGas, /** `i`: number of segments imported from */ public readonly importedSegments: U32, /** `x`: number of extrinsics used in computing the workload */ public readonly extrinsicCount: U32, /** `z`: size of extrinsics used in computing the workload */ public readonly extrinsicSize: U32, /** `e`: number of segments exported into */ public readonly exportedSegments: U32, ) { super(); } } /** * A result of execution of some work package. * * https://graypaper.fluffylabs.dev/#/68eaa1f/139501139501?v=0.6.4 */ declare class WorkResult { static Codec = codec.Class(WorkResult, { serviceId: codec.u32.asOpaque(), codeHash: codec.bytes(HASH_SIZE).asOpaque(), payloadHash: codec.bytes(HASH_SIZE), gas: codec.u64.asOpaque(), result: WorkExecResult.Codec, load: WorkRefineLoad.Codec, }); static create({ serviceId, codeHash, payloadHash, gas, result, load }: CodecRecord) { return new WorkResult(serviceId, codeHash, payloadHash, gas, result, load); } private constructor( /** `s`: Index of the service whose state is to be altered (refine already executed). */ public readonly serviceId: ServiceId, /** `c`: Hash of the code of the service at the time of being reported. */ public readonly codeHash: CodeHash, /** * `y`: Hash of the payload within the work item which was executed in the refine stage to give this result. * * It has no immediate relevance, but is something provided to the accumulation logic of the service. * * https://graypaper.fluffylabs.dev/#/579bd12/134701134701 */ public readonly payloadHash: OpaqueHash, /** * `g`: Gas prioritization ratio. * * Used when determining how much gas should be allocated to execute * of this item's accumulate. */ public readonly gas: ServiceGas, /** `o`: The output or error of the execution of the code. */ public readonly result: WorkExecResult, /** * `u, i, x, z, e`: fields describing the level of activity * which this workload imposed on the core in * bringing the output datum to bear. * * https://graypaper.fluffylabs.dev/#/68eaa1f/141300141500?v=0.6.4 */ public readonly load: WorkRefineLoad, ) {} } type workResult_WorkExecResult = WorkExecResult; declare const workResult_WorkExecResult: typeof WorkExecResult; type workResult_WorkExecResultKind = WorkExecResultKind; declare const workResult_WorkExecResultKind: typeof WorkExecResultKind; type workResult_WorkRefineLoad = WorkRefineLoad; declare const workResult_WorkRefineLoad: typeof WorkRefineLoad; type workResult_WorkResult = WorkResult; declare const workResult_WorkResult: typeof WorkResult; declare namespace workResult { export { workResult_WorkExecResult as WorkExecResult, workResult_WorkExecResultKind as WorkExecResultKind, workResult_WorkRefineLoad as WorkRefineLoad, workResult_WorkResult as WorkResult }; } /** Authorizer hash. */ type AuthorizerHash = Opaque; /** Blake2B hash of a work package. */ type WorkPackageHash = Opaque; /** Work package exported segments merkle root hash. */ type ExportsRootHash = Opaque; /** * Details about the work package being reported on. * * https://graypaper.fluffylabs.dev/#/5f542d7/130e01130e01?v=0.6.2 */ declare class WorkPackageSpec extends WithDebug { static Codec = codec.Class(WorkPackageSpec, { hash: codec.bytes(HASH_SIZE).asOpaque(), length: codec.u32, erasureRoot: codec.bytes(HASH_SIZE), exportsRoot: codec.bytes(HASH_SIZE).asOpaque(), exportsCount: codec.u16, }); static create({ hash, length, erasureRoot, exportsRoot, exportsCount }: CodecRecord) { return new WorkPackageSpec(hash, length, erasureRoot, exportsRoot, exportsCount); } private constructor( /** `h`: The hash of the work package. */ public readonly hash: WorkPackageHash, /** `l`: Auditable work-bundle length. */ public readonly length: U32, /** `u`: The root hash of the erasure coding merkle tree of that work package. */ public readonly erasureRoot: OpaqueHash, /** `e`: The root hash of all data segments exported by this work package. */ public readonly exportsRoot: ExportsRootHash, /** `n`: Number of segments exported by this work package. */ public readonly exportsCount: U16, ) { super(); } } /** * Mapping between work package hash and root hash of it's exports. * * Used to construct a dictionary. */ declare class WorkPackageInfo extends WithDebug { static Codec = codec.Class(WorkPackageInfo, { workPackageHash: codec.bytes(HASH_SIZE).asOpaque(), segmentTreeRoot: codec.bytes(HASH_SIZE).asOpaque(), }); private constructor( /** Hash of the described work package. */ readonly workPackageHash: WorkPackageHash, /** Exports root hash. */ readonly segmentTreeRoot: ExportsRootHash, ) { super(); } static create({ workPackageHash, segmentTreeRoot }: CodecRecord) { return new WorkPackageInfo(workPackageHash, segmentTreeRoot); } } /** * A report of execution of some work package. * * https://graypaper.fluffylabs.dev/#/cc517d7/131c01132401?v=0.6.5 */ declare class WorkReport extends WithDebug { static Codec = codec.Class(WorkReport, { workPackageSpec: WorkPackageSpec.Codec, context: RefineContext.Codec, coreIndex: Compatibility.isGreaterOrEqual(GpVersion.V0_6_5) && !Compatibility.isSuite(TestSuite.JAMDUNA, GpVersion.V0_6_5) ? codec.varU32.convert( (o) => tryAsU32(o), (i) => { if (!isU16(i)) { throw new Error(`Core index exceeds U16: ${i}`); } return tryAsCoreIndex(i); }, ) : codec.u16.asOpaque(), authorizerHash: codec.bytes(HASH_SIZE).asOpaque(), authorizationOutput: codec.blob, segmentRootLookup: readonlyArray(codec.sequenceVarLen(WorkPackageInfo.Codec)), results: codec.sequenceVarLen(WorkResult.Codec).convert( (x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length)), ), authorizationGasUsed: codec.varU64.asOpaque(), }); static create({ workPackageSpec, context, coreIndex, authorizerHash, authorizationOutput, segmentRootLookup, results, authorizationGasUsed, }: CodecRecord) { return new WorkReport( workPackageSpec, context, coreIndex, authorizerHash, authorizationOutput, segmentRootLookup, results, authorizationGasUsed, ); } private constructor( /** `s`: Work package specification. */ public readonly workPackageSpec: WorkPackageSpec, /** `x`: Refinement context. */ public readonly context: RefineContext, /** `c`: Core index on which the work is done. */ public readonly coreIndex: CoreIndex, /** `a`: Hash of the authorizer. */ public readonly authorizerHash: AuthorizerHash, /** `o`: Authorization output. */ public readonly authorizationOutput: BytesBlob, /** `l`: Segment-root lookup * In GP segment-root lookup is a dictionary but dictionary and var-len sequence are equal from codec perspective * https://graypaper.fluffylabs.dev/#/579bd12/13ab0013ad00 */ public readonly segmentRootLookup: readonly WorkPackageInfo[], /** `r`: The results of evaluation of each of the items in the work package. */ public readonly results: FixedSizeArray, /** `g`: Gas used during authorization. */ public readonly authorizationGasUsed: ServiceGas, ) { super(); } } type workReport_AuthorizerHash = AuthorizerHash; type workReport_ExportsRootHash = ExportsRootHash; type workReport_WorkPackageHash = WorkPackageHash; type workReport_WorkPackageInfo = WorkPackageInfo; declare const workReport_WorkPackageInfo: typeof WorkPackageInfo; type workReport_WorkPackageSpec = WorkPackageSpec; declare const workReport_WorkPackageSpec: typeof WorkPackageSpec; type workReport_WorkReport = WorkReport; declare const workReport_WorkReport: typeof WorkReport; declare namespace workReport { export { type workReport_AuthorizerHash as AuthorizerHash, type workReport_ExportsRootHash as ExportsRootHash, type workReport_WorkPackageHash as WorkPackageHash, workReport_WorkPackageInfo as WorkPackageInfo, workReport_WorkPackageSpec as WorkPackageSpec, workReport_WorkReport as WorkReport }; } /** * Required number of credentials for each work report. * The maximal value is `NoOfValidators / NoOfCores` * (i.e. signatures from ALL validators assigned to the core) * however 2/3rds is sufficent. * Since GP defines that value explicitly as "two or three", * we do that as well. * * https://graypaper.fluffylabs.dev/#/579bd12/14b90214bb02 */ type REQUIRED_CREDENTIALS = 2 | 3; declare const REQUIRED_CREDENTIALS_RANGE = [2, 3]; /** Unique validator index & signature. */ declare class Credential extends WithDebug { static Codec = codec.Class(Credential, { validatorIndex: codec.u16.asOpaque(), signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(), }); static create({ validatorIndex, signature }: CodecRecord) { return new Credential(validatorIndex, signature); } private constructor( /** Validator index signing the guarantee. */ public readonly validatorIndex: ValidatorIndex, /** Signature over hash of the work-report. */ public readonly signature: Ed25519Signature, ) { super(); } } /** * Tuple of work-report, a credential and it's corresponding timeslot. * * https://graypaper.fluffylabs.dev/#/579bd12/147102149102 */ declare class ReportGuarantee extends WithDebug { static Codec = codec.Class(ReportGuarantee, { report: WorkReport.Codec, slot: codec.u32.asOpaque(), credentials: codecKnownSizeArray(Credential.Codec, { minLength: REQUIRED_CREDENTIALS_RANGE[0], maxLength: REQUIRED_CREDENTIALS_RANGE[1], typicalLength: REQUIRED_CREDENTIALS_RANGE[1], }), }); static create({ report, slot, credentials }: CodecRecord) { return new ReportGuarantee(report, slot, credentials); } private constructor( /** The work-report being guaranteed. */ public readonly report: WorkReport, /** Timeslot of the report. */ public readonly slot: TimeSlot, /** * The credential is a sequence of two or three tuples of a unique * validator index and a signature. * Credentials must be ordered by their validator index. * * https://graypaper.fluffylabs.dev/#/579bd12/14b90214bb02 */ public readonly credentials: KnownSizeArray, ) { super(); } } declare const GuaranteesExtrinsicBounds = "[0..CoresCount)"; /** * `E_G`: Series of guarantees, at most one for each core. * * Each core index (within work-report) must be unique and guarantees * must be in ascending order of this. * * https://graypaper.fluffylabs.dev/#/579bd12/146402146702 */ type GuaranteesExtrinsic = KnownSizeArray; declare const guaranteesExtrinsicCodec = codecWithContext((context) => codecKnownSizeArray( ReportGuarantee.Codec, { minLength: 0, maxLength: context.coresCount, typicalLength: context.coresCount, }, GuaranteesExtrinsicBounds, ), ); type GuaranteesExtrinsicView = DescribedBy; type guarantees_Credential = Credential; declare const guarantees_Credential: typeof Credential; type guarantees_GuaranteesExtrinsic = GuaranteesExtrinsic; declare const guarantees_GuaranteesExtrinsicBounds: typeof GuaranteesExtrinsicBounds; type guarantees_GuaranteesExtrinsicView = GuaranteesExtrinsicView; type guarantees_REQUIRED_CREDENTIALS = REQUIRED_CREDENTIALS; declare const guarantees_REQUIRED_CREDENTIALS_RANGE: typeof REQUIRED_CREDENTIALS_RANGE; type guarantees_ReportGuarantee = ReportGuarantee; declare const guarantees_ReportGuarantee: typeof ReportGuarantee; declare const guarantees_guaranteesExtrinsicCodec: typeof guaranteesExtrinsicCodec; declare namespace guarantees { export { guarantees_Credential as Credential, type guarantees_GuaranteesExtrinsic as GuaranteesExtrinsic, guarantees_GuaranteesExtrinsicBounds as GuaranteesExtrinsicBounds, type guarantees_GuaranteesExtrinsicView as GuaranteesExtrinsicView, type guarantees_REQUIRED_CREDENTIALS as REQUIRED_CREDENTIALS, guarantees_REQUIRED_CREDENTIALS_RANGE as REQUIRED_CREDENTIALS_RANGE, guarantees_ReportGuarantee as ReportGuarantee, guarantees_guaranteesExtrinsicCodec as guaranteesExtrinsicCodec }; } /** * The index of a ticket entry per validator. * * Constrained by `N = 2`: * https://graypaper.fluffylabs.dev/#/579bd12/417200417400 */ type TicketAttempt = Opaque; declare function tryAsTicketAttempt(x: number): TicketAttempt { return asOpaqueType(tryAsU8(x)); } /* Bandersnatch-signed ticket contest entry. */ declare class SignedTicket extends WithDebug { static Codec = codec.Class(SignedTicket, { // TODO [ToDr] we should verify that attempt is either 0|1|2. attempt: codec.u8.asOpaque(), signature: codec.bytes(BANDERSNATCH_PROOF_BYTES).asOpaque(), }); static create({ attempt, signature }: CodecRecord) { return new SignedTicket(attempt, signature); } private constructor( /** Which attempt was it? */ public readonly attempt: TicketAttempt, /** The bandersnatch membership proof of knowledge. */ public readonly signature: BandersnatchProof, ) { super(); } } /** Anonymous? entry into the ticket contest. */ declare class Ticket extends WithDebug { static Codec = codec.Class(Ticket, { id: codec.bytes(HASH_SIZE), // TODO [ToDr] we should verify that attempt is either 0|1|2. attempt: codec.u8.asOpaque(), }); static create({ id, attempt }: CodecRecord) { return new Ticket(id, attempt); } private constructor( /** * Ticket identifier - a high-entropy unbiasable 32-octet sequence. * * Used both as a score in the ticket contest and as input to the on-chain VRF. */ public readonly id: Bytes<32>, /** Which attempt is it? */ public readonly attempt: TicketAttempt, ) { super(); } } /** `K`: Max number of tickets which may be submitted in a single extrinsic. */ declare const MAX_NUMBER_OF_TICKETS = 16; type MAX_NUMBER_OF_TICKETS = typeof MAX_NUMBER_OF_TICKETS; declare const TicketsExtrinsicBounds = `Size: [0..${MAX_NUMBER_OF_TICKETS})`; /** * A sequence of proofs of valid tickets. * * https://graypaper.fluffylabs.dev/#/579bd12/0f13000f1800 * * Constrained by `K = 16`: * https://graypaper.fluffylabs.dev/#/579bd12/416c00416e00 */ type TicketsExtrinsic = KnownSizeArray; declare const ticketsExtrinsicCodec = codecKnownSizeArray( SignedTicket.Codec, { minLength: 0, maxLength: MAX_NUMBER_OF_TICKETS, typicalLength: MAX_NUMBER_OF_TICKETS, }, TicketsExtrinsicBounds, ); type tickets_MAX_NUMBER_OF_TICKETS = MAX_NUMBER_OF_TICKETS; type tickets_SignedTicket = SignedTicket; declare const tickets_SignedTicket: typeof SignedTicket; type tickets_Ticket = Ticket; declare const tickets_Ticket: typeof Ticket; type tickets_TicketAttempt = TicketAttempt; type tickets_TicketsExtrinsic = TicketsExtrinsic; declare const tickets_ticketsExtrinsicCodec: typeof ticketsExtrinsicCodec; declare const tickets_tryAsTicketAttempt: typeof tryAsTicketAttempt; declare namespace tickets { export { type tickets_MAX_NUMBER_OF_TICKETS as MAX_NUMBER_OF_TICKETS, tickets_SignedTicket as SignedTicket, tickets_Ticket as Ticket, type tickets_TicketAttempt as TicketAttempt, type tickets_TicketsExtrinsic as TicketsExtrinsic, tickets_ticketsExtrinsicCodec as ticketsExtrinsicCodec, tickets_tryAsTicketAttempt as tryAsTicketAttempt }; } /** * Encoded validator keys. * https://graypaper.fluffylabs.dev/#/68eaa1f/0e34030e3603?v=0.6.4 */ declare class ValidatorKeys extends WithDebug { static Codec = codec.Class(ValidatorKeys, { bandersnatch: codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(), ed25519: codec.bytes(ED25519_KEY_BYTES).asOpaque(), }); static create({ bandersnatch, ed25519 }: CodecRecord) { return new ValidatorKeys(bandersnatch, ed25519); } private constructor( /** `kappa_b`: Bandersnatch validator keys for the NEXT epoch. */ public readonly bandersnatch: BandersnatchKey, /** `kappa_e`: Ed25519 validator keys for the NEXT epoch. */ public readonly ed25519: Ed25519Key, ) { super(); } } /** * For the first block in a new epoch, the epoch marker is set * and contains the epoch randomness and validator keys * for the NEXT epoch. * * https://graypaper.fluffylabs.dev/#/579bd12/0e30030e6603 */ declare class EpochMarker extends WithDebug { static Codec = codec.Class(EpochMarker, { entropy: codec.bytes(HASH_SIZE).asOpaque(), ticketsEntropy: codec.bytes(HASH_SIZE).asOpaque(), validators: codecPerValidator(ValidatorKeys.Codec), }); static create({ entropy, ticketsEntropy, validators }: CodecRecord) { return new EpochMarker(entropy, ticketsEntropy, validators); } private constructor( /** `eta_1'`: Randomness for the NEXT epoch. */ public readonly entropy: EntropyHash, /** `eta_2'`: Randomness for the CURRENT epoch. */ public readonly ticketsEntropy: EntropyHash, /** `kappa_b`: Bandersnatch validator keys for the NEXT epoch. */ public readonly validators: PerValidator, ) { super(); } } /** * Return an encoded header without the seal components. * * https://graypaper.fluffylabs.dev/#/68eaa1f/370202370302?v=0.6.4 */ declare const encodeUnsealedHeader = (view: HeaderView): BytesBlob => { // we basically need to omit the last field, perhaps there is better // way to do that, but this seems like the most straightforward const encodedFullHeader = view.encoded().raw; const encodedUnsealedLen = encodedFullHeader.length - BANDERSNATCH_VRF_SIGNATURE_BYTES; return BytesBlob.blobFrom(encodedFullHeader.subarray(0, encodedUnsealedLen)); }; /** * The header of the JAM block. * * https://graypaper.fluffylabs.dev/#/579bd12/0c66000c7200 */ declare class Header extends WithDebug { static Codec = codec.Class(Header, { parentHeaderHash: codec.bytes(HASH_SIZE).asOpaque(), priorStateRoot: codec.bytes(HASH_SIZE).asOpaque(), extrinsicHash: codec.bytes(HASH_SIZE).asOpaque(), timeSlotIndex: codec.u32.asOpaque(), epochMarker: codec.optional(EpochMarker.Codec), ticketsMarker: codec.optional(codecPerEpochBlock(Ticket.Codec)), offendersMarker: codec.sequenceVarLen(codec.bytes(ED25519_KEY_BYTES).asOpaque()), bandersnatchBlockAuthorIndex: codec.u16.asOpaque(), entropySource: codec.bytes(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(), seal: codec.bytes(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(), }); static create(h: CodecRecord
) { return Object.assign(Header.empty(), h); } /** * `H_p`: Hash of the parent header. * * In case of the genesis block, the hash will be zero. */ public parentHeaderHash: HeaderHash = Bytes.zero(HASH_SIZE).asOpaque(); /** `H_r`: The state trie root hash before executing that block. */ public priorStateRoot: StateRootHash = Bytes.zero(HASH_SIZE).asOpaque(); /** `H_x`: The hash of block extrinsic. */ public extrinsicHash: ExtrinsicHash = Bytes.zero(HASH_SIZE).asOpaque(); /** `H_t`: JAM time-slot index. */ public timeSlotIndex: TimeSlot = tryAsTimeSlot(0); /** * `H_e`: Key and entropy relevant to the following epoch in case the ticket * contest does not complete adequately. */ public epochMarker: EpochMarker | null = null; /** * `H_w`: Winning tickets provides the series of 600 slot sealing "tickets" * for the next epoch. */ public ticketsMarker: PerEpochBlock | null = null; /** `H_o`: Sequence of keys of newly misbehaving validators. */ public offendersMarker: Ed25519Key[] = []; /** `H_i`: Block author's index in the current validator set. */ public bandersnatchBlockAuthorIndex: ValidatorIndex = tryAsValidatorIndex(0); /** `H_v`: Entropy-yielding VRF signature. */ public entropySource: BandersnatchVrfSignature = Bytes.zero(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(); /** * `H_s`: Block seal. * * https://graypaper.fluffylabs.dev/#/579bd12/0d0c010d1101 */ public seal: BandersnatchVrfSignature = Bytes.zero(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(); private constructor() { super(); } /** Create an empty header with some dummy values. */ public static empty() { return new Header(); } } /** Undecoded View of the [`Header`]. */ type HeaderView = DescribedBy; /** Encoding of header + hash. */ declare const headerViewWithHashCodec = HeaderViewWithHash.Codec; type PreimageHash = Opaque; /** * Service index (requester) and the data (blob). * * https://graypaper.fluffylabs.dev/#/579bd12/181500181600 */ declare class Preimage extends WithDebug { static Codec = codec.Class(Preimage, { requester: codec.u32.asOpaque(), blob: codec.blob, }); static create({ requester, blob }: CodecRecord) { return new Preimage(requester, blob); } private constructor( /** The service which requested the preimage. */ public readonly requester: ServiceId, /** The preimage data blob. */ public readonly blob: BytesBlob, ) { super(); } } /** * The lookup extrinsic is a sequence of pairs of service indices and data. * * These pairs must be ordered and without duplicates. The data must have been * solicited by a service but not yet be provided. */ type PreimagesExtrinsic = Preimage[]; declare const preimagesExtrinsicCodec = codec.sequenceVarLen(Preimage.Codec); type preimage_Preimage = Preimage; declare const preimage_Preimage: typeof Preimage; type preimage_PreimageHash = PreimageHash; type preimage_PreimagesExtrinsic = PreimagesExtrinsic; declare const preimage_preimagesExtrinsicCodec: typeof preimagesExtrinsicCodec; declare namespace preimage { export { preimage_Preimage as Preimage, type preimage_PreimageHash as PreimageHash, type preimage_PreimagesExtrinsic as PreimagesExtrinsic, preimage_preimagesExtrinsicCodec as preimagesExtrinsicCodec }; } /** * Extrinsic part of the block - the input data being external to the system. * * `E = (E_T, E_D, E_P, E_A, E_G)` * * https://graypaper.fluffylabs.dev/#/579bd12/08ab0008ab00 */ declare class Extrinsic extends WithDebug { static Codec = codec.Class(Extrinsic, { tickets: ticketsExtrinsicCodec, preimages: preimagesExtrinsicCodec, guarantees: guaranteesExtrinsicCodec, assurances: assurancesExtrinsicCodec, disputes: DisputesExtrinsic.Codec, }); static create({ tickets, preimages, assurances, disputes, guarantees }: CodecRecord) { return new Extrinsic(tickets, preimages, guarantees, assurances, disputes); } private constructor( /** * `E_T`: Tickets, used for the mechanism which manages the selection of * validators for the permissioning of block authoring. */ public readonly tickets: TicketsExtrinsic, /** * `E_P`: Static data which is presently being requested to be available for * workloads to be able to fetch on demand. */ public readonly preimages: PreimagesExtrinsic, /** * `E_G`: Reports of newly completed workloads whose accuracy is guaranteed * by specific validators. */ public readonly guarantees: GuaranteesExtrinsic, /** * `E_A`: Assurances by each validator concerning which of the input data of * workloads they have correctly received and are storing locally. */ public readonly assurances: AssurancesExtrinsic, /** * `E_D`: Votes, by validators, on dispute(s) arising between them presently * taking place. */ public readonly disputes: DisputesExtrinsic, ) { super(); } } /** Undecoded View of an [`Extrinsic`]. */ type ExtrinsicView = DescribedBy; /** * The block consists of the header and some external input data (extrinsic). * * `B = (H, E)` * https://graypaper.fluffylabs.dev/#/579bd12/089900089900 */ declare class Block extends WithDebug { static Codec = codec.Class(Block, { header: Header.Codec, extrinsic: Extrinsic.Codec, }); static create({ header, extrinsic }: CodecRecord) { return new Block(header, extrinsic); } private constructor( /** `H`: Block header. */ public readonly header: Header, /** `E`: Extrinsic data. */ public readonly extrinsic: Extrinsic, ) { super(); } } /** Undecoded View of a [`Block`]. */ type BlockView = DescribedBy; type index_Block = Block; declare const index_Block: typeof Block; type index_BlockView = BlockView; type index_CodeHash = CodeHash; type index_CoreIndex = CoreIndex; type index_EntropyHash = EntropyHash; type index_Epoch = Epoch; type index_EpochMarker = EpochMarker; declare const index_EpochMarker: typeof EpochMarker; type index_Extrinsic = Extrinsic; declare const index_Extrinsic: typeof Extrinsic; type index_ExtrinsicHash = ExtrinsicHash; type index_ExtrinsicView = ExtrinsicView; type index_Header = Header; declare const index_Header: typeof Header; type index_HeaderHash = HeaderHash; type index_HeaderView = HeaderView; declare const index_MAX_NUMBER_OF_SEGMENTS: typeof MAX_NUMBER_OF_SEGMENTS; type index_PerEpochBlock = PerEpochBlock; type index_PerValidator = PerValidator; type index_SEGMENT_BYTES = SEGMENT_BYTES; type index_Segment = Segment; type index_SegmentIndex = SegmentIndex; type index_ServiceGas = ServiceGas; type index_ServiceId = ServiceId; type index_StateRootHash = StateRootHash; type index_TimeSlot = TimeSlot; type index_ValidatorIndex = ValidatorIndex; type index_ValidatorKeys = ValidatorKeys; declare const index_ValidatorKeys: typeof ValidatorKeys; type index_WorkReportHash = WorkReportHash; declare const index_assurances: typeof assurances; declare const index_codecPerEpochBlock: typeof codecPerEpochBlock; declare const index_codecPerValidator: typeof codecPerValidator; declare const index_disputes: typeof disputes; declare const index_encodeUnsealedHeader: typeof encodeUnsealedHeader; declare const index_guarantees: typeof guarantees; declare const index_headerViewWithHashCodec: typeof headerViewWithHashCodec; declare const index_preimage: typeof preimage; declare const index_refineContext: typeof refineContext; declare const index_tickets: typeof tickets; declare const index_tryAsCoreIndex: typeof tryAsCoreIndex; declare const index_tryAsEpoch: typeof tryAsEpoch; declare const index_tryAsPerEpochBlock: typeof tryAsPerEpochBlock; declare const index_tryAsPerValidator: typeof tryAsPerValidator; declare const index_tryAsSegmentIndex: typeof tryAsSegmentIndex; declare const index_tryAsServiceGas: typeof tryAsServiceGas; declare const index_tryAsServiceId: typeof tryAsServiceId; declare const index_tryAsTimeSlot: typeof tryAsTimeSlot; declare const index_tryAsValidatorIndex: typeof tryAsValidatorIndex; declare const index_workItem: typeof workItem; declare const index_workPackage: typeof workPackage; declare const index_workReport: typeof workReport; declare const index_workResult: typeof workResult; declare namespace index { export { index_Block as Block, type index_BlockView as BlockView, type index_CodeHash as CodeHash, type index_CoreIndex as CoreIndex, type index_EntropyHash as EntropyHash, type index_Epoch as Epoch, index_EpochMarker as EpochMarker, index_Extrinsic as Extrinsic, type index_ExtrinsicHash as ExtrinsicHash, type index_ExtrinsicView as ExtrinsicView, index_Header as Header, type index_HeaderHash as HeaderHash, type index_HeaderView as HeaderView, index_MAX_NUMBER_OF_SEGMENTS as MAX_NUMBER_OF_SEGMENTS, type index_PerEpochBlock as PerEpochBlock, type index_PerValidator as PerValidator, type index_SEGMENT_BYTES as SEGMENT_BYTES, type index_Segment as Segment, type index_SegmentIndex as SegmentIndex, type index_ServiceGas as ServiceGas, type index_ServiceId as ServiceId, type index_StateRootHash as StateRootHash, type index_TimeSlot as TimeSlot, type index_ValidatorIndex as ValidatorIndex, index_ValidatorKeys as ValidatorKeys, type index_WorkReportHash as WorkReportHash, index_assurances as assurances, index$5 as bytes, index$4 as codec, index_codecPerEpochBlock as codecPerEpochBlock, index_codecPerValidator as codecPerValidator, codec as codecUtils, index$1 as config, index_disputes as disputes, index_encodeUnsealedHeader as encodeUnsealedHeader, index_guarantees as guarantees, index_headerViewWithHashCodec as headerViewWithHashCodec, index_preimage as preimage, index_refineContext as refineContext, index_tickets as tickets, index_tryAsCoreIndex as tryAsCoreIndex, index_tryAsEpoch as tryAsEpoch, index_tryAsPerEpochBlock as tryAsPerEpochBlock, index_tryAsPerValidator as tryAsPerValidator, index_tryAsSegmentIndex as tryAsSegmentIndex, index_tryAsServiceGas as tryAsServiceGas, index_tryAsServiceId as tryAsServiceId, index_tryAsTimeSlot as tryAsTimeSlot, index_tryAsValidatorIndex as tryAsValidatorIndex, index_workItem as workItem, index_workPackage as workPackage, index_workReport as workReport, index_workResult as workResult }; } interface IHostCallMemory { storeFrom(address: U64, bytes: Uint8Array): Result$2; loadInto(result: Uint8Array, startAddress: U64): Result$2; getMemory(): Memory; } declare class HostCallMemory implements IHostCallMemory { constructor(private readonly memory: Memory) {} storeFrom(address: U64, bytes: Uint8Array): Result$2 { if (bytes.length === 0) { return Result.ok(OK); } if (address + tryAsU64(bytes.length) > MEMORY_SIZE) { return Result.error(new OutOfBounds()); } return this.memory.storeFrom(tryAsMemoryIndex(Number(address)), bytes); } loadInto(result: Uint8Array, startAddress: U64): Result$2 { if (result.length === 0) { return Result.ok(OK); } if (startAddress + tryAsU64(result.length) > MEMORY_SIZE) { return Result.error(new OutOfBounds()); } return this.memory.loadInto(result, tryAsMemoryIndex(Number(startAddress))); } getMemory(): Memory { return this.memory; } } interface IHostCallRegisters { get(registerIndex: number): U64; set(registerIndex: number, value: U64): void; } declare class HostCallRegisters implements IHostCallRegisters { constructor(private readonly registers: Registers) {} get(registerIndex: number): U64 { return tryAsU64(this.registers.getU64(registerIndex)); } set(registerIndex: number, value: U64) { this.registers.setU64(registerIndex, value); } } declare const SERVICE_ID_BYTES = 4; declare const CURRENT_SERVICE_ID = tryAsServiceId(2 ** 32 - 1); declare function getServiceIdOrCurrent( regNumber: number, regs: IHostCallRegisters, currentServiceId: ServiceId, ): ServiceId | null { const regValue = regs.get(regNumber); if (regValue === 2n ** 64n - 1n) { return currentServiceId; } return getServiceId(regValue); } declare function getServiceId(serviceId: U64): ServiceId | null { const { lower, upper } = u64IntoParts(serviceId); if (upper === 0) { return tryAsServiceId(lower); } return null; } declare function writeServiceIdAsLeBytes(serviceId: ServiceId, destination: Uint8Array) { check(destination.length >= SERVICE_ID_BYTES, "Not enough space in the destination."); destination.set(u32AsLeBytes(serviceId)); } /** Clamp a U64 to the maximum value of a 32-bit unsigned integer. */ declare function clampU64ToU32(value: U64): U32 { return value > MAX_U32_BIG_INT ? MAX_U32 : tryAsU32(Number(value)); } export { type Args, ArgsDecoder, ArgumentType, BasicBlocks, CURRENT_SERVICE_ID, type ErrorResult, ExtendedWitdthImmediateDecoder, HostCallMemory, HostCallRegisters, HostCallResult, type IHostCallMemory, type IHostCallRegisters, ImmediateDecoder, Mask, MemorySegment, NO_OF_REGISTERS, NibblesDecoder, OK, type OkResult, type Opaque, Program, ProgramDecoder, DebuggerAdapter as Pvm, Registers, Result$2 as Result, SERVICE_ID_BYTES, SpiMemory, SpiProgram, type TaggedError, type TokenOf, WithDebug, type WithOpaque, asOpaqueType, assertEmpty, assertNever, index as block, index$5 as bytes, check, clampU64ToU32, createResults, decodeStandardProgram, ensure, extractCodeAndMetadata, getServiceId, getServiceIdOrCurrent, index$2 as hash, inspect, instructionArgumentTypeMap, index$3 as interpreter, measure, index$6 as numbers, resultToString, seeThrough, writeServiceIdAsLeBytes };