Create a Taproot address, build a transaction spending one of its UTXOs, sign and finalize it:
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';const privKey = hex.decode('a1547d0a01c9acb2b8a4128f97bbcd74d9a5750a9a3d1571ee3d9840b41d1fbb');const pubKey = btc.utils.pubSchnorr(privKey);// Taproot payment for a single key. Also check out p2wpkh, p2sh, p2wsh & others belowconst spend = btc.p2tr(pubKey);console.log(spend.address);// bc1pkw4e67whvet7q6xa854tstt7kjn9f7n3gqvyjqznezqwux0gnzhsrtlvy3const tx = new btc.Transaction();tx.addInput({ ...spend, // adds tapInternalKey & other fields required for signing txid: '75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858', index: 0, witnessUtxo: { script: spend.script, amount: 100_000n }, // amounts are always bigint sats});tx.addOutputAddress(spend.address!, 90_000n); // leftover 10k sats become the feetx.sign(privKey);tx.finalize();console.log(tx.id);// 927bc3441c7b376a83913b534bf10430139d9f64d83cbc38eb3a4e24cce54dc5console.log(tx.hex); // ready to broadcast, e.g. via net.ts EsploraProvider
The rest of the docs cover every payment type, PSBT workflows, UTXO selection and more:
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('030000000000000000000000000000000000000000000000000000000000000001');deepStrictEqual(btc.p2wpkh(PubKey), { type: 'wpkh', address: 'bc1qz69ej270c3q9qvgt822t6pm3zdksk2x35j2jlm', script: hex.decode('0014168b992bcfc44050310b3a94bd0771136d0b28d1'), hash: hex.decode('168b992bcfc44050310b3a94bd0771136d0b28d1'),});// P2SH-P2WPKHdeepStrictEqual(btc.p2sh(btc.p2wpkh(PubKey)), { type: 'sh', address: '3BCuRViGCTXmQjyJ9zjeRUYrdZTUa38zjC', script: hex.decode('a91468602f2db7b7d7cdcd2639ab6bf7f5bfe828e53f87'), redeemScript: hex.decode('0014168b992bcfc44050310b3a94bd0771136d0b28d1'), hash: hex.decode('68602f2db7b7d7cdcd2639ab6bf7f5bfe828e53f'),});
P2SH (Script Hash)
Classic (pre-SegWit) script address. Useful for multisig and other advanced use-cases. Consumes full output of other payments — NOT only script.
Required tx input fields to make it spendable: redeemScript
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('030000000000000000000000000000000000000000000000000000000000000001');// Wrap P2PKH in P2SHdeepStrictEqual(btc.p2sh(btc.p2pkh(PubKey)), { type: 'sh', address: '3EPhLJ1FuR2noj6qrTs4YvepCvB6sbShoV', script: hex.decode('a9148b530b962725af3bb7c818f197c619db3f71495087'), redeemScript: hex.decode('76a914168b992bcfc44050310b3a94bd0771136d0b28d188ac'), hash: hex.decode('8b530b962725af3bb7c818f197c619db3f714950'),});
P2WSH (Witness Script Hash)
SegWit V0 version of P2SH.
In SegWit, signature is removed from tx hash calculation.
Required tx input fields to make it spendable: witnessScript
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('030000000000000000000000000000000000000000000000000000000000000001');deepStrictEqual(btc.p2wsh(btc.p2pkh(PubKey)), { type: 'wsh', address: 'bc1qhxtthndg70cthfasy8y4qlk9h7r3006azn9md0fad5dg9hh76nkqaufnuz', script: hex.decode('0020b996bbcda8f3f0bba7b021c9507ec5bf8717bf5d14cbb6bd3d6d1a82defed4ec'), witnessScript: hex.decode('76a914168b992bcfc44050310b3a94bd0771136d0b28d188ac'), hash: hex.decode('b996bbcda8f3f0bba7b021c9507ec5bf8717bf5d14cbb6bd3d6d1a82defed4ec'),});
P2SH-P2WSH
Not really script type, but construction of P2WSH inside P2SH.
Required tx input fields to make it spendable: redeemScript, witnessScript
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('030000000000000000000000000000000000000000000000000000000000000001');deepStrictEqual(btc.p2sh(btc.p2wsh(btc.p2pkh(PubKey))), { type: 'sh', address: '3EHxWHyLv5Seu5Cd6D1cH56jLKxSi3ps8C', script: hex.decode('a9148a3d36fb710a9c7cae06cfcdf39792ff5773e8f187'), redeemScript: hex.decode('0020b996bbcda8f3f0bba7b021c9507ec5bf8717bf5d14cbb6bd3d6d1a82defed4ec'), witnessScript: hex.decode('76a914168b992bcfc44050310b3a94bd0771136d0b28d188ac'), hash: hex.decode('8a3d36fb710a9c7cae06cfcdf39792ff5773e8f1'),});
P2MS (classic multisig)
Classic / segwit (pre-taproot) M-of-N Multisig. Doesn't have an address, must be wrapped in P2SH / P2WSH / P2SH-P2WSH.
Duplicate public keys are not accepted to reduce mistakes. Use flag allowSamePubkeys to override the behavior, for cases like 2-of-[A,A,B,C], which can be signed by A or (B and C).
TapRoot (SegWit V1) script which replaces both public key and script types from previous versions.
Consumes p2tr(PubKey?, ScriptTree?) and works as PubKey OR ScriptTree, which means
if you use any spendable PubKey and ScriptTree of multi-sig, owner of private key for PubKey will
be able to spend output. If PubKey is undefined we use static unspendable PubKey by default, which leaks information about script type. However, any dynamic unspendable keys will require complex interaction
to sign multi-sig wallets, and there is no BIP/PSBT fields for that yet.
Required tx input fields to make it spendable: tapInternalKey, tapMerkleRoot, tapLeafScript
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('0101010101010101010101010101010101010101010101010101010101010101');// Key Path Spend (owned of private key for PubKey can spend)deepStrictEqual(btc.p2tr(PubKey), { type: 'tr', address: 'bc1p7yu5dsly83jg5tkxcljsa30vnpdpl22wr6rty98t6x6p6ekz2gkqzf2t2s', script: hex.decode('5120f13946c3e43c648a2ec6c7e50ec5ec985a1fa94e1e86b214ebd1b41d66c2522c'), tweakedPubkey: hex.decode('f13946c3e43c648a2ec6c7e50ec5ec985a1fa94e1e86b214ebd1b41d66c2522c'), tapInternalKey: hex.decode('0101010101010101010101010101010101010101010101010101010101010101'),});const clean = (x) => ({ type: x.type, address: x.address, script: hex.encode(x.script) });const PubKey2 = hex.decode('0202020202020202020202020202020202020202020202020202020202020202');const PubKey3 = hex.decode('1212121212121212121212121212121212121212121212121212121212121212');// Nested P2TR, owner of private key for any of PubKeys can spend whole// By default P2TR expects binary tree, but btc.p2tr can build it if list of scripts passed.// Also, you can include {weight: N} to scripts to create differently balanced tree.deepStrictEqual( clean(btc.p2tr(undefined, [btc.p2tr_pk(PubKey), btc.p2tr_pk(PubKey2), btc.p2tr_pk(PubKey3)])), { type: 'tr', // weights for bitcoinjs-lib: [3,2,1] address: 'bc1pj2uvajyygyu2zw0rg0d6yxdsc920kzc5pamfgtlqepe30za922cqjjmkta', script: '512092b8cec8844138a139e343dba219b0c154fb0b140f76942fe0c873178ba552b0', });// If scriptsTree is already binary tree, it will be used as-isdeepStrictEqual( clean(btc.p2tr(undefined, [btc.p2tr_pk(PubKey2), [btc.p2tr_pk(PubKey), btc.p2tr_pk(PubKey3)]])), { type: 'tr', // default weights for bitcoinjs-lib address: 'bc1pvue6sk9efyvcvpzzqkg8at4qy2u67zj7rj5sfsy573m7alxavqjqucc26a', script: '51206733a858b9491986044205907eaea022b9af0a5e1ca904c094f477eefcdd6024', });
First arg is M, if M!=PubKeys.length, it will create a multi-leaf M-of-N taproot script tree.
This allows one to reveal only M PubKeys on spend, without any information about the others.
This is fast for cases like 15-of-20, but extremely slow for cases like 5-of-20.
Duplicate public keys are not accepted to reduce mistakes. Use flag allowSamePubkeys to override the behavior, for cases like 2-of-[A,A,B,C], which can be signed by A or (B and C).
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('0101010101010101010101010101010101010101010101010101010101010101');const PubKey2 = hex.decode('0202020202020202020202020202020202020202020202020202020202020202');const PubKey3 = hex.decode('1212121212121212121212121212121212121212121212121212121212121212');// Simple 3-of-3 multisig// Creates a single script that requires all three pubkeys: [PubKey, PubKey2, PubKey3]deepStrictEqual(btc.p2tr_ns(3, [PubKey, PubKey2, PubKey3]), [ { type: 'tr_ns', script: hex.decode( '200101010101010101010101010101010101010101010101010101010101010101ad200202020202020202020202020202020202020202020202020202020202020202ad201212121212121212121212121212121212121212121212121212121212121212ac' ), },]);// Simple 2-of-3 multisig// If M (pubkeys required) is less than N (# of pubkeys), then multiple scripts are created: [[PubKey, PubKey2], [PubKey, PubKey3], [PubKey2, PubKey3]]const clean = (x) => ({ type: x.type, address: x.address, script: hex.encode(x.script) });deepStrictEqual(clean(btc.p2tr(undefined, btc.p2tr_ns(2, [PubKey, PubKey2, PubKey3]))), { type: 'tr', address: 'bc1pevfcmnkqqq09a4n0fs8c7mwlc6r4efqpvgyqpjvegllavgw235fq3kz7a0', script: '5120cb138dcec0001e5ed66f4c0f8f6ddfc6875ca401620800c99947ffd621ca8d12',});
Duplicate public keys are not accepted to reduce mistakes. Use flag allowSamePubkeys to override the behavior, for cases like 2-of-[A,A,B,C], which can be signed by A or (B and C).
Experimental, use at your own risk.
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('0101010101010101010101010101010101010101010101010101010101010101');const PubKey2 = hex.decode('0202020202020202020202020202020202020202020202020202020202020202');const PubKey3 = hex.decode('1212121212121212121212121212121212121212121212121212121212121212');// 2-of-3 TapRoot multisigdeepStrictEqual(btc.p2tr_ms(2, [PubKey, PubKey2, PubKey3]), { type: 'tr_ms', script: hex.decode( '200101010101010101010101010101010101010101010101010101010101010101ac200202020202020202020202020202020202020202020202020202020202020202ba201212121212121212121212121212121212121212121212121212121212121212ba529c' ),});// Creates a single script for [PubKey, PubKey2, PubKey3]const clean = (x) => ({ type: x.type, address: x.address, script: hex.encode(x.script) });deepStrictEqual(clean(btc.p2tr(undefined, btc.p2tr_ms(2, [PubKey, PubKey2, PubKey3]))), { type: 'tr', address: 'bc1p6m2xevckax9zucumnnyvu4xhxem66ugc5r2zlw2a20s0hxnutl8qfef23s', script: '5120d6d46cb316e98a2e639b9cc8ce54d73677ad7118a0d42fb95d53e0fb9a7c5fce',});
P2TR-PK (Taproot single P2PK script)
Specific case of p2tr_ns(1, [pubkey]), which is the same as the BTC descriptor: tr($H,pk(PUBKEY))
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const PubKey = hex.decode('0101010101010101010101010101010101010101010101010101010101010101');// P2PK for taprootconst clean = (x) => ({ type: x.type, address: x.address, script: hex.encode(x.script) });deepStrictEqual(clean(btc.p2tr(undefined, [btc.p2tr_pk(PubKey)])), { type: 'tr', address: 'bc1pfj6w68w3v2f4pkzesc9tsqfvy5znw5qgydwa832v3v83vjn76kdsmr4360', script: '51204cb4ed1dd1629350d859860ab8012c2505375008235dd3c54c8b0f164a7ed59b',});
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { deepStrictEqual } from 'node:assert';const p2aScript = hex.decode('51024e73');const decoded = btc.OutScript.decode(p2aScript);deepStrictEqual(decoded, { type: 'p2a', script: p2aScript });deepStrictEqual(hex.encode(btc.OutScript.encode(decoded)), '51024e73');
Transaction
Encode/decode
We support both PSBTv0 and PSBTv2 (there is no PSBTv1). Explicit PSBTv0 conversion removes
PSBTv2-only fields after translating the unsigned transaction representation.
Assigned fields from BIPs 322, 353, 372, 373, 375, and 376 are decoded explicitly and survive the
default path. TxOpts.unknown and TxOpts.proprietary govern only genuinely unknown and
proprietary records:
ignore preserves them, but the library may operate without understanding future constraints.
strip accepts and removes them; this is the default and can break interoperability with future
extensions.
strict rejects them.
Undefined bits in PSBTv2 txModifiable follow the unknown policy. strip and strict can also
fingerprint this library or version, while ignore offers better forwarding compatibility at the
cost of interpreting less protocol state. The deprecated allowUnknown boolean maps true to
ignore and false to strip.
When signing an untrusted or multi-party PSBT, pass
{ strictPrevoutValidation: true } to Transaction.fromPSBT. This requires every input to include
a full nonWitnessUtxo matching its outpoint before any signature is produced. It prevents forged
witnessUtxo amounts from making the displayed transaction fee appear lower than the fee that the
valid transaction will actually pay.
// DecodeTransaction.fromRaw(raw: Bytes, opts: TxOpts = {}); // Raw txTransaction.fromPSBT(psbt: Bytes, opts: TxOpts = {}); // PSBT tx// Encodetx.unsignedTx; // Bytes of raw unsigned txtx.hex; // hex encoded signed raw txtx.toPSBT(ver = this.PSBTVersion); // PSBT
Inputs
We have txid (BE) instead of hash (LE) in transactions. We can support both,
but txid is consistent across block explorers, while some explorers treat hash
as txid - so hash is not consistent.
Use getInput and inputsLength to read information about inputs: they return a copy.
This is necessary to avoid accidental modification of internal structures without calling methods (addInput/updateInput) that will verify correctness.
addOutputAddress uses bigint amounts, which means satoshis, not BTC. If you need BTC representation, use Decimal:
import * as btc from '@scure/btc-signer';const amountSatoshi = btc.Decimal.decode('1.5'); // 1.5 btc in satoshi
Use getOutput and outputsLength to read outputs information. This methods returns copy of output, instead of internal representation.
This is necessary to avoid accidental modification of internal structures without calling methods (addOutput/updateOutput) that will verify correctness.
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import * as bip32 from '@scure/bip32';import { deepStrictEqual } from 'node:assert';const testnet = { wif: 0xef, bip32: { public: 0x043587cf, private: 0x04358394, },};// The private keys in the tests below are derived from the following master private key:const epriv = 'tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF';const hdkey = bip32.HDKey.fromExtendedKey(epriv, testnet.bip32);// const seed = 'cUkG8i1RFfWGWy5ziR11zJ5V4U4W3viSFCfyJmZnvQaUsd1xuF3T';const tx = new btc.Transaction();// A creator creating a PSBT for a transaction which creates the following outputs:tx.addOutput({ script: '0014d85c2b71d0060b09c9886aeb815e50991dda124d', amount: btc.Decimal.decode('1.49990000'),});tx.addOutput({ script: '001400aea9a2e5f0f876a588df5546e8742d1d87008f', amount: btc.Decimal.decode('1.00000000'),});// and spends the following inputs:tx.addInput({ txid: '75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858', index: 0,});tx.addInput({ txid: '1dea7cd05979072a3578cab271c02244ea8a090bbb46aa680a65ecd027048d83', index: 1,});// must create this PSBT:const psbt1 = tx.toPSBT();// Given the above PSBT, an updater with only the following:const tx2 = btc.Transaction.fromPSBT(psbt1);tx2.updateInput(0, { nonWitnessUtxo: '0200000001aad73931018bd25f84ae400b68848be09db706eac2ac18298babee71ab656f8b0000000048473044022058f6fc7c6a33e1b31548d481c826c015bd30135aad42cd67790dab66d2ad243b02204a1ced2604c6735b6393e5b41691dd78b00f0c5942fb9f751856faa938157dba01feffffff0280f0fa020000000017a9140fb9463421696b82c833af241c78c17ddbde493487d0f20a270100000017a91429ca74f8a08f81999428185c97b5d852e4063f618765000000', redeemScript: '5221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae', bip32Derivation: [ [ '029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f', { fingerprint: hdkey.fingerprint, path: btc.bip32Path("m/0'/0'/0'") }, ], [ '02dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d7', { fingerprint: hdkey.fingerprint, path: btc.bip32Path("m/0'/0'/1'") }, ], ],});tx2.updateInput(1, { // use witness utxo ({script, amount}) witnessUtxo: btc.RawTx.decode( hex.decode( '0200000000010158e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd7501000000171600145f275f436b09a8cc9a2eb2a2f528485c68a56323feffffff02d8231f1b0100000017a914aed962d6654f9a2b36608eb9d64d2b260db4f1118700c2eb0b0000000017a914b7f5faf40e3d40a5a459b1db3535f2b72fa921e88702483045022100a22edcc6e5bc511af4cc4ae0de0fcd75c7e04d8c1c3a8aa9d820ed4b967384ec02200642963597b9b1bc22c75e9f3e117284a962188bf5e8a74c895089046a20ad770121035509a48eb623e10aace8bfd0212fdb8a8e5af3c94b0b133b95e114cab89e4f7965000000' ) ).outputs[1], redeemScript: '00208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903', witnessScript: '522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae', bip32Derivation: [ [ '03089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc', { fingerprint: hdkey.fingerprint, path: btc.bip32Path("m/0'/0'/2'") }, ], [ '023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e73', { fingerprint: hdkey.fingerprint, path: btc.bip32Path("m/0'/0'/3'") }, ], ],});tx2.updateOutput(0, { bip32Derivation: [ [ '03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca58771', { fingerprint: hdkey.fingerprint, path: btc.bip32Path("m/0'/0'/4'") }, ], ],});tx2.updateOutput(1, { bip32Derivation: [ [ '027f6399757d2eff55a136ad02c684b1838b6556e5f1b6b34282a94b6b50051096', { fingerprint: hdkey.fingerprint, path: btc.bip32Path("m/0'/0'/5'") }, ], ],});// Must create this PSBT:const psbt2 = tx2.toPSBT();// An updater which adds SIGHASH_ALL to the above PSBT must create this PSBT:const tx3 = btc.Transaction.fromPSBT(psbt2);for (let i = 0; i < tx3.inputs.length; i++) tx3.updateInput(i, { sighashType: btc.SigHash.ALL });const psbt3 = tx3.toPSBT();/* Given the above updated PSBT, a signer that supports SIGHASH_ALL for P2PKH and P2WPKH spends and uses RFC6979 for nonce generation and has the following keys: - cP53pDbR5WtAD8dYAW9hhTjuvvTVaEiQBdrz9XPrgLBeRFiyCbQr (m/0'/0'/0') - cR6SXDoyfQrcp4piaiHE97Rsgta9mNhGTen9XeonVgwsh4iSgw6d (m/0'/0'/2')*/// We don't use HDKey, because it will everything because of bip32 derivationconst tx4 = btc.Transaction.fromPSBT(psbt3);tx4.sign(btc.WIF(testnet).decode('cP53pDbR5WtAD8dYAW9hhTjuvvTVaEiQBdrz9XPrgLBeRFiyCbQr'));tx4.sign(btc.WIF(testnet).decode('cR6SXDoyfQrcp4piaiHE97Rsgta9mNhGTen9XeonVgwsh4iSgw6d'));// must create this PSBT:const psbt4 = tx4.toPSBT();// Given the above updated PSBT, a signer with the following keys:// cT7J9YpCwY3AVRFSjN6ukeEeWY6mhpbJPxRaDaP5QTdygQRxP9Au (m/0'/0'/1')// cNBc3SWUip9PPm1GjRoLEJT6T41iNzCYtD7qro84FMnM5zEqeJsE (m/0'/0'/3')const tx5 = btc.Transaction.fromPSBT(psbt3);tx5.sign(btc.WIF(testnet).decode('cT7J9YpCwY3AVRFSjN6ukeEeWY6mhpbJPxRaDaP5QTdygQRxP9Au'));tx5.sign(btc.WIF(testnet).decode('cNBc3SWUip9PPm1GjRoLEJT6T41iNzCYtD7qro84FMnM5zEqeJsE'));// must create this PSBT:const psbt5 = tx5.toPSBT();// Given both of the above PSBTs, a combiner must create this PSBT:const psbt6 = btc.PSBTCombine([psbt4, psbt5]);// Given the above PSBT, an input finalizer must create this PSBT:const tx7 = btc.Transaction.fromPSBT(psbt6);tx7.finalize();const psbt7 = tx7.toPSBT();// Given the above PSBT, a transaction extractor must create this Bitcoin transaction:const tx8 = btc.Transaction.fromPSBT(psbt7);deepStrictEqual( tx8.extract(), hex.decode( '0200000000010258e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd7500000000da00473044022074018ad4180097b873323c0015720b3684cc8123891048e7dbcd9b55ad679c99022073d369b740e3eb53dcefa33823c8070514ca55a7dd9544f157c167913261118c01483045022100f61038b308dc1da865a34852746f015772934208c6d24454393cd99bdf2217770220056e675a675a6d0a02b85b14e5e29074d8a25a9b5760bea2816f661910a006ea01475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752aeffffffff838d0427d0ec650a68aa46bb0b098aea4422c071b2ca78352a077959d07cea1d01000000232200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903ffffffff0270aaf00800000000160014d85c2b71d0060b09c9886aeb815e50991dda124d00e1f5050000000016001400aea9a2e5f0f876a588df5546e8742d1d87008f000400473044022062eb7a556107a7c73f45ac4ab5a1dddf6f7075fb1275969a7f383efff784bcb202200c05dbb7470dbf2f08557dd356c7325c1ed30913e996cd3840945db12228da5f01473044022065f45ba5998b59a27ffe1a7bed016af1f1f90d54b3aa8f7450aa5f56a25103bd02207f724703ad1edb96680b284b56d4ffcb88f7fb759eabbe08aa30f29b851383d20147522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae00000000' ));
UTXO selection
UTXO selection is the process of choosing which UTXOs to use as inputs
when making an on-chain bitcoin payment. The library:
can create tx, integrated with the signer
ensures change address is always specified
supports bip69
supports segwit + taproot
calculates weight with good precision
implements multiple strategies
Taproot estimation is precise, but you have to pass sighashType when using a non-default
sighash because it changes signature size. A Taproot input can advertise paths that the current
wallet cannot spend. Pass the wallet's x-only public keys as filterTaproot to remove unavailable
internal-key and script paths before selection:
Filtering is opt-in: when filterTaproot is omitted, no paths are removed. The standalone
btc.filterTaproot(utxos, [myPublicKey]) utility returns the same filtered candidate records.
Built-in tr_ns and tr_ms paths are checked directly. Custom or unknown leaves are rejected;
callers must filter those paths using their own semantics before invoking this helper. Estimation
and finalization choose the available path with the smallest complete witness, retaining the old
shallowest-path order for equal weights.
Oldest / Newest expects UTXO provided in historical order (oldest first),
otherwise we have no way to detect age of tx.
Strategies
Strategy selection is complicated. Best should be: exactBiggest/accumSmallest.
exactBiggest/accumBiggest creates tx with smallest fees,
but it breaks big outputs to small ones, which in the end will create
a lot of outputs close to dust.
default: good for privacy, same as exactBiggest/accumBiggest
all: send all coins to change address (consolidation)
accum: accumulates inputs until the target value (+fees) is reached, skipping detrimental inputs
exact: accumulates inputs until the target value (+fees) is matched, does not accumulate inputs
that go over the target value (within a threshold)
accumNewest
accumOldest
accumSmallest
accumBiggest
exactNewest/accumNewest
exactNewest/accumOldest
exactNewest/accumSmallest
exactNewest/accumBiggest
exactOldest/accumNewest
exactOldest/accumOldest
exactOldest/accumSmallest
exactOldest/accumBiggest
exactSmallest/accumNewest
exactSmallest/accumOldest
exactSmallest/accumSmallest
exactSmallest/accumBiggest
exactBiggest/accumNewest
exactBiggest/accumOldest
exactBiggest/accumSmallest
exactBiggest/accumBiggest
Example
import * as btc from '@scure/btc-signer';import { hex } from '@scure/base';import { pubECDSA } from '@scure/btc-signer/utils.js';import { deepStrictEqual } from 'node:assert';const privKey = hex.decode('0101010101010101010101010101010101010101010101010101010101010101');const pubKey = pubECDSA(privKey);const regtest = { bech32: 'bcrt', pubKeyHash: 0x6f, scriptHash: 0xc4 };const spend = btc.p2wpkh(pubKey, regtest);const utxo = [ { ...spend, // add witness/redeem scripts from spend // Get txid, index from explorer/network txid: hex.decode('0af50a00a22f74ece24c12cd667c290d3a35d48124a69f4082700589172a3aa2'), index: 0, // utxo tx information // script can be used from spend itself or from explorer witnessUtxo: { script: spend.script, amount: 100_000n }, // value in satoshi }, { ...spend, txid: hex.decode('0af50a00a22f74ece24c12cd667c290d3a35d48124a69f4082700589172a3aa2'), index: 1, witnessUtxo: { script: spend.script, amount: btc.Decimal.decode('1.5') }, // value in btc }, // { // ...spend, // txid: hex.decode('75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858'), // index: 0, // // tx hex from blockchain (required for non-SegWit UTXO) // nonWitnessUtxo: hex.decode( // '0200000001aad73931018bd25f84ae400b68848be09db706eac2ac18298babee71ab656f8b0000000048473044022058f6fc7c6a33e1b31548d481c826c015bd30135aad42cd67790dab66d2ad243b02204a1ced2604c6735b6393e5b41691dd78b00f0c5942fb9f751856faa938157dba01feffffff0280f0fa020000000017a9140fb9463421696b82c833af241c78c17ddbde493487d0f20a270100000017a91429ca74f8a08f81999428185c97b5d852e4063f618765000000' // ), // },];const outputs = [ { address: '2MvpbAgedBzJUBZWesDwdM7p3FEkBEwq3n3', amount: 50_000n }, // amount in satoshi { address: 'bcrt1pw53jtgez0wf69n06fchp0ctk48620zdscnrj8heh86wykp9mv20q7vd3gm', amount: btc.Decimal.decode('0.5'), // amount in btc },];// Send all utxo to specific address (consolidation):// const selected = btc.selectUTXO(utxo, [], 'all', {// changeAddress: 'bcrt1pea3850rzre54e53eh7suwmrwc66un6nmu9npd7eqrhd6g4lh8uqsxcxln8', ...const selected = btc.selectUTXO(utxo, outputs, 'default', { changeAddress: 'bcrt1pea3850rzre54e53eh7suwmrwc66un6nmu9npd7eqrhd6g4lh8uqsxcxln8', // required, address to send change feePerByte: 2n, // require, fee per vbyte in satoshi bip69: true, // lexicographical Indexing of Transaction Inputs and Outputs createTx: true, // create tx with selected inputs/outputs network: regtest,});// selectUTXO returns undefined if there is not enough funds.if (!selected) throw new Error('expected enough funds');deepStrictEqual(selected.fee, 394n); // estimated feedeepStrictEqual(selected.change, true); // change address useddeepStrictEqual(selected.outputs, [ { address: '2MvpbAgedBzJUBZWesDwdM7p3FEkBEwq3n3', amount: 50000n }, { address: 'bcrt1pw53jtgez0wf69n06fchp0ctk48620zdscnrj8heh86wykp9mv20q7vd3gm', amount: 50_000_000n, }, // Change address // NOTE: with bip69 it is not necessarily last item in outputs { address: 'bcrt1pea3850rzre54e53eh7suwmrwc66un6nmu9npd7eqrhd6g4lh8uqsxcxln8', amount: 99_949_606n, },]);// No need to create tx manually!const { tx } = selected;tx.sign(privKey);tx.finalize();deepStrictEqual(tx.id, 'b702078d65edd65a84b2a97a669df5631b06f42a67b0d7090e540b02cc65aed5');// real tx fee, can be bigger than estimated, since we expect signatures of maximal sizedeepStrictEqual(tx.fee, 394n);
Network
Bitcoin nodes can't be used as source-of-truth to construct transactions & get UTXOs.
An extra indexer is required. Our net.js submodule allows to easily fetch UTXOs,
balances, and other data for an address.
See README-fullnode.md for details and
guide on running a full node with an indexer.
import * as btc from '@scure/btc-signer';import { EsploraProvider } from '@scure/btc-signer/net.js';import { pubECDSA } from '@scure/btc-signer/utils.js';const net = new EsploraProvider(fetch, 'http://127.0.0.1:3000');// Methods: `height`, `blockInfo`, `fee`, `balance`, `txCount`, `sendTx`, `waitForTx`, `txInfo`,// `unspent`, `transfers`, `history`, `historyMulti`.// Transient backend failures (429/5xx, dropped connections) are retried with backoff on GETs.// Long scans accept `signal` (AbortSignal) and `onProgress`; raw-tx fan-out is// bounded by `concurrency` (default 8).// Get latest block.async function latestBlock() { const height = await net.height(); const block = await net.blockInfo(height); return { number: block.number, hash: block.hash, timestamp: new Date(block.timestamp) };}// Get per-address transaction history.async function addressTransactions(address: string) { const txs = await net.transfers(address, { limit: 10 }); return txs.map((tx) => ({ txid: tx.txid, block: tx.block, fee: tx.info.fee }));}// Stream history instead of buffering it: rows arrive newest-first while pages// are fetched, and stopping early also stops fetching.async function streamHistory(address: string) { for await (const tx of net.history(address, { onProgress: (p) => console.log(p.percent) })) { if (tx.block !== undefined && tx.block < 800_000) break; console.log(tx.txid, tx.transfers); }}// Merged history for a set of addresses (HD wallets): one txid-deduplicated// stream; each row lists the watched addresses participating in it.async function walletHistory(addresses: string[]) { for await (const tx of net.historyMulti(addresses)) console.log(tx.txid, tx.addresses);}// Broadcast, then wait for confirmation.async function sendAndWait(rawTx: string) { const txid = await net.sendTx(rawTx); return await net.waitForTx(txid, { confirmations: 2, timeoutMs: 3_600_000 });}// Get UTXOs, select inputs, and sign. Call with a key that controls funded UTXOs.async function signSpend(privKey: Uint8Array, to: string, amount: bigint) { const spend = btc.p2wpkh(pubECDSA(privKey)); const unspent = await net.unspent(spend.address!); const feePerByte = await net.fee(2); const selected = btc.selectUTXO(unspent.utxo, [{ address: to, amount }], 'default', { feePerByte, changeAddress: spend.address!, }); if (!selected) throw new Error(`not enough funds for ${spend.address}`); const { tx } = selected; tx.sign(privKey); tx.finalize(); return { txid: tx.id, raw: tx.hex };}// For wrapped or script spends, add caller-owned metadata before selection:// const wrapped = btc.p2sh(btc.p2wpkh(pubECDSA(privKey)));// const base = await net.unspent(wrapped.address!);// const utxo = base.utxo.map((u) => ({ ...u, redeemScript: wrapped.redeemScript }));// const selected = btc.selectUTXO(utxo, outputs, 'default', opts);
First argument is fetch API-compatible transport.
We suggest using micro-ftch package - a wrapper, which supports kill-switch,
logging, timeouts, concurrency limits, replay fixtures, and other useful network controls:
import { ftch } from 'micro-ftch';let NETWORK_ENABLED = true;const fetcher = ftch(fetch, { isValidRequest: () => NETWORK_ENABLED, timeout: 10_000, concurrencyLimit: 4,});const net = new EsploraProvider(fetcher, 'http://127.0.0.1:3000');
MuSig2
MuSig2 implementation conforming to BIP-327
is available in @scure/btc-signer/musig2.js. Check out bip327-musig2.test.ts as well:
Security warning: every MuSig2 secret nonce must be used for exactly one partial signature.
Session.sign() zeroes only the exact Uint8Array passed to it; clones, serialized values,
database records, and process snapshots remain live. Reusing the same nonce in distinct sessions
can reveal the signer's secret key. Stateful signers must keep one authoritative nonce record and
atomically consume it before releasing a partial signature.
npm install @noble/curves
import * as btc from '@scure/btc-signer';import * as musig2 from '@scure/btc-signer/musig2.js';import { schnorr } from '@noble/curves/secp256k1.js';import { deepStrictEqual } from 'node:assert';// MuSig2 Multi-signature for Alice, Bob, and Carol// 1. Key Generation (for each signer: Alice, Bob, Carol)// - Alice's key generationconst aliceSecretKey = btc.utils.randomPrivateKeyBytes(); // Alice generates a random 32-byte secret keyconst alicePublicKey = musig2.IndividualPubkey(aliceSecretKey); // Alice derives her individual public key from her secret key// - Bob's key generationconst bobSecretKey = btc.utils.randomPrivateKeyBytes(); // Bob generates a random 32-byte secret keyconst bobPublicKey = musig2.IndividualPubkey(bobSecretKey); // Bob derives his individual public key from his secret key// - Carol's key generationconst carolSecretKey = btc.utils.randomPrivateKeyBytes(); // Carol generates a random 32-byte secret keyconst carolPublicKey = musig2.IndividualPubkey(carolSecretKey); // Carol derives her individual public key from her secret key// 2. Key Aggregation (All signers participate by sharing public keys)const individualPublicKeys = [alicePublicKey, bobPublicKey, carolPublicKey]; // Collect all individual public keysconst sortedPublicKeys = musig2.sortKeys(individualPublicKeys); // Sort public keys lexicographically (as required by MuSig2)const aggregatePublicKey = musig2.keyAggExport(musig2.keyAggregate(sortedPublicKeys)); // Extract the X-only aggregate public key (32 bytes)// At this point, all signers have the 'aggregatePublicKey' and 'keyAggContext'.// 3. Nonce Generation - Round 1 (Each signer generates and broadcasts public nonce)const msg = new Uint8Array(32).fill(5); // Example message to be signed (32-byte message is recommended for BIP340)// Alice generates her nonceconst aliceNonces = musig2.nonceGen(alicePublicKey, aliceSecretKey, aggregatePublicKey, msg);// Secret nonce: must be kept secret and used only once per signing session!// Public nonce: to be shared with Bob and Carol// Bob generates his nonceconst bobNonces = musig2.nonceGen(bobPublicKey, bobSecretKey, aggregatePublicKey, msg);// Carol generates her nonceconst carolNonces = musig2.nonceGen(carolPublicKey, carolSecretKey, aggregatePublicKey, msg);// Each signer creates own instanceconst session = new musig2.Session( // 4. Nonce Aggregation (All signers participate by sharing public nonces) musig2.nonceAggregate([aliceNonces.public, bobNonces.public, carolNonces.public]), sortedPublicKeys, msg);// At this point, all signers have the 'aggregateNonce'.// 5. Partial Signature Generation - Round 2 (Each signer generates partial signature)// Alice generates her partial signatureconst alicePartialSignature = session.sign(aliceNonces.secret, aliceSecretKey);// Bob generates his partial signatureconst bobPartialSignature = session.sign(bobNonces.secret, bobSecretKey);// Carol generates her partial signatureconst carolPartialSignature = session.sign(carolNonces.secret, carolSecretKey);// 6. Partial Signature Aggregation (Anyone can aggregate partial signatures)const partialSignatures = [alicePartialSignature, bobPartialSignature, carolPartialSignature]; // Collect all partial signaturesconst finalSignature = session.partialSigAgg(partialSignatures); // Aggregate partial signatures to create the final signature// 7. Signature Verification (Anyone can verify the final signature)deepStrictEqual(schnorr.verify(finalSignature, msg, aggregatePublicKey), true);
Ordinals and custom scripts
We support custom scripts. You can pass it as last argument to p2tr.
We've developed separate micro-ordinals package, which contains:
Real code for ordinals / inscriptions / runes
CLI tool that allows to upload files as inscriptions
Example usage of custom scripts
P2P, ElligatorSwift, BIP324
Experimental implementation of ElligatorSwift from BIP324
is available.
ElligatorSwift is Schnorr-like x-only ECDH with public keys indistinguishable from uniformly random bytes.
Bitcoin is more complex than ETH / SOL despite having less features:
Legacy: too much decade-old code / standards
Overengineering: features were designed to be extensible and future-proof; then abandoned when future arrived.
Transaction has version field, which is nice, allowing to change format later, however when there
was first change (SegWit V0), instead of using different tx version, there was hack with zero-inputs prefix
(tx cannot have zero inputs, so inputsCount=0 + '01' flag after that for tx version with witness data).
Probably it was done so it won't interfere with different transaction versions of different coins.
However, there is also txVersion=2 (BIP68) which changes lockTime behaviour, but not tx format.
There is bech32/witness program addresses, which is very extensible. By default rules software should
support future versions (0..16), so there will be no change in libraries to support new addresses.
However, even after first update (version 0 to 1) format of addresses itself changed from bech32 to bech32m,
so whole mechanic of different address versions is already unused. Also, supporting future version
of addresses is cool, but they are currently unspendable and we cannot know rules for spending new version address,
which means any new version address created now will be unspendable in future (SegWitV0->SegWitV1(taproot) even
changes public key format). So we cannot use this whole mechanic of future addresses at all (or users can accidentally create unspendable address and lose coins).
PSBT supports unknown fields, according to spec we need to pass them as is, without modifications.
It was probably done this way to be future-proof: new version of PSBT can be parsed with old parser, which will ignore new fields. However, when future came (PSBTv2), format significantly changed (no global.unsignedTx) anyway.
Bad BIP specs: likely because there is only one relevant BTC Core implementation.
To implement something, specs are not enough: need to read source code of Core (which is very complex, especially functional tests which re-implement parts in python) and other bitcoin libraries (such as bitcoinjs-lib)
No one cares about specs much: for example, in BIP174,
despite being old 2017 spec, formatting issues still haven't been fixed: m/0'/0'/0'
BIP174 multisig example has unsorted partialSig field
inside input (it's better to sort it)
Many PSBT tests are in format of valid/invalid (especially for PSBTv2), which isn't very helpful.
Parser which produces garbage, but doesn't throw exception, is still broken.
Major flaws in PSBT:
PSBT was designed to be opaque key-value store. Combiner only needed to merge dictories, without a need to understand
fields. However, parsing requires to understand unsignedTx, since there is no input/output count in format itself.
Instead of global, inputCount, inputs[], outputCount, outputs[], inputCount and outputCount are stored inside
global.unsignedTx (v0) or global.inputCount/global.outputCount (v2), which means in order to parse
basic structure we need to completely parse global KV and understand its fields.
Security issue: Unknown PSBT fields can be used to pass some code to backdoored wallets while being ignore by others.
In JS, it is even harder to implement properly, because JS doesn't support complex keys in objects / dicts.
There is whole controlBlock of taproot in key inside tapLeafScript, which we need to parse, leading to structure like:
{key: {version, internalKey, merklePath}, value: {script, version}.
But, since there is no support for complex keys, we cannot do correct by construction using js objects,
we need to do this dict as array and constantly check if keys are unique.
Security
The library has been independently audited:
at version 2.2.0, in Apr 2026, by ourselves (self-audited)