Getting Started

Welcome to the extensive guide to programming Bitcoin using Javascript! In this guide we will explain how to create various types of Bitcoin transactions using the BitcoinJS library.

We will use the Bitcoin Core command-line interface in regression test mode mode for various common tasks, as well as some complimentary libraries like bx aka Libbitcoin Explorer.

Throughout this guide, we want to provide you with sufficient explanation to each command to understand it without going into to much detail. You can refer to additional resources to better understand the Bitcoin protocol. For more examples, check out some other tutorials on this site or visit Bitcoin Studio presentations.

At the moment, Bitcoin Javascript tutorials are still very scarce, but we believe it doesn't have to be this way. The following guide intends to address this problem.

Requirements

Having prior theoretical knowledge of the Bitcoin protocol will surely help, but we provide comprehensive explanations throughout this guide suitable for beginners.

Technical requirements

  • Node v10.x or superior
  • BitcoinJS v4.x or superior
  • Bitcoin Core v17.x or superior
  • Libbitcoin Explorer v3.4.x or superior

Unless otherwise noted, the contents of this repository are Copyright ©2018 by Bitcoin Studio and are licensed CC-BY.

Disclaimer

  • This guide is not the official documentation for BitcoinJS Lib
  • You must check the BitcoinJS repository for up-to-date code
  • Non-standard scripts are exposed for educational purposes
  • The author of this guide is not responsible for any loss of funds

Please consider making a donation so that I can continue producing free educational content.

How to Start

Throughout this guide we will use the well known BitcoinJS open source library. Started in 2011 and mainly written and maintained by Daniel Cousens, as well as most of its dependencies. Additional purpose-specific libraries are sometimes required. You can find all you need on the BitcoinJS Organization Repositories.

We will also use the Bitcoin Core command-line interface in regtest mode for various common tasks (decoding raw transaction, sending raw transaction, getting address information, decoding Bitcoin script, funding addresses, ...). You can download the software at bitcoin.org - Bitcoin Core Download Page or at bitcoincore.org - Bitcoin Core Download Page.

Note:
If you don't currently have access to a bitcoin development environment set up, dont' worry, we have your back! We've setup a web based mechanism which provisions your very own private session that includes these tools and comes preconfigured with a bitcoin node in regtest mode. https://bitcoindev.network/bitcoin-cli-sandbox/
Alternatively, we have also provided a simple docker container configured in regtest mode that you can install for testing purposes.

$ docker volume create --name=bitcoind-data
$ docker run -v bitcoind-data:/bitcoin --name=bitcoind-node -d \
     -p 18444:18444 \
     -p 127.0.0.1:18332:18332 \
     bitcoindevelopernetwork/bitcoind-regtest

You are able to use the integrated console of Bitcoin Core GUI (Help > Debug window > Console). The GUI also gives you the ability to check your wallet and transaction details. Otherwise you can type the commands into bitcoin-cli which connects to the bitcoind daemon. Check the documentation of the two websites cited above if you need more help.

Bitcoin Core software is not the only implementation of the Bitcoin protocol and other implementations should work. However Bitcoin Core is by far the most used and most robust implementation. Also, beware of Bitcoin scam forks. Many websites like bitcoin.com are promoting other coins pretending to be a Bitcoin upgrade. Download only trusted Bitcoin software after rigorous due diligence.

You need to make sure that your bitcoin configuration file is set to run Bitcoin Core in Regtest mode. You can replace your default configuration with the one in bitcoin.conf. Make sure it suits your needs before running the software.

The Regtest mode replicates the 100-block maturation time rule, forcing us to wait 101 confirmations to spend a coinbase transaction. So, to be able to start spending coins we need to generate 101 blocks.

$ bitcoin-cli generate 101

Install the javascript libraries.

Be careful, the NPM version of BitcoinJS is not necessarily up to date the github master branch.
This is why the package.json references a github commit.

The source code for this guide is avaible here

$ git clone https://github.com/bitcoin-studio/Bitcoin-Programming-with-BitcoinJS/
$ cd code
$ npm install

Complementary libraries and scripts

The complementary library bx aka Libbitcoin Explorer is useful for some quick tasks like generating seed entropy or computing a hash. For address derivation tasks or others, make sure to configure the bx.cfg configuration file appropriately.

You will find a number of handy scripts in the ./code directory. It will be much easier to follow along this guide if you always use the same addresses, in NodeJS and in Bitcoin Core. The generate_wallets.js script will help you with wallet generation and private key importation. Check out the next section on Generating and Importing Wallets for more information.

You can find a simple handy base converter in baseConverter.js

Finally, numbers in Bitcoin script require to be encoded in little endian hexadecimal. BitcoinJS takes care of that but in case you need it check out the int2lehex.sh bash script. Don't forget to $ chmod 755 integer2lehex.sh.

Transaction Basics

In order to follow along with this guide, you need to understand some basics about Bitcoin transaction. So let's quickly describe them before starting.

There are two categories of transactions, Pay To PubKey Hash and Pay To Script Hash respectively. We will illustrate the first category in part two of this guide, and the second on part three.

A Bitcoin transaction is composed of one or more inputs, each of them consuming the value of a corresponding previous unspent transaction outputs, and creates one or more unspent transaction outputs.

An unspent transaction output is commonly abbreviated as UTXO. So in order to spend a UTXO, we have to create an input that will reference it and provide some kind of unlocking script.

The unlocking script is created in accordance with the rules specified in the UTXO locking script.

The Bitcoin system is charged with making sure the signatures are correct, that the UTXOs exist and are spendable, and that the sum of the output values is less than or equal to the sum of the input values. The difference between the sum of inputs and outputs value becomes fees paid to miners for including the transaction.

Legacy, Embedded Backward-compatible Segwit and Native Segwit outputs

The two categories described above, Pay To PubKey Hash and Pay To Script Hash, are actually available in three different flavours: legacy, embedded Segwit and native Segwit.

Legacy is the output type before the Segregated Witness soft fork, activated on August 23, 2017. It comprises of P2PKH and P2SH. Native Segwit outputs comprise P2WPKH and P2WSH.

Embedded Segwit has been developed to ensure a smooth transition to Segwit. The idea is to embed P2WPKH or P2WSH into a regular P2SH. The two resulting types are abbreviated in P2SH-P2WPKH and P2SH-P2WSH.