\r
import { KeyPair, NamedData, WalletType } from '#types'\r
import { Account, AccountList } from '../account'\r
+import { _backup } from './backup'\r
import { Block } from '../block'\r
import { ADDRESS_GAP } from '../constants'\r
import { bytes, hex, utf8 } from '../convert'\r
import { _create } from './create'\r
import { Database } from '../database'\r
+import { _get } from './get'\r
import { _load } from './load'\r
+import { _restore } from './restore'\r
import { Rpc } from '../rpc'\r
import { default as VaultWorker } from '../vault/vault'\r
import { WorkerQueue } from '../vault/worker-queue'\r
static #isInternal: boolean = false\r
static DB_NAME = 'Wallet'\r
\r
- /**\r
- * Retrieves a wallet from the database.\r
- */\r
- static async #get (id: string) {\r
- try {\r
- const record = await Database.get<NamedData>(id, this.DB_NAME)\r
- return record[id]\r
- } catch (err) {\r
- throw new Error('Failed to get wallet from database', { cause: err })\r
- }\r
- }\r
-\r
/**\r
* Creates a new HD wallet by using an entropy value generated using a\r
* cryptographically strong pseudorandom number generator.\r
}\r
\r
/**\r
- * Retrieves all wallet IDs from the database.\r
+ * Retrieves all encrypted wallets from the database.\r
*\r
- * @returns Array of hexadecimal-formatted wallet IDs\r
+ * @returns Array of wallets with encrypted secrets and unencrypted metadata\r
*/\r
- static async export (): Promise<NamedData[]> {\r
- try {\r
- const response = await Database.getAll<NamedData>(this.DB_NAME)\r
- const ids = Object.keys(response)\r
- return ids.map(id => response[id])\r
- } catch (err) {\r
- console.error(err)\r
- return []\r
- }\r
+ static async backup (): Promise<NamedData[]> {\r
+ return _backup()\r
}\r
\r
/**\r
}\r
\r
/**\r
- * Retrieves an existing wallet from the database using its UUID.\r
+ * Instantiates a Wallet from an existing record in the database using its UUID.\r
*\r
* @param {string} id - Generated when the wallet was created or imported\r
- * @returns {Wallet} Restored locked Wallet\r
+ * @returns {Promise<Wallet>} Restored locked Wallet\r
*/\r
- static async restore (id: string): Promise<Wallet> {\r
- try {\r
- if (typeof id !== 'string' || id === '') {\r
- throw new TypeError('Wallet ID is required to restore')\r
- }\r
- const { type } = await this.#get(id)\r
- if (type !== 'BIP-44' && type !== 'BLAKE2b' && type !== 'Ledger') {\r
- throw new Error('Invalid wallet type from database')\r
- }\r
+ static async restore (id: string): Promise<Wallet>\r
+ /**\r
+ * Instantiates Wallet objects from records in the database.\r
+ *\r
+ * @param {string} id - Generated when the wallet was created or imported\r
+ * @returns {Promise<Wallet[]>} Restored locked Wallets\r
+ */\r
+ static async restore (): Promise<Wallet[]>\r
+ static async restore (id?: string): Promise<Wallet | Wallet[]> {\r
+ const backups = await _restore(id)\r
+ const wallets = backups.map(backup => {\r
Wallet.#isInternal = true\r
- const self = new this(type, id)\r
- return self\r
- } catch (err) {\r
- throw new Error('Failed to restore wallet', { cause: err })\r
- }\r
+ return new this(backup.type, backup.id)\r
+ })\r
+ return typeof id === 'string' ? wallets[0] : wallets\r
}\r
\r
#accounts: AccountList\r
}\r
\r
/**\r
- * Removes encrypted secrets in storage and releases variable references to\r
- * allow garbage collection.\r
+ * Removes encrypted secrets in storage, releases variable references to\r
+ * allow garbage collection, and terminates vault worker.\r
*/\r
async destroy (): Promise<void> {\r
try {\r
if (typeof password !== 'string') {\r
throw new TypeError('Password must be a string')\r
}\r
- const { iv, salt, encrypted } = await Wallet.#get(this.#id)\r
+ const { iv, salt, encrypted } = await _get(this.#id)\r
const { isUnlocked } = await this.#vault.request<boolean>({\r
action: 'unlock',\r
type: this.#type,\r
*/
toBlake2bSeed (format: 'hex'): Promise<string>
}
-
/**
* Implementation derived from blake2b@2.1.4. Copyright 2017 Emil Bay
* <github@tixz.dk> (https://github.com/emilbayes/blake2b). See LICENSES/ISC.txt
/**
* Sets the `signature` property of the block to a precalculated value.
*
- * @param {string} [key] - 64-byte hexadecimal signature
+ * @param {string} signature - 64-byte hexadecimal signature
+ * @returns Block with `signature` value set
*/
sign (signature: string): Block
/**
* the `signature` property of the block.
*
* @param {string} [key] - 32-byte hexadecimal private key to use for signing
+ * @returns Block with `signature` value set
*/
sign (key: string): Promise<Block>
/**
- * Signs the block using a Wallet. If successful, the result is stored in
- * the `signature` property of the block. The wallet must be unlocked prior to
- * signing.
- *
- * @param {Wallet} wallet - Wallet to use for signing
- * @param {number} index - Account in wallet to use for signing
- */
- sign (wallet: Wallet, index: number): Promise<Block>
- /**
* Signs the block using a Ledger hardware wallet. If that fails, an error is
* thrown with the status code from the device. If successful, the result is
* stored in the `signature` property of the block. The wallet must be unlocked
*
* @param {number} index - Account index between 0x0 and 0x7fffffff
* @param {object} [frontier] - JSON of frontier block for offline signing
+ * @returns Block with `signature` value set
*/
sign (index: number, frontier?: Block): Promise<Block>
/**
+ * Signs the block using a Wallet. If successful, the result is stored in
+ * the `signature` property of the block. The wallet must be unlocked prior to
+ * signing.
+ *
+ * @param {Wallet} wallet - Wallet to use for signing
+ * @param {number} index - Account in wallet to use for signing
+ * @returns Block with `signature` value set
+ */
+ sign (wallet: Wallet, index: number): Promise<Block>
+ /**
* Verifies the signature of the block. If a key is not provided, the public
* key of the block's account will be used if it exists.
*
export type Data = boolean | number | number[] | string | string[] | ArrayBuffer | CryptoKey | { [key: string]: Data }
-/**
-* 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<Entropy>
- /**
- * Generate between 16-32 bytes of entropy.
- * @param {number} size - Number of bytes to generate in multiples of 4
- */
- static create (size: number): Promise<Entropy>
- /**
- * Import existing entropy and validate it.
- * @param {string} hex - Hexadecimal string
- */
- static import (hex: string): Promise<Entropy>
- /**
- * Import existing entropy and validate it.
- * @param {ArrayBuffer} buffer - Byte buffer
- */
- static import (buffer: ArrayBuffer): Promise<Entropy>
- /**
- * Import existing entropy and validate it.
- * @param {Uint8Array} bytes - Byte array
- */
- static import (bytes: Uint8Array<ArrayBuffer>): Promise<Entropy>
- /**
- * Randomizes the bytes, rendering the original values generally inaccessible.
- */
- destroy (): boolean
-}
-
export type NamedData<T extends Data = Data> = {
[key: string]: T
}
/**
* Converts a decimal amount of nano from one unit divider to another.
*
-* @param {bigint|string} amount - Decimal amount to convert
+* @param {(bigint|number|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<string>
+export declare function convert (amount: bigint | number | string, inputUnit: string, outputUnit: string): string
+export declare function convert (amount: bigint | number | string, inputUnit: string, outputUnit: string, format?: 'bigint' | 'string'): bigint
declare function hash (data: string | string[], encoding?: 'hex'): Uint8Array<ArrayBuffer>
/**
* Signs arbitrary strings with a private key using the Ed25519 signature scheme.
*/
static create (type: 'BIP-44' | 'BLAKE2b', password: string, mnemonicSalt?: string): Promise<Wallet>
/**
- * Retrieves all wallet IDs from the database.
+ * Retrieves all encrypted wallets from the database.
*
- * @returns Array of hexadecimal-formatted wallet IDs
+ * @returns Array of wallets with encrypted secrets and unencrypted metadata
*/
- static export (): Promise<NamedData[]>
+ static backup (): Promise<NamedData[]>
/**
* Imports an existing HD wallet by using an entropy value generated using a
* cryptographically strong pseudorandom number generator.NamedD
*
- * @param {string} password - Encrypts the wallet to lock and unlock it
- * @param {string} [salt=''] - Used when generating the final seed
- * @returns {Wallet} A newly instantiated Wallet
+ * @param {string} type - Algorithm used to generate wallet and child accounts
+ * @param {string} password - Encrypts the wallet to lock and unlock it. Discard as soon as possible after loading the wallet.
+ * @param {string} seed - Used to derive child accounts
+ * @returns Wallet in a locked state
*/
- static import (type: 'BIP-44' | 'BLAKE2b', password: string, seed: string): Promise<Wallet>
+ static load (type: 'BIP-44' | 'BLAKE2b', password: string, seed: string): Promise<Wallet>
/**
* Imports an existing 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 {Wallet} A newly instantiated Wallet
+ * @param {string} type - Algorithm used to generate wallet and child accounts
+ * @param {string} password - Encrypts the wallet to lock and unlock it. Discard as soon as possible after loading the wallet.
+ * @param {string} mnemonicPhrase - Used to derive the wallet seed
+ * @param {string} [mnemonicSalt] - Used to alter the seed derived from the mnemonic phrase
+ * @returns Wallet in a locked state
*/
- static import (type: 'BIP-44' | 'BLAKE2b', password: string, mnemonicPhrase: string, mnemonicSalt?: string): Promise<Wallet>
+ static load (type: 'BIP-44' | 'BLAKE2b', password: string, mnemonicPhrase: string, mnemonicSalt?: string): Promise<Wallet>
/**
- * Retrieves an existing wallet from the database using its UUID.
+ * Instantiates a Wallet from an existing record in the database using its UUID.
*
* @param {string} id - Generated when the wallet was created or imported
- * @returns {Wallet} Restored locked Wallet
+ * @returns {Promise<Wallet>} Restored locked Wallet
*/
static restore (id: string): Promise<Wallet>
+ /**
+ * Instantiates Wallet objects from records in the database.
+ *
+ * @param {string} id - Generated when the wallet was created or imported
+ * @returns {Promise<Wallet[]>} Restored locked Wallets
+ */
+ static restore (): Promise<Wallet[]>
get id (): string
get vault (): WorkerQueue
get type (): WalletType
* Retrieves an account 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.account(5))
- * // outputs sixth account of the wallet
- * // {
- * // privateKey: <...>,
- * // index: 5
- * // }
+ * const account = await wallet.account(1)
+ * // outputs the second account of the wallet
+ * console.log(account)
+ * // { address: <...>, publicKey: <...>, index: 1, <etc...> }
* ```
*
- * @param {number} index - Wallet index of secret key. Default: 0
- * @returns {Account} Account derived at the specified wallet index
+ * @param {number} index - Wallet index of account. Default: 0
+ * @returns Promise for the Account at the specified index
*/
account (index?: number): Promise<Account>
/**
* that index in the wallet.
*
* ```
- * console.log(await wallet.accounts(5))
- * // outputs sixth account of the wallet
+ * const accounts = await wallet.accounts(0, 1))
+ * // outputs the first and second account of the wallet
+ * console.log(accounts)
* // {
- * // 5: {
- * // privateKey: <...>,
- * // index: 5
- * // }
+ * // 0: {
+ * // address: <...>,
+ * // publicKey: <...>,
+ * // index: 0,
+ * // <etc...>
+ * // },
+ * // 1: {
+ * // address: <...>,
+ * // publicKey: <...>,
+ * // index: 1,
+ * // <etc...>
+ * // }
* // }
+ * // individual accounts can be referenced using array index notation
+ * console.log(accounts[1])
+ * // { address: <...>, publicKey: <...>, index: 1, <etc...> }
* ```
*
- * @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
+ * If `from` is greater than `to`, their values will be swapped.
+ * @param {number} from - Start index of accounts. Default: 0
+ * @param {number} to - End index of accounts. Default: `from`
+ * @returns {AccountList} Promise for a list of Accounts at the specified indexes
*/
accounts (from?: number, to?: number): Promise<AccountList>
/**
- * Removes encrypted secrets in storage and releases variable references to
- * allow garbage collection.
+ * Removes encrypted secrets in storage, releases variable references to
+ * allow garbage collection, and terminates vault worker.
*/
destroy (): Promise<void>
/**
*
* @param {number} index - Account to use for signing
* @param {(Block)} block - Block data to be hashed and signed
- * @returns {Promise<string>} Hexadecimal-formatted 64-byte signature
*/
- sign (index: number, block: Block): Promise<Uint8Array<ArrayBuffer>>
- /**
- * Signs a block using the private key of the account at the wallet index
- * specified. The signature is appended to the signature field of the block
- * before being returned. The wallet must be unlocked prior to signing.
- *
- * @param {number} index - Account to use for signing
- * @param {(Block)} block - Block data to be hashed and signed
- * @returns {Promise<string>} Hexadecimal-formatted 64-byte signature
- */
- sign (index: number, block: Block, format: 'hex'): Promise<string>
+ sign (index: number, block: Block): Promise<void>
/**
* Unlocks the wallet using the same password as used prior to lock it.
*
export declare class Ledger extends Wallet {
#private
static DynamicTransport: typeof TransportBLE | typeof TransportUSB | typeof TransportHID
- static get listenTimeout (): 30000
- static get openTimeout (): 3000
- /**
- * Check which transport protocols are supported by the browser and return the
- * transport type according to the following priorities: Bluetooth, USB, HID.
- */
- static get isUnsupported (): boolean
+ static SYMBOL: Symbol
/**
* Creates a new Ledger hardware wallet communication layer by dynamically
* importing the ledger.js service.
* be extracted from the device.
*/
static import (): Promise<Ledger>
- get status (): DeviceStatus
private constructor ()
+ get status (): DeviceStatus
/**
- * Gets the public key for an account from the Ledger device.
+ * Gets the index and public key for an account from the Ledger device.
*
- * @param {number[]} indexes - Indexes of the accounts
- * @returns {Promise<Account>}
+ * @param {number} index - Wallet index of the account
+ * @returns Promise for the Account at the index specified
*/
account (index: number): Promise<Account>
/**
- * Retrieves accounts from a wallet using its child key derivation function.
+ * Retrieves accounts from a Ledger wallet using its internal secure software.
* Defaults to the first account at index 0.
*
* The returned object will have keys corresponding with the requested range
* that index in the wallet.
*
* ```
- * console.log(await wallet.accounts(5))
- * // outputs sixth account of the wallet
+ * const accounts = await wallet.accounts(0, 1))
+ * // outputs the first and second account of the wallet
+ * console.log(accounts)
* // {
- * // 5: {
- * // privateKey: <...>,
- * // index: 5
- * // }
+ * // 0: {
+ * // address: <...>,
+ * // publicKey: <...>,
+ * // index: 0,
+ * // <etc...>
+ * // },
+ * // 1: {
+ * // address: <...>,
+ * // publicKey: <...>,
+ * // index: 1,
+ * // <etc...>
+ * // }
* // }
+ * // individual accounts can be referenced using array index notation
+ * console.log(accounts[1])
+ * // { address: <...>, publicKey: <...>, index: 1, <etc...> }
* ```
*
- * @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
+ * If `from` is greater than `to`, their values will be swapped.
+ * @param {number} from - Start index of accounts. Default: 0
+ * @param {number} to - End index of accounts. Default: `from`
+ * @returns {AccountList} Promise for a list of Accounts at the specified indexes
*/
accounts (from?: number, to?: number): Promise<AccountList>
/**
* @returns True if successfully locked
*/
lock (): Promise<boolean>
- onConnectUsb: (e: USBConnectionEvent) => Promise<void>
- onDisconnectUsb: (e: USBConnectionEvent) => Promise<void>
- /**
- * Sign a block with the Ledger device.
- *
- * @param {number} index - Account number
- * @param {object} block - Block data to sign
- * @returns {Promise<string>} Signature
- */
- sign (index: number, block: Block): Promise<Uint8Array<ArrayBuffer>>
/**
* Sign a block with the Ledger device.
*
* @param {number} index - Account number
- * @param {object} block - Block data to sign
- * @returns {Promise<string>} Signature
+ * @param {Block} block - Block data to sign
+ * @param {Block} [frontier] - Previous block data to cache in the device
*/
- sign (index: number, block: Block, format?: 'hex', frontier?: Block): Promise<string>
+ sign (index: number, block: Block, frontier?: Block): Promise<void>
/**
* Attempts to connect to the Ledger device.
*