Created
November 3, 2018 03:28
-
-
Save cgcardona/f72dcd476b9860bfaeba431f4a576eb8 to your computer and use it in GitHub Desktop.
BITBOX script to create a P2SH output w/ a custom script
This file contains 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
let BITBOXCli = require("bitbox-sdk/lib/bitbox-sdk").default; | |
let BITBOX = new BITBOXCli(); | |
let main = async () => { | |
let mnemonic = "put your mnemonic here"; | |
// root seed buffer | |
let rootSeed = BITBOX.Mnemonic.toSeed(mnemonic); | |
// master HDNode | |
let masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "bitcoincash"); | |
// HDNode of BIP44 account | |
let account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'"); | |
// derive HDNode | |
let node = BITBOX.HDNode.derivePath(account, "0/0"); | |
// cashAddress | |
let cashAddress = BITBOX.HDNode.toCashAddress(node); | |
// get utxo from rest.bitcoin | |
let result = await BITBOX.Address.utxo(cashAddress); | |
// create instance of TransactionBuilder | |
let transactionBuilder = new BITBOX.TransactionBuilder(); | |
// original amount | |
let originalAmount = result[0].satoshis; | |
// index of vout | |
let vout = result[0].vout; | |
// txid of vout | |
let txid = result[0].txid; | |
// add input | |
transactionBuilder.addInput(txid, vout); | |
// calculate tx size for 1 sat/b fee | |
let byteCount = BITBOX.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: 2 }); | |
let sendAmount = originalAmount - byteCount; | |
// encode custom script | |
let script = BITBOX.Script.encode([ | |
Buffer.from("BOX", "ascii"), | |
BITBOX.Script.opcodes.OP_CAT, | |
Buffer.from("BITBOX", "ascii"), | |
BITBOX.Script.opcodes.OP_EQUAL | |
]); | |
// hash160 script buffer | |
let p2sh_hash160 = BITBOX.Crypto.hash160(script); | |
// encode hash160 as P2SH output | |
let scriptPubKey = BITBOX.Script.scriptHash.output.encode(p2sh_hash160); | |
// derive address from P2SH output | |
let address = BITBOX.Address.fromOutputScript(scriptPubKey); | |
// add output | |
transactionBuilder.addOutput(address, sendAmount); | |
// HDNode to keypair | |
let key = BITBOX.HDNode.toKeyPair(node); | |
// empty redeemScript var | |
let redeemScript; | |
// sign input | |
transactionBuilder.sign( | |
0, | |
key, | |
redeemScript, | |
transactionBuilder.hashTypes.SIGHASH_ALL, | |
originalAmount | |
); | |
// build to hex | |
let hex = transactionBuilder.build().toHex(); | |
// POST to BCH network | |
let success = await BITBOX.RawTransactions.sendRawTransaction(hex); | |
console.log("success: ", success); | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment