Skip to content

Instantly share code, notes, and snippets.

@osoftware
Last active August 31, 2019 12:02
Show Gist options
  • Save osoftware/d7c5ef4d23e253f28e7d1533c66dc4f2 to your computer and use it in GitHub Desktop.
Save osoftware/d7c5ef4d23e253f28e7d1533c66dc4f2 to your computer and use it in GitHub Desktop.
Bitcoin Cash Covenant with Spedn
import { BITBOX } from "bitbox-sdk";
import { SigHash, Spedn, TxBuilder } from "spedn";
async function main() {
// BITBOX boilerplace
const bitbox = new BITBOX();
const mnemonic = "draw parade crater busy book swim soldier tragic exit feel top civil";
const wallet = bitbox.HDNode.fromSeed(bitbox.Mnemonic.toSeed(mnemonic));
const alice = bitbox.HDNode.derivePath(wallet, "m/44'/145'/0'/0/0");
// Compile a contract that checks that the provided preimage matches the tx preimage.
const compiler = new Spedn();
const Covenant = await compiler.compileCode(`
contract Covenant(Ripemd160 alice) {
challenge spend(Sig sig, PubKey pubKey, bin preimage) {
verify hash160(pubKey) == alice;
verify checkSig(sig, pubKey);
verify checkDataSig(toDataSig(sig), sha256(preimage), pubKey);
// here go the actual covenant conditions...
}
}
`);
compiler.dispose();
// Instantiate the contract for Alice's key.
const covenant = new Covenant({
alice: alice.getIdentifier()
});
// Find Alice's coins
const coins = await covenant.findCoins("mainnet");
// Spend all Alice's coint to a new address (500000 sat) and the change back to the covenant.
const txid = await new TxBuilder("mainnet")
.from(coins, (input, context) =>
input.spend({
sig: context.sign(alice.keyPair, SigHash.SIGHASH_ALL),
pubKey: alice.getPublicKeyBuffer(),
preimage: context.preimage(SigHash.SIGHASH_ALL)
})
)
.to("bitcoincash:qrc2jhalczuka8q3dvk0g8mnkqx79wxp9gvvqvg7qt", 500000)
.to(covenant.getAddress("mainnet"))
.broadcast();
console.log(txid);
}
main();
{
"name": "bitbox-example",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"private": true,
"dependencies": {
"bitbox-sdk": "^8.5.1",
"spedn": "^0.1.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment