Custom Python P2MS Auditor
Custom Python P2MS Auditor
In this final guide, we will build a Python script that parses a raw P2MS ScriptPubKey. The script will identify the M (required) and N (total) values and list the hex of every authorized public key.
The P2MS Auditor
def audit_p2ms_script(script_hex):
# 1. Check for the multisig opcode (ae) at the end
if not script_hex.endswith("ae"):
print("[ERROR] Not a P2MS script (missing OP_CHECKMULTISIG)")
return
# 2. Extract M (The first byte)
# OP_1 = 0x51, OP_2 = 0x52, etc.
m_val = int(script_hex[:2], 16) - 0x50
# 3. Extract N (The byte before ae)
n_val = int(script_hex[-4:-2], 16) - 0x50
print(f"--- P2MS Script Audit ---")
print(f"[*] Required Signatures (M): {m_val}")
print(f"[*] Total Public Keys (N): {n_val}")
print(f"--------------------------")
# 4. Extract the Public Keys
# We skip the first 2 chars (M) and last 4 chars (N + AE)
keys_data = script_hex[2:-4]
# Iterate through the keys (assuming compressed 33-byte keys)
# Each key is [PushByte][33 Bytes] = 34 bytes = 68 hex chars
pointer = 0
key_index = 1
while pointer \u003c len(keys_data):
push_byte = int(keys_data[pointer:pointer+2], 16)
key_hex = keys_data[pointer+2:pointer+2+(push_byte*2)]
print(f"[*] Key #{key_index}: {key_hex}")
pointer += 2 + (push_byte * 2)
key_index += 1
# --- Simulation ---
# Case: A standard 2-of-3 Multisig script
# OP_2 [Key1] [Key2] [Key3] OP_3 OP_CHECKMULTISIG
p2ms_script = "522102f9e61c56f7e841f77d337d45e4120f44e132e01b3d36b85994f31c28b5e28a95210333333333333333333333333333333333333333333333333333333333333333332102aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa53ae"
audit_p2ms_script(p2ms_script)
How to Run the Auditor
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
p2ms_auditor.py. -
Run it using
python3 p2ms_auditor.py.
Technical Takeaways
-
Transparency: P2MS is completely transparent. Anyone can see how many partners are in a joint account and who they are. This is why P2SH is preferred for privacy.
-
Opcode Offsets: Notice the
- 0x50logic. In Bitcoin script,OP_1is0x51. This mapping allows us to translate hex back into numbers. -
Parsing Complexity: Because keys can be different lengths, a real auditor must read the "Push Data" byte before every key to know where the next one starts.
Congratulations! You have completed the P2MS (Pay-to-Multisig) module. You now understand the foundation of Bitcoin's collaborative security.
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: