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) 2024-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"""Helpful routines for mempool testing."""6import random8from .blocktools import (9COINBASE_MATURITY,10)11from .messages import (12COutPoint,13CTransaction,14CTxIn,15CTxInWitness,16CTxOut,17)18from .script import (19CScript,20OP_RETURN,21)22from .util import (23assert_equal,24assert_greater_than,25create_lots_of_big_transactions,26gen_return_txouts,27)28from .wallet import (29MiniWallet,30)32# Default for -minrelaytxfee in sat/kvB33DEFAULT_MIN_RELAY_TX_FEE = 10034# Default for -incrementalrelayfee in sat/kvB35DEFAULT_INCREMENTAL_RELAY_FEE = 10036DEFAULT_CLUSTER_LIMIT = 6437DEFAULT_CLUSTER_SIZE_LIMIT_KVB = 10139TRUC_MAX_VSIZE = 1000040TRUC_CHILD_MAX_VSIZE = 100042def assert_mempool_contents(test_framework, node, expected=None, sync=True):43"""Assert that all transactions in expected are in the mempool,44and no additional ones exist. 'expected' is an array of45CTransaction objects46"""47if sync:48test_framework.sync_mempools()49if not expected:50expected = []51assert_equal(len(expected), len(set(expected)))52mempool = node.getrawmempool(verbose=False)53assert_equal(len(mempool), len(expected))54for tx in expected:55assert tx.txid_hex in mempool58def fill_mempool(test_framework, node, *, tx_sync_fun=None):59"""Fill mempool until eviction.61Allows for simpler testing of scenarios with floating mempoolminfee > minrelay62Requires -maxmempool=5.63To avoid unintentional tx dependencies, the mempool filling txs are created with a64tagged ephemeral miniwallet instance.65"""66test_framework.log.info("Fill the mempool until eviction is triggered and the mempoolminfee rises")67txouts = gen_return_txouts()68minrelayfee = node.getnetworkinfo()['relayfee']70tx_batch_size = 171num_of_batches = 7572# Generate UTXOs to flood the mempool73# 1 to create a tx initially that will be evicted from the mempool later74# 75 transactions each with a fee rate higher than the previous one75ephemeral_miniwallet = MiniWallet(node, tag_name="fill_mempool_ephemeral_wallet")76test_framework.generate(ephemeral_miniwallet, 1 + num_of_batches * tx_batch_size)78# Mine enough blocks so that the UTXOs are allowed to be spent79test_framework.generate(node, COINBASE_MATURITY - 1)81# Get all UTXOs up front to ensure none of the transactions spend from each other, as that may82# change their effective feerate and thus the order in which they are selected for eviction.83confirmed_utxos = [ephemeral_miniwallet.get_utxo(confirmed_only=True) for _ in range(num_of_batches * tx_batch_size + 1)]84assert_equal(len(confirmed_utxos), num_of_batches * tx_batch_size + 1)86test_framework.log.debug("Create a mempool tx that will be evicted")87tx_to_be_evicted_id = ephemeral_miniwallet.send_self_transfer(88from_node=node, utxo_to_spend=confirmed_utxos.pop(0), fee_rate=minrelayfee)["txid"]90def send_batch(fee):91utxos = confirmed_utxos[:tx_batch_size]92create_lots_of_big_transactions(ephemeral_miniwallet, node, fee, tx_batch_size, txouts, utxos)93del confirmed_utxos[:tx_batch_size]95# Increase the tx fee rate to give the subsequent transactions a higher priority in the mempool96# The tx has an approx. vsize of 65k, i.e. multiplying the previous fee rate (in sats/kvB)97# by 130 should result in a fee that corresponds to 2x of that fee rate98base_fee = minrelayfee * 13099batch_fees = [(i + 1) * base_fee for i in range(num_of_batches)]101test_framework.log.debug("Fill up the mempool with txs with higher fee rate")102for fee in batch_fees[:-3]:103send_batch(fee)104tx_sync_fun() if tx_sync_fun else test_framework.sync_mempools() # sync before any eviction105assert_equal(node.getmempoolinfo()["mempoolminfee"], minrelayfee)106for fee in batch_fees[-3:]:107send_batch(fee)108tx_sync_fun() if tx_sync_fun else test_framework.sync_mempools() # sync after all evictions110test_framework.log.debug("The tx should be evicted by now")111# The number of transactions created should be greater than the ones present in the mempool112assert_greater_than(tx_batch_size * num_of_batches, len(node.getrawmempool()))113# Initial tx created should not be present in the mempool anymore as it had a lower fee rate114assert tx_to_be_evicted_id not in node.getrawmempool()116test_framework.log.debug("Check that mempoolminfee is larger than minrelaytxfee")117assert_equal(node.getmempoolinfo()['minrelaytxfee'], minrelayfee)118assert_greater_than(node.getmempoolinfo()['mempoolminfee'], minrelayfee)120def tx_in_orphanage(node, tx: CTransaction) -> bool:121"""Returns true if the transaction is in the orphanage."""122found = [o for o in node.getorphantxs(verbosity=1) if o["txid"] == tx.txid_hex and o["wtxid"] == tx.wtxid_hex]123return len(found) == 1125def create_large_orphan():126"""Create huge orphan transaction"""127tx = CTransaction()128# Nonexistent UTXO129tx.vin = [CTxIn(COutPoint(random.randrange(1 << 256), random.randrange(1, 100)))]130tx.wit.vtxinwit = [CTxInWitness()]131tx.wit.vtxinwit[0].scriptWitness.stack = [CScript(b'X' * 390000)]132tx.vout = [CTxOut(100, CScript([OP_RETURN, b'a' * 20]))]133return tx
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.