Node.js encode/decode hex and publishing data to the bitcoin blockchain
Okay so I'm trying to publish data on the bitcoin blockchain from bash using createrawtransaction and decoderawtransaction and here's what I've learned. Hopefully this will save someone from suffering.
How to encode and decode hex strings and decimals in Node.js
String to hex
Buffer(str).toString('hex')
hex to string
Buffer(hexstr, 'hex').toString()
decimal to hex
(5).toString(16)
hex to decimal
parseInt('4e', 16)
How to create a data transaction in Node.js with OP_RETURN
This SO question helped a lot.
I'm not going to repeat everything that's already said there, but a few pointers:
- If you don't use the
dummy_addresshe gives then this method will not work. - Don't even try putting the data straight into
createrawtransaction, it's not possible. - Unless you're using bitcoin version 0.11 or newer, then all you need to do is put
{"data": "your hexified data"}intovout- much easier. child_process.execFileis much safer and maybe even more confy thanchild_process.exec, BUTdecoderawtransactiondoesn't seem wo work for me withexecFile.moveis notsend. The former only moves numbers between accounts on your local machine. Send actually creates a transaction.
Summary
Always check the version of software you're using :) This has been a terrible week and getting the thing to work feels like I've broken through a brick wall.