Merge bitcoin/bitcoin#36040: Wallet: Don't backdate locktime rbf
What changed, and why it matters
This change fixes a privacy leak in Bitcoin Core's wallet. When users used the 'bumpfee' feature to replace a transaction with a higher fee, the replacement could sometimes end up with an older 'locktime' than the original transaction. This unusual pattern could be spotted by anyone observing the blockchain and used as a fingerprint to identify transactions created by Bitcoin Core (or Electrum). The fix ensures the replacement's locktime is never older than the original's, removing that tell.
This is a privacy-hardening fix; operators and users relying on bumpfee should upgrade to a release containing this commit. No immediate emergency response is required because funds are not directly at risk, but wallet fingerprinting can degrade long-term privacy.
Security signals we found
Privacy/fingerprinting issue in wallet transaction creation
Replacement transaction locktime can be lower than original transaction locktime
Anti-fee-sniping random backdating can produce identifiable on-chain pattern
Fix adds minimum locktime constraint passed through CoinControl
Functional test confirms bumped locktime is not backdated below original
Evidence from the diff
Bitcoin Core’s anti-fee-sniping logic sets nLockTime to the current tip height and, 10% of the time, randomly backdates it by up to 99 blocks. When bumpfee created a replacement transaction, it ran this logic from scratch. If the original transaction had a higher locktime (e.g., because it was created when the chain was higher, or with a recent random backdate), the replacement could get a lower locktime, producing a non-monotonic replacement chain. This is a wallet fingerprint. The patch adds a m_minimum_locktime field to CCoinControl, populated in feebumper.cpp with the original transaction’s nLockTime, and passes it to DiscourageFeeSniping as a floor for backdating. It also handles stale-tip and minimum-above-tip edge cases by falling back to 0 when appropriate. Tests are added for both unit and functional behavior.
Changed components
src/wallet/coincontrol.hsrc/wallet/feebumper.cppsrc/wallet/spend.cppsrc/wallet/spend.hsrc/wallet/test/spend_tests.cpptest/functional/wallet_bumpfee.pyInspect captured patch +171 / −8
### src/wallet/coincontrol.h
@@ -115,6 +115,8 @@ class CCoinControl
uint32_t m_version = DEFAULT_WALLET_TX_VERSION;
//! Locktime
std::optional<uint32_t> m_locktime;
+ //! Minimum locktime for the transaction being created
+ std::optional<uint32_t> m_minimum_locktime;
//! Caps weight of resulting tx
std::optional<int> m_max_tx_weight{std::nullopt};
### src/wallet/feebumper.cpp
@@ -319,6 +319,9 @@ Result CreateRateBumpTransaction(CWallet& wallet, const Txid& txid, const CCoinC
// We cannot source new unconfirmed inputs(bip125 rule 2)
new_coin_control.m_min_depth = 1;
+ // Save the previous locktime as the minimum value for anti fee sniping
+ assert(!new_coin_control.m_locktime.has_value());
+ new_coin_control.m_minimum_locktime = tx->nLockTime;
auto res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, new_coin_control, false);
if (!res) {
### src/wallet/spend.cpp
@@ -993,7 +993,7 @@ static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256&
}
void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast,
- interfaces::Chain& chain, const uint256& block_hash, int block_height)
+ interfaces::Chain& chain, const uint256& block_hash, int block_height, uint32_t minimum_height)
{
// All inputs must be added by now
assert(!tx.vin.empty());
@@ -1024,13 +1024,21 @@ void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast,
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
- if (rng_fast.randrange(10) == 0) {
- tx.nLockTime = std::max(0, int(tx.nLockTime) - int(rng_fast.randrange(100)));
+ if (rng_fast.randrange(10) == 0 && tx.nLockTime > minimum_height) {
+ // If a minimum_height is passed, the backdating is limited between
+ // the current height and the minimum_height.
+ int range = std::min(100, int(block_height - static_cast<int>(minimum_height) + 1));
+ tx.nLockTime = int(tx.nLockTime) - int(rng_fast.randrange(range));
}
} else {
// If our chain is lagging behind, we can't discourage fee sniping nor help
- // the privacy of high-latency transactions. To avoid leaking a potentially
- // unique "nLockTime fingerprint", set nLockTime to a constant.
+ // the privacy of high-latency transactions. Use minimum_height so new
+ // sends still get a constant 0 fingerprint.
+ tx.nLockTime = minimum_height;
+ }
+ // If minimum_height is ahead of the local tip, use 0 so the tx stays final
+ // and we do not fingerprint the lagging tip.
+ if (minimum_height > static_cast<uint32_t>(block_height)) {
tx.nLockTime = 0;
}
// Sanity check all values
@@ -1328,7 +1336,11 @@ static util::Result<CreatedTransactionResult> CreateTransactionInternal(
use_anti_fee_sniping = false;
}
if (use_anti_fee_sniping) {
- DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight());
+ uint32_t minimum_height = 0;
+ if (coin_control.m_minimum_locktime.has_value() && coin_control.m_minimum_locktime < LOCKTIME_THRESHOLD) {
+ minimum_height = coin_control.m_minimum_locktime.value();
+ }
+ DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight(), minimum_height);
}
// Calculate the transaction fee
### src/wallet/spend.h
@@ -196,9 +196,12 @@ util::Result<SelectionResult> SelectCoins(const CWallet& wallet, CoinsResult& av
/**
* Set a height-based locktime for new transactions (uses the height of the
- * current chain tip unless we are not synced with the current chain
+ * current chain tip unless we are not synced with the current chain).
+ * The locktime is occasionally backdated, but never below minimum_height
+ * and at most 99 blocks below the best known tip.
+ * If minimum_height is above the local tip, locktime is 0.
*/
-void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, interfaces::Chain& chain, const uint256& block_hash, int block_height);
+void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast, interfaces::Chain& chain, const uint256& block_hash, int block_height, uint32_t minimum_height = 0);
/**
* Create a new transaction paying the recipients with a set of coins
### src/wallet/test/spend_tests.cpp
@@ -3,8 +3,14 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/amount.h>
+#include <interfaces/chain.h>
#include <key.h>
+#include <primitives/transaction.h>
+#include <random.h>
#include <script/solver.h>
+#include <test/util/setup_common.h>
+#include <uint256.h>
+#include <util/time.h>
#include <validation.h>
#include <wallet/coincontrol.h>
#include <wallet/spend.h>
@@ -120,5 +126,94 @@ BOOST_FIXTURE_TEST_CASE(wallet_duplicated_preset_inputs_test, TestChain100Setup)
BOOST_CHECK(!CreateTransaction(*wallet, recipients, /*change_pos=*/std::nullopt, coin_control));
}
+BOOST_FIXTURE_TEST_CASE(discourage_fee_sniping_backdating_bounds, TestChain100Setup)
+{
+ // Verify that DiscourageFeeSniping works as expected when called with the minimum_height
+ // parameter. This only happens while replacing a transaction (bumpfee).
+ FastRandomContext rng_fast(true);
+
+ // Mine 11 more blocks, so that the tip ends up above height 110.
+ for (int i{0}; i < 11; ++i) {
+ CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
+ }
+ const CBlockIndex* tip{WITH_LOCK(Assert(m_node.chainman)->GetMutex(),
+ return m_node.chainman->ActiveChain().Tip())};
+ const int block_height{tip->nHeight};
+ const uint256 block_hash{tip->GetBlockHash()};
+ auto& chain{*m_node.chain};
+
+ CMutableTransaction mtx;
+ mtx.vin.emplace_back(COutPoint{Txid::FromUint256(uint256::ONE), 0},
+ CScript(), CTxIn::MAX_SEQUENCE_NONFINAL);
+
+ // Backdating is constrained to [block_height - 99, block_height].
+ bool backdated{false};
+ bool saw_tip_locktime{false};
+ // Require a tip above 110 so that block_height - 110 cannot underflow when
+ // converted to the uint32_t minimum_height parameter.
+ BOOST_REQUIRE(block_height > 110);
+ for (int i{0}; i < 200; ++i) {
+ DiscourageFeeSniping(mtx, rng_fast, chain, block_hash, block_height, block_height - 110);
+ BOOST_CHECK_LE(mtx.nLockTime, static_cast<uint32_t>(block_height));
+ BOOST_CHECK_GE(mtx.nLockTime, static_cast<uint32_t>(block_height - 99));
+ if (mtx.nLockTime == static_cast<uint32_t>(block_height)) {
+ saw_tip_locktime = true;
+ } else {
+ backdated = true;
+ }
+ }
+ BOOST_CHECK(backdated);
+ BOOST_CHECK(saw_tip_locktime);
+
+ // Check that backdating can reach the minimum height.
+ backdated = false;
+ for (int i{0}; i < 200; ++i) {
+ DiscourageFeeSniping(mtx, rng_fast, chain, block_hash, block_height, block_height - 1);
+ BOOST_CHECK_LE(mtx.nLockTime, static_cast<uint32_t>(block_height));
+ BOOST_CHECK_GE(mtx.nLockTime, static_cast<uint32_t>(block_height - 1));
+ if (mtx.nLockTime < static_cast<uint32_t>(block_height)) {
+ BOOST_CHECK_EQUAL(mtx.nLockTime, static_cast<uint32_t>(block_height - 1));
+ backdated = true;
+ }
+ }
+ BOOST_CHECK(backdated);
+
+ // A minimum at the tip leaves no room for backdating.
+ DiscourageFeeSniping(mtx, rng_fast, chain, block_hash, block_height, block_height);
+ BOOST_CHECK_EQUAL(mtx.nLockTime, static_cast<uint32_t>(block_height));
+
+ // If minimum_height > block_height the locktime is set to 0.
+ DiscourageFeeSniping(mtx, rng_fast, chain, block_hash, block_height, block_height + 1);
+ BOOST_CHECK_EQUAL(mtx.nLockTime, 0);
+}
+
+BOOST_FIXTURE_TEST_CASE(discourage_fee_sniping_stale_tip, TestChain100Setup)
+{
+ // Verify DiscourageFeeSniping on a stale tip when minimum_height is set.
+ FastRandomContext rng_fast;
+
+ const CBlockIndex* tip{WITH_LOCK(Assert(m_node.chainman)->GetMutex(),
+ return m_node.chainman->ActiveChain().Tip())};
+ const int block_height{tip->nHeight};
+ const uint256 block_hash{tip->GetBlockHash()};
+ auto& chain{*m_node.chain};
+
+ CMutableTransaction mtx;
+ mtx.vin.emplace_back(COutPoint{Txid::FromUint256(uint256::ONE), 0},
+ CScript(), CTxIn::MAX_SEQUENCE_NONFINAL);
+
+ // Make the tip stale by moving the time 9 hours forward, so that it is
+ // older than the 8 hours IsCurrentForAntiFeeSniping allows
+ SetMockTime(std::chrono::seconds{tip->GetBlockTime()} + std::chrono::hours{9});
+ // Stale chain with a minimum_height lower than the block_height
+ // should set the locktime to minimum_height
+ DiscourageFeeSniping(mtx, rng_fast, chain, block_hash, block_height, block_height - 10);
+ BOOST_CHECK_EQUAL(mtx.nLockTime, static_cast<uint32_t>(block_height - 10));
+ // Stale chain with a minimum_height higher than the block_height
+ // should set the locktime to 0
+ DiscourageFeeSniping(mtx, rng_fast, chain, block_hash, block_height, block_height + 1);
+ BOOST_CHECK_EQUAL(mtx.nLockTime, 0);
+}
+
BOOST_AUTO_TEST_SUITE_END()
} // namespace wallet
### test/functional/wallet_bumpfee.py
@@ -101,6 +101,7 @@ def run_test(self):
test_locked_wallet_fails(self, rbf_node, dest_address)
test_change_script_match(self, rbf_node, dest_address)
test_maxtxfee_fails(self, rbf_node, dest_address)
+ test_bumpfee_fee_sniping_check(self, rbf_node, peer_node)
# These tests wipe out a number of utxos that are expected in other tests
test_small_output_with_feerate_succeeds(self, rbf_node, dest_address)
test_no_more_inputs_fails(self, rbf_node, dest_address)
@@ -896,6 +897,53 @@ def test_bumpfee_with_feerate_ignores_walletincrementalrelayfee(self, rbf_node,
rbf_node.bumpfee(tx["txid"], {"fee_rate": 2.1})
self.clear_mempool()
+def test_bumpfee_fee_sniping_check(self, rbf_node, peer_node):
+ # Make sure there is enough balance
+ peer_node.sendtoaddress(rbf_node.getnewaddress(), 1)
+ self.generate(peer_node, 1)
+
+ locktime = rbf_node.getblockcount()
+ assert_greater_than(locktime, 100)
+
+ # Create a replaceable tx with an explicit locktime 100 blocks below the current height.
+ # Anti-fee-sniping normally sets the locktime to the current height, and occasionally
+ # (10% of the time) backdates it by a random 0-99 blocks. A locktime 100 blocks back
+ # can't be produced by either, so if the bumped tx has this locktime, we know it was
+ # copied from the original transaction rather than recomputed by anti-fee-sniping.
+ dest = rbf_node.getnewaddress()
+ res = rbf_node.send(
+ outputs=[{dest: 1}],
+ options={
+ "locktime": locktime - 100,
+ "replaceable": True,
+ "subtract_fee_from_outputs": [0],
+ },
+ )
+ txid = res["txid"]
+
+ original_locktime = rbf_node.gettransaction(txid, verbose=True)["decoded"]["locktime"]
+ assert_equal(original_locktime, locktime - 100)
+
+ # Make the tip stale.
+ tip_time = rbf_node.getblockheader(rbf_node.getbestblockhash())["time"]
+ stale_tip = 9 * 60 * 60 # 9 hours
+ rbf_node.setmocktime(tip_time + stale_tip)
+
+ # Rate bump with a stale tip: keep the original transaction's locktime.
+ bumped = rbf_node.bumpfee(txid)['txid']
+ bumped_locktime = rbf_node.gettransaction(bumped, verbose=True)["decoded"]["locktime"]
+ assert_equal(bumped_locktime, original_locktime)
+
+ # Set the mock time back to 0 (None)
+ rbf_node.setmocktime(0)
+
+ # With a fresh tip, the next bump must advance the locktime into the 99-block window.
+ rebumped = rbf_node.bumpfee(bumped)["txid"]
+ rebumped_locktime = rbf_node.gettransaction(rebumped, verbose=True)["decoded"]["locktime"]
+ assert locktime - 99 <= rebumped_locktime <= locktime, rebumped_locktime
+
+ self.clear_mempool()
+
def test_bumpfee_uncomputable_cluster(self, rbf_node, dest_address):
self.log.info('Test that bumpfee fails when unconfirmed UTXOs depend on an enormous cluster')Why this scored 41/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.