P2PKH address

Generate address

 1import hashlib
 2
 3from buidl.ecc import PrivateKey, Signature
 4from buidl.bech32 import decode_bech32
 5from buidl.helper import decode_base58, big_endian_to_int
 6from buidl.script import P2PKHScriptPubKey, RedeemScript, WitnessScript, P2WPKHScriptPubKey
 7from buidl.tx import Tx, TxIn, TxOut
 8
 9h = hashlib.sha256(b'correct horse battery staple').digest()
10private_key = PrivateKey(secret=big_endian_to_int(h), network="signet")
11address = private_key.point.address(network="signet")
12print('Address:', str(address))
13# outputs: Address: mrdwvWkma2D6n9mGsbtkazedQQuoksnqJV

Spend from address

Assuming the previously generated address has received funds, we can spend them. In order to spend them, we'll need information about the transaction id (txid) and a vector of an output (vout). You can get both from an explorer or by querying your running Bitcoin node by running listunspent along with some filters:

bitcoin-cli listunspent 1 9999999 "[\"address\"]"

Note that you must have an address in the watchlist in order to get any output. To add an address to a watchlist run importaddress:

bitcoin-cli importaddress <address> "<label>" false false

 1# we are continuing the code from above
 2
 3txid = bytes.fromhex("06633b187444530eb74284730e45c00946b7f83c4acca5213037e44406b0dceb")
 4vout = 1
 5
 6# Specify the amount send to your P2WSH address.
 7COIN = 100000000
 8amount = int(0.001 * COIN)
 9
10# Calculate an amount for the upcoming new UTXO. Set a high fee (5%) to bypass bitcoind minfee
11# setting on regtest.
12amount_less_fee = int(amount * 0.99)
13
14# Create the txin structure, which includes the outpoint. The scriptSig defaults to being empty as
15# is necessary for spending a P2WSH output.
16txin = TxIn(txid, vout)
17
18# Specify a destination address and create the txout.
19h160 = decode_bech32("tb1qqqlcpznqkfa65wqd48mzzghpwzefgpvtvl0a7k")[2]
20txout = TxOut(amount=amount_less_fee, script_pubkey=P2WPKHScriptPubKey(h160))
21
22tx = Tx(1, [txin], [txout], 0, network="signet")
23
24# Sign the transaction (buidl makes a request to the explorer to fetch public key here)
25tx.sign_p2pkh(0, private_key)
26
27# Done! Print the transaction
28print(tx.serialize().hex())
29# outputs: 0100000001ebdcb00644e4373021a5cc4a3cf8b74609c0450e738442b70e534474183b6306010000006a4730440220026f57ed7143868dba36b4bc3123719a9a4bb65a479ab2e086de9f93e4c43f1c02204943c6e5ead4de886aa1b4777cffa072a21c8d4c13743543d1a4e1f06ab28d0301210378d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71ffffffff01b882010000000000160014003f808a60b27baa380da9f62122e170b294058b00000000

Now that we have our signed and encoded transaction, we can broadcast it using sendrawtransaction:

bitcoin-cli sendrawtransaction <transaction>

If the transaction is broadcasted successfully a transaction id will be returned. In this case it was ee002c8a2d9a791382600c5e9526faf173c60827abde4f34dd2267d480aa66bd.