Last active
June 21, 2016 07:50
-
-
Save bkawk/fc9c2e5eaf2b84a6e85dc86cfc73e447 to your computer and use it in GitHub Desktop.
Bitcoin Transaction with MetaData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Require the libraries we need to make this magic happen | |
var bitcoin = require(‘bitcoinjs-lib’); | |
var request = require(‘request’); | |
var blockchain = require(‘blockchain.info’); | |
var blockexplorer = require(‘blockchain.info/blockexplorer’); | |
// Export this module so you can easily call it from your main application | |
exports.opReturn = function (message, fromKey, toAddress) { | |
// Create a new promise that can only resolve or reject | |
return new Promise(function(resolve, reject) { | |
// Declare a few variables | |
var network = bitcoin.networks.mainnet; // Specify we want to use the main net not the test net | |
var keyPair = bitcoin.ECPair.fromWIF(fromKey); // Get the keypair from the WIF | |
var address = keyPair.getAddress(); // Get the address from the WIF | |
// Lets get the unspent tranasctins for the address | |
var url = "https://blockchain.info/id/unspent?active="+address; | |
request(url, function (error, response, body) { | |
if (!error && response.statusCode == 200) { | |
// Get the data back and parse it | |
var body = JSON.parse(body); | |
var tx = new bitcoin.TransactionBuilder(network); // Start to build the tranasction | |
var data = new Buffer(message); // Message is inserted | |
var dataScript = bitcoin.script.nullDataOutput(data); | |
// These must be atleast 9000 Satoshi to allow for 3000 for each recipient and 3000 for the miners fee | |
// You need to loop over and sum the value, here we just get the first two, I have a gist for this. | |
var unspent = body.unspent_outputs[1].tx_hash_big_endian; | |
var unspent = body.unspent_outputs[2].tx_hash_big_endian; | |
tx.addInput(unspent, 0); | |
// End Loop | |
// Build and sign the transaction | |
tx.addOutput(dataScript, 0); | |
tx.addOutput(toAddress, 3000); // Specify we want to send 3000 satoshi to another address | |
tx.addOutput(address, 3000); // Specify we want to send 3000 satoshi back to ourselves | |
tx.sign(0, keyPair); // Sign the transaction | |
var txRaw = tx.build(); // Raw transaction | |
var txId = txRaw.getId() // Transaction ID | |
var hex = txRaw.toHex(); //Convert the transction to hex ready for transmitting | |
// and push the transaction to the blockchain (please wait) | |
request.post("http://btc.blockr.io/api/v1/tx/push").form({hex:hex}); | |
resolve(hex); // Resolve the promise | |
} else{ | |
reject(error); // Reject the poromise | |
}; | |
}) | |
}); // — END PROMISE | |
};// END FUNCTION |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment