Convert Figma logo to code with AI

bitcoinjs logobitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.

5,794
2,135
5,794
32

Top Related Projects

Optimized C library for EC operations on curve secp256k1

3,021

Javascript bitcoin library for node.js and browsers

4,900

A full stack for bitcoin and blockchain-based applications

6,325

An alternative full node bitcoin implementation written in Go (golang)

15,961

JavaScript library of crypto standards.

Quick Overview

BitcoinJS is a JavaScript library for Bitcoin-related functions. It provides a comprehensive set of tools for creating, signing, and validating Bitcoin transactions, as well as managing keys and addresses. The library is designed to work in both Node.js and browser environments.

Pros

  • Extensive functionality for Bitcoin operations
  • Well-maintained and actively developed
  • Cross-platform compatibility (Node.js and browser)
  • Strong community support and documentation

Cons

  • Steep learning curve for beginners
  • Limited support for some advanced Bitcoin features
  • Requires careful handling of private keys and sensitive data
  • Performance may be slower compared to native implementations

Code Examples

Creating a Bitcoin address:

const bitcoin = require('bitcoinjs-lib');
const network = bitcoin.networks.testnet;

const keyPair = bitcoin.ECPair.makeRandom({ network });
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey, network });

console.log(address);

Creating and signing a transaction:

const bitcoin = require('bitcoinjs-lib');
const network = bitcoin.networks.testnet;

const keyPair = bitcoin.ECPair.fromWIF('your_private_key_wif', network);
const psbt = new bitcoin.Psbt({ network });

psbt.addInput({
  hash: 'previous_tx_hash',
  index: 0,
  nonWitnessUtxo: Buffer.from('previous_tx_hex', 'hex'),
});

psbt.addOutput({
  address: 'recipient_address',
  value: 50000, // Amount in satoshis
});

psbt.signInput(0, keyPair);
psbt.finalizeAllInputs();

const tx = psbt.extractTransaction();
console.log(tx.toHex());

Generating a multisig address:

const bitcoin = require('bitcoinjs-lib');
const network = bitcoin.networks.testnet;

const pubkeys = [
  Buffer.from('pubkey1_hex', 'hex'),
  Buffer.from('pubkey2_hex', 'hex'),
  Buffer.from('pubkey3_hex', 'hex'),
];

const { address } = bitcoin.payments.p2sh({
  redeem: bitcoin.payments.p2ms({ m: 2, pubkeys, network }),
  network,
});

console.log(address);

Getting Started

To get started with BitcoinJS, follow these steps:

  1. Install the library using npm:

    npm install bitcoinjs-lib
    
  2. Import the library in your JavaScript file:

    const bitcoin = require('bitcoinjs-lib');
    
  3. Choose the appropriate network (mainnet or testnet):

    const network = bitcoin.networks.testnet; // or bitcoin.networks.bitcoin for mainnet
    
  4. Start using the library's functions to create addresses, sign transactions, or perform other Bitcoin-related operations as shown in the code examples above.

Competitor Comparisons

Optimized C library for EC operations on curve secp256k1

Pros of secp256k1

  • Highly optimized C implementation for better performance
  • Provides low-level cryptographic functions for advanced use cases
  • Extensively tested and audited for security

Cons of secp256k1

  • Requires compilation and is not directly usable in JavaScript environments
  • Limited to secp256k1 curve operations, less versatile than bitcoinjs-lib
  • Steeper learning curve for developers unfamiliar with C

Code Comparison

secp256k1:

secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
unsigned char msg32[32];
unsigned char seckey[32];
secp256k1_ecdsa_signature signature;
secp256k1_ecdsa_sign(ctx, &signature, msg32, seckey, NULL, NULL);

bitcoinjs-lib:

const bitcoin = require('bitcoinjs-lib');
const keyPair = bitcoin.ECPair.makeRandom();
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey });
const txb = new bitcoin.TransactionBuilder();
txb.sign(0, keyPair);

Summary

secp256k1 is a low-level, high-performance cryptographic library focused on the secp256k1 elliptic curve, while bitcoinjs-lib is a more comprehensive JavaScript library for Bitcoin-related operations. secp256k1 offers better performance and is suitable for projects requiring optimized cryptographic operations, but it's less accessible for web developers. bitcoinjs-lib provides a higher-level API and is more versatile for general Bitcoin development in JavaScript environments.

3,021

Javascript bitcoin library for node.js and browsers

Pros of bcoin

  • Full-featured Bitcoin implementation with node, wallet, and mining capabilities
  • Written in modern JavaScript (ES6+) with better performance
  • More comprehensive and actively maintained

Cons of bcoin

  • Larger codebase and steeper learning curve
  • Heavier resource requirements for full node functionality
  • Less focused on specific Bitcoin operations compared to bitcoinjs-lib

Code Comparison

bcoin (wallet creation):

const {WalletDB} = require('bcoin');
const walletdb = new WalletDB({ memory: true });
await walletdb.open();
const wallet = await walletdb.create();

bitcoinjs-lib (key pair generation):

const bitcoin = require('bitcoinjs-lib');
const keyPair = bitcoin.ECPair.makeRandom();
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey });

bcoin provides a more comprehensive wallet management system, while bitcoinjs-lib offers simpler, lower-level Bitcoin operations. bcoin's approach is suitable for full node implementations, whereas bitcoinjs-lib is more focused on specific Bitcoin transactions and scripting tasks.

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project. bcoin is better for full-featured Bitcoin applications, while bitcoinjs-lib is ideal for lightweight clients and specific Bitcoin operations.

4,900

A full stack for bitcoin and blockchain-based applications

Pros of Bitcore

  • More comprehensive suite of tools, including a full node implementation
  • Better documentation and examples for beginners
  • Actively maintained with regular updates

Cons of Bitcore

  • Larger codebase, potentially more complex for simple projects
  • Less flexible for advanced customization
  • Slower adoption of new Bitcoin features compared to Bitcoinjs-lib

Code Comparison

Bitcoinjs-lib (creating a transaction):

const txb = new bitcoin.TransactionBuilder()
txb.addInput(prevTxHash, prevTxIndex)
txb.addOutput(recipientAddress, amount)
txb.sign(0, keyPair)
const tx = txb.build()

Bitcore (creating a transaction):

const tx = new bitcore.Transaction()
  .from(utxo)
  .to(recipientAddress, amount)
  .sign(privateKey)

Both libraries offer similar functionality for basic Bitcoin operations, but Bitcoinjs-lib tends to be more low-level and flexible, while Bitcore provides a higher-level abstraction. Bitcoinjs-lib is often preferred for its lightweight nature and extensive customization options, making it popular among developers building complex Bitcoin applications. Bitcore, on the other hand, offers a more user-friendly approach with its comprehensive toolset, making it suitable for beginners and projects requiring a full suite of Bitcoin-related functionalities.

6,325

An alternative full node bitcoin implementation written in Go (golang)

Pros of btcd

  • Written in Go, offering better performance and concurrency
  • Full-node implementation, providing complete blockchain validation
  • Extensive API for blockchain interaction and custom applications

Cons of btcd

  • Larger resource footprint due to full-node nature
  • Steeper learning curve for developers not familiar with Go

Code Comparison

btcd (Go):

block := wire.MsgBlock{}
err := block.Deserialize(blockReader)
if err != nil {
    return err
}

bitcoinjs-lib (JavaScript):

const block = Block.fromBuffer(blockBuffer)

Key Differences

  • btcd is a full Bitcoin node implementation, while bitcoinjs-lib is a library for creating Bitcoin transactions and scripts
  • btcd provides more comprehensive blockchain interaction, whereas bitcoinjs-lib focuses on transaction creation and signing
  • btcd is better suited for building Bitcoin-related services and applications, while bitcoinjs-lib is ideal for wallet development and simple Bitcoin operations

Use Cases

  • btcd: Running a full Bitcoin node, building blockchain explorers, or creating custom Bitcoin-based applications
  • bitcoinjs-lib: Developing Bitcoin wallets, creating and signing transactions, or integrating Bitcoin functionality into web applications

Both projects have their strengths, and the choice between them depends on the specific requirements of your Bitcoin-related project.

15,961

JavaScript library of crypto standards.

Pros of crypto-js

  • Broader scope: Supports a wide range of cryptographic functions beyond just Bitcoin
  • Lightweight: Smaller library size, suitable for general-purpose cryptography tasks
  • Browser compatibility: Designed to work well in both Node.js and browser environments

Cons of crypto-js

  • Less Bitcoin-specific: Lacks specialized Bitcoin functionality and ecosystem integration
  • Not actively maintained: Less frequent updates and potentially outdated implementations
  • Limited documentation: Fewer examples and resources compared to bitcoinjs-lib

Code Comparison

crypto-js (AES encryption):

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
console.log(decrypted.toString(CryptoJS.enc.Utf8));

bitcoinjs-lib (Creating a Bitcoin transaction):

const txb = new bitcoin.TransactionBuilder();
txb.addInput('TX_ID', OUTPUT_INDEX);
txb.addOutput(RECIPIENT_ADDRESS, AMOUNT);
txb.sign(0, keyPair);
const tx = txb.build();

Both libraries serve different purposes. crypto-js is a general-purpose cryptography library, while bitcoinjs-lib is specifically designed for Bitcoin-related operations. Choose based on your project's requirements and focus.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

BitcoinJS kawaii logo

(Logo by @sawaratsuki1004)

(LICENSE for the logo is on SAWARATSUKI Github repo)

Github CI NPM code style: prettier

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

Visit our documentation to explore the available resources. We're continually enhancing our documentation with additional features for an enriched experience. If you need further guidance beyond what our examples offer, don't hesitate to ask for help. We're here to assist you.

You can find a Web UI that covers most of the psbt.ts, transaction.ts and p2*.ts APIs here.

How can I contact the developers outside of Github?

Most of the time, this is not appropriate. Creating issues and pull requests in the open will help others with similar issues, so please try to use public issues and pull requests for communication.

That said, sometimes developers might be open to taking things off the record (ie. You want to share code that you don't want public to get help with it). In that case, please negotiate on the public issues as to where you will contact.

We have created public rooms on IRC (#bitcoinjs on libera.chat) and Matrix (#bitcoinjs-dev:matrix.org). These two channels have been joined together in a Matrix "Space" which has the Matrix room AND an IRC bridge room that can converse with the IRC room. The "Space" is #bitcoinjs-space:matrix.org.

Matrix and IRC both have functions for direct messaging, but IRC is not end to end encrypted, so Matrix is recommended for most communication. The official Matrix client maintained by the Matrix core team is called "Element" and can be downloaded here: https://element.io/download (Account creation is free on the matrix.org server, which is the default setting for Element.)

We used to have a Slack. It is dead. If you find it, no one will answer you most likely.

No we will not make a Discord.

Installation

npm install bitcoinjs-lib
# optionally, install a key derivation library as well
npm install ecpair bip32
# ecpair is the ECPair class for single keys
# bip32 is for generating HD keys

Previous versions of the library included classes for key management (ECPair, HDNode(->"bip32")) but now these have been separated into different libraries. This lowers the bundle size significantly if you don't need to perform any crypto functions (converting private to public keys and deriving HD keys).

Typically we support the Node Maintenance LTS version. TypeScript target will be set to the ECMAScript version in which all features are fully supported by current Active Node LTS. However, depending on adoption among other environments (browsers etc.) we may keep the target back a year or two. If in doubt, see the main_ci.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 authoritative source of best practice, but, at the very least:

  • Don't reuse 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'd like to use a different (more modern) build tool than browserify, you can compile just this library and its dependencies into a single JavaScript file:

$ npm install bitcoinjs-lib browserify
$ npx browserify --standalone bitcoin -o bitcoinjs-lib.js <<< "module.exports = require('bitcoinjs-lib');"

Which you can then import as an ESM module:

<script type="module">import "/scripts/bitcoinjs-lib.js"</script>

Using Taproot:

When utilizing Taproot features with bitcoinjs-lib, you may need to include an additional ECC (Elliptic Curve Cryptography) library. The commonly used tiny-secp256k1 library, however, might lead to compatibility issues due to its reliance on WASM (WebAssembly). The following alternatives may be used instead, though they may be significantly slower for high volume of signing and pubkey deriving operations.

Alternatives for ECC Library:

  1. @bitcoinjs-lib/tiny-secp256k1-asmjs A version of tiny-secp256k1 compiled to ASM.js directly from the WASM version, potentially better supported in browsers. This is the slowest option.
  2. @bitcoinerlab/secp256k1 Another alternative library for ECC functionality. This requires access to the global BigInt primitive. For advantages and detailed comparison of these libraries, visit: tiny-secp256k1 GitHub page.

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 at least 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).

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/BIP350 compliant Bech32/Bech32m 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

NPM DownloadsLast 30 Days