Created
November 24, 2017 22:26
-
-
Save coinables/c9f853ad863de09df006ad03e1f297e7 to your computer and use it in GitHub Desktop.
SegWit Private Key Sweep in NodeJS With BitcoinJS
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
var bitcoin = require("bitcoinjs-lib"); | |
var request = require("request"); | |
//push transaction | |
function pushTX(pload, callback){ | |
request({ | |
url: "https://api.blockcypher.com/v1/btc/main/txs/push", | |
method: "POST", | |
json: true, | |
headers: {"content-type": "application/json"}, | |
body: pload | |
}, function(err, response, body){ | |
if(err){ | |
//no response or error POST to chainso | |
console.log(body); | |
callback("failed"); | |
} else { | |
console.log(JSON.stringify(body)); | |
callback(JSON.stringify(body)); | |
}; | |
}); | |
}; | |
function p2shWitSweep(privkey, addressout, callback){ | |
var NETWORK = bitcoin.networks.bitcoin; | |
var keyPair = bitcoin.ECPair.fromWIF(privkey, NETWORK); | |
var pubKey = keyPair.getPublicKeyBuffer(); | |
var pubKeyHash = bitcoin.crypto.hash160(pubKey); | |
var redeemScript = bitcoin.script.witnessPubKeyHash.output.encode(pubKeyHash); | |
var redeemScriptHash = bitcoin.crypto.hash160(redeemScript); | |
var scriptPubKey = bitcoin.script.scriptHash.output.encode(redeemScriptHash); | |
var address = bitcoin.address.fromOutputScript(scriptPubKey, NETWORK); | |
var txb = new bitcoin.TransactionBuilder(NETWORK); | |
request({ | |
url: "https://api.smartbit.com.au/v1/blockchain/address/"+address+"/unspent", | |
json: true | |
}, function(err, resp, data){ | |
//fetch utxo | |
var numutxo = data.unspent.length; | |
console.log("utxos: "+numutxo); | |
var totalVal = 0; | |
for(i=0; i<numutxo; i++){ | |
totalVal += data.unspent[i].value_int; | |
txb.addInput(data.unspent[i].txid, data.unspent[i].n); | |
} | |
//calc fee and add output address | |
var satoshifees = numutxo * 7000; | |
var amountToSend = totalVal - satoshifees; | |
txb.addOutput(addressout, amountToSend); | |
//sign each input | |
for(i=0; i<numutxo; i++){ | |
txb.sign(i, keyPair, redeemScript, null, data.unspent[i].value_int); | |
} | |
//build tx | |
var tx = txb.build(); | |
var tx_txid = tx.getId(); | |
var tx_raw = tx.toHex(); | |
var pload = { | |
"tx": tx_raw.toString() | |
}; | |
console.log("hextx: "+tx_raw); | |
//broadcast | |
pushTX(pload, function(result){ | |
console.log(result); | |
callback(result); | |
}); | |
}); | |
} | |
p2shWitSweep("L28QQ43mQMPZj2vxFKbELC9rnudcmkwhjqHJ5tDNStqtbZkUeg7k", "17v9bcxrrKF4V2uyRtZR9QHRRcMFvG7pdq", function(txdata){ | |
console.log("Output: "+txdata); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment