Skip to content

Instantly share code, notes, and snippets.

@assafshomer
Created March 10, 2016 11:08
Show Gist options
  • Save assafshomer/bda3076d48cf66a588f6 to your computer and use it in GitHub Desktop.
Save assafshomer/bda3076d48cf66a588f6 to your computer and use it in GitHub Desktop.
bitcoinjs-lib txid
var bitcoin = require('bitcoinjs-lib')
var keyPair = bitcoin.ECPair.makeRandom()
// Print your private key (in WIF format)
console.log(keyPair.toWIF())
// => Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct
// Print your public key address
console.log(keyPair.getAddress())
// => 14bZ7YWde4KdRb5YN7GYkToz3EHVCvRxkF
var tx = new bitcoin.TransactionBuilder()
// Add the input (who is paying):
// [previous transaction hash, index of the output to use]
var txId = 'aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31'
tx.addInput(txId, 0)
// Add the output (who to pay to):
// [payee's address, amount in satoshis]
tx.addOutput("1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK", 15000)
// Initialize a private key using WIF
var privateKeyWIF = 'L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'
var keyPair = bitcoin.ECPair.fromWIF(privateKeyWIF)
// Sign the first input with the new key
tx.sign(0, keyPair)
result = tx.build()
// Print transaction serialized as hex
console.log(result.toHex())
// => 0100000001313eb630b128102b60241ca895f1d0ffca21 ...
// Calculate Transaction ID
var txid = bitcoin.bufferutils.reverse(result.getHash()).toString('hex')
console.log('txid',txid)
// You could now push the transaction onto the Bitcoin network manually
// (see https://blockchain.info/pushtx)
@Ranguna
Copy link

Ranguna commented Sep 15, 2018

I can't find bufferutils in the latest bitcoinjs so here's another way to do it.
Tx hashes are just "reversed bytes" of the double sha256 hash of the hex:

rawtx.build().getHash().hexSlice().match(/../g).reverse().join("")

Here we are splitting the hex hash into two 2 byte hex string (or 1 byte hash buffer) groups and reversing them, pretty simple 👌

@wesleyfsmith
Copy link

Thanks to both of you for this! Very useful for checking if a tx has already been broadcast and our application needs to re sync.

@samanyousefi
Copy link

inline: 16 you write a txId (var txId = 'aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31')
but i cant understand how i can create this txtid with bitcoinjs-lib module or another things, and finaly i work with a 3rth party web site like blockcypher, please say how i should create txId

@gabmontes
Copy link

gabmontes commented Jul 25, 2024

This gist is only valid up to bitcoinjs-lib@5 as TransactionBuilder was removed in version 6 in favor of Psbt.

See: https://github.com/bitcoinjs/bitcoinjs-lib/blob/v6.0.0/CHANGELOG.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment