Skip to content

Instantly share code, notes, and snippets.

@a-r-d
Last active October 26, 2023 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-r-d/ec00f13a4ada64c0d186eba908457cee to your computer and use it in GitHub Desktop.
Save a-r-d/ec00f13a4ada64c0d186eba908457cee to your computer and use it in GitHub Desktop.
How to correctly check a native segwit address if its derived from an a given xpub
"""
This works as of October 2023
pip3 install bitcoinlib
"""
from bitcoinlib.keys import HDKey
def check_address_in_xpub(xpub, address_to_check, segwit_type):
hdkey = HDKey(xpub, witness_type='segwit')
for i in range(0, 10): # Replace 20 with however many addresses you want to check
path = f"m/0/{i}"
subkey = hdkey.subkey_for_path(path)
derived_address = subkey.address(script_type=segwit_type)
print("Derived address: ", derived_address)
if derived_address == address_to_check:
print("Yeah it's in there!")
return True
print("Nope, not in there.")
return False
# You want this if the address starts with bc1
segwit_type = 'p2wpkh' # set to 'p2sh_p2wpkh' for non-native SegWit, 'p2wpkh' for native SegWit
xpub = "xpub..."
address_to_check = "bc1..."
print(check_address_in_xpub(xpub, address_to_check, segwit_type))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment