From: Chris Duncan Date: Wed, 23 Jul 2025 19:48:19 +0000 (-0700) Subject: Add more type definitions. X-Git-Tag: v0.10.5~55^2~7 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=c7777730884e949fd004bf173933a9f3c8bdaad3;p=libnemo.git Add more type definitions. --- diff --git a/src/types.d.ts b/src/types.d.ts index 4f5f371..64d87dd 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -1,6 +1,10 @@ //! SPDX-FileCopyrightText: 2025 Chris Duncan //! SPDX-License-Identifier: GPL-3.0-or-later +import { default as TransportBLE } from '@ledgerhq/hw-transport-web-ble' +import { default as TransportUSB } from '@ledgerhq/hw-transport-webusb' +import { default as TransportHID } from '@ledgerhq/hw-transport-webhid' + /** * Represents a single Nano address and the associated public key. To include the * matching private key, it must be known at the time of object instantiation. @@ -150,6 +154,68 @@ export declare class AccountList extends Object { [Symbol.iterator] (): Iterator } +/** +* Represents a mnemonic phrase that identifies a wallet as defined by BIP-39. +*/ +export declare class Bip39Mnemonic { + #private + get phrase (): string + private constructor () + /** + * Imports and validates an existing mnemonic phrase. + * + * The phrase must be valid according to the BIP-39 specification. Typically + * wallets use the maximum of 24 words. + * + * @param {string} phrase - String of 12, 15, 18, 21, or 24 words + * @returns {string} Mnemonic phrase validated using the BIP-39 wordlist + */ + static fromPhrase (phrase: string): Promise + /** + * Derives a mnemonic phrase from source of entropy or seed. + * + * The entropy must be between 32-64 characters to stay within the defined + * limit of 128-256 bits. Typically wallets use the maximum entropy allowed. + * + * @param {string} entropy - Hexadecimal string + * @returns {string} Mnemonic phrase created using the BIP-39 wordlist + */ + static fromEntropy (entropy: string): Promise + /** + * SHA-256 hash of entropy that is appended to the entropy and subsequently + * used to generate the mnemonic phrase. + * + * @param {Entropy} entropy - Cryptographically strong pseudorandom data of length N bits + * @returns {Promise} First N/32 bits of the hash as a hexadecimal string + */ + static checksum (entropy: Entropy): Promise + /** + * Validates a mnemonic phrase. + * + * @param {string} mnemonic - Mnemonic phrase to validate + * @returns {boolean} True if the mnemonic phrase is valid + */ + static validate (mnemonic: string): Promise + toBip39Seed (passphrase: string): Promise> + /** + * Converts the mnemonic phrase to a BIP-39 seed. + * + * A passphrase string can be specified. If the passphrase is undefined, null, + * or not a string, the empty string ("") is used instead. + * + * @param {string} [passphrase=''] - Used as the PBKDF2 salt. Default: "" + * @returns {string} Hexadecimal seed + */ + toBip39Seed (passphrase: string, format: 'hex'): Promise + toBlake2bSeed (): Promise> + /** + * Converts the mnemonic phrase to a BLAKE2b seed. + * + * @returns {string} Hexadecimal seed + */ + toBlake2bSeed (format: 'hex'): Promise +} + /** * Represents a block as defined by the Nano cryptocurrency protocol. The Block * class is abstract and cannot be directly instantiated. Every block must be one @@ -278,6 +344,55 @@ export declare class ChangeBlock extends Block { export type Data = boolean | number[] | string | ArrayBuffer +/** +* Represents a cryptographically strong source of entropy suitable for use in +* BIP-39 mnemonic phrase generation and consequently BIP-44 key derivation. +* +* The constructor will accept one of several different data types under certain +* constraints. If the constraints are not met, an error will be thrown. If no +* value, or the equivalent of no value, is passed to the constructor, then a +* brand new source of entropy will be generated at the maximum size of 256 bits. +*/ +export declare class Entropy { + #private + static MIN: 16 + static MAX: 32 + static MOD: 4 + get bits (): string + get buffer (): ArrayBuffer + get bytes (): Uint8Array + get hex (): string + private constructor () + /** + * Generate 256 bits of entropy. + */ + static create (): Promise + /** + * Generate between 16-32 bytes of entropy. + * @param {number} size - Number of bytes to generate in multiples of 4 + */ + static create (size: number): Promise + /** + * Import existing entropy and validate it. + * @param {string} hex - Hexadecimal string + */ + static import (hex: string): Promise + /** + * Import existing entropy and validate it. + * @param {ArrayBuffer} buffer - Byte buffer + */ + static import (buffer: ArrayBuffer): Promise + /** + * Import existing entropy and validate it. + * @param {Uint8Array} bytes - Byte array + */ + static import (bytes: Uint8Array): Promise + /** + * Randomizes the bytes, rendering the original values generally inaccessible. + */ + destroy (): boolean +} + export type NamedData = { [key: string]: T } @@ -353,6 +468,500 @@ export declare class Rolodex { static verify (name: string, signature: string, ...data: string[]): Promise } +type SweepResult = { + status: "success" | "error" + address: string + message: string +} +/** +* Converts a decimal amount of nano from one unit divider to another. +* +* @param {bigint|string} amount - Decimal amount to convert +* @param {string} inputUnit - Current denomination +* @param {string} outputUnit - Desired denomination +*/ +export declare function convert (amount: bigint | string, inputUnit: string, outputUnit: string): Promise +declare function hash (data: string | string[], encoding?: 'hex'): Uint8Array +/** +* Signs arbitrary strings with a private key using the Ed25519 signature scheme. +* +* @param {Key} key - Hexadecimal-formatted private key to use for signing +* @param {...string} input - Data to be signed +* @returns {Promise} Hexadecimal-formatted signature +*/ +export declare function sign (key: Key, ...input: string[]): Promise +/** +* Collects the funds from a specified range of accounts in a wallet and sends +* them all to a single recipient address. Hardware wallets are unsupported. +* +* @param {Rpc|string|URL} rpc - RPC node information required to refresh accounts, calculate PoW, and process blocks +* @param {Blake2bWallet|Bip44Wallet|LedgerWallet} wallet - Wallet from which to sweep funds +* @param {string} recipient - Destination address for all swept funds +* @param {number} from - Starting account index to sweep +* @param {number} to - Ending account index to sweep +* @returns An array of results including both successes and failures + */ +export declare function sweep (rpc: Rpc | string | URL, wallet: Blake2bWallet | Bip44Wallet | LedgerWallet, recipient: string, from?: number, to?: number): Promise +/** +* Verifies the signature of arbitrary strings using a public key. +* +* @param {Key} key - Hexadecimal-formatted public key to use for verification +* @param {string} signature - Hexadcimal-formatted signature +* @param {...string} input - Data to be verified +* @returns {Promise} True if the data was signed by the public key's matching private key +*/ +export declare function verify (key: Key, signature: string, ...input: string[]): Promise + +export declare const Tools: { + convert: typeof convert + hash: typeof hash + sign: typeof sign + sweep: typeof sweep + verify: typeof verify +} + +/** +* Represents a wallet containing numerous Nano accounts derived from a single +* source, the form of which can vary based on the type of wallet. The Wallet +* class itself is abstract and cannot be directly instantiated. Currently, three +* types of wallets are supported, each as a derived class: Bip44Wallet, +* Blake2bWallet, LedgerWallet. +*/ +export declare abstract class Wallet { + #private + abstract ckd (index: number[]): Promise + get id (): string + get isLocked (): boolean + get isUnlocked (): boolean + get mnemonic (): string | null + get seed (): string | null + constructor (id: Entropy, seed?: Uint8Array, mnemonic?: Bip39Mnemonic) + /** + * Retrieves an account from a wallet using its child key derivation function. + * Defaults to the first account at index 0. + * + * ``` + * console.log(await wallet.account(5)) + * // outputs sixth account of the wallet + * // { + * // privateKey: <...>, + * // index: 5 + * // } + * ``` + * + * @param {number} index - Wallet index of secret key. Default: 0 + * @returns {Account} Account derived at the specified wallet index + */ + account (index?: number): Promise + /** + * Retrieves accounts from a wallet using its child key derivation function. + * Defaults to the first account at index 0. + * + * The returned object will have keys corresponding with the requested range + * of account indexes. The value of each key will be the Account derived for + * that index in the wallet. + * + * ``` + * console.log(await wallet.accounts(5)) + * // outputs sixth account of the wallet + * // { + * // 5: { + * // privateKey: <...>, + * // index: 5 + * // } + * // } + * ``` + * + * @param {number} from - Start index of secret keys. Default: 0 + * @param {number} to - End index of secret keys. Default: `from` + * @returns {AccountList} Object with keys of account indexes and values of the corresponding Accounts + */ + accounts (from?: number, to?: number): Promise + /** + * Removes encrypted secrets in storage and releases variable references to + * allow garbage collection. + */ + destroy (): Promise + /** + * Locks the wallet and all currently derived accounts with a password that + * will be needed to unlock it later. + * + * @param {Key} password Used to lock the wallet + * @returns True if successfully locked + */ + lock (password: Key): Promise + /** + * Refreshes wallet account balances, frontiers, and representatives from the + * current state on the network. + * + * A successful response will set these properties on each account. + * + * @param {Rpc|string|URL} rpc - RPC node information required to refresh accounts, calculate PoW, and process blocks + * @returns {Promise} Accounts with updated balances, frontiers, and representatives + */ + refresh (rpc: Rpc | string | URL, from?: number, to?: number): Promise + /** + * Unlocks the wallet using the same password as used prior to lock it. + * + * @param {Key} password Used previously to lock the wallet + * @returns True if successfully unlocked + */ + unlock (password: Key): Promise + /** + * Fetches the lowest-indexed unopened account from a wallet in sequential + * order. An account is unopened if it has no frontier block. + * + * @param {Rpc|string|URL} rpc - RPC node information required to refresh accounts, calculate PoW, and process blocks + * @param {number} batchSize - Number of accounts to fetch and check per RPC callout + * @param {number} from - Account index from which to start the search + * @returns {Promise} The lowest-indexed unopened account belonging to the wallet + */ + unopened (rpc: Rpc, batchSize?: number, from?: number): Promise +} + +/** +* Hierarchical deterministic (HD) wallet created by using a source of entropy to +* derive a mnemonic phrase. The mnemonic phrase, in combination with an optional +* salt, is used to generate a seed. A value can be provided as a parameter for +* entropy, mnemonic + salt, or seed; if no argument is passed, a new entropy +* value will be generated using a cryptographically strong pseudorandom number +* generator. +* +* Importantly, the salt is not stored in the instantiated Wallet object. If a +* salt is used, then losing it means losing the ability to regenerate the seed +* from the mnemonic. +* +* Accounts are derived from the seed. Private keys are derived using a BIP-44 +* derivation path. The public key is derived from the private key using the +* Ed25519 key algorithm. Account addresses are derived as described in the nano +* documentation (https://docs.nano.org) +* +* A password must be provided when creating or importing the wallet and is used +* to lock and unlock the wallet. The wallet will be initialized as locked. When +* the wallet is unlocked, a new password can be specified using the lock() +* method. +*/ +export declare class Bip44Wallet extends Wallet { + #private + private constructor () + /** + * Creates a new HD wallet by using an entropy value generated using a + * cryptographically strong pseudorandom number generator. + * + * @param {string} password - Encrypts the wallet to lock and unlock it + * @param {string} [salt=''] - Used when generating the final seed + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static create (password: string, salt?: string): Promise + /** + * Creates a new HD wallet by using an entropy value generated using a + * cryptographically strong pseudorandom number generator. + * + * @param {Uint8Array} key - Encrypts the wallet to lock and unlock it + * @param {string} [salt=''] - Used when generating the final seed + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static create (key: Uint8Array, salt?: string): Promise + /** + * Creates a new HD wallet by using a pregenerated entropy value. The user + * must ensure that it is cryptographically strongly random. + * + * @param {string} password - Used to lock and unlock the wallet + * @param {string} entropy - Used when generating the initial mnemonic phrase + * @param {string} [salt=''] - Used when generating the final seed + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static fromEntropy (password: string, entropy: string, salt?: string): Promise + /** + * Creates a new HD wallet by using a pregenerated entropy value. The user + * must ensure that it is cryptographically strongly random. + * + * @param {Uint8Array} key - Used to lock and unlock the wallet + * @param {string} entropy - Used when generating the initial mnemonic phrase + * @param {string} [salt=''] - Used when generating the final seed + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static fromEntropy (key: Uint8Array, entropy: string, salt?: string): Promise + /** + * Creates a new HD wallet by using a pregenerated mnemonic phrase. + * + * @param {string} password - Used to lock and unlock the wallet + * @param {string} mnemonic - Used when generating the final seed + * @param {string} [salt=''] - Used when generating the final seed + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static fromMnemonic (password: string, mnemonic: string, salt?: string): Promise + /** + * Creates a new HD wallet by using a pregenerated mnemonic phrase. + * + * @param {Uint8Array} key - Used to lock and unlock the wallet + * @param {string} mnemonic - Used when generating the final seed + * @param {string} [salt=''] - Used when generating the final seed + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static fromMnemonic (key: Uint8Array, mnemonic: string, salt?: string): Promise + /** + * Creates a new HD wallet by using a pregenerated seed value. This seed cannot + * be used to regenerate any higher level randomness which includes entropy, + * mnemonic phrase, and salt. + * + * @param {string} password - Used to lock and unlock the wallet + * @param {string} seed - Hexadecimal 128-character string used to derive private-public key pairs + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static fromSeed (password: string, seed: string): Promise + /** + * Creates a new HD wallet by using a pregenerated seed value. This seed cannot + * be used to regenerate any higher level randomness which includes entropy, + * mnemonic phrase, and salt. + * + * @param {Uint8Array} key - Used to lock and unlock the wallet + * @param {string} seed - Hexadecimal 128-character string used to derive private-public key pairs + * @returns {Bip44Wallet} A newly instantiated Bip44Wallet + */ + static fromSeed (key: Uint8Array, seed: string): Promise + /** + * Retrieves an existing HD wallet from session storage using its ID. + * + * @param {string} id - Generated when the wallet was initially created + * @returns {Bip44Wallet} Restored locked Bip44Wallet + */ + static restore (id: string): Promise + /** + * Derives BIP-44 Nano account private keys. + * + * @param {number[]} indexes - Indexes of the accounts + * @returns {Promise} + */ + ckd (indexes: number[]): Promise +} + +/** +* BLAKE2b wallet created by deriving a mnemonic phrase from a seed or vice +* versa. If no value is provided for either, a new BIP-39 seed and mnemonic will +* be generated using a cryptographically strong pseudorandom number generator. +* +* Account private keys are derived on an ad hoc basis using the Blake2b hashing +* function. Account public key are derived from the private key using the +* Ed25519 key algorithm. Account addresses are derived from the public key as +* described in the Nano documentation. +* https://docs.nano.org/integration-guides/the-basics/ +* +* A password must be provided when creating or importing the wallet and is used +* to lock and unlock the wallet. The wallet will be initialized as locked. When +* the wallet is unlocked, a new password can be specified using the lock() +* method. +*/ +export declare class Blake2bWallet extends Wallet { + #private + private constructor () + /** + * Creates a new BLAKE2b wallet by using a seed generated using a + * cryptographically strong pseudorandom number generator. + * + * @param {string} password - Encrypts the wallet to lock and unlock it + * @returns {Blake2bWallet} A newly instantiated Blake2bWallet + */ + static create (password: string): Promise + /** + * Creates a new BLAKE2b wallet by using a seed generated using a + * cryptographically strong pseudorandom number generator. + * + * @param {Uint8Array} key - Encrypts the wallet to lock and unlock it + * @returns {Blake2bWallet} A newly instantiated Blake2bWallet + */ + static create (key: Uint8Array): Promise + /** + * Creates a new BLAKE2b wallet by using a pregenerated seed. The user must + * ensure that it is cryptographically strongly random. + * + * @param {string} password - Used to lock and unlock the wallet + * @param {string} seed - Hexadecimal 64-character string used to derive private-public key pairs + * @returns {Blake2bWallet} A newly instantiated Blake2bWallet + */ + static fromSeed (password: string, seed: string): Promise + /** + * Creates a new BLAKE2b wallet by using a pregenerated seed. The user must + * ensure that it is cryptographically strongly random. + * + * @param {Uint8Array} key - Used to lock and unlock the wallet + * @param {string} seed - Hexadecimal 64-character string used to derive private-public key pairs + * @returns {Blake2bWallet} A newly instantiated Blake2bWallet + */ + static fromSeed (key: Uint8Array, seed: string): Promise + /** + * Creates a new BLAKE2b wallet by using a pregenerated mnemonic phrase. + * + * @param {string} password - Used to lock and unlock the wallet + * @param {string} mnemonic - Used when generating the final seed + * @returns {Blake2bWallet} A newly instantiated Blake2bWallet + */ + static fromMnemonic (password: string, mnemonic: string): Promise + /** + * Creates a new BLAKE2b wallet by using a pregenerated mnemonic phrase. + * + * @param {Uint8Array} key - Used to lock and unlock the wallet + * @param {string} mnemonic - Used when generating the final seed + * @returns {Blake2bWallet} A newly instantiated Blake2bWallet + */ + static fromMnemonic (key: Uint8Array, mnemonic: string): Promise + /** + * Retrieves an existing BLAKE2b wallet from session storage using its ID. + * + * @param {string} id - Generated when the wallet was initially created + * @returns {Blake2bWallet} Restored locked Blake2bWallet + */ + static restore (id: string): Promise + /** + * Derives BLAKE2b account private keys. + * + * @param {number[]} indexes - Indexes of the accounts + * @returns {Promise} + */ + ckd (indexes: number[]): Promise +} + +type DeviceStatus = 'DISCONNECTED' | 'BUSY' | 'LOCKED' | 'CONNECTED' +interface LedgerResponse { + status: string +} +interface LedgerVersionResponse extends LedgerResponse { + name: string | null + version: string | null +} +interface LedgerSignResponse extends LedgerResponse { + signature: string | null + hash?: string +} +/** +* Ledger hardware wallet created by communicating with a Ledger device via ADPU +* calls. This wallet does not feature any seed nor mnemonic phrase as all +* private keys are held in the secure chip of the device. As such, the user +* is responsible for using Ledger technology to back up these pieces of data. +* +* Usage of this wallet is generally controlled by calling functions of the +* `ledger` object. For example, the wallet interface should have a button to +* initiate a device connection by calling `wallet.ledger.connect()`. For more +* information, refer to the ledger.js service file. +*/ +export declare class LedgerWallet extends Wallet { + #private + get listenTimeout (): 30000 + get openTimeout (): 3000 + get status (): DeviceStatus + DynamicTransport: typeof TransportBLE | typeof TransportUSB | typeof TransportHID + private constructor () + /** + * Check which transport protocols are supported by the browser and set the + * transport type according to the following priorities: Bluetooth, USB, HID. + */ + checkBrowserSupport (): Promise + /** + * Check if the Nano app is currently open and set device status accordingly. + * + * @returns Device status as follows: + * - DISCONNECTED: Failed to communicate properly with the app + * - BUSY: Nano app is not currently open + * - LOCKED: Nano app is open but the device locked after a timeout + * - CONNECTED: Nano app is open and listening + */ + connect (): Promise + /** + * Creates a new Ledger hardware wallet communication layer by dynamically + * importing the ledger.js service. + * + * @returns {LedgerWallet} A wallet containing accounts and a Ledger device communication object + */ + static create (): Promise + /** + * Removes encrypted secrets in storage and releases variable references to + * allow garbage collection. + */ + destroy (): Promise + init (): Promise + /** + * Revokes permission granted by the user to access the Ledger device. + * + * The 'quit app' ADPU command has not passed testing, so this is the only way + * to ensure the connection is severed at this time. `setTimeout` is used to + * expire any lingering transient user activation. + * + * Overrides the default wallet `lock()` method since as a hardware wallet it + * does not need to be encrypted by software. + * + * @returns True if successfully locked + */ + lock (): Promise + onConnectUsb: (e: USBConnectionEvent) => Promise + onDisconnectUsb: (e: USBConnectionEvent) => Promise + /** + * Retrieves an existing Ledger wallet from session storage using its ID. + * + * @param {string} id - Generated when the wallet was initially created + * @returns {LedgerWallet} Restored LedgerWallet + */ + static restore (id: string): Promise + /** + * Sign a block with the Ledger device. + * + * @param {number} index - Account number + * @param {object} block - Block data to sign + * @returns {Promise} Status, signature, and block hash + */ + sign (index: number, block: SendBlock | ReceiveBlock | ChangeBlock): Promise + /** + * Sign a nonce with the Ledger device. + * + * @param {number} index - Account number + * @param {Uint8Array} nonce - 128-bit value to sign + * @returns {Promise} Status and signature + */ + sign (index: number, nonce: Uint8Array): Promise + /** + * Attempts to connect to the Ledger device. + * + * Overrides the default wallet `unlock()` method since as a hardware wallet it + * does not need to be encrypted by software. + * + * @returns True if successfully unlocked + */ + unlock (): Promise + /** + * Update cache from raw block data. Suitable for offline use. + * + * @param {number} index - Account number + * @param {object} block - JSON-formatted block data + */ + updateCache (index: number, block: { + [key: string]: string + }): Promise + /** + * Update cache from a block hash by calling out to a node. Suitable for online + * use only. + * + * @param {number} index - Account number + * @param {string} hash - Hexadecimal block hash + * @param {Rpc} rpc - Rpc class object with a node URL + */ + updateCache (index: number, hash: string, rpc: Rpc): Promise + /** + * Get the version of the current process. If a specific app is running, get + * the app version. Otherwise, get the Ledger BOLOS version instead. + * + * https://developers.ledger.com/docs/connectivity/ledgerJS/open-close-info-on-apps#get-information + * + * @returns Status, process name, and version + */ + version (): Promise + /** + * Gets the public key for an account from the Ledger device. + * + * @param {number[]} indexes - Indexes of the accounts + * @returns {Promise} + */ + ckd (indexes: number[]): Promise +} + /** * Processes a queue of tasks using Web Workers. */