Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2014-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test mempool re-org scenarios.7Test re-org scenarios with a mempool that contains transactions8that spend (directly or indirectly) coinbase transactions.9"""11import time13from test_framework.messages import (14CInv,15MSG_WTX,16msg_getdata,17)18from test_framework.p2p import (19P2PTxInvStore,20p2p_lock,21)22from test_framework.test_framework import BitcoinTestFramework23from test_framework.util import assert_equal, assert_raises_rpc_error24from test_framework.wallet import MiniWallet25from test_framework.blocktools import (26create_empty_fork,27)29# Number of blocks to create in temporary blockchain branch for reorg testing30# needs to be long enough to allow MTP to move arbitrarily forward31FORK_LENGTH = 2033class MempoolCoinbaseTest(BitcoinTestFramework):34def set_test_params(self):35self.num_nodes = 236self.extra_args = [37[38'[email protected]', # immediate tx relay39],40[]41]43def trigger_reorg(self, fork_blocks, node):44"""Trigger reorg of the fork blocks."""45for block in fork_blocks:46node.submitblock(block.serialize().hex())47assert_equal(self.nodes[0].getbestblockhash(), fork_blocks[-1].hash_hex)49def test_reorg_relay(self):50self.log.info("Test that transactions from disconnected blocks are available for relay immediately")51# Prevent time from moving forward52self.nodes[1].setmocktime(int(time.time()))53self.connect_nodes(0, 1)54self.generate(self.wallet, 3)56# Disconnect node0 and node1 to create different chains.57self.disconnect_nodes(0, 1)58# Connect a peer to node1, which doesn't have immediate tx relay59peer1 = self.nodes[1].add_p2p_connection(P2PTxInvStore())61# Create a transaction that is included in a block.62tx_disconnected = self.wallet.send_self_transfer(from_node=self.nodes[1])63self.generate(self.nodes[1], 1, sync_fun=self.no_op)65# Create a transaction and submit it to node1's mempool.66tx_before_reorg = self.wallet.send_self_transfer(from_node=self.nodes[1])68# Create a child of that transaction and submit it to node1's mempool.69tx_child = self.wallet.send_self_transfer(utxo_to_spend=tx_disconnected["new_utxo"], from_node=self.nodes[1])70assert_equal(self.nodes[1].getmempoolentry(tx_child["txid"])["ancestorcount"], 1)71assert_equal(len(peer1.get_invs()), 0)73# node0 has a longer chain in which tx_disconnected was not confirmed.74self.generate(self.nodes[0], 3, sync_fun=self.no_op)76# Reconnect the nodes and sync chains. node0's chain should win.77self.connect_nodes(0, 1)78self.sync_blocks()80# Child now has an ancestor from the disconnected block81assert_equal(self.nodes[1].getmempoolentry(tx_child["txid"])["ancestorcount"], 2)82assert_equal(self.nodes[1].getmempoolentry(tx_before_reorg["txid"])["ancestorcount"], 1)84# peer1 should not have received an inv for any of the transactions during this time, as no85# mocktime has elapsed for those transactions to be announced. Likewise, it cannot86# request very recent, unanounced transactions.87assert_equal(len(peer1.get_invs()), 0)88# It's too early to request these two transactions89requests_too_recent = msg_getdata([CInv(t=MSG_WTX, h=tx["tx"].wtxid_int) for tx in [tx_before_reorg, tx_child]])90peer1.send_and_ping(requests_too_recent)91for _ in range(len(requests_too_recent.inv)):92peer1.sync_with_ping()93with p2p_lock:94assert "tx" not in peer1.last_message95assert "notfound" in peer1.last_message97# Request the tx from the disconnected block98request_disconnected_tx = msg_getdata([CInv(t=MSG_WTX, h=tx_disconnected["tx"].wtxid_int)])99peer1.send_and_ping(request_disconnected_tx)101# The tx from the disconnected block was never announced, and it entered the mempool later102# than the transactions that are too recent.103assert_equal(len(peer1.get_invs()), 0)104with p2p_lock:105# However, the node will answer requests for the tx from the recently-disconnected block.106assert_equal(peer1.last_message["tx"].tx.wtxid_hex,tx_disconnected["tx"].wtxid_hex)108self.nodes[1].setmocktime(int(time.time()) + 300)109peer1.sync_with_ping()110# the transactions are now announced111assert_equal(len(peer1.get_invs()), 3)112for _ in range(3):113# make sure all tx requests have been responded to114peer1.sync_with_ping()115last_tx_received = peer1.last_message["tx"]117tx_after_reorg = self.wallet.send_self_transfer(from_node=self.nodes[1])118request_after_reorg = msg_getdata([CInv(t=MSG_WTX, h=tx_after_reorg["tx"].wtxid_int)])119assert tx_after_reorg["txid"] in self.nodes[1].getrawmempool()120peer1.send_and_ping(request_after_reorg)121with p2p_lock:122assert_equal(peer1.last_message["tx"], last_tx_received)124def run_test(self):125self.wallet = MiniWallet(self.nodes[0])126wallet = self.wallet128# Prevent clock from moving blocks further forward in time129now = int(time.time())130self.nodes[0].setmocktime(now)132# Start with a 200 block chain133assert_equal(self.nodes[0].getblockcount(), 200)135self.log.info("Add 4 coinbase utxos to the miniwallet")136# Block 76 contains the first spendable coinbase txs.137first_block = 76139# Three scenarios for re-orging coinbase spends in the memory pool:140# 1. Direct coinbase spend : spend_1141# 2. Indirect (coinbase spend in chain, child in mempool) : spend_2 and spend_2_1142# 3. Indirect (coinbase and child both in chain) : spend_3 and spend_3_1143# Use re-org to make all of the above coinbase spends invalid (immature coinbase),144# and make sure the mempool code behaves correctly.145b = [self.nodes[0].getblockhash(n) for n in range(first_block, first_block+4)]146coinbase_txids = [self.nodes[0].getblock(h)['tx'][0] for h in b]147utxo_1 = wallet.get_utxo(txid=coinbase_txids[1])148utxo_2 = wallet.get_utxo(txid=coinbase_txids[2])149utxo_3 = wallet.get_utxo(txid=coinbase_txids[3])150self.log.info("Create three transactions spending from coinbase utxos: spend_1, spend_2, spend_3")151spend_1 = wallet.create_self_transfer(utxo_to_spend=utxo_1)152spend_2 = wallet.create_self_transfer(utxo_to_spend=utxo_2)153spend_3 = wallet.create_self_transfer(utxo_to_spend=utxo_3)155self.log.info("Create another transaction which is time-locked to 300 seconds in the future")156future = now + 300157utxo = wallet.get_utxo(txid=coinbase_txids[0])158timelock_tx = wallet.create_self_transfer(159utxo_to_spend=utxo,160locktime=future,161)['hex']163self.log.info("Check that the time-locked transaction is too immature to spend")164assert_raises_rpc_error(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx)166self.log.info("Broadcast and mine spend_2 and spend_3")167spend_2_id = wallet.sendrawtransaction(from_node=self.nodes[0], tx_hex=spend_2['hex'])168wallet.sendrawtransaction(from_node=self.nodes[0], tx_hex=spend_3['hex'])169self.log.info("Generate a block")170self.generate(self.nodes[0], 1)171self.log.info("Check that time-locked transaction is still too immature to spend")172assert_raises_rpc_error(-26, 'non-final', self.nodes[0].sendrawtransaction, timelock_tx)174self.log.info("Create spend_2_1 and spend_3_1")175spend_2_1 = wallet.create_self_transfer(utxo_to_spend=spend_2["new_utxo"], version=1)176spend_3_1 = wallet.create_self_transfer(utxo_to_spend=spend_3["new_utxo"])178self.log.info("Broadcast and mine spend_3_1")179spend_3_1_id = self.nodes[0].sendrawtransaction(spend_3_1['hex'])180self.log.info("Generate a block")182# Prep for fork, only go FORK_LENGTH seconds into the MTP future max183fork_blocks = create_empty_fork(self.nodes[0], fork_length=FORK_LENGTH)185# Jump node and MTP 300 seconds and generate a slightly weaker chain than reorg one186self.nodes[0].setmocktime(future)187self.generate(self.nodes[0], FORK_LENGTH - 1)188block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time']189assert(block_time >= now + 300)191# generate() implicitly syncs blocks, so that peer 1 gets the block before timelock_tx192# Otherwise, peer 1 would put the timelock_tx in m_lazy_recent_rejects193self.log.info("The time-locked transaction can now be spent")194timelock_tx_id = self.nodes[0].sendrawtransaction(timelock_tx)196self.log.info("Add spend_1 and spend_2_1 to the mempool")197spend_1_id = self.nodes[0].sendrawtransaction(spend_1['hex'])198spend_2_1_id = self.nodes[0].sendrawtransaction(spend_2_1['hex'])200assert_equal(set(self.nodes[0].getrawmempool()), {spend_1_id, spend_2_1_id, timelock_tx_id})201self.sync_all()203self.trigger_reorg(fork_blocks, self.nodes[0])204self.sync_blocks()206# We went backwards in time to boot timelock_tx_id207fork_block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time']208assert fork_block_time < block_time210self.log.info("The time-locked transaction is now too immature and has been removed from the mempool")211self.log.info("spend_3_1 has been re-orged out of the chain and is back in the mempool")212assert_equal(set(self.nodes[0].getrawmempool()), {spend_1_id, spend_2_1_id, spend_3_1_id})214self.log.info("Reorg out enough blocks to get spend_2 back in the mempool, along with its child")216while (spend_2_id not in self.nodes[0].getrawmempool()):217b = self.nodes[0].getbestblockhash()218for node in self.nodes:219node.invalidateblock(b)221assert(spend_2_id in self.nodes[0].getrawmempool())222assert(spend_2_1_id in self.nodes[0].getrawmempool())224# Chain 10 more transactions off of spend_2_1225self.log.info("Give spend_2 some more descendants by creating a chain of 10 transactions spending from it")226parent_utxo = spend_2_1["new_utxo"]227for i in range(10):228tx = wallet.create_self_transfer(utxo_to_spend=parent_utxo, version=1)229self.nodes[0].sendrawtransaction(tx['hex'])230parent_utxo = tx["new_utxo"]232self.log.info("Use invalidateblock to re-org back and make all those coinbase spends immature/invalid")233b = self.nodes[0].getblockhash(first_block + 100)235# Use invalidateblock to go backwards in MTP time.236# invalidateblock actually moves MTP backwards, making timelock_tx_id valid again.237for node in self.nodes:238node.invalidateblock(b)240self.log.info("Check that the mempool is empty")241assert_equal(set(self.nodes[0].getrawmempool()), set())242self.sync_all()244self.test_reorg_relay()247if __name__ == '__main__':248MempoolCoinbaseTest(__file__).main()
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.