How would one decode an OP_RETURN output message?
I successfully created an OP_RETURN output using the following example:
const data = Buffer.from("message", "utf8");
const embed = bitcoin.payments.embed({ data: [data] });
txb.addOutput(embed.output, 0);
However, I'm not sure how to decode the OP_RETURN message on the other end:
"value": 0.00000000,
"n": 0,
"scriptPubKey": {
"asm": "OP_RETURN 596f7527726520612077697a6172642c2048617272792e",
"hex": "6a17596f7527726520612077697a6172642c2048617272792e",
"type": "nulldata"
}
Does bitcoinjs-lib have a method that would allow for this? Similar to how this service managed to decode it in the "Script [bin]" field, (https://blockchair.com/bitcoin/address/d-0fc560df0773c2d96719f0aa5c37f3f8).
Thank you.
I figured it out!
let asm = "OP_RETURN 596f7527726520612077697a6172642c2048617272792e";
if (asm.includes("OP_RETURN")) {
asm = asm.replace("OP_RETURN", "");
asm = asm.trim();
}
const asmBuffer = new Buffer(asm, "hex");
const message = asmBuffer.toString();
console.log(message);
I'm still learning so if this is not the standard/best approach please let me know.
OP_RETURN can have multiple pieces of data, (hence why data is an array) which when shown as asm will be separated with a space. That will break your code.
Okay, I think I understand. So it may make more sense to split the string like so to capture each piece of potential data:
const asm = "OP_RETURN 596f7527726520612077697a6172642c2048617272792e";
let messages = [];
const data = asm.split(" ");
data.forEach((message) => {
message = new Buffer(message, "hex");
message = message.toString();
messages.push(message);
});
console.log(messages);
That would fail since the string "OP_RETURN" is not hex.
Understood. So I would need to check if the message is hex before proceeding within the forEach. Thanks, Jonathan! And thanks for your many other comments throughout this repo. You've definitely helped me more than once.