{"id":10577,"library":"bitcoinjs-lib","title":"BitcoinJS Lib","description":"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.","status":"active","version":"7.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/bitcoinjs/bitcoinjs-lib","tags":["javascript","bitcoinjs","bitcoin","browserify","typescript"],"install":[{"cmd":"npm install bitcoinjs-lib","lang":"bash","label":"npm"},{"cmd":"yarn add bitcoinjs-lib","lang":"bash","label":"yarn"},{"cmd":"pnpm add bitcoinjs-lib","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for ECPair functionality (e.g., generating key pairs, signing) as key management was externalized.","package":"ecpair","optional":true},{"reason":"Required for BIP32 HD key derivation functionalities as key management was externalized.","package":"bip32","optional":true},{"reason":"An Elliptic Curve Cryptography (ECC) library is required to initialize `ecpair` and `bip32`.","package":"@noble/secp256k1","optional":true}],"imports":[{"note":"While CommonJS `require` is supported for Node.js, ESM `import * as bitcoin` is the recommended pattern for modern applications. This provides access to all exported modules under the `bitcoin` namespace.","wrong":"const bitcoin = require('bitcoinjs-lib');","symbol":"bitcoin","correct":"import * as bitcoin from 'bitcoinjs-lib';"},{"note":"Use named imports for specific functionalities like `Transaction` or `Psbt` to leverage tree-shaking, particularly for browser builds. The library does not provide a default export.","wrong":"import bitcoinjsLib from 'bitcoinjs-lib';","symbol":"Transaction, networks, Psbt","correct":"import { Transaction, networks, Psbt } from 'bitcoinjs-lib';"},{"note":"Since `bitcoinjs-lib` v6, `ECPair` and `bip32` functionalities have been extracted into separate packages (`ecpair` and `bip32` respectively) to reduce the core library's bundle size. They must be imported from their own packages and initialized with an ECC curve library (e.g., `tiny-secp256k1` or `@noble/secp256k1`). Attempting to import them directly from `bitcoinjs-lib` will result in an `undefined` or similar error.","wrong":"import { ECPair } from 'bitcoinjs-lib';","symbol":"ECPair, BIP32","correct":"import * as ecc from '@noble/secp256k1';\nimport * as ECPairFactory from 'ecpair';\nconst ECPair = ECPairFactory.ECPairFactory(ecc);\n// Similarly for bip32: import * as bip32Factory from 'bip32'; const bip32 = bip32Factory.BIP32Factory(ecc);"}],"quickstart":{"code":"import * as ecc from '@noble/secp256k1'; // Or 'tiny-secp256k1'\nimport * as ECPairFactory from 'ecpair';\nimport { Psbt, payments, networks } from 'bitcoinjs-lib';\n\n// 1. Initialize ECPair with an ECC library (required since v6)\nconst ECPair = ECPairFactory.ECPairFactory(ecc);\n\n// 2. Generate a key pair for a new P2WPKH (SegWit) address\nconst keyPair = ECPair.makeRandom({ network: networks.testnet });\nconst { address } = payments.p2wpkh({ pubkey: keyPair.publicKey, network: networks.testnet });\n\nconsole.log('New SegWit Testnet Address:', address);\nconsole.log('WIF (WARNING: DO NOT SHARE OR USE IN PRODUCTION):', keyPair.toWIF());\n\n// 3. Create a Partially Signed Bitcoin Transaction (PSBT)\n// This is a simplified example; real PSBTs require fetching actual UTXO details.\nconst psbt = new Psbt({ network: networks.testnet })\n  .addInput({\n    hash: '8f72289c02d75a8a113333333333333333333333333333333333333333333333', // Dummy TX ID\n    index: 0,\n    // For P2WPKH, witnessUtxo is required\n    witnessUtxo: { script: payments.p2wpkh({ pubkey: keyPair.publicKey }).output!, value: 20000 },\n  })\n  .addOutput({\n    address: 'tb1qgs400u6kqvq977gskv0d5x0r0sfgz7454w077e', // Another dummy testnet address\n    value: 10000,\n  });\n\n// 4. Sign the input\npsbt.signInput(0, keyPair);\n\n// 5. Finalize the input (adds witness data)\npsbt.finalizeAllInputs();\n\n// 6. Extract the signed transaction (hex format) and log it\nconst transaction = psbt.extractTransaction().toHex();\nconsole.log('Signed Transaction (Hex):', transaction);\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Install `ecpair`, `bip32`, and an ECC library (e.g., `@noble/secp256k1`). Import and initialize them as shown in the quickstart or their respective documentation.","message":"The `ECPair` and `bip32` key management classes were externalized into separate packages (`ecpair` and `bip32`) starting from `bitcoinjs-lib` v6. These must now be installed and imported independently and initialized with an ECC curve library (e.g., `@noble/secp256k1` or `tiny-secp256k1`).","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Always pin `bitcoinjs-lib` to a specific stable version (e.g., `^7.0.0`) in your `package.json` and deploy only officially released versions.","message":"The `master` branch is unstable and serves as the development branch. It is explicitly not recommended for production use. Only officially tagged releases are considered stable and suitable for applications.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Access transaction ID via `psbt.data.globalMap.unsignedTx.getId()` or `getHash()` methods, instead of relying on the full `Transaction` API directly from `unsignedTx`.","message":"In `bitcoinjs-lib` v7, the `Psbt.data.globalMap.unsignedTx` property's type changed from a `Transaction` object to a `TransactionFromBuffer` object. This impacts direct access to transaction details from this field, which is now optimized for `txid/wtxid` calculation without full transaction parsing.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"If you relied on `Psbt.signInput` returning `void`, adapt your code for method chaining or ignore the return value. This is generally an improvement for fluent API design.","message":"In `bitcoinjs-lib` v7, `Psbt.signInput` now returns `this` (the Psbt instance) instead of `void`. While this allows for method chaining, it's a change in return type that might affect existing code if the return value was explicitly assumed to be `void`.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Perform security audits, review release notes, and inspect the source code and dependencies regularly to ensure suitability for your application.","message":"Given the critical nature of Bitcoin libraries, thorough auditing of `bitcoinjs-lib` and all its dependencies is strongly recommended before production deployment. The project advocates a 'Don't trust. Verify.' philosophy.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `ecpair` (and/or `bip32`) is installed. Import `ECPairFactory` from `ecpair` (e.g., `import * as ECPairFactory from 'ecpair';`) and initialize it with an ECC library (e.g., `const ECPair = ECPairFactory.ECPairFactory(ecc);`).","cause":"Attempting to use `ECPairFactory` (or `BIP32Factory`) without correct import and initialization, typically because the `ecpair` or `bip32` packages are not installed or an ECC library is not provided.","error":"Cannot read properties of undefined (reading 'ECPairFactory')"},{"fix":"Use the methods provided by `TransactionFromBuffer` (e.g., `getId()` or `getHash()`) directly on `psbt.data.globalMap.unsignedTx`.","cause":"Accessing methods of the `Transaction` object directly from `Psbt.data.globalMap.unsignedTx` in `bitcoinjs-lib` v7. The type has changed to `TransactionFromBuffer` for performance.","error":"TypeError: Psbt.data.globalMap.unsignedTx.getHash is not a function"},{"fix":"Ensure that each input added to the PSBT has the necessary UTXO information (`witnessUtxo` or `nonWitnessUtxo`) corresponding to the script type you are attempting to sign.","cause":"The PSBT was created without proper input information, specifically `witnessUtxo` or `nonWitnessUtxo` being missing for the respective script type (e.g., P2WPKH needs `witnessUtxo`, P2PKH needs `nonWitnessUtxo`).","error":"Error: No inputs to sign."},{"fix":"Verify that the `keyPair` used for signing corresponds to the private key of the address funding the specific input (index X) you are trying to sign. Also ensure the input details in the PSBT are accurate and complete.","cause":"The `keyPair` provided to `psbt.signInput(X, keyPair)` does not match the public key associated with the UTXO in input X, or the input data is insufficient for signing.","error":"Error: Key pair for input #X not provided."}],"ecosystem":"npm"}