BitcoinJS Lib

7.0.1 · active · verified Sun Apr 19

bitcoinjs-lib is a foundational JavaScript library for interacting with the Bitcoin protocol in both Node.js and browser environments. Written in TypeScript, it provides essential functionalities for creating and manipulating Bitcoin transactions, managing addresses, and working with various script types. The current stable version is 7.0.1. The project follows a release cadence where only tagged releases are considered stable, with the `master` branch serving as the unstable development branch. Key differentiators include its strong emphasis on security through auditability and extensive testing (over 95% test coverage), its modular design (e.g., separating key management into `ecpair` and `bip32` packages to reduce bundle size), and its commitment to open standards and a helpful community. It does not handle key derivation itself, offloading this to specialized, smaller libraries.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a P2WPKH (SegWit) address and construct/sign a basic Partially Signed Bitcoin Transaction (PSBT) using `bitcoinjs-lib` along with the external `ecpair` and an ECC curve library.

import * as ecc from '@noble/secp256k1'; // Or 'tiny-secp256k1'
import * as ECPairFactory from 'ecpair';
import { Psbt, payments, networks } from 'bitcoinjs-lib';

// 1. Initialize ECPair with an ECC library (required since v6)
const ECPair = ECPairFactory.ECPairFactory(ecc);

// 2. Generate a key pair for a new P2WPKH (SegWit) address
const keyPair = ECPair.makeRandom({ network: networks.testnet });
const { address } = payments.p2wpkh({ pubkey: keyPair.publicKey, network: networks.testnet });

console.log('New SegWit Testnet Address:', address);
console.log('WIF (WARNING: DO NOT SHARE OR USE IN PRODUCTION):', keyPair.toWIF());

// 3. Create a Partially Signed Bitcoin Transaction (PSBT)
// This is a simplified example; real PSBTs require fetching actual UTXO details.
const psbt = new Psbt({ network: networks.testnet })
  .addInput({
    hash: '8f72289c02d75a8a113333333333333333333333333333333333333333333333', // Dummy TX ID
    index: 0,
    // For P2WPKH, witnessUtxo is required
    witnessUtxo: { script: payments.p2wpkh({ pubkey: keyPair.publicKey }).output!, value: 20000 },
  })
  .addOutput({
    address: 'tb1qgs400u6kqvq977gskv0d5x0r0sfgz7454w077e', // Another dummy testnet address
    value: 10000,
  });

// 4. Sign the input
psbt.signInput(0, keyPair);

// 5. Finalize the input (adds witness data)
psbt.finalizeAllInputs();

// 6. Extract the signed transaction (hex format) and log it
const transaction = psbt.extractTransaction().toHex();
console.log('Signed Transaction (Hex):', transaction);

view raw JSON →