Skip to content

Instantly share code, notes, and snippets.

@msinkec
Created December 14, 2023 13:15
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/06fd7a1c699bb480b6e4038fdb0fc314 to your computer and use it in GitHub Desktop.
Save msinkec/06fd7a1c699bb480b6e4038fdb0fc314 to your computer and use it in GitHub Desktop.
Deploy 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()
print(lockPub.to_hex())
alicePriv = PrivateKey("TODO")
alicePub = alicePriv.get_public_key()
# TODO: set values for input tx (P2WPKH)
txid = '495d504eadc55f33f755e04c8c6692d64333d82214d476a5481f6c67c5e89d73'
vout = 1
amount = 0.00002000
fee = 0.00000125
locktime = '10edba65'
# lock script:
lock_redeem_script = Script(
[ locktime,
'OP_CHECKLOCKTIMEVERIFY',
'OP_DROP',
lockPub.to_hex(),
'OP_CHECKSIG',
]
)
toaddress = P2wshAddress.from_script(lock_redeem_script)
# create transaction input from tx id of utxo
txin = TxInput(txid, vout)
redeem_script1 = Script(
['OP_DUP', 'OP_HASH160', alicePub.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'])
# create transaction output
txout = TxOutput(to_satoshis(amount - fee), toaddress.to_script_pub_key())
# create transaction
tx = Transaction([txin], [txout], has_segwit=True)
print("\nraw transaction (no witness data):\n" + tx.serialize())
sig1 = alicePriv.sign_segwit_input(tx, 0, redeem_script1, to_satoshis(amount))
tx.witnesses.append(Script([sig1, alicePub.to_hex()]))
# print raw signed transaction ready to be broadcasted
print("\nRaw signed transaction:\n" + tx.serialize())
print("\nTxId:", tx.get_txid())
#import hashlib
#lock_redeem_script_bytes = bytes.fromhex(lock_redeem_script.to_hex())
#sha256_hash = hashlib.sha256(lock_redeem_script_bytes)
#hash_bytes = sha256_hash.digest()
#hash_hex_string = hash_bytes.hex()
#print('\n\nWitness script', lock_redeem_script.to_hex())
#print('SHA-256 Hash:', hash_hex_string)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment