TeachMeBitcoin

Custom Python Time Auditor

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

Custom Python Timestamp Auditor

In this simulation, we will implement the Median Time Past (MTP) and 2-Hour Future Rule validation logic used by Bitcoin full nodes.

The Python Timestamp Auditor

import time

def calculate_mtp(previous_timestamps):
    """Calculates the median of the last 11 timestamps."""
    if not previous_timestamps:
        return 0
    sorted_times = sorted(previous_timestamps[-11:])
    return sorted_times[len(sorted_times) // 2]

def validate_block_time(block_time, prev_timestamps, network_time):
    print(f"--- Auditing Block Timestamp: {block_time} ---")

    # 1. Check Median Time Past (Minimum)
    mtp = calculate_mtp(prev_timestamps)
    if block_time <= mtp:
        print(f"[!] REJECTED: Block time {block_time} is NOT greater than MTP {mtp}.")
        return False
    print(f"[OK] MTP check passed. {block_time} > {mtp}")

    # 2. Check Future Drift (Maximum)
    two_hours_seconds = 2 * 60 * 60
    if block_time > (network_time + two_hours_seconds):
        print(f"[!] REJECTED: Block time {block_time} is more than 2 hours ahead of network time {network_time}.")
        return False
    print(f"[OK] Future drift check passed. {block_time} is within 2 hours of {network_time}")

    print("[SUCCESS] Block timestamp is consensus-valid.")
    return True

# --- Simulation ---

# 1. Historical timestamps (last 11 blocks)
history = [1600000000 + (i * 600) for i in range(11)]
current_network_time = history[-1] + 600 # Assume we are 10 mins after last block

# 2. Test Case A: Valid Block
print("Test Case 1: Honest Miner")
validate_block_time(current_network_time + 10, history, current_network_time)

# 3. Test Case B: Backdated Block (MTP Violation)
print("\nTest Case 2: Backdated Block Attack")
validate_block_time(1600001000, history, current_network_time)

# 4. Test Case C: Future Block (2-Hour Violation)
print("\nTest Case 3: Future Block Attack")
validate_block_time(current_network_time + 10000, history, current_network_time)

How to Run the Simulator

  1. Ensure you have Python 3 installed.
  2. Copy the code into a file named time_auditor.py.
  3. Run it using python3 time_auditor.py.

Technical Takeaways

  1. Safety Buffer: The MTP ensures that even if one miner has a broken clock, the rest of the network remains stable.
  2. Relative vs. Absolute: Bitcoin's time is relative to its own history. The node doesn't care if the block time matches the "real" time exactly; it only cares if it matches the Network Adjusted Time and follows the MTP rule.
  3. Miner Strategy: Miners typically set their timestamps to their current system time to ensure their blocks are accepted by the widest possible number of nodes.

Congratulations! You have completed the Block Timestamp module. You now understand how Bitcoin keeps time in a world without a master clock.

☕ 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!