segregated witness – How do I exploit python-bitcoin-utils so as to add an OP_RETURN message right into a bitcoin transaction?

0
68


I’ve the next code that efficiently created a bitcoin transaction with python-bitcoin-utils:

from bitcoinutils.utils import to_satoshis
from bitcoinutils.setup import setup
from bitcoinutils.transactions import Transaction, TxInput, TxOutput
from bitcoinutils.script import Script
from bitcoinutils.keys import PrivateKey as utilPrivKey
from bitcoinutils.constants import SIGHASH_ALL, SIGHASH_ANYONECANPAY

setup('testnet')

# personal key for tb1qj6zz96g8xgrwpgmdlvmkrjlwzz54sf47086yc9
priv = utilPrivKey.from_wif('PRIVATE KEY FOR SENDING ADDRESS')

pub = priv.get_public_key().to_hex()
addrs_for_script = priv.get_public_key().get_address()

# personal key for tb1qxgm8j0cq7tnftef3t563psl56gtmzxanm5c9uy
recPrivKey = utilPrivKey.from_wif('PRIVATE KEY FOR RECEIVING ADDRESS')

# This UTXO has 0.00009839 btc
txin1 = TxInput("102172a062da813c3aa8cc2fb3d523cf2db300e54cd680c2129c23c97db9dd8e", 0)

# This UTXO has 0.00026859 btc
txin2 = TxInput("b3fcae0b28b387475a123c056298aec0ba3759cd019f9d0975f5af0874f395ff", 1)

addr = recPrivKey.get_public_key().get_segwit_address()
addr_non_seg = recPrivKey.get_public_key().get_address()

# the script code required for signing for p2wpkh is identical as p2pkh
script_code = Script(['OP_DUP', 'OP_HASH160', addrs_for_script.to_hash160(),
                        'OP_EQUALVERIFY', 'OP_CHECKSIG'])

# remaining 0.00005 is tx charges
txout = TxOutput(to_satoshis(0.00031698), addr.to_script_pub_key())

# create transaction from inputs/outputs -- default locktime is used
tx = Transaction([txin1, txin2], [txout], has_segwit=True)

txsign1 = priv.sign_segwit_input(tx, 0, script_code, to_satoshis(0.00009839), SIGHASH_ALL | SIGHASH_ANYONECANPAY)
tx.witnesses = [ Script([txsign1, pub]) ]

txsign2 = priv.sign_segwit_input(tx, 1, script_code, to_satoshis(0.00026859), SIGHASH_ALL)
tx.witnesses.append( Script([txsign2, pub]) )

signed_tx = tx.serialize()
print("uncooked tx under this line")
print(signed_tx)
print("uncooked tx above this line")

How would I modify this code to additionally add an OP_RETURN worth to the transaction?

LEAVE A REPLY

Please enter your comment!
Please enter your name here