<img src="https://user-images.githubusercontent.com/4631227/191834116-59cf590e-25cc-4956-ae5c-812ea464f324.png" height="100" />

[GitHub](https://github.com/LedgerHQ/ledger-live/),
[Ledger Devs Discord](https://developers.ledger.com/discord-pro),
[Developer Portal](https://developers.ledger.com/)

## @ledgerhq/hw-app-btc

Ledger Hardware Wallet BTC JavaScript bindings. Also supports many altcoins.

***

## Are you adding Ledger support to your software wallet?

You may be using this package to communicate with the Bitcoin Nano App.

For a smooth and quick integration:

*   See the developers’ documentation on the [Developer Portal](https://developers.ledger.com/docs/transport/overview/) and
*   Go on [Discord](https://developers.ledger.com/discord-pro/) to chat with developer support and the developer community.

***

## API

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

#### Table of Contents

*   [bippath](#bippath)
*   [deriveChildPublicKey](#derivechildpublickey)
    *   [Parameters](#parameters)
*   [Btc](#btc)
    *   [Parameters](#parameters-1)
    *   [Examples](#examples)
    *   [getWalletXpub](#getwalletxpub)
        *   [Parameters](#parameters-2)
    *   [getWalletPublicKey](#getwalletpublickey)
        *   [Parameters](#parameters-3)
        *   [Examples](#examples-1)
    *   [signMessage](#signmessage)
        *   [Parameters](#parameters-4)
        *   [Examples](#examples-2)
    *   [createPaymentTransaction](#createpaymenttransaction)
        *   [Parameters](#parameters-5)
        *   [Examples](#examples-3)
    *   [signPsbtBuffer](#signpsbtbuffer)
        *   [Parameters](#parameters-6)
    *   [signP2SHTransaction](#signp2shtransaction)
        *   [Parameters](#parameters-7)
        *   [Examples](#examples-4)
    *   [splitTransaction](#splittransaction)
        *   [Parameters](#parameters-8)
        *   [Examples](#examples-5)
    *   [serializeTransactionOutputs](#serializetransactionoutputs)
        *   [Parameters](#parameters-9)
        *   [Examples](#examples-6)
    *   [getTrustedInput](#gettrustedinput)
        *   [Parameters](#parameters-10)
    *   [getTrustedInputBIP143](#gettrustedinputbip143)
        *   [Parameters](#parameters-11)
*   [BtcNew](#btcnew)
    *   [getWalletXpub](#getwalletxpub-1)
        *   [Parameters](#parameters-12)
    *   [getWalletPublicKey](#getwalletpublickey-1)
        *   [Parameters](#parameters-13)
    *   [createPaymentTransaction](#createpaymenttransaction-1)
        *   [Parameters](#parameters-14)
    *   [signPsbtBuffer](#signpsbtbuffer-1)
        *   [Parameters](#parameters-15)
    *   [signMessage](#signmessage-1)
        *   [Parameters](#parameters-16)
*   [descrTemplFrom](#descrtemplfrom)
    *   [Parameters](#parameters-17)
*   [BtcOld](#btcold)
    *   [getWalletPublicKey](#getwalletpublickey-2)
        *   [Parameters](#parameters-18)
        *   [Examples](#examples-7)
    *   [createPaymentTransaction](#createpaymenttransaction-2)
        *   [Parameters](#parameters-19)
        *   [Examples](#examples-8)
*   [CreateTransactionArg](#createtransactionarg)
    *   [Properties](#properties)
*   [AddressFormat](#addressformat)
*   [computeTaprootOutputKey](#computetaprootoutputkey)
    *   [Parameters](#parameters-20)
*   [AccountType](#accounttype)
    *   [spendingCondition](#spendingcondition)
        *   [Parameters](#parameters-21)
    *   [setInput](#setinput)
        *   [Parameters](#parameters-22)
    *   [setOwnOutput](#setownoutput)
        *   [Parameters](#parameters-23)
    *   [getDescriptorTemplate](#getdescriptortemplate)
*   [SingleKeyAccount](#singlekeyaccount)
*   [getTaprootOutputKey](#gettaprootoutputkey)
    *   [Parameters](#parameters-24)
*   [AppClient](#appclient)
    *   [Parameters](#parameters-25)
*   [ClientCommandInterpreter](#clientcommandinterpreter)
    *   [Parameters](#parameters-26)
*   [MerkelizedPsbt](#merkelizedpsbt)
    *   [Parameters](#parameters-27)
*   [Merkle](#merkle)
    *   [Parameters](#parameters-28)
*   [MerkleMap](#merklemap)
    *   [Parameters](#parameters-29)
*   [WalletPolicy](#walletpolicy)
    *   [Parameters](#parameters-30)
*   [extract](#extract)
    *   [Parameters](#parameters-31)
*   [finalize](#finalize)
    *   [Parameters](#parameters-32)
*   [clearFinalizedInput](#clearfinalizedinput)
    *   [Parameters](#parameters-33)
*   [writePush](#writepush)
    *   [Parameters](#parameters-34)
*   [serializeTransactionOutputs](#serializetransactionoutputs-1)
    *   [Parameters](#parameters-35)
    *   [Examples](#examples-9)
*   [SignP2SHTransactionArg](#signp2shtransactionarg)
    *   [Properties](#properties-1)
*   [determineAccountType](#determineaccounttype)
    *   [Parameters](#parameters-36)
*   [getDerivationAccessors](#getderivationaccessors)
    *   [Parameters](#parameters-37)
*   [checkElementBip32Derivation](#checkelementbip32derivation)
    *   [Parameters](#parameters-38)
*   [extractAccountPath](#extractaccountpath)
    *   [Parameters](#parameters-39)
*   [checkOutputBip32Derivation](#checkoutputbip32derivation)
    *   [Parameters](#parameters-40)
*   [getScriptPubKeyFromNonWitnessUtxo](#getscriptpubkeyfromnonwitnessutxo)
    *   [Parameters](#parameters-41)
*   [getInputScriptPubKey](#getinputscriptpubkey)
    *   [Parameters](#parameters-42)
*   [fixDerivationFingerprints](#fixderivationfingerprints)
    *   [Parameters](#parameters-43)
*   [setElementBip32DerivationData](#setelementbip32derivationdata)
    *   [Parameters](#parameters-44)
*   [populateMissingBip32Derivations](#populatemissingbip32derivations)
    *   [Parameters](#parameters-45)
*   [determineInputScriptType](#determineinputscripttype)
    *   [Parameters](#parameters-46)
*   [analyzeInput](#analyzeinput)
    *   [Parameters](#parameters-47)
*   [analyzeAllInputs](#analyzeallinputs)
    *   [Parameters](#parameters-48)
*   [deserializePsbt](#deserializepsbt)
    *   [Parameters](#parameters-49)
*   [createWalletPolicy](#createwalletpolicy)
    *   [Parameters](#parameters-50)
*   [createProgressCallback](#createprogresscallback)
    *   [Parameters](#parameters-51)
*   [finalizePsbtAndExtract](#finalizepsbtandextract)
    *   [Parameters](#parameters-52)
*   [KnownAddressDerivationsMap](#knownaddressderivationsmap)
*   [SignPsbtBufferOptions](#signpsbtbufferoptions)
    *   [knownAddressDerivations](#knownaddressderivations)
*   [DerivationElementType](#derivationelementtype)
*   [DerivationAccessors](#derivationaccessors)
*   [ScriptType](#scripttype)
*   [splitSaplingPart](#splitsaplingpart)
    *   [Parameters](#parameters-53)
*   [splitOrchardPart](#splitorchardpart)
    *   [Parameters](#parameters-54)
*   [TransactionInput](#transactioninput)
*   [TransactionOutput](#transactionoutput)
*   [Transaction](#transaction)
*   [SaplingData](#saplingdata)

### bippath

BIP32 Path Handling for Bitcoin Wallets

This file provides utility functions to handle BIP32 paths,
which are commonly used in hierarchical deterministic (HD) wallets.
It includes functions to convert BIP32 paths to and from different formats,
extract components from extended public keys (xpubs), manipulate path elements,
and derive child public keys locally (for non-hardened derivation).

### deriveChildPublicKey

Derives a child public key from a parent public key using BIP32 non-hardened derivation.
This allows deriving child keys locally without device interaction.

#### Parameters

*   `parentPubkey` **[Buffer](https://nodejs.org/api/buffer.html)** The parent compressed public key (33 bytes)
*   `parentChaincode` **[Buffer](https://nodejs.org/api/buffer.html)** The parent chaincode (32 bytes)
*   `index` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The child index (must be non-hardened, i.e., < 0x80000000)

<!---->

*   Throws **any** Error if attempting hardened derivation or invalid inputs

Returns **{pubkey: [Buffer](https://nodejs.org/api/buffer.html), chaincode: [Buffer](https://nodejs.org/api/buffer.html)}** The derived child public key and chaincode

### Btc

Bitcoin API.

#### Parameters

*   `transport`  The transport layer used for communication.
*   `scrambleKey`  This parameter is deprecated and no longer needed.
*   `currency`  The currency to use, defaults to "bitcoin".

#### Examples

```javascript
import Btc from "@ledgerhq/hw-app-btc";
const btc = new Btc({ transport, currency: "bitcoin" });
```

#### getWalletXpub

Get an XPUB with a ledger device

##### Parameters

*   `arg` **{path: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), xpubVersion: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}** derivation parameter*   path: a BIP 32 path of the account level. (e.g. The derivation path `84'/0'/0'`
        follows the `purpose' / coin_type' / account'` standard, with purpose=84, coin\_type=0, account=0)
    *   xpubVersion: the XPUBVersion of the coin used. (refer to ledgerjs/packages/cryptoassets/src/currencies.ts
        for the XPUBVersion value if needed)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** XPUB of the account

#### getWalletPublicKey

##### Parameters

*   `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** a BIP 32 path (i.e. the `purpose’ / coin_type’ / account’ / change / address_index` standard)
*   `opts` **{verify: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?, format: [AddressFormat](#addressformat)?}?**&#x20;
*   `options`  an object with optional these fields:*   verify (boolean) whether ask user to confirm the address on the device

    *   format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter.NB The normal usage is to use:*   legacy format with 44' paths

    *   p2sh format with 49' paths

    *   bech32 format with 84' paths

    *   bech32m format with 86' paths

    *   cashaddr in case of Bitcoin Cash

##### Examples

```javascript
btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress)
btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress)
```

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{publicKey: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), bitcoinAddress: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), chainCode: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}>**&#x20;

#### signMessage

You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign.

##### Parameters

*   `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;
*   `messageHex` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;

##### Examples

```javascript
btc.signMessage("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) {
var v = result['v'] + 27 + 4;
var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64');
console.log("Signature : " + signature);
}).catch(function(ex) {console.log(ex);});
```

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{v: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), r: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), s: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}>**&#x20;

#### createPaymentTransaction

To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters

##### Parameters

*   `arg` **[CreateTransactionArg](#createtransactionarg)**&#x20;
*   `inputs`  is an array of \[ transaction, output\_index, optional redeem script, optional sequence ] where*   transaction is the previously computed transaction object for this UTXO
    *   output\_index is the output in the transaction used as input for this UTXO (counting from 0)
    *   redeem script is the optional redeem script to use when consuming a Segregated Witness input
    *   sequence is the sequence number to use for this input (when using RBF), or non present
*   `associatedKeysets`  is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
*   `changePath`  is an optional BIP 32 path pointing to the path to the public key used to compute the change address
*   `outputScriptHex`  is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount
*   `lockTime`  is the optional lockTime of the transaction to sign, or default (0)
*   `sigHashType`  is the hash type of the transaction to sign, or default (all)
*   `segwit`  is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit.
*   `additionals`  list of additionnal options*   "bech32" for spending native segwit outputs
    *   "bech32m" for spending segwit v1+ outputs
    *   "abc" for bch
    *   "gold" for btg
    *   "decred" for decred
    *   "zcash" for zcash
    *   "bipxxx" for using BIPxxx
    *   "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200)
*   `expiryHeight`  is an optional Buffer for zec overwinter / sapling Txs
*   `useTrustedInputForSegwit`  trust inputs for segwit transactions. If app version >= 1.4.0 this should be true.

##### Examples

```javascript
btc.createTransaction({
inputs: [ [tx1, 1] ],
associatedKeysets: ["0'/0/0"],
outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
}).then(res => ...);
```

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** the signed transaction ready to be broadcast

#### signPsbtBuffer

Signs a PSBT buffer using the Bitcoin app (new protocol).

*   If the PSBT is v2, it is deserialized directly.
*   If the PSBT is v0, it is converted to v2 internally.
*   The account type (legacy, wrapped segwit, native segwit, taproot) is
    inferred from PSBT data when possible, or from the provided options.

Note: All internal inputs (inputs that can be signed by the device) must
belong to the same account and use the same account type. Mixed input types
or inputs from different accounts are not supported and will throw an error.

##### Parameters

*   `psbtBuffer` **[Buffer](https://nodejs.org/api/buffer.html)** Raw PSBT buffer (v0 or v2) to be signed.
*   `options` **[SignPsbtBufferOptions](#signpsbtbufferoptions)** Signing configuration.

    *   `options.finalizePsbt`  Whether to finalize the PSBT after signing.
        If true, the returned `tx` is a fully signed
        transaction ready for broadcast.
    *   `options.accountPath`  BIP32 account path (for example,
        "m/84'/0'/0'"). Required. Used to populate missing BIP32 derivation
        information when the PSBT lacks it, and as the signing account path.
    *   `options.addressFormat`  Explicit address format to use when the
        account type cannot be inferred from the PSBT ("legacy", "p2sh",
        "bech32", or "bech32m").
    *   `options.onDeviceSignatureRequested`  Callback when signature is about to be requested from device.
    *   `options.onDeviceSignatureGranted`  Callback when the first signature is granted by device.
    *   `options.onDeviceStreaming`  Callback to track signing progress with index and total.
    *   `options.knownAddressDerivations`  Map from scriptPubKey hash (hex) to { pubkey, path }.
        Required. Built by the caller from the wallet's known addresses (receive/change).

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{psbt: [Buffer](https://nodejs.org/api/buffer.html), tx: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?}>** An object containing:*   `psbt`: the serialized PSBT (with signatures; finalized if
    `finalizePsbt` is true).
*   `tx`: the fully signed transaction hex string, only when
    `finalizePsbt` is true; omitted when not finalizing.

#### signP2SHTransaction

To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction\_async with the folowing parameters

##### Parameters

*   `arg` **[SignP2SHTransactionArg](#signp2shtransactionarg)**&#x20;
*   `inputs`  is an array of \[ transaction, output\_index, redeem script, optional sequence ] where*   transaction is the previously computed transaction object for this UTXO
    *   output\_index is the output in the transaction used as input for this UTXO (counting from 0)
    *   redeem script is the mandatory redeem script associated to the current P2SH input
    *   sequence is the sequence number to use for this input (when using RBF), or non present
*   `associatedKeysets`  is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
*   `outputScriptHex`  is the hexadecimal serialized outputs of the transaction to sign
*   `lockTime`  is the optional lockTime of the transaction to sign, or default (0)
*   `sigHashType`  is the hash type of the transaction to sign, or default (all)

##### Examples

```javascript
btc.signP2SHTransaction({
inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ],
associatedKeysets: ["0'/0/0"],
outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
}).then(result => ...);
```

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>>** the signed transaction ready to be broadcast

#### splitTransaction

For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO.

##### Parameters

*   `transactionHex` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** a raw hexadecimal serialized transaction
*   `isSegwitSupported` **([boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))** is a boolean indicating if the segwit is supported (optional, default `false`)
*   `hasExtraData`  is a boolean (komodo, zencash and zcash include extraData in their transactions, others don't) (optional, default `false`)
*   `additionals` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** list of additionnal options (optional, default `[]`)

##### Examples

```javascript
const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000");
```

Returns **[Transaction](#transaction)** the transaction object deserialized from the raw hexadecimal transaction

#### serializeTransactionOutputs

Serialize a transaction's outputs to hexadecimal

##### Parameters

*   `t` **[Transaction](#transaction)**&#x20;

##### Examples

```javascript
const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000");
const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex');
```

Returns **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

#### getTrustedInput

Trusted input is the hash of a UTXO that needs to be signed
For Legacy transactions, the app has some APDUs flows that do the amount check for an UTXO,
by parsing the transaction that created this UTXO

##### Parameters

*   `indexLookup` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `transaction` **[Transaction](#transaction)**&#x20;
*   `additionals` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**  (optional, default `[]`)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**&#x20;

#### getTrustedInputBIP143

Trusted input is the hash of a UTXO that needs to be signed. BIP143 is used for Segwit inputs.

##### Parameters

*   `indexLookup` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `transaction` **[Transaction](#transaction)**&#x20;
*   `additionals` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**  (optional, default `[]`)

Returns **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;

### BtcNew

This class implements the same interface as BtcOld (formerly
named Btc), but interacts with Bitcoin hardware app version 2.1.0+
which uses a totally new APDU protocol. This new
protocol is documented at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md>

Since the interface must remain compatible with BtcOld, the methods
of this class are quite clunky, because it needs to adapt legacy
input data into the PSBT process. In the future, a new interface should
be developed that exposes PSBT to the outer world, which would render
a much cleaner implementation.

#### getWalletXpub

This is a new method that allow users to get an xpub at a standard path.
Standard paths are described at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description>

This boils down to paths (N=0 for Bitcoin, N=1 for Testnet):
M/44'/N'/x'/\*\*
M/48'/N'/x'/y'/\*\*
M/49'/N'/x'/\*\*
M/84'/N'/x'/\*\*
M/86'/N'/x'/\*\*

The method was added because of added security in the hardware app v2+. The
new hardware app will allow export of any xpub up to and including the
deepest hardened key of standard derivation paths, whereas the old app
would allow export of any key.

This caused an issue for callers of this class, who only had
getWalletPublicKey() to call which means they have to constuct xpub
themselves:

Suppose a user of this class wants to create an account xpub on a standard
path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32)
by requesting the parent key M/44'/0'. The new app won't allow that, because
it only allows exporting deepest level hardened path. So the options are to
allow requesting M/44'/0' from the app, or to add a new function
"getWalletXpub".

We opted for adding a new function, which can greatly simplify client code.

##### Parameters

*   `$0` **{path: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), xpubVersion: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}**&#x20;

    *   `$0.path` &#x20;
    *   `$0.xpubVersion` &#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**&#x20;

#### getWalletPublicKey

This method returns a public key, a bitcoin address, and and a chaincode
for a specific derivation path.

Limitation: If the path is not a leaf node of a standard path, the address
will be the empty string "", see this.getWalletAddress() for details.

##### Parameters

*   `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;
*   `opts` **{verify: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?, format: [AddressFormat](#addressformat)?}?**&#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{publicKey: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), bitcoinAddress: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), chainCode: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}>**&#x20;

#### createPaymentTransaction

Build and sign a transaction. See Btc.createPaymentTransaction for
details on how to use this method.

This method will convert the legacy arguments, CreateTransactionArg, into
a psbt which is finally signed and finalized, and the extracted fully signed
transaction is returned.

##### Parameters

*   `arg` **[CreateTransactionArg](#createtransactionarg)**&#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**&#x20;

#### signPsbtBuffer

Signs a PSBT buffer using the Bitcoin app (new protocol).

*   If the PSBT is v2, it is deserialized directly.
*   If the PSBT is v0, it is converted to v2 internally.
*   The account type (legacy, wrapped segwit, native segwit, taproot) is
    inferred from PSBT data when possible, or from the provided options.

Note: All internal inputs (inputs that can be signed by the device) must
belong to the same account and use the same account type. Mixed input types
or inputs from different accounts are not supported and will throw an error.

##### Parameters

*   `psbtBuffer` **[Buffer](https://nodejs.org/api/buffer.html)** Raw PSBT buffer (v0 or v2) to be signed.
*   `options` **[SignPsbtBufferOptions](#signpsbtbufferoptions)** Signing configuration.

    *   `options.finalizePsbt`  Whether to finalize the PSBT after signing.
        If true, the returned `tx` is a fully signed
        transaction ready for broadcast.
    *   `options.accountPath`  BIP32 account path (for example,
        "m/84'/0'/0'"). Required. Used to populate missing BIP32 derivation
        information when the PSBT lacks it, and as the signing account path.
    *   `options.addressFormat`  Explicit address format to use when the
        account type cannot be inferred from the PSBT ("legacy", "p2sh",
        "bech32", or "bech32m").
    *   `options.onDeviceSignatureRequested`  Callback when signature is about to be requested from device.
    *   `options.onDeviceSignatureGranted`  Callback when the first signature is granted by device.
    *   `options.onDeviceStreaming`  Callback to track signing progress with index and total.
    *   `options.knownAddressDerivations`  Map from scriptPubKey hash (hex) to { pubkey, path }.
        Required. Built by the caller from the wallet's known addresses (receive/change).
        Used to populate missing BIP32 derivations in the PSBT.

Returns **any** An object containing:*   `psbt`: the serialized PSBT (with signatures; finalized if
    `finalizePsbt` is true).
*   `tx`: the fully signed transaction hex string, only when
    `finalizePsbt` is true; omitted when not finalizing.

#### signMessage

Signs an arbitrary hex-formatted message with the private key at
the provided derivation path according to the Bitcoin Signature format
and returns v, r, s.

##### Parameters

*   `$0` **{path: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), messageHex: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}**&#x20;

    *   `$0.path` &#x20;
    *   `$0.messageHex` &#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{v: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), r: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), s: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}>**&#x20;

### descrTemplFrom

This function returns a descriptor template based on the address format.
See <https://github.com/LedgerHQ/app-bitcoin-new/blob/develop/doc/wallet.md> for details of
the bitcoin descriptor template.

#### Parameters

*   `addressFormat` **[AddressFormat](#addressformat)**&#x20;

Returns **DefaultDescriptorTemplate**&#x20;

### BtcOld

This Bitcoin old API is compatible with versions of the Bitcoin nano app that are earlier than 2.1.0

#### getWalletPublicKey

##### Parameters

*   `path` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** a BIP 32 path
*   `opts` **{verify: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?, format: [AddressFormat](#addressformat)?}?**&#x20;
*   `options`  an object with optional these fields:*   verify (boolean) will ask user to confirm the address on the device

    *   format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter.NB The normal usage is to use:*   legacy format with 44' paths

    *   p2sh format with 49' paths

    *   bech32 format with 84' paths

    *   bech32m format with 86' paths

    *   cashaddr in case of Bitcoin Cash

##### Examples

```javascript
btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress)
btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress)
```

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<{publicKey: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), bitcoinAddress: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), chainCode: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}>**&#x20;

#### createPaymentTransaction

To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters

##### Parameters

*   `arg` **[CreateTransactionArg](#createtransactionarg)**&#x20;
*   `inputs`  is an array of \[ transaction, output\_index, optional redeem script, optional sequence ] where*   transaction is the previously computed transaction object for this UTXO
    *   output\_index is the output in the transaction used as input for this UTXO (counting from 0)
    *   redeem script is the optional redeem script to use when consuming a Segregated Witness input
    *   sequence is the sequence number to use for this input (when using RBF), or non present
*   `associatedKeysets`  is an array of BIP 32 paths pointing to the path to the private key used for each UTXO
*   `changePath`  is an optional BIP 32 path pointing to the path to the public key used to compute the change address
*   `outputScriptHex`  is the hexadecimal serialized outputs of the transaction to sign
*   `lockTime`  is the optional lockTime of the transaction to sign, or default (0)
*   `sigHashType`  is the hash type of the transaction to sign, or default (all)
*   `segwit`  is an optional boolean indicating wether to use segwit or not
*   `additionals`  list of additionnal options*   "bech32" for spending native segwit outputs
    *   "abc" for bch
    *   "gold" for btg
    *   "decred" for decred
    *   "zcash" for zcash
    *   "bipxxx" for using BIPxxx
    *   "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200)
*   `expiryHeight`  is an optional Buffer for zec overwinter / sapling Txs
*   `useTrustedInputForSegwit`  trust inputs for segwit transactions

##### Examples

```javascript
btc.createTransaction({
inputs: [ [tx1, 1] ],
associatedKeysets: ["0'/0/0"],
outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac"
}).then(res => ...);
```

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** the signed transaction ready to be broadcast

### CreateTransactionArg

Type: {inputs: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<\[[Transaction](#transaction), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))?]>, associatedKeysets: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>, changePath: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?, outputScriptHex: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), lockTime: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?, blockHeight: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?, sigHashType: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?, segwit: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?, additionals: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>, expiryHeight: [Buffer](https://nodejs.org/api/buffer.html)?, useTrustedInputForSegwit: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?, onDeviceStreaming: function (arg0: {progress: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), total: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), index: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}): void?, onDeviceSignatureRequested: function (): void?, onDeviceSignatureGranted: function (): void?}

#### Properties

*   `inputs` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<\[[Transaction](#transaction), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))?]>**&#x20;
*   `associatedKeysets` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**&#x20;
*   `changePath` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?**&#x20;
*   `outputScriptHex` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;
*   `lockTime` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?**&#x20;
*   `blockHeight` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?**&#x20;
*   `sigHashType` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?**&#x20;
*   `segwit` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?**&#x20;
*   `additionals` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**&#x20;
*   `expiryHeight` **[Buffer](https://nodejs.org/api/buffer.html)?**&#x20;
*   `useTrustedInputForSegwit` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?**&#x20;
*   `onDeviceStreaming` **function (arg0: {progress: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), total: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), index: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}): void?**&#x20;
*   `onDeviceSignatureRequested` **function (): void?**&#x20;
*   `onDeviceSignatureGranted` **function (): void?**&#x20;

### AddressFormat

address format is one of legacy | p2sh | bech32 | bech32m | cashaddr

Type: (`"legacy"` | `"p2sh"` | `"bech32"` | `"bech32m"` | `"cashaddr"`)

### computeTaprootOutputKey

Computes the taproot output key (BIP341) from an internal x-only pubkey.
Standalone so derivation population can build a hash-based lookup without AccountType.

#### Parameters

*   `internalXonlyPubkey` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

Returns **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

### AccountType

Encapsulates differences between account types, for example p2wpkh,
p2wpkhWrapped, p2tr.

#### spendingCondition

Generates a scriptPubKey (output script) from a list of public keys. If a
p2sh redeemScript or a p2wsh witnessScript is needed it will also be set on
the returned SpendingCondition.

The pubkeys are expected to be 33 byte ecdsa compressed pubkeys.

##### Parameters

*   `pubkeys` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>**&#x20;

Returns **SpendingCondition**&#x20;

#### setInput

Populates the psbt with account type-specific data for an input.

##### Parameters

*   `i` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The index of the input map to populate
*   `inputTx` **([Buffer](https://nodejs.org/api/buffer.html) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))** The full transaction containing the spent output. This may
    be omitted for taproot.
*   `spentOutput` **SpentOutput** The amount and spending condition of the spent output
*   `pubkeys` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** The 33 byte ecdsa compressed public keys involved in the input
*   `pathElems` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>>** The paths corresponding to the pubkeys, in same order.

Returns **void**&#x20;

#### setOwnOutput

Populates the psbt with account type-specific data for an output. This is typically
done for change outputs and other outputs that goes to the same account as
being spent from.

##### Parameters

*   `i` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The index of the output map to populate
*   `cond` **SpendingCondition** The spending condition for this output
*   `pubkeys` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** The 33 byte ecdsa compressed public keys involved in this output
*   `paths` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>>** The paths corresponding to the pubkeys, in same order.

Returns **void**&#x20;

#### getDescriptorTemplate

Returns the descriptor template for this account type. Currently only
DefaultDescriptorTemplates are allowed, but that might be changed in the
future. See class WalletPolicy for more information on descriptor
templates.

Returns **DefaultDescriptorTemplate**&#x20;

### SingleKeyAccount

**Extends BaseAccount**

Superclass for single signature accounts. This will make sure that the pubkey
arrays and path arrays in the method arguments contains exactly one element
and calls an abstract method to do the actual work.

### getTaprootOutputKey

Calculates a taproot output key from an internal key (BIP341).

#### Parameters

*   `internalPubkey` **[Buffer](https://nodejs.org/api/buffer.html)** A 32 byte x-only taproot internal key

Returns **[Buffer](https://nodejs.org/api/buffer.html)** The output key

### AppClient

This class encapsulates the APDU protocol documented at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md>

#### Parameters

*   `transport` **Transport**&#x20;

### ClientCommandInterpreter

This class will dispatch a client command coming from the hardware device to
the appropriate client command implementation. Those client commands
typically requests data from a merkle tree or merkelized maps.

A ClientCommandInterpreter is prepared by adding the merkle trees and
merkelized maps it should be able to serve to the hardware device. This class
doesn't know anything about the semantics of the data it holds, it just
serves merkle data. It doesn't even know in what context it is being
executed, ie SignPsbt, getWalletAddress, etc.

If the command yelds results to the client, as signPsbt does, the yielded
data will be accessible after the command completed by calling getYielded(),
which will return the yields in the same order as they came in.

#### Parameters

*   `progressCallback` **function (): void**&#x20;

### MerkelizedPsbt

**Extends PsbtV2**

This class merkelizes a PSBTv2, by merkelizing the different
maps of the psbt. This is used during the transaction signing process,
where the hardware app can request specific parts of the psbt from the
client code and be sure that the response data actually belong to the psbt.
The reason for this is the limited amount of memory available to the app,
so it can't always store the full psbt in memory.

The signing process is documented at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt>

#### Parameters

*   `psbt` **PsbtV2**&#x20;

### Merkle

This class implements the merkle tree used by Ledger Bitcoin app v2+,
which is documented at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md>

#### Parameters

*   `leaves` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>**&#x20;
*   `hasher` **function (buf: [Buffer](https://nodejs.org/api/buffer.html)): [Buffer](https://nodejs.org/api/buffer.html)**  (optional, default `crypto.sha256`)

### MerkleMap

This implements "Merkelized Maps", documented at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps>

A merkelized map consist of two merkle trees, one for the keys of
a map and one for the values of the same map, thus the two merkle
trees have the same shape. The commitment is the number elements
in the map followed by the keys' merkle root followed by the
values' merkle root.

#### Parameters

*   `keys` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** Sorted list of (unhashed) keys
*   `values` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** values, in corresponding order as the keys, and of equal length

### WalletPolicy

The Bitcon hardware app uses a descriptors-like thing to describe
how to construct output scripts from keys. A "Wallet Policy" consists
of a "Descriptor Template" and a list of "keys". A key is basically
a serialized BIP32 extended public key with some added derivation path
information. This is documented at
<https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md>

#### Parameters

*   `descriptorTemplate` **DefaultDescriptorTemplate**&#x20;
*   `key` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;

### extract

This implements the "Transaction Extractor" role of BIP370 (PSBTv2
<https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor>). However
the role is partially documented in BIP174 (PSBTv0
<https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor>).

#### Parameters

*   `psbt` **PsbtV2**&#x20;

Returns **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

### finalize

This roughly implements the "input finalizer" role of BIP370 (PSBTv2
<https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki>). However
the role is documented in BIP174 (PSBTv0
<https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki>).

Verify that all inputs have a signature, and set inputFinalScriptwitness
and/or inputFinalScriptSig depending on the type of the spent outputs. Clean
fields that aren't useful anymore, partial signatures, redeem script and
derivation paths.

#### Parameters

*   `psbt` **PsbtV2** The psbt with all signatures added as partial sigs, either
    through PSBT\_IN\_PARTIAL\_SIG or PSBT\_IN\_TAP\_KEY\_SIG

Returns **void**&#x20;

### clearFinalizedInput

Deletes fields that are no longer neccesary from the psbt.

Note, the spec doesn't say anything about removing ouput fields
like PSBT\_OUT\_BIP32\_DERIVATION\_PATH and others, so we keep them
without actually knowing why. I think we should remove them too.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;

### writePush

Writes a script push operation to buf, which looks different
depending on the size of the data. See
<https://en.bitcoin.it/wiki/Script#Constants>

#### Parameters

*   `buf` **BufferWriter** the BufferWriter to write to
*   `data` **[Buffer](https://nodejs.org/api/buffer.html)** the Buffer to be pushed.

### serializeTransactionOutputs

#### Parameters

*   `$0` **[Transaction](#transaction)**&#x20;

    *   `$0.outputs` &#x20;

#### Examples

```javascript
const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000");
const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex');
```

Returns **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

### SignP2SHTransactionArg

Type: {inputs: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<\[[Transaction](#transaction), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))]>, associatedKeysets: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>, outputScriptHex: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), lockTime: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?, sigHashType: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?, segwit: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?, transactionVersion: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?}

#### Properties

*   `inputs` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<\[[Transaction](#transaction), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) | null | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))]>**&#x20;
*   `associatedKeysets` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>**&#x20;
*   `outputScriptHex` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;
*   `lockTime` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?**&#x20;
*   `sigHashType` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?**&#x20;
*   `segwit` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?**&#x20;
*   `transactionVersion` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?**&#x20;

### determineAccountType

Determines the account type based on detected script type, account path, or options.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `detectedScriptType` **([ScriptType](#scripttype) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))**&#x20;
*   `accountPath` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>**&#x20;
*   `addressFormat` **[AddressFormat](#addressformat)?**&#x20;

Returns **[AccountType](#accounttype)**&#x20;

### getDerivationAccessors

Returns accessors for BIP32 derivation operations based on element type.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `type` **[DerivationElementType](#derivationelementtype)**&#x20;

Returns **[DerivationAccessors](#derivationaccessors)**&#x20;

### checkElementBip32Derivation

Generic method to check BIP32 derivation for either an input or output.

#### Parameters

*   `accessors` **[DerivationAccessors](#derivationaccessors)**&#x20;
*   `elementIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

Returns **{belongsToSigner: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean), accountPath: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>}**&#x20;

### extractAccountPath

Returns belongsToSigner: true because this function is only called after
a master fingerprint match against the connected signer (hardware wallet).
This is unrelated to the BIP44 "internal chain" (change = 1) concept.

#### Parameters

*   `fullPath` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>**&#x20;

Returns **{belongsToSigner: `true`, accountPath: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>}**&#x20;

### checkOutputBip32Derivation

Checks if an output has a valid BIP32 derivation with the correct master fingerprint.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `outputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**&#x20;

### getScriptPubKeyFromNonWitnessUtxo

Extracts the scriptPubKey from a non-witness UTXO by parsing the previous transaction.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;

Returns **([Buffer](https://nodejs.org/api/buffer.html) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))**&#x20;

### getInputScriptPubKey

Extracts the scriptPubKey from an input's UTXO data.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;

Returns **([Buffer](https://nodejs.org/api/buffer.html) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))**&#x20;

### fixDerivationFingerprints

Generic method to fix BIP32 derivations with wrong master fingerprint.

#### Parameters

*   `client` **SignPsbtClient**&#x20;
*   `accessors` **[DerivationAccessors](#derivationaccessors)**&#x20;
*   `elementIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)>**&#x20;

### setElementBip32DerivationData

Generic method to set BIP32 derivation data on an input or output.

#### Parameters

*   `accessors` **[DerivationAccessors](#derivationaccessors)**&#x20;
*   `elementIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `pubkey` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `path` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>**&#x20;
*   `accountType` **[AccountType](#accounttype)**&#x20;

Returns **void**&#x20;

### populateMissingBip32Derivations

Populates missing BIP32 derivations using the provided known-address map.
The map must be built by the caller from the wallet's known addresses (e.g. receive/change).

#### Parameters

*   `client` **SignPsbtClient**&#x20;
*   `psbt` **PsbtV2**&#x20;
*   `inputCount` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `accountPath` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>**&#x20;
*   `knownAddressDerivations` **[Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), {pubkey: [Buffer](https://nodejs.org/api/buffer.html), path: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>}>**&#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<void>**&#x20;

### determineInputScriptType

Determines the script type for a single input from witness UTXO or redeem script.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;

Returns **([ScriptType](#scripttype) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))**&#x20;

### analyzeInput

Analyzes a single input to determine if it belongs to the connected signer and extracts account path and script type.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputIndex` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

Returns **{belongsToSigner: [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean), accountPath: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>, scriptType: ([ScriptType](#scripttype) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))}**&#x20;

### analyzeAllInputs

Analyzes all inputs and returns resolved account path, detected script type, and internal input indices.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `inputCount` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `accountPathOption` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?**&#x20;

Returns **{accountPath: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>, detectedScriptType: ([ScriptType](#scripttype) | [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined)), internalInputIndices: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>}**&#x20;

### deserializePsbt

Deserializes a raw PSBT buffer (v0 or v2) into a PsbtV2 instance.

#### Parameters

*   `psbtBuffer` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;

Returns **PsbtV2**&#x20;

### createWalletPolicy

Creates a WalletPolicy for the given account.

#### Parameters

*   `masterFp` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `accountPath` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>**&#x20;
*   `accountXpub` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**&#x20;
*   `accountType` **[AccountType](#accounttype)**&#x20;

Returns **[WalletPolicy](#walletpolicy)**&#x20;

### createProgressCallback

Creates a progress callback that notifies onDeviceStreaming and onDeviceSignatureGranted.

#### Parameters

*   `inputCount` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;
*   `options` **{onDeviceSignatureRequested: function (): void?, onDeviceSignatureGranted: function (): void?, onDeviceStreaming: function (arg: {progress: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), total: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), index: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}): void?}**&#x20;

Returns **function (): void**&#x20;

### finalizePsbtAndExtract

Optionally finalizes the PSBT and, when finalizing, extracts the transaction.
When not finalizing, only the serialized PSBT (with partial signatures) is
returned; extraction is not performed because FINAL\_SCRIPTWITNESS is not set.

#### Parameters

*   `psbt` **PsbtV2**&#x20;
*   `shouldFinalize` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**&#x20;

Returns **{psbt: [Buffer](https://nodejs.org/api/buffer.html), tx: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?}**&#x20;

### KnownAddressDerivationsMap

Map from scriptPubKey hash (hex) to derivation data.
Used to populate missing BIP32 derivations from the wallet's known addresses.

Type: [Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), {pubkey: [Buffer](https://nodejs.org/api/buffer.html), path: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>}>

### SignPsbtBufferOptions

Options for signPsbtBuffer. Used internally by signPsbt modules.

#### knownAddressDerivations

Map from scriptPubKey hash (hex) to { pubkey, path }. Built from wallet's known addresses.

Type: [KnownAddressDerivationsMap](#knownaddressderivationsmap)

### DerivationElementType

Discriminator for input vs output derivation handling.
Used to consolidate duplicate code for BIP32 derivation operations.

Type: (`"input"` | `"output"`)

### DerivationAccessors

Accessors for BIP32 derivation operations that abstract over inputs vs outputs.
This allows reusing the same derivation logic for both element types.

### ScriptType

Union type for supported Bitcoin script types.
Extends @ledgerhq/psbtv2 ScriptType with "p2sh-p2wpkh" (alias for derivation/signing).

Type: (Psbtv2ScriptType | `"p2sh-p2wpkh"`)

### splitSaplingPart

Splits the Sapling part of a Zcash v5 transaction buffer according to <https://zips.z.cash/zip-0225>

#### Parameters

*   `transaction` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `offset` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;

Returns **{sapling: [SaplingData](#saplingdata)?, offset: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}**&#x20;

### splitOrchardPart

Splits the Orchard part of a Zcash v5 transaction buffer according to <https://zips.z.cash/zip-0225>

#### Parameters

*   `transaction` **[Buffer](https://nodejs.org/api/buffer.html)**&#x20;
*   `offset` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)**&#x20;

Returns **{orchard: OrchardData?, offset: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)}**&#x20;

### TransactionInput

### TransactionOutput

### Transaction

### SaplingData
