karask / python-bitcoin-utils

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

Calculating script hash from P2TR address, its public key or Script #65

Closed ongrid closed 3 months ago

ongrid commented 3 months ago

Does your library provide native conversion from p2tr address to its scripthash? I need this for querying Electrumx indexer to discover unspent UTXOs belonging to P2TR address but didn't find more elegant way to do this than using custom hashlib-based function:

from pycoin.symbols.btc import network as btc_mainnet
from pycoin.symbols.xtn import network as btc_testnet
import hashlib

def get_script_hash(addr, network="mainnet"):
    if network == "mainnet":
        pycsymbol = btc_mainnet
    elif network == "testnet":
        pycsymbol = btc_testnet
    script = pycsymbol.parse.address(addr).script()
    return hashlib.sha256(script).digest()[::-1].hex()
karask commented 3 months ago

The hash of the script is probably used in Electrumx to uniquely identify (for indexing purposes) the script.

Afaik it is not used in the Bitcoin protocol and thus the library does not support it. The way you calculate it above seems OK to me. Just send that to electrumx.

ongrid commented 3 months ago

Thanks for the explanation. I will keep this function within my sandbox 1