Custom Python ScriptSig Decoder
Custom Python ScriptSig Decoder
In this final simulation, we will write a script that parses a raw ScriptSig from a Legacy transaction. We will identify the signature and the public key, and deconstruct the lengths of these data pushes.
The Python ScriptSig Decoder
def decode_scriptsig(scriptsig_hex):
# Convert hex string to bytes
data = bytes.fromhex(scriptsig_hex)
cursor = 0
print(f"--- Decoding Raw ScriptSig ---")
# 1. Read Signature Length (Usually 0x47 or 0x48)
sig_len = data[cursor]
cursor += 1
# 2. Extract Signature (DER Encoded)
signature = data[cursor:cursor+sig_len]
cursor += sig_len
# 3. Read Public Key Length (Usually 0x21 for compressed)
pubkey_len = data[cursor]
cursor += 1
# 4. Extract Public Key
pubkey = data[cursor:cursor+pubkey_len]
# Analysis
print(f"\n[Signature Data]")
print(f"[*] Length: {sig_len} bytes")
print(f"[*] SIGHASH: 0x{signature[-1]:02x}")
print(f"[*] Raw: {signature.hex()[:30]}...")
print(f"\n[Public Key Data]")
print(f"[*] Length: {pubkey_len} bytes")
print(f"[*] Type: {'Compressed' if pubkey_len == 33 else 'Uncompressed'}")
print(f"[*] Hex: {pubkey.hex()}")
# --- Simulation ---
# A real P2PKH ScriptSig hex:
# [47] -> Sig Len (71)
# [3044...01] -> DER Signature + SIGHASH_ALL
# [21] -> Pubkey Len (33)
# [02...8f] -> Compressed Pubkey
sample_scriptsig = (
"47" +
"3044022026859367ca7e2c943806297491730419266993a46611f71a0673c683c316226a022003c274191730419266993a46611f71a0673c683c316226a01" +
"21" +
"0281cd6495d3550e553c3066d40026a090ef666993a46611f71a0673c683c31622"
)
decode_scriptsig(sample_scriptsig)
How to Run the Decoder
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
scriptsig_decoder.py. -
Run it using
python3 scriptsig_decoder.py.
Technical Takeaways
-
Prefix-Based Parsing: Note how we use the first byte to tell us how many bytes to read next. This is how Bitcoin's streaming parser works.
-
SIGHASH Discovery: The last byte of the signature (
0x01in our example) is the SIGHASH flag. This is what makes the signature "valid" for the whole transaction. -
Transparency: Even though the signature looks like random gibberish, it has a strict internal structure (DER) that allows nodes to verify it.
Congratulations! You have completed the ScriptSig module. You now understand the "Key" that unlocks the world's most valuable ledger.
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: