Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// atomicSwapContract returns an output script that may be redeemed by one of
// two signature scripts:
//
// <their sig> <their pubkey> <initiator secret> 1
//
// <my sig> <my pubkey> 0
//
// The first signature script is the normal redemption path done by the other
// party and requires the initiator's secret. The second signature script is
// the refund path performed by us, but the refund can only be performed after
// locktime.
func atomicSwapContract(pkhMe, pkhThem *[ripemd160.Size]byte, locktime int64, secretHash []byte) ([]byte, error) {
b := txscript.NewScriptBuilder()
b.AddOp(txscript.OP_IF) // Normal redeem path
{
// Require initiator's secret to be a known length that the redeeming
// party can audit. This is used to prevent fraud attacks between two
// currencies that have different maximum data sizes.
b.AddOp(txscript.OP_SIZE)
b.AddInt64(secretSize)
b.AddOp(txscript.OP_EQUALVERIFY)
// Require initiator's secret to be known to redeem the output.
b.AddOp(txscript.OP_SHA256)
b.AddData(secretHash)
b.AddOp(txscript.OP_EQUALVERIFY)
// Verify their signature is being used to redeem the output. This
// would normally end with OP_EQUALVERIFY OP_CHECKSIG but this has been
// moved outside of the branch to save a couple bytes.
b.AddOp(txscript.OP_DUP)
b.AddOp(txscript.OP_HASH160)
b.AddData(pkhThem[:])
}
b.AddOp(txscript.OP_ELSE) // Refund path
{
// Verify locktime and drop it off the stack (which is not done by
// CLTV).
b.AddInt64(locktime)
b.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
b.AddOp(txscript.OP_DROP)
// Verify our signature is being used to redeem the output. This would
// normally end with OP_EQUALVERIFY OP_CHECKSIG but this has been moved
// outside of the branch to save a couple bytes.
b.AddOp(txscript.OP_DUP)
b.AddOp(txscript.OP_HASH160)
b.AddData(pkhMe[:])
}
b.AddOp(txscript.OP_ENDIF)
// Complete the signature check.
b.AddOp(txscript.OP_EQUALVERIFY)
b.AddOp(txscript.OP_CHECKSIG)
return b.Script()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment