This library is designed to parse and create Bitcoin Descriptors, including Miniscript and Taproot script trees and generate Partially Signed Bitcoin Transactions (PSBTs). It also provides PSBT signers and finalizers for single-signature, BIP32 and Hardware Wallets.
npm install @bitcoinerlab/descriptors @bitcoinerlab/secp256k1 @bitcoinerlab/miniscript-policiesThis quick example compiles a timelocked Miniscript policy, creates a descriptor address to fund, then builds, signs, and finalizes a PSBT that spends that funded UTXO and prints the final transaction hex.
const ecpair = ECPair.makeRandom(); // Creates a signer for a single-key wallet
// Timelocked policy: signature + relative timelock (older)
const { miniscript } = compilePolicy('and(pk(@bob),older(10))');
const descriptor = `wsh(${miniscript.replace('@bob', toHex(ecpair.publicKey))})`;
// 1) Build the output description
const fundedOutput = new Output({ descriptor });
const address = fundedOutput.getAddress(); // Fund this address
// 2) Prepare PSBT input/output
const psbt = new Psbt();
const txHex = 'FUNDING_TX_HEX'; // hex of the tx that funded the address above
const vout = 0; // Output index (vout) of that UTXO within FUNDING_TX_HEX
const finalizeInput = fundedOutput.updatePsbtAsInput({ psbt, txHex, vout });
const recipient = new Output({
descriptor: 'addr(bc1qgw6xanldsz959z45y4dszehx4xkuzf7nfhya8x)'
}); // Final address where we'll send the funds after timelock
recipient.updatePsbtAsOutput({ psbt, value: 10000n }); // input covers this+fees
// 3) Sign and finalize
signers.signECPair({ psbt, ecpair });
finalizeInput({ psbt });
console.log('Push this: ' + psbt.extractTransaction().toHex());- Parses and creates Bitcoin Descriptors (including those based on the Miniscript language).
- Supports Taproot descriptors with trees:
tr(KEY,TREE)(tapscript). - Generates Partially Signed Bitcoin Transactions (PSBTs).
- Provides PSBT finalizers and signers for single-signature, BIP32 and Hardware Wallets (currently supports Ledger devices; more devices are planned).
Starting in 3.x, this library is aligned with the modern bitcoinjs stack (bitcoinjs-lib 7.x).
In practical terms, this means:
- byte arrays are represented as
Uint8Array; - satoshi values are represented as
bigint.
If you need older bitcoinjs versions, keep using @bitcoinerlab/descriptors 2.x.
If you want Taproot trees (tr(KEY,TREE)), use 3.x.
This library has two main capabilities related to Bitcoin descriptors. Firstly, it can generate addresses and scriptPubKeys from descriptors. These addresses and scriptPubKeys can be used to receive funds from other parties. Secondly, the library is able to sign transactions and spend unspent outputs described by those same descriptors. In order to do this, the descriptors must first be set into a PSBT.
If you are not familiar with Bitcoin descriptors and partially signed Bitcoin transactions (PSBTs), click on the section below to expand and read more about these concepts.
Concepts
In Bitcoin, a transaction consists of a set of inputs that are spent into a different set of outputs. Each input spends an output in a previous transaction. A Bitcoin descriptor is a string of text that describes the rules and conditions required to spend an output in a transaction.
For example, wpkh(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9) is a descriptor that describes a pay-to-witness-public-key-hash (P2WPKH) type of output with the specified public key. If you know the corresponding private key for the transaction for which this descriptor is an output, you can spend it.
Descriptors can express much more complex conditions, such as multi-party cooperation, time-locked outputs and more. These conditions can be expressed using the Bitcoin Miniscript language, which is a way of writing Bitcoin Scripts in a structured and more easily understandable way.
A PSBT (Partially Signed Bitcoin Transaction) is a format for sharing Bitcoin transactions between different parties.
PSBTs come in handy when working with descriptors, especially when using scripts, because they allow multiple parties to collaborate in the signing process. This is especially useful when using hardware wallets or other devices that require separate signatures or authorizations.
Before we dive in, it's worth mentioning that we have several comprehensive guides available covering different aspects of the library. These guides provide explanations and code examples in interactive playgrounds, allowing you to see the changes in the output as you modify the code. This hands-on learning experience, combined with clear explanations, helps you better understand how to use the library effectively. Check out the available guides here.
Furthermore, we've meticulously documented our API. For an in-depth look into Classes, functions and types, head over here.
To use this library (and accompanying libraries), you can install them using:
npm install @bitcoinerlab/descriptors
npm install @bitcoinerlab/miniscript
npm install @bitcoinerlab/secp256k1The library can be split into four main parts:
- The
Outputclass is the central component for managing descriptors. It facilitates the creation of outputs to receive funds and enables the signing and finalization of PSBTs (Partially Signed Bitcoin Transactions) for spending UTXOs (Unspent Transaction Outputs). - PSBT signers and finalizers, which are used to manage the signing and finalization of PSBTs.
keyExpressionsandscriptExpressions, which provide functions to create key and standard descriptor expressions (strings) from structured data.- Hardware wallet integration, which provides support for interacting with hardware wallets such as Ledger devices.
The Output class is dynamically created by providing a cryptographic secp256k1 engine as shown below:
import * as ecc from '@bitcoinerlab/secp256k1';
import * as descriptors from '@bitcoinerlab/descriptors';
const { Output } = descriptors.DescriptorsFactory(ecc);Once set up, you can obtain an instance for an output, described by a descriptor such as a wpkh, as follows:
const wpkhOutput = new Output({
descriptor:
'wpkh(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9)'
});For advanced spend-path control (for example signersPubKeys, taprootSpendPath, and tapLeaf), see Spending-path selection: from WSH Miniscript to Taproot.
Detailed information about constructor parameters can be found in the API documentation and in this Stack Exchange answer.
Some commonly used constructor parameters are:
index: for ranged descriptors ending in*.change: for multipath key expressions such as/**or/<0;1>/*. For example, in/<0;1>/*, usechange: 0orchange: 1.
The Output class offers various helpful methods, including getAddress(), which returns the address associated with the descriptor, getScriptPubKey(), which returns the scriptPubKey for the descriptor, expand(), which decomposes a descriptor into its elemental parts, updatePsbtAsInput() and updatePsbtAsOutput().
The library supports a wide range of descriptor types, including:
- Pay-to-Public-Key-Hash (P2PKH):
pkh(KEY) - Pay-to-Witness-Public-Key-Hash (P2WPKH):
wpkh(KEY) - Pay-to-Script-Hash (P2SH):
sh(SCRIPT) - Pay-to-Witness-Script-Hash (P2WSH):
wsh(SCRIPT) - Pay-to-Taproot (P2TR) with key-only or script tree:
tr(KEY)andtr(KEY,TREE) - Address-based descriptors:
addr(ADDRESS)
These descriptors can be used with various key expressions, including raw public keys, BIP32 derivation paths and more.
For example, a Taproot descriptor with script leaves can look like:
tr(INTERNAL_KEY,{pk(KEY_A),{pk(KEY_B),and_v(v:pk(KEY_C),older(144))}})
This means the output has an internal-key spend path and additional script-path options inside the tree.
The updatePsbtAsInput() method is an essential part of the library, responsible for adding an input to the PSBT corresponding to the UTXO described by the descriptor. Additionally, when the descriptor expresses an absolute time-spending condition, such as "This UTXO can only be spent after block N", updatePsbtAsInput() adds timelock information to the PSBT.
To call updatePsbtAsInput(), use the following syntax:
import { Psbt } from 'bitcoinjs-lib';
const psbt = new Psbt();
const inputFinalizer = output.updatePsbtAsInput({ psbt, txHex, vout, rbf });Here, psbt refers to an instance of the bitcoinjs-lib Psbt class. The parameter txHex denotes a hex string that serializes the previous transaction containing this output. Meanwhile, vout is an integer that marks the position of the output within that transaction. Finally, rbf is an optional parameter (defaulting to true) used to indicate whether the transaction uses Replace-By-Fee (RBF). When RBF is enabled, transactions can be replaced while they are in the mempool with others that have higher fees. Note that RBF is enabled for the entire transaction if at least one input signals it. Also, note that transactions using relative time locks inherently opt into RBF due to the nSequence range used.
The method returns the inputFinalizer() function. This finalizer function completes a PSBT input by adding the unlocking script (scriptWitness or scriptSig) that satisfies the previous output's spending conditions. Bear in mind that both scriptSig and scriptWitness incorporate signatures. As such, you should complete all necessary signing operations before calling inputFinalizer(). Detailed explanations on the inputFinalizer method can be found in the Signers and Finalizers section.
Similarly, updatePsbtAsOutput allows you to add an output to a PSBT. For instance, to configure a psbt that sends 10,000 sats to the SegWit address bc1qgw6xanldsz959z45y4dszehx4xkuzf7nfhya8x:
const recipientOutput = new Output({
descriptor: `addr(bc1qgw6xanldsz959z45y4dszehx4xkuzf7nfhya8x)`
});
recipientOutput.updatePsbtAsOutput({ psbt, value: 10000n });For further information on using the Output class, refer to the comprehensive guides that offer explanations and playgrounds to help learn the module. For specific details on the methods, refer directly to the API.
Most applications do not need expand() for normal receive/spend flows. It is mainly useful for debugging and introspection (for example, checking expanded expressions, key mappings, scripts, and parsed metadata).
const { expand } = descriptors.DescriptorsFactory(ecc);
const info = expand({ descriptor });For full details on returned fields, refer to the API.
When a descriptor has more than one valid way to spend, the library needs to know which path you intend to use.
For wsh(miniscript) and sh(wsh(miniscript)), this is usually done with signersPubKeys: you pass the public keys expected to sign and the library selects the most optimal satisfiable branch.
signersPubKeys is passed as an array of public keys (Uint8Array[]).
If omitted, the library assumes all descriptor keys may sign.
Example with two BIP32-derived keys and one preferred signer:
import { randomBytes } from 'crypto';
import * as ecc from '@bitcoinerlab/secp256k1';
import { DescriptorsFactory, keyExpressionBIP32 } from '@bitcoinerlab/descriptors';
const { Output, BIP32 } = DescriptorsFactory(ecc);
const masterNode = BIP32.fromSeed(randomBytes(64));
const originPath = "/84'/0'/0'";
const keyPathA = '/0/0';
const keyPathB = '/0/1';
const keyExprA = keyExpressionBIP32({ masterNode, originPath, keyPath: keyPathA });
const keyExprB = keyExpressionBIP32({ masterNode, originPath, keyPath: keyPathB });
const signerPubKeyA = masterNode.derivePath( `m${originPath}${keyPathA}`).publicKey;
// Two possible branches:
// - branch 1: signature by keyA + older(10)
// - branch 2: signature by keyB (no timelock)
const output = new Output({
descriptor: `wsh(andor(pk(${keyExprA}),older(10),pk(${keyExprB})))`,
signersPubKeys: [signerPubKeyA] // choose the keyA (timelock branch)
});Taproot uses the same idea. For tr(KEY,TREE), signersPubKeys helps determine which leaves are satisfiable and which satisfiable path is more optimal. In addition, Taproot provides two optional controls:
-
taprootSpendPath('key' | 'script') to force key-path or script-path spending. -
tapLeafto force a specific script leaf when using script path.If
taprootSpendPathis omitted fortr(KEY,TREE), the library uses script path and auto-selects the most optimal satisfiable leaf from available spending data (includingsignersPubKeysand preimages when relevant).
If you specifically plan to spend from the internal key, set:
new Output({
descriptor: 'tr(INTERNAL_KEY,{pk(KEY_A),pk(KEY_B)})',
taprootSpendPath: 'key'
});If you want to force a specific script leaf:
new Output({
descriptor: 'tr(INTERNAL_KEY,{pk(KEY_A),pk(KEY_B)})',
taprootSpendPath: 'script',
tapLeaf: 'pk(KEY_A)'
});These spending-path parameters (signersPubKeys, taprootSpendPath, tapLeaf) are only needed when spending/finalizing UTXOs with multiple candidate paths. They are not needed just to derive addresses or scriptPubKeys.
For a focused walkthrough of constructor choices (including signersPubKeys) and practical usage of updatePsbtAsInput, getAddress and getScriptPubKey, see this Stack Exchange answer.
This library encompasses a PSBT finalizer as well as three distinct signers: ECPair for single-signatures, BIP32 and Ledger (specifically crafted for Ledger Wallet devices, with upcoming support for other devices planned).
To incorporate these functionalities, use the following import statement:
import { signers } from '@bitcoinerlab/descriptors';For signing operations, utilize the methods provided by the signers:
// For Ledger
await signers.signLedger({ psbt, ledgerManager });
// For BIP32 - https://github.com/bitcoinjs/bip32
signers.signBIP32({ psbt, masterNode });
// For ECPair - https://github.com/bitcoinjs/ecpair
signers.signECPair({ psbt, ecpair }); // Here, `ecpair` is an instance of the bitcoinjs-lib ECPairInterfaceDetailed information on Ledger integration will be provided in subsequent sections.
When finalizing the psbt, the updatePsbtAsInput method plays a key role. When invoked, the output.updatePsbtAsInput() sets up the psbt by designating the output as an input and, if required, adjusts the transaction locktime. In addition, it returns a inputFinalizer function tailored for this specific psbt input.
-
For each unspent output from a previous transaction that you're referencing in a
psbtas an input to be spent, call theupdatePsbtAsInputmethod:const inputFinalizer = output.updatePsbtAsInput({ psbt, txHex, vout });
-
Once you've completed the necessary signing operations on the
psbt, use the returned finalizer function on each input:inputFinalizer({ psbt });
-
The finalizer function returned from
updatePsbtAsInputadds the necessary unlocking script (scriptWitnessorscriptSig) that satisfies theOutput's spending conditions. Remember, bothscriptSigandscriptWitnesscontain signatures. Ensure that all necessary signing operations are completed before finalizing. -
When using
updatePsbtAsInput, thetxHexparameter is crucial. For Segwit inputs, you can choose to passtxIdandvalueinstead oftxHex(valueisbigintin v3). However, ensure the accuracy of thevalueto avoid potential fee attacks. When unsure, usetxHexand skiptxIdandvalue. -
Hardware wallets require the full
txHexfor Segwit.
This library also provides a series of function helpers designed to streamline the generation of descriptor strings. These strings can serve as input parameters in the Output class constructor. These helpers are nested within the scriptExpressions module. You can import them as illustrated below:
import { scriptExpressions } from '@bitcoinerlab/descriptors';Within the scriptExpressions module, there are functions designed to generate descriptors for commonly used scripts. Some examples include pkhBIP32(), shWpkhBIP32(), wpkhBIP32(), pkhLedger(), shWpkhLedger() and wpkhLedger(). Refer to the API for a detailed list and further information.
When using BIP32-based descriptors, the following parameters are required for the scriptExpressions functions:
pkhBIP32(params: {
masterNode: BIP32Interface; //bitcoinjs-lib BIP32 - https://github.com/bitcoinjs/bip32
network?: Network; //A bitcoinjs-lib network
account: number;
change?: number | undefined; //0 -> external (receive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string; //You can use change & index or a keyPath such as "/0/0"
isPublic?: boolean; //Whether to use xpub or xprv
})For functions suffixed with Ledger (designed to generate descriptors for Ledger Hardware devices), replace masterNode with ledgerManager. Detailed information on Ledger integration will be provided in the following section.
The keyExpressions category includes functions that generate string representations of key expressions for public keys.
This library includes the following keyExpressions: keyExpressionBIP32 and keyExpressionLedger. They can be imported as follows:
import { keyExpressionBIP32, keyExpressionLedger } from '@bitcoinerlab/descriptors';The parameters required for these functions are:
function keyExpressionBIP32({
masterNode: BIP32Interface; //bitcoinjs-lib BIP32 - https://github.com/bitcoinjs/bip32
originPath: string;
change?: number | undefined; //0 -> external (receive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string | undefined; //In the case of the Ledger, keyPath can also use multipath (e.g. /<0;1>/number)
isPublic?: boolean;
});For the keyExpressionLedger function, you'd use ledgerManager instead of masterNode.
Both functions will generate strings that fully define BIP32 keys. For example:
[d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*
Read Bitcoin Core descriptors documentation to learn more about Key Expressions.
This library currently provides integration with Ledger wallets. Support for more devices is planned.
Before we dive in, note that, in addition to the documentation below, it is highly recommended to visit the Ledger Playground with an interactive code sandbox of this lib interacting with a Ledger device.
To use this library with Ledger devices, you must first install Ledger support:
npm install @ledgerhq/ledger-bitcoin @ledgerhq/hw-transport-node-hidFor Ledger device signing, import the necessary functions as follows:
import Transport from '@ledgerhq/hw-transport-node-hid'; //or hw-transport-web-hid, for web
import { AppClient } from '@ledgerhq/ledger-bitcoin';
import { ledger } from '@bitcoinerlab/descriptors';Then, use the following code to assert that the Ledger app is running Bitcoin Test version 2.1.0 or higher and to create a new Ledger client:
const transport = await Transport.create();
//Throws if not running Bitcoin Test >= 2.1.0
await ledger.assertLedgerApp({ transport, name: 'Bitcoin Test', minVersion: '2.1.0' });
const ledgerClient = new AppClient(transport);
const ledgerManager = { ledgerClient, ledgerState: {}, ecc, network };Here, transport is an instance of a Transport object that allows communication with Ledger devices. You can use any of the transports provided by Ledger.
To register the policies of non-standard descriptors on the Ledger device, use the following code:
await ledger.registerLedgerWallet({
ledgerManager,
descriptor: wshDescriptor,
policyName: 'BitcoinerLab'
});This code will auto-skip the policy registration process if it already exists. Please refer to Ledger documentation to learn more about their Wallet Policies registration procedures.
Finally, ledgerManager.ledgerState is an object used to store information related to Ledger devices. Although Ledger devices themselves are stateless, this object can be used to store information such as xpubs, master fingerprints and wallet policies. You can pass an initially empty object that will be updated with more information as it is used. The object can be serialized and stored for future use.
The API reference for the ledger module provides a comprehensive list of functions related to the Ledger Hardware Wallet, along with detailed explanations of their parameters and behavior.
For more information, refer to the following resources:
-
Guides: Comprehensive explanations and playgrounds to help you learn how to use the module.
-
API: Dive into the details of the Classes, functions and types.
-
Stack Exchange answer: Focused explanation on the constructor, specifically the
signersPubKeysparameter and the usage ofupdatePsbtAsInput,getAddressandgetScriptPubKey. -
Integration tests: Well-commented code examples showcasing the usage of all functions in the module.
-
Local Documentation: Generate comprehensive API documentation from the source code:
git clone https://github.com/bitcoinerlab/descriptors cd descriptors/ npm install npm run docsThe generated documentation will be available in the
docs/directory. Open theindex.htmlfile to view the documentation.
The project was initially developed and is currently maintained by Jose-Luis Landabaso. Contributions and help from other developers are welcome.
Here are some resources to help you get started with contributing:
To download the source code and build the project, follow these steps:
- Clone the repository:
git clone https://github.com/bitcoinerlab/descriptors.git- Install the dependencies:
npm install- Build the project:
npm run buildThis will build the project and generate the necessary files in the dist directory.
Before committing any code, make sure it passes all tests.
Run unit tests:
npm run test:unitRun the full test pipeline (lint + build + unit + integration):
npm run testIntegration tests require Docker. Make sure the docker command is installed and available in your PATH. When integration tests run, they automatically start or reuse a local container with the regtest services needed by this repository.
And, in case you have a Ledger device:
npm run test:integration:ledgerThis project is licensed under the MIT License.