How to create a raw transaction using bitcoinjs-lib

bitcoinjs-lib is an awesome library for all sort of Bitcoin operations written for Node.js. It’s used in many projects and services you probably already use such as: Blockchain.info, Coinkite, Skyhook ATM, GreenAddress etc..

Please note: Generating raw transactions is pretty advanced and can put your coins at risk if you don’t pay attention to details, please do the following on the testnet and not on the live network.

First let’s include the library in our project:

Next, we will need to import the private key of the Bitcoin address we want to transfer coins from

You can also see the public address for a given private key to make sure you’re using the correct one

Now let’s use bitcoinjs-lib’s TransactionBuilder to create our new raw transaction

Our next step is to add inputs to our transaction. Remember, inputs should include the transaction hash of an unspent output in the address you’re sending from. For example, if you look at this transaction, you can see that the address 17hFoVScNKVDfDTT6vVhjYwvCu6iDEiXC4 received 0.0015BTC from 1EvQUoukdKY5Fw3mqAx5AnaM4qogB5k6qZ, but also in the same transaction some coins were also sent to 1MoK3Dxtrk3QD96oraWTCjbzwXjtHHe9h1 (this is probably a change address).

If we were to build a raw transaction that sends out money from 17hFoVScNKVDfDTT6vVhjYwvCu6iDEiXC4 to a new address we own, we would use:

The second field in the addInput function takes the output index that belongs to the input we would like to spend, since the output index id that belongs to 17hFoVScNKVDfDTT6vVhjYwvCu6iDEiXC4 is 1 we would use that. 0 belongs to the other address that received coins in the same transaction (as you can see here, under the n value in the vout field).

Now we’ll add the output to our transaction, the output is where the coins will be sent to. The first field is the public address you’re sending to and the second field is the amount (in satoshis) you will be sending. Obviously you cannot send out more BTC that is available in a specific input, however ALL the coins in the relevant output HAS to be spent in every transaction, so if you have 150000 satoshis in the relevant output you have to define any amount up to that and whatever you leave behind will be considered the fee for this transaction, so if you have 150000 satoshis in that output and you define 149000 in your new output, 1000 satoshis will go to the miner as fee.

All we have to do next it to sign the transaction and console.log the hexadecimal representation of it

If you were to broadcast this raw transaction to the network you could use either blockchain.info’s pushtx page, Bitpay’s insight send tx page, Blockr.io’s tx send page, or even use the bitcoin-core interface by typing “bitcoind sendrawtransaction hex”.

Here’s the entire code sample: