3) src.js
Now we will add logic for parsing our Json file we grabbed from our Bitcoin full node. This will parse the hexadecimal witness data and output a text file with hexadecimal chunks sorted accordingly.
Locate
tx.json
file we grabbed from our Bitcoin full node. Place this in our project directoryMyDigitalArtifact
.Create a new file in the
MyDigitalArtifact
directory titledsrc.js
Insert the following code.
const fs = require('fs');
const bitcoinjs = require('bitcoinjs-lib');
const inputFile = 'tx.json';
const outputPath = 'DigitalArtifactParsed.txt';
function getOpName(op) {
for (let key in bitcoinjs.script.OPS) {
if (bitcoinjs.script.OPS[key] === op) {
return key;
}
}
return null;
}
function parseTx() {
const jsonContent = JSON.parse(fs.readFileSync(inputFile));
const witness = Buffer.from(jsonContent['vin'][0]['txinwitness'][1], 'hex');
let position = 0;
let opChunks = [];
while (position < witness.length) {
// Determine the next opcode's size
const opcode = witness[position];
position++;
if (opcode <= bitcoinjs.script.OPS.OP_PUSHDATA4) {
let size;
if (opcode < bitcoinjs.script.OPS.OP_PUSHDATA1) {
size = opcode;
} else if (opcode === bitcoinjs.script.OPS.OP_PUSHDATA1) {
size = witness.readUInt8(position);
position++;
} else if (opcode === bitcoinjs.script.OPS.OP_PUSHDATA2) {
size = witness.readUInt16LE(position);
position += 2;
} else {
size = witness.readUInt32LE(position);
position += 4;
}
opChunks.push(`OP_PUSHBYTES_${size} ${witness.slice(position, position + size).toString('hex')}`);
position += size;
} else {
// Map the opcode to its corresponding string representation
const opName = Object.keys(bitcoinjs.script.OPS).find(key => bitcoinjs.script.OPS[key] === opcode);
opChunks.push(opName);
}
}
// Write the results to a file
fs.writeFileSync(outputPath, opChunks.join('\\n'));
}
parseTx();
In your terminal window inside the directory run
node src.js
Last updated