What is bitcoinjs-lib?
The bitcoinjs-lib npm package is a library for Bitcoin-related operations in JavaScript. It provides tools for creating, signing, and verifying Bitcoin transactions, as well as generating and managing Bitcoin addresses and keys.
What are bitcoinjs-lib's main functionalities?
Generate a Bitcoin Address
This feature allows you to generate a new Bitcoin address. The code creates a random key pair and derives a Bitcoin address from the public key.
const bitcoin = require('bitcoinjs-lib');
const keyPair = bitcoin.ECPair.makeRandom();
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey });
console.log(address);
Create a Bitcoin Transaction
This feature allows you to create a Bitcoin transaction. The code builds a transaction by adding inputs and outputs, and then signs it with the private key.
const bitcoin = require('bitcoinjs-lib');
const keyPair = bitcoin.ECPair.fromWIF('your-private-key');
const txb = new bitcoin.TransactionBuilder();
txb.addInput('previous-txid', 0); // Add input (previous transaction)
txb.addOutput('recipient-address', 100000); // Add output (recipient address and amount in satoshis)
txb.sign(0, keyPair); // Sign the transaction
const tx = txb.build().toHex();
console.log(tx);
Verify a Bitcoin Transaction
This feature allows you to verify a Bitcoin transaction. The code parses a transaction from its hexadecimal representation and checks if all inputs have valid scripts.
const bitcoin = require('bitcoinjs-lib');
const tx = bitcoin.Transaction.fromHex('transaction-hex');
const txb = bitcoin.TransactionBuilder.fromTransaction(tx);
const isValid = txb.inputs.every(input => input.script && input.script.length > 0);
console.log(isValid);
Other packages similar to bitcoinjs-lib
bitcore-lib
Bitcore-lib is another JavaScript library for Bitcoin-related operations. It offers similar functionalities to bitcoinjs-lib, such as creating and signing transactions, generating addresses, and managing keys. Bitcore-lib is part of the Bitcore project, which includes additional tools and services for Bitcoin development.
bcoin
Bcoin is a full Bitcoin node implementation in JavaScript. It provides a comprehensive set of tools for Bitcoin development, including wallet management, transaction creation, and blockchain interaction. Bcoin is more feature-rich compared to bitcoinjs-lib, as it can run as a full node and participate in the Bitcoin network.
bitcoin-core
Bitcoin-core is a JavaScript library for interacting with Bitcoin Core, the reference implementation of the Bitcoin protocol. It allows developers to communicate with a Bitcoin Core node using RPC calls, enabling functionalities such as transaction creation, address management, and blockchain querying. Unlike bitcoinjs-lib, which is a standalone library, bitcoin-core relies on a running Bitcoin Core node.
BitcoinJS (bitcoinjs-lib)
A javascript Bitcoin library for node.js and browsers. Written in TypeScript, but committing the JS files to verify.
Released under the terms of the MIT LICENSE.
Should I use this in production?
If you are thinking of using the master branch of this library in production, stop.
Master is not stable; it is our development branch, and only tagged releases may be classified as stable.
Can I trust this code?
Don't trust. Verify.
We recommend every user of this library and the bitcoinjs ecosystem audit and verify any underlying code for its validity and suitability, including reviewing any and all of your project's dependencies.
Mistakes and bugs happen, but with your help in resolving and reporting issues, together we can produce open source software that is:
- Easy to audit and verify,
- Tested, with test coverage >95%,
- Advanced and feature rich,
- Standardized, using prettier and Node
Buffer
's throughout, and - Friendly, with a strong and helpful community, ready to answer questions.
Documentation
Presently, we do not have any formal documentation other than our examples, please ask for help if our examples aren't enough to guide you.
Installation
npm install bitcoinjs-lib
Typically we support the Node Maintenance LTS version.
If in doubt, see the .travis.yml for what versions are used by our continuous integration tests.
WARNING: We presently don't provide any tooling to verify that the release on npm
matches GitHub. As such, you should verify anything downloaded by npm
against your own verified copy.
Usage
Crypto is hard.
When working with private keys, the random number generator is fundamentally one of the most important parts of any software you write.
For random number generation, we default to the randombytes
module, which uses window.crypto.getRandomValues
in the browser, or Node js' crypto.randomBytes
, depending on your build system.
Although this default is ~OK, there is no simple way to detect if the underlying RNG provided is good enough, or if it is catastrophically bad.
You should always verify this yourself to your own standards.
This library uses tiny-secp256k1, which uses RFC6979 to help prevent k
re-use and exploitation.
Unfortunately, this isn't a silver bullet.
Often, Javascript itself is working against us by bypassing these counter-measures.
Problems in Buffer (UInt8Array)
, for example, can trivially result in catastrophic fund loss without any warning.
It can do this through undermining your random number generation, accidentally producing a duplicate k
value, sending Bitcoin to a malformed output script, or any of a million different ways.
Running tests in your target environment is important and a recommended step to verify continuously.
Finally, adhere to best practice.
We are not an authorative source of best practice, but, at the very least:
- Don't re-use addresses.
- Don't share BIP32 extended public keys ('xpubs'). They are a liability, and it only takes 1 misplaced private key (or a buggy implementation!) and you are vulnerable to catastrophic fund loss.
- Don't use
Math.random
- in any way - don't. - Enforce that users always verify (manually) a freshly-decoded human-readable version of their intended transaction before broadcast.
- Don't ask users to generate mnemonics, or 'brain wallets', humans are terrible random number generators.
- Lastly, if you can, use Typescript or similar.
Browser
The recommended method of using bitcoinjs-lib
in your browser is through Browserify.
If you're familiar with how to use browserify, ignore this and carry on, otherwise, it is recommended to read the tutorial at https://browserify.org/.
NOTE: We use Node Maintenance LTS features, if you need strict ES5, use --transform babelify
in conjunction with your browserify
step (using an es2015
preset).
WARNING: iOS devices have problems, use atleast buffer@5.0.5 or greater, and enforce the test suites (for Buffer
, and any other dependency) pass before use.
Typescript or VSCode users
Type declarations for Typescript are included in this library. Normal installation should include all the needed type information.
Examples
The below examples are implemented as integration tests, they should be very easy to understand.
Otherwise, pull requests are appreciated.
Some examples interact (via HTTPS) with a 3rd Party Blockchain Provider (3PBP).
- Generate a random address
- Import an address via WIF
- Generate a 2-of-3 P2SH multisig address
- Generate a SegWit address
- Generate a SegWit P2SH address
- Generate a SegWit 3-of-4 multisig address
- Generate a SegWit 2-of-2 P2SH multisig address
- Support the retrieval of transactions for an address (3rd party blockchain)
- Generate a Testnet address
- Generate a Litecoin address
- Create a 1-to-1 Transaction
- Create a 2-to-2 Transaction
- Create (and broadcast via 3PBP) a typical Transaction
- Create (and broadcast via 3PBP) a Transaction with an OP_RETURN output
- Create (and broadcast via 3PBP) a Transaction with a 2-of-4 P2SH(multisig) input
- Create (and broadcast via 3PBP) a Transaction with a SegWit P2SH(P2WPKH) input
- Create (and broadcast via 3PBP) a Transaction with a SegWit P2WPKH input
- Create (and broadcast via 3PBP) a Transaction with a SegWit P2PK input
- Create (and broadcast via 3PBP) a Transaction with a SegWit 3-of-4 P2SH(P2WSH(multisig)) input
- Verify a Transaction signature
- Import a BIP32 testnet xpriv and export to WIF
- Export a BIP32 xpriv, then import it
- Export a BIP32 xpub
- Create a BIP32, bitcoin, account 0, external address
- Create a BIP44, bitcoin, account 0, external address
- Create a BIP49, bitcoin testnet, account 0, external address
- Use BIP39 to generate BIP32 addresses
- Create (and broadcast via 3PBP) a Transaction where Alice can redeem the output after the expiry (in the past)
- Create (and broadcast via 3PBP) a Transaction where Alice can redeem the output after the expiry (in the future)
- Create (and broadcast via 3PBP) a Transaction where Alice and Bob can redeem the output at any time
- Create (but fail to broadcast via 3PBP) a Transaction where Alice attempts to redeem before the expiry
If you have a use case that you feel could be listed here, please ask for it!
Contributing
See CONTRIBUTING.md.
Running the test suite
npm test
npm run-script coverage
Complementing Libraries
- BIP21 - A BIP21 compatible URL encoding library
- BIP38 - Passphrase-protected private keys
- BIP39 - Mnemonic generation for deterministic keys
- BIP32-Utils - A set of utilities for working with BIP32
- BIP66 - Strict DER signature decoding
- BIP68 - Relative lock-time encoding library
- BIP69 - Lexicographical Indexing of Transaction Inputs and Outputs
- Base58 - Base58 encoding/decoding
- Base58 Check - Base58 check encoding/decoding
- Bech32 - A BIP173 compliant Bech32 encoding library
- coinselect - A fee-optimizing, transaction input selection module for bitcoinjs-lib.
- merkle-lib - A performance conscious library for merkle root and tree calculations.
- minimaldata - A module to check bitcoin policy: SCRIPT_VERIFY_MINIMALDATA
Alternatives
LICENSE MIT