Last active
October 26, 2023 03:30
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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