|
| 1 | +const bitcoin = require('bitcoinjs-lib'); |
| 2 | +const classify = require('bitcoinjs-lib/src/classify'); |
| 3 | + |
| 4 | +const decodeFormat = (tx) => ({ |
| 5 | + txid: tx.getId(), |
| 6 | + version: tx.version, |
| 7 | + locktime: tx.locktime, |
| 8 | +}); |
| 9 | + |
| 10 | +const decodeInput = function (tx) { |
| 11 | + const result = []; |
| 12 | + tx.ins.forEach(function (input, n) { |
| 13 | + result.push({ |
| 14 | + txid: input.hash.reverse().toString('hex'), |
| 15 | + n: input.index, |
| 16 | + script: bitcoin.script.toASM(input.script), |
| 17 | + sequence: input.sequence, |
| 18 | + }); |
| 19 | + }); |
| 20 | + return result; |
| 21 | +}; |
| 22 | + |
| 23 | +const decodeOutput = function (tx, network) { |
| 24 | + const format = function (out, n, network) { |
| 25 | + const vout = { |
| 26 | + satoshi: out.value, |
| 27 | + value: (1e-8 * out.value).toFixed(8), |
| 28 | + n: n, |
| 29 | + scriptPubKey: { |
| 30 | + asm: bitcoin.script.toASM(out.script), |
| 31 | + hex: out.script.toString('hex'), |
| 32 | + type: classify.output(out.script), |
| 33 | + addresses: [], |
| 34 | + }, |
| 35 | + }; |
| 36 | + switch (vout.scriptPubKey.type) { |
| 37 | + case 'pubkeyhash': |
| 38 | + case 'scripthash': |
| 39 | + vout.scriptPubKey.addresses.push(bitcoin.address.fromOutputScript(out.script, network)); |
| 40 | + break; |
| 41 | + case 'witnesspubkeyhash': |
| 42 | + case 'witnessscripthash': |
| 43 | + const data = bitcoin.script.decompile(out.script)[1]; |
| 44 | + vout.scriptPubKey.addresses.push(bitcoin.address.toBech32(data, 0, network.bech32)); |
| 45 | + break; |
| 46 | + } |
| 47 | + return vout; |
| 48 | + }; |
| 49 | + |
| 50 | + const result = []; |
| 51 | + tx.outs.forEach(function (out, n) { |
| 52 | + result.push(format(out, n, network)); |
| 53 | + }); |
| 54 | + return result; |
| 55 | +}; |
| 56 | + |
| 57 | +class TxDecoder { |
| 58 | + constructor(rawTx, network = bitcoin.networks.bitcoin) { |
| 59 | + this.tx = bitcoin.Transaction.fromHex(rawTx); |
| 60 | + this.format = decodeFormat(this.tx); |
| 61 | + this.inputs = decodeInput(this.tx); |
| 62 | + this.outputs = decodeOutput(this.tx, network); |
| 63 | + } |
| 64 | + |
| 65 | + decode() { |
| 66 | + const result = {}; |
| 67 | + const self = this; |
| 68 | + Object.keys(self.format).forEach(function (key) { |
| 69 | + result[key] = self.format[key]; |
| 70 | + }); |
| 71 | + result.outputs = self.outputs; |
| 72 | + result.inputs = self.inputs; |
| 73 | + return result; |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +module.exports.decodeRawHex = (rawTx, network = bitcoin.networks.bitcoin) => { |
| 78 | + return new TxDecoder(rawTx, network).decode(); |
| 79 | +}; |
0 commit comments