A class to discover funds in a Bitcoin network using descriptors. The DiscoveryFactory function internally creates and returns an instance of this class. The returned class is specialized for the provided Explorer, which is responsible for fetching blockchain data like transaction details.

Hierarchy

  • Discovery

Constructors

  • Constructs a Discovery instance. Discovery is used to discover funds in a Bitcoin network using descriptors.

    Parameters

    • options: {
          descriptorsCacheSize: number;
          outputsPerDescriptorCacheSize: number;
      } = ...
      • descriptorsCacheSize: number

        Cache size limit for descriptor expressions. The cache is used to speed up data queries by avoiding unnecessary recomputations. However, it is essential to manage the memory usage of the application. If the cache size is unbounded, it could lead to excessive memory usage and degrade the application's performance, especially when dealing with a large number of descriptor expressions. On the other hand, a very small cache size may lead to more frequent cache evictions, causing the library to return a different reference for the same data when the same method is called multiple times, even if the underlying data has not changed. This is contrary to the immutability principles that the library is built upon. Ultimately, this limit acts as a trade-off between memory usage, computational efficiency, and immutability. Set to 0 for unbounded caches.

        Default Value

        1000
        
      • outputsPerDescriptorCacheSize: number

        Cache size limit for outputs per descriptor, related to the number of outputs in ranged descriptor expressions. Similar to the descriptorsCacheSize, this cache is used to speed up data queries and avoid recomputations. As each descriptor can have multiple indices (if ranged), the number of outputs can grow rapidly, leading to increased memory usage. Setting a limit helps keep memory usage in check, while also maintaining the benefits of immutability and computational efficiency. Set to 0 for unbounded caches.

        Default Value

        10000
        

    Returns Discovery

Properties

#derivers: {
    deriveScriptPubKey: ((networkId, descriptor, index) => Buffer);
    deriveUtxosAndBalanceByOutput: ((networkId, txMap, descriptorMap, descriptor, index, txStatus) => {
        utxos: string[];
        balance: number;
    });
    deriveUtxosAndBalance: ((networkId, txMap, descriptorMap, descriptorOrDescriptors, txStatus) => {
        utxos: string[];
        balance: number;
    });
    deriveUsedDescriptors: ((discoveryData, networkId) => string[]);
    deriveUsedAccounts: ((discoveryData, networkId) => string[]);
    deriveAccountDescriptors: ((account) => [string, string]) & Memoized<((account) => [string, string])>;
    deriveHistoryByOutput: ((txMap, descriptorMap, descriptor, index, txStatus) => TxData[]);
    deriveHistory: ((txMap, descriptorMap, descriptorOrDescriptors, txStatus) => TxData[]);
    transactionFromHex: ((hex) => Transaction) & Memoized<((hex) => Transaction)>;
}

Type declaration

  • deriveScriptPubKey: ((networkId, descriptor, index) => Buffer)
      • (networkId, descriptor, index): Buffer
      • Parameters

        Returns Buffer

  • deriveUtxosAndBalanceByOutput: ((networkId, txMap, descriptorMap, descriptor, index, txStatus) => {
        utxos: string[];
        balance: number;
    })
      • (networkId, txMap, descriptorMap, descriptor, index, txStatus): {
            utxos: string[];
            balance: number;
        }
      • Parameters

        Returns {
            utxos: string[];
            balance: number;
        }

        • utxos: string[]
        • balance: number
  • deriveUtxosAndBalance: ((networkId, txMap, descriptorMap, descriptorOrDescriptors, txStatus) => {
        utxos: string[];
        balance: number;
    })
      • (networkId, txMap, descriptorMap, descriptorOrDescriptors, txStatus): {
            utxos: string[];
            balance: number;
        }
      • Parameters

        Returns {
            utxos: string[];
            balance: number;
        }

        • utxos: string[]
        • balance: number
  • deriveUsedDescriptors: ((discoveryData, networkId) => string[])
      • (discoveryData, networkId): string[]
      • Extracts and returns descriptor expressions that are associated with at least one utilized scriptPubKey from the discovery information. The function is optimized to maintain and return the same array object for each unique networkId if the resulting expressions did not change. This helps to avoid unnecessary data processing and memory usage.

        Parameters

        Returns string[]

        Descriptor expressions.

  • deriveUsedAccounts: ((discoveryData, networkId) => string[])
      • (discoveryData, networkId): string[]
      • Parameters

        Returns string[]

  • deriveAccountDescriptors: ((account) => [string, string]) & Memoized<((account) => [string, string])>
  • deriveHistoryByOutput: ((txMap, descriptorMap, descriptor, index, txStatus) => TxData[])
  • deriveHistory: ((txMap, descriptorMap, descriptorOrDescriptors, txStatus) => TxData[])
      • (txMap, descriptorMap, descriptorOrDescriptors, txStatus): TxData[]
      • Parameters

        Returns TxData[]

  • transactionFromHex: ((hex) => Transaction) & Memoized<((hex) => Transaction)>
#discoveryData: DiscoveryData

Methods

  • Private

    Ensures that a scriptPubKey is unique and has not already been set by a different descriptor. This prevents accounting for duplicate unspent transaction outputs (utxos) and balances when different descriptors could represent the same scriptPubKey (e.g., xpub vs wif).

    Parameters

    • options: {
          networkId: NetworkId;
          scriptPubKey: Buffer;
      }
      • networkId: NetworkId

        Network to check.

      • scriptPubKey: Buffer

        The scriptPubKey to check for uniqueness.

    Returns void

    Throws

    If the scriptPubKey is not unique.

  • Asynchronously discovers an output, given a descriptor expression and index. It first retrieves the output, computes its scriptHash, and fetches the transaction history associated with this scriptHash from the explorer. It then updates the internal discoveryData accordingly.

    This function has side-effects as it modifies the internal discoveryData state of the Discovery class instance. This state keeps track of transaction info and descriptors relevant to the discovery process.

    This method is useful for updating the state based on new transactions and output.

    This method does not retrieve the txHex associated with the Output. An additional #fetchTxs must be performed.

    Parameters

    • options: {
          descriptor: string;
          index?: number;
      }
      • descriptor: string

        The descriptor expression associated with the scriptPubKey to discover.

      • Optional index?: number

        The descriptor index associated with the scriptPubKey to discover (if ranged).

    Returns Promise<boolean>

    A promise that resolves to a boolean indicating whether any transactions were found for the provided scriptPubKey.

  • Asynchronously fetches all raw transaction data from all transactions associated with all the outputs fetched.

    Returns Promise<void>

    Resolves when all the transactions have been fetched and stored in discoveryData.

  • Asynchronously fetches one or more descriptor expressions, retrieving all the historical txs associated with the outputs represented by the expressions.

    Parameters

    • options: {
          descriptor?: string;
          index?: number;
          descriptors?: string[];
          gapLimit?: number;
          onUsed?: ((descriptorOrDescriptors) => void);
          onChecking?: ((descriptorOrDescriptors) => void);
          next?: (() => Promise<void>);
      }
      • Optional descriptor?: string

        Descriptor expression representing one or potentially multiple outputs if ranged. Use either descriptor or descriptors, but not both simultaneously.

      • Optional index?: number

        An optional index associated with a ranged descriptor. Not applicable when using the descriptors array, even if its elements are ranged.

      • Optional descriptors?: string[]

        Array of descriptor expressions. Use either descriptors or descriptor, but not both simultaneously.

      • Optional gapLimit?: number

        The gap limit for the fetch operation when retrieving ranged descriptors.

        Default Value

        20
        
      • Optional onUsed?: ((descriptorOrDescriptors) => void)
          • (descriptorOrDescriptors): void
          • Optional callback function triggered once a descriptor's output has been identified as previously used in a transaction. It provides a way to react or perform side effects based on this finding.

            Parameters

            • descriptorOrDescriptors: string | string[]

              The original descriptor or array of descriptors that have been determined to have a used output.

            Returns void

      • Optional onChecking?: ((descriptorOrDescriptors) => void)
          • (descriptorOrDescriptors): void
          • Optional callback function invoked at the beginning of checking a descriptor to determine its usage status. This can be used to signal the start of a descriptor's check, potentially for logging or UI updates.

            Parameters

            • descriptorOrDescriptors: string | string[]

              The descriptor or array of descriptors being checked.

            Returns void

      • Optional next?: (() => Promise<void>)
          • (): Promise<void>
          • Optional function triggered immediately after detecting that a descriptor's output has been used previously. By invoking this function, it's possible to initiate parallel discovery processes. The primary discover method will only resolve once both its main discovery process and any supplementary processes initiated by next have completed. Essentially, it ensures that all discovery, both primary and secondary, finishes before moving on.

            Returns Promise<void>

    Returns Promise<void>

    Resolves when the fetch operation completes. If used expressions are found, waits for the discovery of associated transactions.

  • Retrieves the fetching status and the timestamp of the last fetch for a descriptor.

    Use this function to check if the data for a specific descriptor, or an index within a ranged descriptor, is currently being fetched or has been fetched.

    This function also helps to avoid errors when attempting to derive data from descriptors with incomplete data, ensuring that subsequent calls to data derivation methods such as getUtxos or getBalance only occur once the necessary data has been successfully retrieved (and does not return undefined).

    Parameters

    • __namedParameters: {
          descriptor: string;
          index?: number;
      }
      • descriptor: string

        Descriptor expression representing one or potentially multiple outputs if ranged.

      • Optional index?: number

        An optional index associated with a ranged descriptor.

    Returns undefined | {
        fetching: boolean;
        timeFetched: number;
    }

    An object with the fetching status (fetching) and the last fetch time (timeFetched), or undefined if never fetched.

  • Makes sure that data was retrieved before trying to derive from it

    Parameters

    • __namedParameters: {
          descriptor?: string;
          index?: number;
          descriptors?: string[];
      }
      • Optional descriptor?: string

        Descriptor expression representing one or potentially multiple outputs if ranged. Use either descriptor or descriptors, but not both simultaneously.

      • Optional index?: number

        An optional index associated with a ranged descriptor. Not applicable when using the descriptors array, even if its elements are ranged.

      • Optional descriptors?: string[]

        Array of descriptor expressions. Use either descriptors or descriptor, but not both simultaneously.

    Returns void

  • Asynchronously discovers standard accounts (pkh, sh(wpkh), wpkh) associated with a master node. It uses a given gap limit for discovery.

    Parameters

    • options: {
          masterNode: BIP32Interface;
          gapLimit?: number;
          onAccountUsed?: ((account) => void);
          onAccountChecking?: ((account) => void);
      }
      • masterNode: BIP32Interface

        The master node to discover accounts from.

      • Optional gapLimit?: number

        The gap limit for address discovery

        Default Value

        20
        
      • Optional onAccountUsed?: ((account) => void)
          • (account): void
          • Optional callback function triggered when an account (associated with the master node) has been identified as having past transactions. It's called with the external descriptor of the account (keyPath = /0/*) that is active.

            Parameters

            • account: string

              The external descriptor of the account that has been determined to have prior transaction activity.

            Returns void

      • Optional onAccountChecking?: ((account) => void)
          • (account): void
          • Optional callback function invoked just as the system starts to evaluate the transaction activity of an account (associated with the master node). Useful for signaling the initiation of the discovery process for a particular account, often for UI updates or logging purposes.

            Parameters

            • account: string

              The external descriptor of the account that is currently being evaluated for transaction activity.

            Returns void

    Returns Promise<void>

    Resolves when all the standrd accounts from the master node have been discovered.

  • Retrieves the array of descriptors with used outputs. The result is cached based on the size specified in the constructor. As long as this cache size is not exceeded, this function will maintain the same object reference if the returned array hasn't changed. This characteristic can be particularly beneficial in React and similar projects, where re-rendering occurs based on reference changes.

    Returns string[]

    Returns an array of descriptor expressions. These are derived from the discovery information.

  • Retrieves all the accounts with used outputs: those descriptors with keyPaths ending in {/0/*, /1/*}. An account is identified by its external descriptor keyPath = /0/*. The result is cached based on the size specified in the constructor. As long as this cache size is not exceeded, this function will maintain the same object reference if the returned array remains unchanged. This characteristic can be especially beneficial in React or similar projects, where re-rendering occurs based on reference changes.

    Returns string[]

    An array of accounts, each represented as its external descriptor expression.

  • Retrieves descriptor expressions associated with a specific account. The result is cached based on the size specified in the constructor. As long as this cache size is not exceeded, this function will maintain the same object reference. This characteristic can be especially beneficial in React or similar projects, where re-rendering occurs based on reference changes.

    Parameters

    • options: {
          account: string;
      }
      • account: string

        The account associated with the descriptors.

    Returns [string, string]

    An array of descriptor expressions associated with the specified account.

  • Retrieves unspent transaction outputs (UTXOs) and balance associated with one or more descriptor expressions and transaction status.

    This method is useful for accessing the available funds for specific descriptor expressions in the wallet, considering the transaction status (confirmed, unconfirmed, or both).

    The return value is computed based on the current state of discoveryData. The method uses memoization to maintain the same object reference for the returned result, given the same input parameters, as long as the corresponding UTXOs in discoveryData haven't changed. This can be useful in environments such as React where preserving object identity can prevent unnecessary re-renders.

    Parameters

    Returns {
        utxos: string[];
        balance: number;
    }

    An object containing the UTXOs associated with the scriptPubKeys and the total balance of these UTXOs.

    • utxos: string[]
    • balance: number
  • Convenience function which internally invokes the getUtxosAndBalance(options).balance method.

    Parameters

    Returns number

  • Convenience function which internally invokes the getUtxosAndBalance(options).utxos method.

    Parameters

    Returns string[]

  • Retrieves the next available index for a given descriptor.

    The method retrieves the currently highest index used, and returns the next available index by incrementing it by 1.

    Parameters

    • options: {
          descriptor: string;
          txStatus?: TxStatus;
      }
      • descriptor: string

        The ranged descriptor expression for which to retrieve the next available index.

      • Optional txStatus?: TxStatus

        A scriptPubKey will be considered as used when its transaction status is txStatus extracting UTXOs and balance.

        Default Value

        TxStatus.ALL
        

    Returns number

    The next available index.

  • Retrieves the transaction history for one or more descriptor expressions.

    This method is useful for accessing transaction records associated with one or more descriptor expressions and transaction status.

    The return value is computed based on the current state of discoveryData. The method uses memoization to maintain the same object reference for the returned result, given the same input parameters, as long as the corresponding transaction records in discoveryData haven't changed.

    This can be useful in environments such as React where preserving object identity can prevent unnecessary re-renders.

    Parameters

    Returns TxData[]

    An array containing transaction info associated with the descriptor expressions.

  • Retrieves the hexadecimal representation of a transaction (TxHex) from the discoveryData given the transaction ID (TxId) or a Unspent Transaction Output (Utxo)

    Parameters

    • options: {
          txId?: string;
          utxo?: string;
      }
      • Optional txId?: string

        The transaction ID.

      • Optional utxo?: string

        The UTXO.

    Returns string

    The hexadecimal representation of the transaction.

    Throws

    Will throw an error if the transaction ID is invalid or if the TxHex is not found.

  • Retrieves the transaction data as a bitcoinjs-lib Transaction object given the transaction ID (TxId) or a Unspent Transaction Output (Utxo). The transaction data is obtained by first getting the transaction hexadecimal representation using getTxHex() method.

    Use this method for quick access to the Transaction object, which avoids the need to parse the transaction hexadecimal representation (txHex). The data will have already been computed and cached for efficiency within the Discovery class.

    Parameters

    • options: {
          txId?: string;
          utxo?: string;
      }
      • Optional txId?: string

        The transaction ID.

      • Optional utxo?: string

        The UTXO.

    Returns Transaction

    The transaction data as a Transaction object.

  • Given an unspent tx output, this function retrieves its descriptor.

    Parameters

    • __namedParameters: {
          utxo: string;
      }
      • utxo: string

        The UTXO.

    Returns undefined | {
        descriptor: string;
        index?: number;
    }

  • Retrieves the Explorer instance.

    Returns Explorer

    The Explorer instance.