Skip to content

Instantly share code, notes, and snippets.

@ottosch
Created December 14, 2023 13:56
Show Gist options
  • Save ottosch/ff84abd92107b0d8b6d90e5b76c62915 to your computer and use it in GitHub Desktop.
Save ottosch/ff84abd92107b0d8b6d90e5b76c62915 to your computer and use it in GitHub Desktop.
Extracts JPEG from transaction 033d185d1a04c4bd6de9bb23985f8c15aa46234206ad29101c31f4b33f1a0e49
#! /usr/bin/env node
const { Transaction } = require("bitcoinjs-lib");
const fs = require("fs");
const inputFile = "txhex";
const outputFile = "output.bin";
let hex = fs.readFileSync(inputFile, "utf8");
let tx = Transaction.fromHex(Buffer.from(hex, "hex"));
let data = Buffer.alloc(0);
for (let input of tx.ins) {
let script = input.script;
let cursor = 0;
while (cursor < script.length) {
let opcode = script[cursor];
cursor++;
if (opcode === 0x4c) {
let size = script.readUIntLE(cursor, 1);
cursor += 1;
let chunk = script.subarray(cursor, cursor + size);
data = Buffer.concat([data, chunk]);
cursor += size;
} else if (opcode === 0x4d) {
let size = script.readUIntLE(cursor, 2);
cursor += 2;
let chunk = script.subarray(cursor, cursor + size);
data = Buffer.concat([data, chunk]);
cursor += size;
} else if (opcode >= 0x01 && opcode <= 0x4b) {
break; // redeem script
} else {
console.error(`unexpected opcode: ${opcode.toString(16)}`);
process.exit(1);
}
}
}
fs.writeFileSync(outputFile, data);
console.log(`wrote: ${data.length} bytes to ${outputFile}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment