karask / python-bitcoin-utils

Library to interact with the Bitcoin network. Ideal for low-level learning and experimenting.
MIT License
287 stars 104 forks source link

Craft P2TR rawtx #46

Closed MarshmallowCrypto closed 1 year ago

MarshmallowCrypto commented 1 year ago

Hey,

In the redme file it says this " Spend from a taproot address https://github.com/karask/python-bitcoin-utils/blob/master/examples/spend_p2tr_default_path.py - single input, single output default key path spending. "

But in that file there is nothing about spening from a P2TR address. Its just transaction from and to a P2pkhAddress. I have been looking for a python code to craft raw transactions for P2RT addresses but havent been able to find it. I was able to use your wallet generation code like this to craft the P2TR taproot address. But I really need a code on how to then make raw transcations and sign them using taproot address.

def generate_bitcoin_data():
    # Setup the environment for mainnet
    setup('mainnet')

    # Create a truly random private key
    priv = PrivateKey()

    # Get the public key
    pub = priv.get_public_key()

    # Get Taproot address and related details
    address_taproot = pub.get_taproot_address()

    return {
        "private_key_wif": priv.to_wif(compressed=True),
        "public_key": pub.to_hex(compressed=True),
        "taproot_address": address_taproot.to_string(),
        "taproot_witness_program": address_taproot.to_witness_program(),
        "segwit_version": address_taproot.get_type()
    }

Do you have it or know where I can find a code for that?

karask commented 1 year ago

The file you linked spends a taproot output using the key spending path. Note the use of 'sign_taproot_output' and the parameters it takes, i.e. spending taproot.

For spending a P2PKH output see https://github.com/karask/python-bitcoin-utils/blob/master/examples/p2pkh_transaction.py

MarshmallowCrypto commented 1 year ago

But I am looking to spend p2tr not p2pkh

karask commented 1 year ago

Please read my previous reply carefully. I linked a P2PKH example so that you see the differences from the file you linked.

Example https://github.com/karask/python-bitcoin-utils/blob/master/examples/spend_p2tr_default_path.py (that you linked initially) spends a UTXO with txid 7b6412a0eed56338731e83c606f13ebb7a3756b3e4e1dbbe43a7db8d09106e56 and the second output (the one with 5000 sats). That is a taproot address.

Study it carefully to see what is happening.