Getting Started with the BitGo SDK

The BitGo JavaScript SDK makes it easy to get started developing with the Bitcoin protocol using multi-sig wallets. The SDK provides developers with a high-level, easy-to-use abstraction of the protocol which may be more palatable to those still getting acclimated to programming with the cryptocurrency. The built-in security suite, trusted by top-tier exchanges like Bitstamp provide developers with the piece-of-mind in knowing that they no longer have to rely on a homebrew security stack. This blog post will take you through the process of using the SDK to send and receive Bitcoin from scratch.

Requirements

This tutorial assumes comfort with javascript, Github, and APIs. Please ensure that you have the following:

test.bitgo.com which is the recommended starting point for developers new to Bitcoin.

  • A BitGo testnet account on test.bitgo.com.
  • An access token from your test.bitgo.com account.
  • The latest version of nodeJS and npm.
  • Mac OS X or Linux-based OS

Let’s Get Started!

First let’s create a folder for our new project, feel free to name it however you’d like. 

$ mkdir BitGoProject
$ cd BitGoProject
$ npm install bitgo

You’ve just installed the BitGo JS SDK, we’ll get started by authenticating our BitGo access token.

Authentication

From our BitGo project folder, we can start developing our codebase. Use your text editor to create a file called authentication.js and enter the following:

var BitGoJS = require('bitgo');

if (process.argv.length < 3) {
console.log("usage:\n\t" + process.argv[0] + " " + process.argv[1] + " ");
process.exit(-1);
}

// For Testnet environment set env to test
// For Livenet environment set env to prod
var accessToken = process.argv[2];
var bitgo = new BitGoJS.BitGo({env: 'test', accessToken: accessToken});
console.log("BitGoJS library version: " + bitgo.version());
bitgo.session({})
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log(err);
});

Save this and close it out. We’ll be using this to get acclimated to authenticating with BitGo servers and to verify that our access token is valid.

Setup the access token as an environment variable before we run the script.

$ export ACCESS_TOKEN='fcb5dc6200ce9 ... f95c0a1063ed8883'

Let’s double-check to make sure that the environment variable was setup correctly. Enter the following and ensure that the access token that you set is printed to the screen.

$ echo $ACCESS_TOKEN

After verifying that your access token is set, run the following and verify that your output looks similar:

$ node authentication.js $ACCESS_TOKEN

BitGoJS library version: 0.11.27

{ id: ‘11cfbed2333261c0120hb97ac54015a2’,
client: ‘bitgo’,
user: ‘1182f52d4fe2627d67d914153d99a37c’,
scope:
[ ‘wallet_view_all’,
‘wallet_spend_all’,
‘wallet_manage_all’,
‘wallet_create’,
‘openid’,
‘profile’ ],
created: ‘2015–08–15T22:36:02.424Z’,
expires: ‘2025–08–12T22:36:02.424Z’,
origin: ‘test.bitgo.com’,
label: ‘Test Token’,
unlock:
{ time: ‘2015–08–15T22:36:02.425Z’,
expires: ‘2025–08–12T22:36:02.424Z’,
txValueLimit: 500000000,
txValue: 0 } }

Let’s take a moment to double check our token parameters to ensure that we can follow through with the tutorial, make sure that you have the following:

  • Your scope includes wallet_create and wallet_spend_all.
  • Your origin is test.bitgo.com.
  • The timestamp under expires is greater than the time you expect it to take you to complete this tutorial.
  • Your txValueLimit is greater than 5 BTC or 500,000,000 Satoshis or any value higher than what we would expect to receive from a reasonable testnet faucet.

Creating a wallet

BitGo users have the benefit of creating Bitcoin wallets that are both protected by a unique password as well as two-factor authentication in the web-client. BitGo wallets have the additional benefit of advanced treasury controls that can allow multiple users to share a wallet with a specific set of policies as well as spending limits and address whitelisting. To create a wallet create a file called createWallet.js and enter and save the following text:

var BitGoJS = require('bitgo');
var bitgo = new BitGoJS.BitGo({env: 'test', accessToken: process.env.ACCESS_TOKEN});

if (process.argv.length < 3) {
console.log("usage:\n\t" + process.argv[0] + " " + process.argv[1] + "

var label = process.argv[2];
var walletPassword = process.argv[3];

// Create the wallet
bitgo.wallets().createWalletWithKeychains({"passphrase": walletPassword, "label": label}, function(err, result) {
if (err) { console.dir(err); throw new Error("Error creating wallet!"); }
console.log("Wallet Created: " + result.wallet.id());
console.dir(result.wallet.wallet);

// console.log("BACK THIS UP: ");
// console.log("User keychain encrypted xPrv: " + result.userKeychain.encryptedXprv);
// console.log("Backup keychain encrypted xPrv: " + result.backupKeychain.encryptedXprv);
});

For demonstration purposes, the encrypted xPrv will not be printed out, if you’d like to print them out and store them securely, please feel free to do so.

Once you have verified that your environment variable has been set we can try running createWallet.js. Enter the following and confirm that you are able to view the wallet address:

$ node createWallet.js TESTWALLET WALLETPASS

Wallet Created: 2MtbsXjJ5GJRcCPnMruZZpYVUq348mwfKfD
{ _id: ‘11cff1aab5be51c212a40e5ce91c0ee4’,
id: ‘2MtbsXjJ5GJRcCPnMruZZpYVUq348mwfKfD’,
label: ‘TESTWALLET’,
isActive: true,
type: ‘safehd’,
freeze: {},
adminCount: 1,
disableTransactionNotifications: false,
private: { keychains: [ [Object], [Object], [Object] ] },
permissions: ‘admin,spend,view’,
admin: { users: [ [Object] ] },
tags: [],
spendingAccount: true,
pendingApprovals: [],
confirmedBalance: 0,
balance: 0,
unconfirmedSends: 0,
unconfirmedReceives: 0 }

You’ve officially created your first BitGo wallet through the API! If you log in to your BitGo account you will see a new wallet appear on the main dashboard. This wallet is fully accessible and configurable through both the website as well as the API. The next step will be to fund the wallet so that we can attempt to create a Bitcoin transaction using the wallet. You can grab your wallet address from the id: field. The one that I had created was2MtbsXjJ5GJRcCPnMruZZpYVUq348mwfKfD. You have two options for funding the address:

  • Tweet me at @lopp with your Testnet wallet id / Bitcoin address to receive some Testnet Bitcoin. Warning: This will take longer than the testnet faucet.
  • For those seeking instant gratification, enter your address in a Testnet Faucet to receive Testnet Bitcoin

Checking Address Balance

Once you have sent some Testnet Bitcoin to your wallet, you’ll want to ensure that the Bitcoin are there in your wallet. To do so create a file called getAddressBalance.js with the following code:

var BitGoJS = require('bitgo');
var bitgo = new BitGoJS.BitGo({env: 'test', accessToken: process.env.ACCESS_TOKEN});

if (process.argv.length < 2) {
console.log("usage:\n\t" + process.argv[0] + " " + process.argv[1] + "

");
process.exit(-1);
}

if (process.argv.length > 2) {
address = process.argv[2];
}

bitgo.wallets().get({type: 'bitcoin', id: address}, function(err, wallet) {
if (err) { console.log(err); process.exit(-1); }
console.log('Wallet balance is: ');
console.log(wallet.balance() + ' Satoshis');
});

To check your balance run the following using your Bitcoin address that was used for receiving Testnet Bitcoin.

$ node getAddressBalance.js 2MxMZR4UozWWoA1phQ48aKuaL6ZoEj9cc9T

Ensure that your response resembles the following, and that your wallet has a positive balance:

Wallet Balance is:
88000000 Satoshis

Once you have a balance in your wallet, you’ll be ready to send off some Bitcoin!

Sending Bitcoin

Sending Bitcoin is made easy with the BitGo JS SDK. All you need is some identifying information for the originating wallet. As well as the destination wallet address and the amount that is to be sent. Create the following script and save it as sendBitcoins.js.

var BitGoJS = require('bitgo');
var bitgo = new BitGoJS.BitGo({env: 'test', accessToken: process.env.ACCESS_TOKEN});

if (process.argv.length < 6) {
console.log("usage:\n\t" + process.argv[0] + " " + process.argv[1] + " ");
process.exit(-1);
}

var walletId = process.argv[2];
var walletPassphrase = process.argv[3];
var destinationAddress = process.argv[4];
var amountSatoshis = parseInt(process.argv[5], 10);

var sendBitcoin = function() {
console.log("Getting wallet..");

// Now get the wallet
bitgo.wallets().get({id: walletId}, function(err, wallet) {
if (err) { console.log("Error getting wallet!"); console.dir(err); return process.exit(-1); }
console.log("Balance is: " + (wallet.balance() / 1e8).toFixed(4));

wallet.sendCoins({ address: destinationAddress, amount: amountSatoshis, walletPassphrase: walletPassphrase, minConfirms: 0 },
function(err, result) {
if (err) { console.log("Error sending coins!"); console.dir(err); return process.exit(-1); }

console.dir(result);
process.exit(0);
}
);
});
};

sendBitcoin();

To run the script you will need the following parameters: walletID, walletPassphrase, destinationAddress, amountSatoshis. These parameters will be entered like so:

node sendBitcoin.js walletId walletPassphrase destinationAddress amountSatoshis

Run the sendBitcoin.js script on the command line to unlock and send all of the Testnet Bitcoin that you have in the wallet.

node sendBitcoin.js 2Mx8…y7Ca WALLETPASS 2Mxe…JyNA 880000

The response should resemble the following:

Getting wallet..

Balance is: 0.8800

{ status: ‘accepted’, tx: ‘0100000001d4c1b098298a92a411729dcd09fc914135757b8ff9a524d237
571974b55a96f401000000fdfe0000483045022100ef0c945212f8143f37fc
2b4e55a606e991983a7d366b938ab1c4661398faa35202203f40d85badd
0767499f11fcca4b6539dc344ca4b9abbfbed99834848b8f3588c01483045
022100907cfeab746606834bcc9d567073595993458c02bd0d2b30b6cd1
a557aed51440220485b99d2d755edd5a27b0434c82c8e12d138cf731807
c88ca4eea4511967b449014c69522102cb59daed7704b60b168c5bf976a
52638564e703c37ae0dabe0f8e1b2b17900a821024feadc485e4b97f95fe
c55a2e46269715f9f882af83df39caaec5914bc24d01b2102683b28d6af56
ff686de4bb0be639715645fe956012c11bbc6406f9e91856b3c353aeffffff
ff02e44931050000000017a914574360792c61c1a9f66a6fde802a88d62705
fdd487806d0d000000000017a9143b4acb201fc43596e01c091dc63fe41c
1c4c5c2d8700000000’,

hash: ‘97b5cb5d9979aa8f5389a649ee90655c480e02e8552194803f021c
2c953243ab’,fee: 3740,feeRate: 10000 }

Congratulations, you made it through the entire lifecycle of a Bitcoin transaction using the BitGo JS SDK!

We’re excited to see what you’ll build next

The BitGo JS SDK helps power and protect some of the largest Bitcoin exchanges and hedge funds around the world. We’re excited to see how the BitGo SDK will help power the next generation of Bitcoin apps. Let us know what you think of the BitGo SDK on Twitter!