/** * Utilities: assertions, conversions. * @module */ import type { HashInstance, HashState } from './hashes-abstract.ts'; /** * Bytes API type helpers for old + new TypeScript. * * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. * We can't use specific return type, because TS 5.6 will error. * We can't use generic return type, because most TS 5.9 software will expect specific type. * * Maps typed-array input leaves to broad forms. * These are compatibility adapters, not ownership guarantees. * * - `TArg` keeps byte inputs broad. * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. */ export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; /** Maps typed-array output leaves to narrow TS-compatible forms. */ export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; /** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { [K in keyof A]: TRet; }) => TArg) & { [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; } : T extends [infer A, ...infer R] ? [TArg, ...{ [K in keyof R]: TArg; }] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ [K in keyof R]: TArg; }] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { [K in keyof T]: TArg; } : T : TypedArg); /** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { [K in keyof A]: TArg; }) => TRet) & { [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; } : T extends [infer A, ...infer R] ? [TRet, ...{ [K in keyof R]: TRet; }] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ [K in keyof R]: TRet; }] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { [K in keyof T]: TRet; } : T : TypedRet) : never; /** Whether the current platform is little-endian. */ export declare const isLE: boolean; declare const assertLE: (littleEndian?: boolean) => void; /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */ /** * Checks whether a value is a byte-oriented Uint8Array view. * @param a - value to inspect. * @returns True when the value is a Uint8Array-compatible byte view. * @example * ```ts * import { isBytes } from '@awasm/noble/utils.js'; * isBytes(new Uint8Array([1, 2, 3])); * ``` */ export declare function isBytes(a: unknown): a is Uint8Array; /** * Asserts something is boolean. * @param b - value to validate. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { abool } from '@awasm/noble/utils.js'; * abool(true); * ``` */ export declare function abool(b: boolean): void; /** * Asserts something is a non-negative safe integer. * @param n - value to validate. * @param title - optional field name for error messages. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * ```ts * import { anumber } from '@awasm/noble/utils.js'; * anumber(7, 'count'); * ``` */ export declare function anumber(n: number, title?: string): void; /** * Asserts something is Uint8Array. * @param value - byte array candidate. * @param length - optional exact length requirement. * @param title - optional field name for error messages. * @returns The validated byte array. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * ```ts * import { abytes } from '@awasm/noble/utils.js'; * abytes(new Uint8Array([1, 2, 3]), 3, 'msg'); * ``` */ export declare function abytes(value: TArg, length?: number, title?: string): TRet; /** * Asserts a hash-like instance has not been destroyed or finished. * @param instance - instance to validate. * @param checkFinished - whether to reject already-finished instances. * @throws If the documented runtime validation or state check fails. {@link Error} * @example * ```ts * import { aexists } from '@awasm/noble/utils.js'; * aexists({ destroyed: false, finished: false }); * ``` */ export declare function aexists(instance: any, checkFinished?: boolean): void; /** * Asserts an output buffer is a byte array with sufficient capacity. * @param out - destination buffer. * @param instance - object exposing `outputLen`. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * ```ts * import { aoutput } from '@awasm/noble/utils.js'; * aoutput(new Uint8Array(32), { outputLen: 32 }); * ``` */ export declare function aoutput(out: any, instance: any): void; /** * Asserts a hash surface looks like one produced by the hash factory. * @param h - hash surface to validate. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @throws If a documented runtime validation or state check fails. {@link Error} * @example * ```ts * import { sha256 } from '@awasm/noble'; * import { ahash } from '@awasm/noble/utils.js'; * ahash(sha256); * ``` */ export declare function ahash(h: TArg>): void; /** Compatibility alias matching noble-hashes `CHash` consumers. */ export type CHash<_T = any, Opts = undefined> = HashInstance; /** Compatibility alias matching noble-hashes `CHashXOF` consumers. */ export type CHashXOF<_T = any, Opts = undefined> = HashInstance; /** Opaque state returned by `hash.create().exportState()`. */ export type { HashState }; /** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */ export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; /** * Casts a typed-array view to bytes over the same memory region. * Shared buffer view in native memory order; used for internal state init, not endian-normalized serialization. * @param arr - source typed-array view. * @returns Byte view over the same buffer region. * @example * ```ts * import { u8 } from '@awasm/noble/utils.js'; * u8(new Uint32Array([1])); * ``` */ export declare function u8(arr: TArg): TRet; /** * Casts a typed-array view to 32-bit words over the same memory region. * Shared native-order word view; byteOffset must be 4-byte aligned and trailing 1..3 bytes are ignored. * @param arr - source typed-array view. * @returns Uint32Array view over the same buffer region. * @example * ```ts * import { u32 } from '@awasm/noble/utils.js'; * u32(new Uint8Array([1, 2, 3, 4])); * ``` */ export declare function u32(arr: TArg): TRet; /** * Byte-swaps each 32-bit word on big-endian platforms. * @param arr - word array to normalize in place. * @returns The input array after any required byte swaps. * @example * ```ts * import { swap32IfBE } from '@awasm/noble/utils.js'; * const words = new Uint32Array([0x11223344]); * swap32IfBE(words); * ``` */ export declare function swap32IfBE(arr: TArg): TRet; /** * Zeroize typed arrays in place. Warning: JS provides no guarantees. * @param arrays - arrays to overwrite with zeros. * @example * ```ts * import { clean } from '@awasm/noble/utils.js'; * const buf = new Uint8Array([1, 2, 3]); * clean(buf); * ``` */ export declare function clean(...arrays: TArg): void; /** * Fast zeroization for large byte buffers. * @param dst - destination buffer. * @param len - prefix length to clear. * @example * ```ts * import { cleanFast } from '@awasm/noble/utils.js'; * cleanFast(new Uint8Array(16), 8); * ``` */ export declare const cleanFast: (dst: TArg, len?: number) => void; /** * Create a DataView over the same buffer region; writes through it mutate the original array. * @param arr - source typed-array view. * @returns DataView over the same buffer region. * @example * ```ts * import { createView } from '@awasm/noble/utils.js'; * createView(new Uint8Array(8)); * ``` */ export declare function createView(arr: TArg): DataView; /** * Checks if two byte arrays overlap in the same underlying buffer. * This is invalid and can corrupt data. * @param a - first byte view. * @param b - second byte view. * @returns True when the byte ranges overlap. * @example * ```ts * import { overlapBytes } from '@awasm/noble/utils.js'; * const buf = new Uint8Array(8); * overlapBytes(buf.subarray(0, 4), buf.subarray(2, 6)); * ``` */ export declare function overlapBytes(a: TArg, b: TArg): boolean; export declare const __TEST: Readonly<{ assertLE: typeof assertLE; }>; /** * Convert byte array to hex string. Uses built-in function, when available. * @param bytes - bytes to encode. * @returns Lowercase hex string. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { bytesToHex } from '@awasm/noble/utils.js'; * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); * ``` */ export declare function bytesToHex(bytes: TArg): string; /** * Convert hex string to byte array. Uses built-in function, when available. * @param hex - hex string to decode. * @returns Decoded bytes. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * ```ts * import { hexToBytes } from '@awasm/noble/utils.js'; * hexToBytes('cafe0123'); * ``` */ export declare function hexToBytes(hex: string): TRet; /** * There is no setImmediate in browser and setTimeout is slow. * Call of async fn will return Promise, which will be fullfiled only on * next scheduler queue processing step and this is exactly what we need. * This yields to the Promise/microtask scheduler queue, not to timers or the full macrotask event loop. * @example * ```ts * import { nextTick } from '@awasm/noble/utils.js'; * await nextTick(); * ``` */ export declare const nextTick: () => Promise; /** * Returns control to the Promise/microtask scheduler every `tick` ms to avoid blocking long loops. * @param iters - number of loop iterations. * @param tick - maximum milliseconds to spend before yielding. * @param cb - callback invoked for each iteration index. */ export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; /** * Converts string to bytes using UTF8 encoding. * Built-in doesn't validate input to be string: we do the check. * Non-ASCII details are delegated to the platform TextEncoder. * @param str - string to encode. * @returns UTF-8 bytes. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { utf8ToBytes } from '@awasm/noble/utils.js'; * utf8ToBytes('abc'); * ``` */ export declare function utf8ToBytes(str: string): TRet; /** * Convert byte array to string, assuming UTF8 encoding. * Input validation and malformed-sequence handling are delegated to TextDecoder: * invalid UTF-8 is replacement-decoded, not rejected. * @param bytes - bytes to decode. * @returns UTF-8 string. * @example * ```ts * import { bytesToUtf8 } from '@awasm/noble/utils.js'; * bytesToUtf8(new Uint8Array([97, 98, 99])); * ``` */ export declare function bytesToUtf8(bytes: TArg): string; /** * Checks whether a byte array is aligned to a 4-byte offset. * @param bytes - byte view to inspect. * @returns True when the view is 32-bit aligned. * @example * ```ts * import { isAligned32 } from '@awasm/noble/utils.js'; * isAligned32(new Uint8Array(8)); * ``` */ export declare function isAligned32(bytes: TArg): boolean; /** * By default, returns u8a of expected length. * When `out` is specified, it checks it for validity and uses it. * @param expectedLength - expected output length in bytes. * @param out - optional caller-provided destination buffer. * @param onlyAligned - whether to require 32-bit alignment for `out`. * @returns Output buffer with the expected length. * @throws On wrong argument types. {@link TypeError} * @throws If a documented runtime validation or state check fails. {@link Error} * @example * ```ts * import { getOutput } from '@awasm/noble/utils.js'; * getOutput(16); * ``` */ export declare function getOutput(expectedLength: number, out?: TArg, onlyAligned?: boolean): TRet; /** * Encodes the AEAD length block as aadLength || dataLength. * Callers pass lengths already scaled to the mode's unit: * octets for ChaCha20-Poly1305, bits for GCM/GCM-SIV. * @param dataLength - encoded data length. * @param aadLength - encoded AAD length. * @param isLE - whether to write values in little-endian order. * @returns Encoded 16-byte length block. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * ```ts * import { u64Lengths } from '@awasm/noble/utils.js'; * u64Lengths(16, 8, true); * ``` */ export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet; /** KDFs can accept string or Uint8Array for user convenience. */ export type KDFInput = string | Uint8Array; /** * Helper for KDFs: consumes Uint8Array or string. * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer. * @param data - string or bytes input. * @param errorTitle - optional field name for byte validation. * @returns Byte representation of the input. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { kdfInputToBytes } from '@awasm/noble/utils.js'; * kdfInputToBytes('password'); * ``` */ export declare function kdfInputToBytes(data: TArg, errorTitle?: string): TRet; /** * Copies several Uint8Arrays into one. * @param arrays - arrays to concatenate. * @returns Concatenated bytes. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { concatBytes } from '@awasm/noble/utils.js'; * concatBytes(new Uint8Array([1]), new Uint8Array([2, 3])); * ``` */ export declare function concatBytes(...arrays: TArg): TRet; /** * Fast copy for validated, in-bounds byte ranges. * Overlap is intentionally unsupported here for speed: hot callers only pass disjoint ranges, * and same-buffer moves must use copyWithin()/set() at the call site instead. * @param dst - destination byte array. * @param dstPos - write offset in destination. * @param src - source byte array. * @param srcPos - read offset in source. * @param len - number of bytes to copy. * @example * ```ts * import { copyFast } from '@awasm/noble/utils.js'; * const dst = new Uint8Array(4); * copyFast(dst, 1, new Uint8Array([7, 8]), 0, 2); * ``` */ export declare function copyFast(dst: TArg, dstPos: number, src: TArg, srcPos: number, len: number): void; /** * Fast copy for validated, in-bounds 32-bit word ranges. * Overlap is intentionally unsupported here for speed: hot callers only pass disjoint ranges, * and same-buffer moves must use copyWithin()/set() at the call site instead. * @param dst - destination word array. * @param dstPos - write offset in destination. * @param src - source word array. * @param srcPos - read offset in source. * @param len - number of words to copy. * @example * ```ts * import { copyFast32 } from '@awasm/noble/utils.js'; * const dst = new Uint32Array(4); * copyFast32(dst, 1, new Uint32Array([7, 8]), 0, 2); * ``` */ export declare function copyFast32(dst: TArg, dstPos: number, src: TArg, srcPos: number, len: number): void; /** * Callers must pass a validated byte array; Uint8Array.from() would otherwise coerce arbitrary iterables. * Copies into a detached Uint8Array instead of using slice(), because Buffer.slice() aliases memory. * @param bytes - bytes to copy. * @returns Detached copy of the input bytes. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { copyBytes } from '@awasm/noble/utils.js'; * copyBytes(new Uint8Array([1, 2, 3])); * ``` */ export declare function copyBytes(bytes: TArg): TRet; /** * Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. * Current callers pass one-byte hashAlgs suffixes for 2.16.840.1.101.3.4.2., * so the DER length byte stays 0x09. * @param suffix - final OID suffix byte. * @returns DER-encoded OID bytes. * @example * ```ts * import { oidNist } from '@awasm/noble/utils.js'; * oidNist(1); * ``` */ export declare const oidNist: (suffix: number) => TRet; type EmptyObj = {}; /** * Merges default options and passed options. * This mutates `defaults`, so callers pass fresh defaults when they need reuse. * @param defaults - default option object. * @param opts - caller-provided overrides. * @returns Merged options object. * @throws On wrong argument types. {@link TypeError} * @example * ```ts * import { checkOpts } from '@awasm/noble/utils.js'; * checkOpts({ a: 1 }, { b: 2 }); * ``` */ export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; /** Async execution options shared by generator-backed wrappers. */ export type AsyncOpts = { /** Total number of progress units for the run. */ total: number; /** Maximum time in ms before yielding control in async mode. */ asyncTick?: number; /** * Optional progress callback receiving values in the `[0, 1]` range. * @param progress - normalized progress value in the `[0, 1]` range. */ onProgress?: (progress: number) => void; /** Optional serialized-state size in bytes for resumable async work. */ stateBytes?: number; /** * Save callback for resumable async work. * @param state - serialized algorithm state bytes. */ save?: (state: Uint8Array) => void; /** * Restore callback for resumable async work. * @param state - serialized algorithm state bytes. */ restore?: (state: Uint8Array) => void; /** Optional scheduler override used instead of the default microtask tick. */ nextTick?: () => Promise; }; /** Common async-call options for APIs that expose `.async(...)`. */ export type AsyncRunOpts = Pick; /** Factory that turns per-call async options into a progress/yield callback. */ export type AsyncSetup = (opts: AsyncOpts) => (inc?: number) => boolean; /** Function with a matching `.async(...)` variant. */ export type AsyncFn = ((...args: T) => R) & { async: (...args: T) => Promise; }; /** Converts a sync function shape into a sync + async callable shape. */ export type Asyncify any> = AsyncFn, ReturnType>; /** * Build sync and async wrappers from the same generator body. * @param cb_ - generator callback shared by sync and async variants. * @returns Function exposing both sync and `.async(...)` entrypoints. * @example * ```ts * import { mkAsync } from '@awasm/noble/utils.js'; * const twice = mkAsync(function* (_setup, value: number) { * return value * 2; * }); * await twice.async(2); * ``` */ export declare function mkAsync(cb_: TArg<(setup: AsyncSetup, ...args: T) => Generator>): AsyncFn; /** * Compares two byte arrays in kinda constant time once lengths already match. * Different lengths return false immediately. * @param a - first byte array. * @param b - second byte array. * @returns True when the byte arrays are equal. * @example * ```ts * import { equalBytes } from '@awasm/noble/utils.js'; * equalBytes(new Uint8Array([1, 2]), new Uint8Array([1, 2])); * ``` */ export declare function equalBytes(a: TArg, b: TArg): boolean; /** * Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. * @param bytesLength - number of random bytes to generate. * @returns Random bytes. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @throws If a documented runtime validation or state check fails. {@link Error} * @example * ```ts * import { randomBytes } from '@awasm/noble/utils.js'; * randomBytes(16); * ``` */ export declare function randomBytes(bytesLength?: number): TRet; /** Sync cipher: takes byte array and returns byte array. */ export type Cipher = { /** * Encrypt plaintext bytes. * @param plaintext - plaintext bytes to encrypt. * @returns Ciphertext bytes. */ encrypt(plaintext: TArg): TRet; /** * Decrypt ciphertext bytes. * @param ciphertext - ciphertext bytes to decrypt. * @returns Plaintext bytes. */ decrypt(ciphertext: TArg): TRet; }; /** Async cipher e.g. from built-in WebCrypto. */ export type AsyncCipher = { /** * Encrypt plaintext bytes asynchronously. * @param plaintext - plaintext bytes to encrypt. * @returns Promise resolving to ciphertext bytes. */ encrypt(plaintext: TArg): Promise>; /** * Decrypt ciphertext bytes asynchronously. * @param ciphertext - ciphertext bytes to decrypt. * @returns Promise resolving to plaintext bytes. */ decrypt(ciphertext: TArg): Promise>; }; /** Cipher with `output` argument which can optimize by doing 1 less allocation. */ export type CipherWithOutput = Cipher & { encrypt(plaintext: TArg, output?: TArg): TRet; decrypt(ciphertext: TArg, output?: TArg): TRet; }; type RemoveNonceInner = ((...args: T) => Ret) extends (arg0: any, arg1: any, ...rest: infer R) => any ? (key: Uint8Array, ...args: R) => Ret : never; /** Removes the nonce parameter from a nonce-taking cipher factory type. */ export type RemoveNonce any> = RemoveNonceInner, ReturnType>; /** Cipher factory shape that accepts `(key, nonce, ...args)`. */ export type CipherWithNonce = ((key: TArg, nonce: TArg, ...args: any[]) => TRet) & { nonceLength?: number; }; /** * Uses CSPRNG for nonce and injects it into ciphertext. * For `encrypt`, a `nonceLength`-byte nonce is fetched from CSPRNG and * prepended to encrypted ciphertext. For `decrypt`, the first `nonceLength` * bytes of ciphertext are treated as nonce. * * The wrapper always allocates a fresh `nonce || ciphertext` buffer on encrypt * and intentionally does not support caller-provided destination buffers. * Too-short decrypt inputs are split into short/empty nonce views and then * delegated to the wrapped cipher instead of being rejected here first. * * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha * should be limited to `2**23` (8M) messages to get a collision chance of * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to * `2**-33`, still negligible but creeping up. * @param fn - nonce-taking cipher factory. * @param randomBytes_ - CSPRNG used to generate nonces. * @returns Cipher factory that prepends managed nonces to ciphertext. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * ```ts * import { managedNonce } from '@awasm/noble/utils.js'; * import { xchacha20poly1305 } from '@awasm/noble'; * const cipher = managedNonce(xchacha20poly1305)(new Uint8Array(32)); * const sealed = cipher.encrypt(new Uint8Array([1, 2, 3])); * cipher.decrypt(sealed); * ``` */ export declare function managedNonce(fn: T, randomBytes_?: typeof randomBytes): TRet>; //# sourceMappingURL=utils.d.ts.map