Custom Python Locktime Decoder
Custom Python Locktime Decoder
In this final simulation, we will build a script that extracts and decodes the nLockTime field from a raw transaction hex. The script will automatically determine if the lock is based on blocks or time and output a human-readable interpretation.
The Python Locktime Parser
import struct
from datetime import datetime
def decode_nlocktime(tx_hex):
# nLockTime is ALWAYS the last 4 bytes of a transaction
tx_bytes = bytes.fromhex(tx_hex)
raw_locktime = tx_bytes[-4:]
# Unpack as little-endian uint32
nLockTime = struct.unpack('<I', raw_locktime)[0]
print(f"--- Decoding nLockTime: {nLockTime} ---")
if nLockTime == 0:
print("[*] Status: Final (No Lock)")
return
# Apply the 500,000,000 threshold
if nLockTime < 500000000:
print(f"[*] Type: Block Height")
print(f"[*] Condition: Valid at or after block {nLockTime:,}")
else:
print(f"[*] Type: Unix Timestamp")
# Convert to human-readable date
date_str = datetime.utcfromtimestamp(nLockTime).strftime('%Y-%m-%d %H:%M:%S UTC')
print(f"[*] Condition: Valid after {date_str}")
# --- Simulation ---
# Scenario A: Block Height 700,000 (0x000aad0a -> 0aaad000)
# Last 4 bytes: 60ae0a00
print("Scenario A:")
decode_nlocktime("010000000000000000000000000060ae0a00")
# Scenario B: Unix Timestamp for Jan 1, 2024 (1704067200)
# Hex: 0x6591ea80 -> 80ea9165
print("\nScenario B:")
decode_nlocktime("010000000000000000000000000080ea9165")
# Scenario C: Default (No Lock)
print("\nScenario C:")
decode_nlocktime("010000000000000000000000000000000000")
How to Run the Decoder
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
locktime_decoder.py. -
Run it using
python3 locktime_decoder.py.
Technical Takeaways
-
Fixed Positioning: Because nLockTime is at the end, we can easily find it using
tx_bytes[-4:], even without parsing the rest of the transaction. -
Deterministic Rules: The 500 million threshold is a "consensus constant." Every node on the network uses this exact math to decide if your transaction is allowed in a block.
-
Human Visibility: While the hex looks like random noise, it contains precise temporal instructions that govern the future of your coins.
Congratulations! You have completed the Locktime module. You now understand how Bitcoin controls the flow of value through time.
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: