Custom Python Sequence Parser
Custom Python Sequence Parser
In this final guide, we will write a script that decodes the nSequence field of a transaction input. This script will determine if RBF is enabled and, if so, whether the field is also being used for BIP 68 relative timelocks.
The Python Sequence Decoder
import struct
def decode_sequence(sequence_hex):
# Convert hex to bytes and unpack as uint32 little-endian
seq_bytes = bytes.fromhex(sequence_hex)
nSequence = struct.unpack('<I', seq_bytes)[0]
print(f"--- Decoding nSequence: 0x{nSequence:08x} ---")
# 1. Check for Finality / RBF
if nSequence == 0xffffffff:
print("[*] RBF: Disabled (Final)")
print("[*] Locktime: Disabled")
elif nSequence <= 0xfffffffd:
print("[*] RBF: Enabled (BIP 125)")
# 2. Check for BIP 68 Relative Timelock
# Bit 31 is the 'Disable' bit (0x80000000)
bip68_disabled = nSequence \u0026 (1 \u003c\u003c 31)
if not bip68_disabled:
print("[SUCCESS] BIP 68 Relative Timelock Active")
# Bit 22 is the 'Type' bit (0x00400000)
is_time = nSequence \u0026 (1 \u003c\u003c 22)
# Bits 0-15 is the Value
value = nSequence \u0026 0xffff
if is_time:
print(f"[*] Lock Type: Time ({value * 512} seconds)")
else:
print(f"[*] Lock Type: Blocks ({value} blocks)")
else:
print("[*] BIP 68: Disabled")
# --- Simulation ---
# Scenario A: Standard RBF transaction
print("Scenario A:")
decode_sequence("fdffffff") # 0xfffffffd
# Scenario B: 10-block Relative Timelock
print("\nScenario B:")
decode_sequence("0a000000") # 0x0000000a
# Scenario C: Final (No RBF, No Lock)
print("\nScenario C:")
decode_sequence("ffffffff")
How to Run the Parser
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
sequence_parser.py. -
Run it using
python3 sequence_parser.py.
Technical Takeaways
-
Dual Purpose: Notice how the same 4 bytes can signal two entirely different protocol features (RBF and BIP 68) depending on which bits are flipped.
-
Bitwise Mastery: The protocol uses bit-masks (like
0x80000000) to extract data without wasting space. -
Consensus Power: Every full node in the world runs this exact logic to decide whether to accept your transaction into its mempool or blocks.
Congratulations! You have completed the Sequence & Timelocks module. You now understand the temporal dimension of the Bitcoin protocol.
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: