Custom Python PSBT Decoder
Custom Python PSBT Decoder
In this final guide, we will build a Python script that decodes a PSBT Base64 string and verifies its integrity. We will check for the "Magic Bytes" and identify the different sections of the file.
The PSBT Auditor
import base64
def audit_psbt(psbt_base64):
try:
# 1. Decode Base64 to Raw Bytes
raw_bytes = base64.b64decode(psbt_base64)
except Exception as e:
print("[ERROR] Invalid Base64 string!")
return
print(f"--- PSBT Binary Audit ---")
print(f"[*] Total Length: {len(raw_bytes)} bytes")
# 2. Check Magic Bytes (psbt\\xff)
magic = raw_bytes[:5]
if magic == b'psbt\\xff' or magic == b'psbt\\xdf': # Handling different encodings
print(f"[*] Magic Bytes: VALID ({magic.hex()})")
elif magic.startswith(b'psbt'):
print(f"[*] Magic Bytes: VALID (psbt header found)")
else:
print(f"[!] WARNING: Magic bytes mismatch! Found: {magic.hex()}")
# 3. Locate the Global Map
# The Global Map starts immediately after the 5 magic bytes
# Each map entry: [KeyLen][KeyType][KeyData][ValLen][ValData]
print(f"[*] Internal Map Structure Detected...")
# 4. Heuristic: Look for partial signatures (Key Type 0x02)
sig_count = raw_bytes.count(b'\\x02', 5) # Rough estimate
print(f"[*] Estimated Partial Signatures: {sig_count}")
# 5. Extraction Logic (Simplified)
# A real decoder would iterate through keys 0x00 to 0x05
if b'\\x00' in raw_bytes[5:20]:
print("[*] Global Unsigned Transaction: FOUND")
# --- Simulation ---
# A real PSBT usually looks like this:
# cHNidP8BAHUCAAAAARm...
example_psbt = "cHNidP8BAHUCAAAAAf//////////////////////////////////////////AAAAAAD/////Af6p6A8AAAAAABYAFH6nE39Y6S77CIs+Vn0fCgE8E8E8AAAAAA=="
audit_psbt(example_psbt)
How to Run the Decoder
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
psbt_auditor.py. -
Run it using
python3 psbt_auditor.py.
Technical Takeaways
-
Format Verification: The
psbtmagic header is the first line of defense for a wallet to ensure it isn't trying to parse garbage data. -
Stateless Metadata: Notice how the PSBT is much larger than a standard transaction. This is because it carries its own "state"—it doesn't need to look at a blockchain to be signed.
-
Collaborative Signing: Because PSBT uses a Key-Value map, different software can add their own "proprietary" keys to the file without breaking the standard for others.
Congratulations! You have completed the PSBT (BIP 174) module. You now understand the language used by modern Bitcoin wallets to collaborate.
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: