Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Last active August 29, 2023 10:44
Show Gist options
  • Save cgcardona/a7366e28c6186f722df7658ab767e16b to your computer and use it in GitHub Desktop.
Save cgcardona/a7366e28c6186f722df7658ab767e16b to your computer and use it in GitHub Desktop.
Bitcoin Cash P2SH input -> P2PKH output example w/ BITBOX
const mnemonic = "";
// root seed buffer
const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic);
// master HDNode
const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "bitcoincash");
// HDNode of BIP44 account
const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'");
// derive HDNode
const node = BITBOX.HDNode.derivePath(account, "0/0");
const cashAddress = BITBOX.HDNode.toCashAddress(node);
const 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
const p2sh_hash160 = BITBOX.Crypto.hash160(script);
// encode hash160 as P2SH output
const scriptPubKey = BITBOX.Script.scriptHash.output.encode(p2sh_hash160);
// get p2sh address from output script
const p2shAddress = BITBOX.Address.fromOutputScript(scriptPubKey);
BITBOX.Address.utxo(p2shAddress).then(result => {
if (!result[0]) return;
const transactionBuilder = new BITBOX.TransactionBuilder();
// original amount of satoshis in vin
const originalAmount = result[0].satoshis;
// index of vout
const vout = result[0].vout;
// txid of vout
const txid = result[0].txid;
// return false;
// create instance of Transaction Builder class
transactionBuilder.addInput(txid, vout);
// set fee and send amount
let fee = 550;
let sendAmount = originalAmount - fee;
// add output
transactionBuilder.addOutput(cashAddress, sendAmount);
// encode locking script
let encodedScript = BITBOX.Script.encode(script);
// HDNode to keypair
let keyPair = BITBOX.HDNode.toKeyPair(node);
// create unlocking script
let script2 = [Buffer.from("BIT", "ascii")];
// concat scripts together
let children = script2.concat(script);
// encode scripts
let encodedScript2 = BITBOX.Script.encode(children);
// set input script
transactionBuilder.addInputScript(vout, encodedScript2);
// to hex
// let hex = tx.toHex();
const hex = transactionBuilder.build().toHex();
// POST to BCH network
BITBOX.RawTransactions.sendRawTransaction(hex).then(
result => {
console.log(result);
},
err => {
console.log(err);
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment