Skip to content

Instantly share code, notes, and snippets.

@msinkec
Created December 14, 2023 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msinkec/e1495c02a524596ae5ff7b99d33bc52b to your computer and use it in GitHub Desktop.
Save msinkec/e1495c02a524596ae5ff7b99d33bc52b to your computer and use it in GitHub Desktop.
Redeem time-locked BTC transaction
from bitcoinutils.setup import setup
from bitcoinutils.utils import to_satoshis
from bitcoinutils.transactions import Transaction, TxInput, TxOutput
from bitcoinutils.keys import PrivateKey, P2wshAddress, P2wpkhAddress
from bitcoinutils.script import Script
def main():
# always remember to setup the network
setup('testnet')
lockPriv = PrivateKey("TODO")
lockPub = lockPriv.get_public_key()
# TODO: set values
txid = 'TODO'
vout = 0
amount = 0.00001725
fee = 0.00000140
locktime = '10edba65'
# lock Script:
lock_redeem_script = Script(
[ locktime,
'OP_CHECKLOCKTIMEVERIFY',
'OP_DROP',
lockPub.to_hex(),
'OP_CHECKSIG',
]
)
fromAddress = P2wshAddress.from_script(lock_redeem_script)
print(fromAddress.to_string())
toAddress = P2wpkhAddress.from_address(
"TODO")
# create transaction input from tx id of UTXO
txin = TxInput(txid, vout)
txOut1 = TxOutput(to_satoshis(amount - fee), toAddress.to_script_pub_key())
tx = Transaction([txin], [txOut1], has_segwit=True)
# Normal unlock:
sig1 = lockPriv.sign_segwit_input(tx, 0, lock_redeem_script, to_satoshis(amount))
tx.witnesses.append(Script([
sig1,
lock_redeem_script.to_hex()]))
print(tx.inputs)
# print raw signed transaction ready to be broadcasted
print("\nRaw signed transaction:\n" + tx.serialize())
print("\nTxId:", tx.get_txid())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment