Custom Python Extended Key Auditor
Custom Python Extended Key Auditor
In this final guide, we will build a Python script that parses an xpub string. We will decode the Base58Check wrapper and extract the hidden metadata: version bytes, depth, parent fingerprint, child index, and the all-important Chain Code.
The Extended Key Auditor
# The 58 characters for decoding
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def decode_base58(s):
"""Simple Base58 decoder."""
num = 0
for char in s:
num = num * 58 + ALPHABET.index(char)
combined = num.to_bytes(82, 'big') # 78 payload + 4 checksum
return combined[:-4] # Remove checksum
def audit_extended_key(xpub_string):
print(f"--- Extended Key (BIP32) Audit ---")
print(f"[*] Input: {xpub_string}")
try:
# 1. Decode payload
payload = decode_base58(xpub_string)
# 2. Extract Components
version = payload[0:4]
depth = payload[4]
fingerprint = payload[5:9]
child_index = int.from_bytes(payload[9:13], 'big')
chain_code = payload[13:45]
key_data = payload[45:78]
# 3. Print Results
print(f"[*] Version Bytes: {version.hex()}")
print(f"[*] Depth: {depth}")
print(f"[*] Parent Fingerprint: {fingerprint.hex()}")
print(f"[*] Child Index: {child_index}")
print(f"[*] Chain Code: {chain_code.hex()}")
print(f"[*] Key Data: {key_data.hex()}")
# Verification of type
if version.hex() == "0488b21e":
print("[INFO] This is a Mainnet XPUB.")
elif version.hex() == "04b24746":
print("[INFO] This is a Mainnet ZPUB (SegWit).")
except Exception as e:
print(f"[ERROR] Audit failed: {e}")
# --- Simulation ---
# A standard BIP32 Master xpub
test_xpub = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqeseD26wldDA486XzB72sHAnNmd4X"
audit_extended_key(test_xpub)
How to Run the Auditor
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
xpub_auditor.py. -
Run it using
python3 xpub_auditor.py.
Technical Takeaways
-
Chain Code Access: Notice how easy it is to extract the 32-byte chain code. This is why you should keep your
xpubprivate if you are concerned about address privacy. -
Depth: If the depth is
0, you are looking at a master key. If it is1or higher, this key was derived from a parent. -
Self-Contained: The reason an
xpubis so long is that it must carry its own "Lineage" (fingerprint and index) so that a wallet can place it correctly in the HD tree.
Congratulations! You have completed the Extended Keys (xpub / xprv master keys) module. You now understand the hierarchical architecture that powers modern Bitcoin self-custody.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: