<p>You can use <a href="https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py" rel="nofollow noreferrer">the reference Python implementation of bech32 / bech32m</a>. Decode the address using <a href="https://github.com/sipa/bech32/blob/7a7d7ab158db7078a333384e0e918c90dbc42917/ref/python/segwit_addr.py#L73-L89" rel="nofollow noreferrer"><code>bech32_decode</code></a> and get the human readable part, data encoded (the scriptPubKey you are looking for), and whether this address is bech32 or bech32m.</p>

CC BY-SA 4.0
2023-05-04T08:14:44.850Z
2023-05-04T08:14:44.850Z
Antoine Poinsot
<p>The scriptpubkey for a P2WPKH address is <code>0x0014{20-byte-key-hash}</code> (from <a href="https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wpkh" rel="nofollow noreferrer">bip141</a>)</p>
<p>You get the keyhash by decoding the address from the bech32 encoding.</p>
<p>You can use <a href="https://github.com/mcdallas/cryptotools/blob/dbdced863bd2622f4cb41595df1ecad399760d78/cryptotools/BTC/address.py#L175C1-L176" rel="nofollow noreferrer">this</a> library (I am the author) to do that or to construct the spending output.</p>
<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; from cryptotools import Address

&gt;&gt;&gt; addr = Address('bc1qh2egksgfejqpktc3kkdtuqqrukrpzzp9lr0phn')
&gt;&gt;&gt; addr.type()
&lt;ADDRESS.P2WPKH: 'P2WPKH'&gt;

&gt;&gt;&gt; output = addr._receive(50_000_000)
&gt;&gt;&gt; output.script.hex()
'0014bab28b4109cc801b2f11b59abe0003e586110825'
</code></pre>

CC BY-SA 4.0
2023-05-03T22:58:45.940Z
Thanks for the answer, my address is a segwit_v1 (bech32m). Will cryptotools work with that? And would the answer need to be modified in that case?
ChristianOConnor
CC BY-SA 4.0
2023-05-03T23:02:25.750Z
Oops sorry I missed that, no taproot support yet.
Mike D
CC BY-SA 4.0
2023-05-03T23:06:24.770Z
No problem, thanks for trying
ChristianOConnor
CC BY-SA 4.0
2023-05-03T22:56:18.480Z
2023-05-03T22:56:18.480Z
Mike D
<p>I have this function that converts a Bitcoin private key as an integer to a public key and an address.</p>
<pre><code>def get_seg_v1_from_pkey(imported_key):
    imported_key_toint = int(imported_key)
    privKeytoHex = imported_key_toint.to_bytes(32, 'big').hex()
    prv = HDKey(privKeytoHex)
    prv_tnet = TNetHDKey(privKeytoHex)
    pubkey = prv.public_hex
    pub_tnet = prv_tnet.public_hex
    version = 0x01
    address = program_to_witness(version, pubkey[2:], main=True)
    address_testnet = pubkeyhash_to_addr_bech32(pubkeyhash=pub_tnet[2:], prefix='tb', witver=1, separator='1', checksum_xor=0x2bc830a3)
    return pubkey, address, address_testnet  
</code></pre>
<p>HDKey imports the integer into a proper private key object like what is used in <a href="https://github.com/bitcoinops/taproot-workshop" rel="nofollow noreferrer">https://github.com/bitcoinops/taproot-workshop</a>. TNetHDKey is a custom function I wrote that does the same thing as HDKey but it stores the private key in a way that makes it easily convertible to a testnet address.</p>
<p>I want to get the scriptPubKey from an address like in this function in <a href="https://github.com/bitcoinops/taproot-workshop" rel="nofollow noreferrer">https://github.com/bitcoinops/taproot-workshop</a>:</p>
<pre><code>def create_spending_transaction(self, txid, version=1, nSequence=0):
    &quot;&quot;&quot;Construct a CTransaction object that spends the first ouput from txid.&quot;&quot;&quot;
    # Construct transaction
    spending_tx = CTransaction()

    # Populate the transaction version
    spending_tx.nVersion = version

    # Populate the locktime
    spending_tx.nLockTime = 0

    # Populate the transaction inputs
    outpoint = COutPoint(int(txid, 16), 0)
    spending_tx_in = CTxIn(outpoint=outpoint, nSequence=nSequence)
    spending_tx.vin = [spending_tx_in]

    # Generate new Bitcoin Core wallet address
    dest_addr = self.nodes[0].getnewaddress(address_type=&quot;bech32&quot;)
    scriptpubkey = bytes.fromhex(self.nodes[0].getaddressinfo(dest_addr)['scriptPubKey'])

    # Complete output which returns 0.5 BTC to Bitcoin Core wallet
    amount_sat = int(0.5 * 100_000_000)
    dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
    spending_tx.vout = [dest_output]

    return spending_tx  
</code></pre>
<p>Notice these lines in the above function:</p>
<pre><code># Generate new Bitcoin Core wallet address
dest_addr = self.nodes[0].getnewaddress(address_type=&quot;bech32&quot;)
scriptpubkey = bytes.fromhex(self.nodes[0].getaddressinfo(dest_addr)['scriptPubKey'])  
</code></pre>
<p><code>self.nodes[0]</code> refers to a running instance of bitcoind on your computer. I want to replicate this function without requiring a running instance of bitcoind. In my version of this function I plan on passing in <code>dest_addr</code> because I won't have a bitcoind instance to generate it. Is there a way to get a scriptPubKey from a raw segwit v1 address?</p>

<address><taproot><bech32-address><p2tr><bip350-bech32m>
Get the scriptPubKey from a Taproot address
ChristianOConnor
# Get the scriptPubKey from a Taproot address

(Asked by: username_0 on 2023-05-03)

I have this function that converts a Bitcoin private key as an integer to a public key and an address.

```
def get_seg_v1_from_pkey(imported_key):
    imported_key_toint = int(imported_key)
    privKeytoHex = imported_key_toint.to_bytes(32, 'big').hex()
    prv = HDKey(privKeytoHex)
    prv_tnet = TNetHDKey(privKeytoHex)
    pubkey = prv.public_hex
    pub_tnet = prv_tnet.public_hex
    version = 0x01
    address = program_to_witness(version, pubkey[2:], main=True)
    address_testnet = pubkeyhash_to_addr_bech32(pubkeyhash=pub_tnet[2:], prefix='tb', witver=1, separator='1', checksum_xor=0x2bc830a3)
    return pubkey, address, address_testnet  

```

HDKey imports the integer into a proper private key object like what is used in <https://github.com/bitcoinops/taproot-workshop>. TNetHDKey is a custom function I wrote that does the same thing as HDKey but it stores the private key in a way that makes it easily convertible to a testnet address.

I want to get the scriptPubKey from an address like in this function in <https://github.com/bitcoinops/taproot-workshop>:

```
def create_spending_transaction(self, txid, version=1, nSequence=0):
    """Construct a CTransaction object that spends the first ouput from txid."""
    # Construct transaction
    spending_tx = CTransaction()

    # Populate the transaction version
    spending_tx.nVersion = version

    # Populate the locktime
    spending_tx.nLockTime = 0

    # Populate the transaction inputs
    outpoint = COutPoint(int(txid, 16), 0)
    spending_tx_in = CTxIn(outpoint=outpoint, nSequence=nSequence)
    spending_tx.vin = [spending_tx_in]

    # Generate new Bitcoin Core wallet address
    dest_addr = self.nodes[0].getnewaddress(address_type="bech32")
    scriptpubkey = bytes.fromhex(self.nodes[0].getaddressinfo(dest_addr)['scriptPubKey'])

    # Complete output which returns 0.5 BTC to Bitcoin Core wallet
    amount_sat = int(0.5 * 100_000_000)
    dest_output = CTxOut(nValue=amount_sat, scriptPubKey=scriptpubkey)
    spending_tx.vout = [dest_output]

    return spending_tx  

```

Notice these lines in the above function:

```
# Generate new Bitcoin Core wallet address
dest_addr = self.nodes[0].getnewaddress(address_type="bech32")
scriptpubkey = bytes.fromhex(self.nodes[0].getaddressinfo(dest_addr)['scriptPubKey'])  

```

`self.nodes[0]` refers to a running instance of bitcoind on your computer. I want to replicate this function without requiring a running instance of bitcoind. In my version of this function I plan on passing in `dest_addr` because I won't have a bitcoind instance to generate it. Is there a way to get a scriptPubKey from a raw segwit v1 address?

**Tags:** address, taproot, bech32-address, p2tr, bip350-bech32m


---

## 2 answers

### Answer by username_1 on 2023-05-04. Score: 2 | Accepted answer

You can use [the reference Python implementation of bech32 / bech32m](https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py). Decode the address using [`bech32_decode`](https://github.com/sipa/bech32/blob/7a7d7ab158db7078a333384e0e918c90dbc42917/ref/python/segwit_addr.py#L73-L89) and get the human readable part, data encoded (the scriptPubKey you are looking for), and whether this address is bech32 or bech32m.


---

### Answer by username_2 on 2023-05-03. Score: 1

The scriptpubkey for a P2WPKH address is `0x0014{20-byte-key-hash}` (from [bip141](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wpkh))

You get the keyhash by decoding the address from the bech32 encoding.

You can use [this](https://github.com/mcdallas/cryptotools/blob/dbdced863bd2622f4cb41595df1ecad399760d78/cryptotools/BTC/address.py#L175C1-L176) library (I am the author) to do that or to construct the spending output.

```python
>>> from cryptotools import Address

>>> addr = Address('bc1qh2egksgfejqpktc3kkdtuqqrukrpzzp9lr0phn')
>>> addr.type()
<ADDRESS.P2WPKH: 'P2WPKH'>

>>> output = addr._receive(50_000_000)
>>> output.script.hex()
'0014bab28b4109cc801b2f11b59abe0003e586110825'

```

> **Comments:**
> **username_0**: Thanks for the answer, my address is a segwit_v1 (bech32m). Will cryptotools work with that? And would the answer need to be modified in that case?  
> **username_2**: Oops sorry I missed that, no taproot support yet.  
> **username_0**: No problem, thanks for trying  

---

