Hello!
Is it possible to use this module in order to parse raw transaction data and get destination Bitcoin addresses from it?
I've managed to parse raw transaction from hex string:
const bitcoinJs = require('bitcoinjs-lib');
const rawTx = '010...000';
const tx = bitcoinJs.Transaction.fromHex(rawTx);
console.log(JSON.stringify(tx, null, 4));
But how do I get destinations addresses from it?
Thank you.
Well, looks like I've finally managed to extract address from script output.
Here's my implementation:
const _ = require('lodash');
const bitcoinJs = require('bitcoinjs-lib');
const Buffer = require('buffer').Buffer;
const rawTx = '010...000';
const tx = bitcoinJs.Transaction.fromHex(rawTx);
_.forEach(tx.outs, out => {
if (bitcoinJs.script.isPubKeyHashOutput(out.script)) {
const pubKey = Buffer.from(out.script, 3, 20);
const address = bitcoinJs.address.fromOutputScript(pubKey);
console.log(address);
}
});
Is this a most optimal way to do this? Do you have any suggestions of how I can improve it?
Is it enough to only check for PubKeyHashOutput for general transactions? Or do I need to implement some other script types also?
The library is very well written, it was a pleasure reading it's source code. Great job!
Thanks.
Don't forget about script-hash outputs, they also have an address!
let bitcoinjs = require('bitcoinjs-lib')
// ...
let tx = bitcoinjs.Transaction.fromHex('010...000')
tx.outs.forEach((out) => {
let address
try {
address = bitcoinjs.address.fromOutputScript(out.script)
} catch (e) {}
if (address) console.log(address)
})
@afk11 to be honest, I do the above so often, I'd rather just have no error thrown and instead return null...
Maybe fromOutputScriptUnsafe
It seems most people do this too, or they have some other assumption that means they can rely on it not throwing.
In any case, I think null would avoid the try/catch boiler plate.
https://github.com/xorq/easybtc/blob/46c8821cee303aed829160fd50eb2269e290a9d4/models/crypto.js#L432
https://github.com/darkwallet/darkwallet/blob/4c51dacacb8541305f1442ef7fa1628eb7c19a79/src/js/frontend/controllers/browser.js#L56
https://github.com/CoinSpace/cs-wallet/blob/ee49f55018dc2b275a799682c6343a474b69b51d/lib/wallet.js#L158
https://github.com/blocktrail/blocktrail-webwallet/blob/f87fb007c918c723d9de206e0c28238211f7a7a1/src/lib/blocktrail-sdk/lib/wallet.js#L298
The only question is whether we make a new method to avoid breaking people who upgrade without looking at the CHANGELOG.
Oh, thank you @dcousens . Is bitcoinjs.address.fromOutputScript(out.script) enough to parse all commonly used transaction types?
@maxsummers it is enough to obtain an "address" from the 2 commonly used script types that have addresses: P2PKH, P2SH.
It does not support stealth addresses, or other complex ECDH protocols.
Thank you, this really helps.
Most helpful comment
@afk11 to be honest, I do the above so often, I'd rather just have no error thrown and instead return
null...Maybe
fromOutputScriptUnsafe