TeachMeBitcoin

Custom Python Locktime Decoder

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

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

  1. Ensure you have Python 3 installed.

  2. Copy the code into a file named locktime_decoder.py.

  3. Run it using python3 locktime_decoder.py.

Technical Takeaways

  1. 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.

  2. 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.

  3. 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.

☕ Help support TeachMeBitcoin

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:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!