Inside Bitcoin
Opening the selected file…
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// Copyright (c) 2017-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_WALLET_COINSELECTION_H6#define BITCOIN_WALLET_COINSELECTION_H8#include <consensus/amount.h>9#include <consensus/consensus.h>10#include <outputtype.h>11#include <policy/feerate.h>12#include <primitives/transaction.h>13#include <random.h>14#include <util/check.h>15#include <util/insert.h>16#include <util/result.h>18#include <optional>21namespace wallet {22//! lower bound for randomly-chosen target change amount23inline constexpr CAmount CHANGE_LOWER{50'000};24//! upper bound for randomly-chosen target change amount25inline constexpr CAmount CHANGE_UPPER{1'000'000};27/** A UTXO under consideration for use in funding a new transaction. */28struct COutput {29private:30/** The output's value minus fees required to spend it and bump its unconfirmed ancestors to the target feerate. */31std::optional<CAmount> effective_value;33/** The fee required to spend this output at the transaction's target feerate and to bump its unconfirmed ancestors to the target feerate. */34std::optional<CAmount> fee;36public:37/** The outpoint identifying this UTXO */38COutPoint outpoint;40/** The output itself */41CTxOut txout;43/**44* Depth in block chain.45* If > 0: the tx is on chain and has this many confirmations.46* If = 0: the tx is waiting confirmation.47* If < 0: a conflicting tx is on chain and has this many confirmations. */48int depth;50/** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */51int input_bytes;53/** Whether we know how to spend this output, ignoring the lack of keys */54bool solvable;56/**57* Whether this output is considered safe to spend. Unconfirmed transactions58* from outside keys and unconfirmed replacement transactions are considered59* unsafe and will not be used to fund new spending transactions.60*/61bool safe;63/** The time of the transaction containing this output as determined by CWalletTx::nTimeSmart */64int64_t time;66/** Whether the transaction containing this output is sent from the owning wallet */67bool from_me;69/** The fee required to spend this output at the consolidation feerate. */70CAmount long_term_fee{0};72/** The fee necessary to bump this UTXO's ancestor transactions to the target feerate */73CAmount ancestor_bump_fees{0};75COutput(const COutPoint& outpoint, const CTxOut& txout, int depth, int input_bytes, bool solvable, bool safe, int64_t time, bool from_me, const std::optional<CFeeRate> feerate = std::nullopt)76: outpoint{outpoint},77txout{txout},78depth{depth},79input_bytes{input_bytes},80solvable{solvable},81safe{safe},82time{time},83from_me{from_me}84{85if (feerate) {86// base fee without considering potential unconfirmed ancestors87fee = input_bytes < 0 ? 0 : feerate.value().GetFee(input_bytes);88effective_value = txout.nValue - fee.value();89}90}92COutput(const COutPoint& outpoint, const CTxOut& txout, int depth, int input_bytes, bool solvable, bool safe, int64_t time, bool from_me, const CAmount fees)93: COutput(outpoint, txout, depth, input_bytes, solvable, safe, time, from_me)94{95// if input_bytes is unknown, then fees should be 0, if input_bytes is known, then the fees should be a positive integer or 0 (input_bytes known and fees = 0 only happens in the tests)96assert((input_bytes < 0 && fees == 0) || (input_bytes > 0 && fees >= 0));97fee = fees;98effective_value = txout.nValue - fee.value();99}101bool operator<(const COutput& rhs) const102{103return outpoint < rhs.outpoint;104}106void ApplyBumpFee(CAmount bump_fee)107{108assert(bump_fee >= 0);109ancestor_bump_fees = bump_fee;110assert(fee);111*fee += bump_fee;112// Note: assert(effective_value - bump_fee == nValue - fee.value());113effective_value = txout.nValue - fee.value();114}116CAmount GetFee() const117{118assert(fee.has_value());119return fee.value();120}122CAmount GetEffectiveValue() const123{124assert(effective_value.has_value());125return effective_value.value();126}128bool HasEffectiveValue() const { return effective_value.has_value(); }129};131/** Parameters for one iteration of Coin Selection. */132struct CoinSelectionParams {133/** Randomness to use in the context of coin selection. */134FastRandomContext& rng_fast;135/** Size of a change output in bytes, determined by the output type. */136int change_output_size = 0;137/** Size of the input to spend a change output in virtual bytes. */138int change_spend_size = 0;139/** Mininmum change to target in Knapsack solver and CoinGrinder:140* select coins to cover the payment and at least this value of change. */141CAmount m_min_change_target{0};142/** Minimum amount for creating a change output.143* If change budget is smaller than min_change then we forgo creation of change output.144*/145CAmount min_viable_change{0};146/** Cost of creating the change output. */147CAmount m_change_fee{0};148/** Cost of creating the change output + cost of spending the change output in the future. */149CAmount m_cost_of_change{0};150/** The targeted feerate of the transaction being built. */151CFeeRate m_effective_feerate;152/** The feerate estimate used to estimate an upper bound on what should be sufficient to spend153* the change output sometime in the future. */154CFeeRate m_long_term_feerate;155/** If the cost to spend a change output at the discard feerate exceeds its value, drop it to fees. */156CFeeRate m_discard_feerate;157/** Size of the transaction before coin selection, consisting of the header and recipient158* output(s), excluding the inputs and change output(s). */159int tx_noinputs_size = 0;160/** Indicate that we are subtracting the fee from outputs */161bool m_subtract_fee_outputs = false;162/** When true, always spend all (up to OUTPUT_GROUP_MAX_ENTRIES) or none of the outputs163* associated with the same address. This helps reduce privacy leaks resulting from address164* reuse. Dust outputs are not eligible to be added to output groups and thus not considered. */165bool m_avoid_partial_spends = false;166/**167* When true, allow unsafe coins to be selected during Coin Selection. This may spend unconfirmed outputs:168* 1) Received from other wallets, 2) replacing other txs, 3) that have been replaced.169*/170bool m_include_unsafe_inputs = false;171/** The version of the transaction we are trying to create. */172uint32_t m_version{CTransaction::CURRENT_VERSION};173/** The maximum weight for this transaction. */174std::optional<int> m_max_tx_weight{std::nullopt};176CoinSelectionParams(FastRandomContext& rng_fast, int change_output_size, int change_spend_size,177CAmount min_change_target, CFeeRate effective_feerate,178CFeeRate long_term_feerate, CFeeRate discard_feerate, int tx_noinputs_size, bool avoid_partial,179std::optional<int> max_tx_weight = std::nullopt)180: rng_fast{rng_fast},181change_output_size(change_output_size),182change_spend_size(change_spend_size),183m_min_change_target(min_change_target),184m_effective_feerate(effective_feerate),185m_long_term_feerate(long_term_feerate),186m_discard_feerate(discard_feerate),187tx_noinputs_size(tx_noinputs_size),188m_avoid_partial_spends(avoid_partial),189m_max_tx_weight(max_tx_weight)190{191}192CoinSelectionParams(FastRandomContext& rng_fast)193: rng_fast{rng_fast} {}194};196/** Parameters for filtering which OutputGroups we may use in coin selection.197* We start by being very selective and requiring multiple confirmations and198* then get more permissive if we cannot fund the transaction. */199struct CoinEligibilityFilter200{201/** Minimum number of confirmations for outputs that we sent to ourselves.202* We may use unconfirmed UTXOs sent from ourselves, e.g. change outputs. */203const int conf_mine;204/** Minimum number of confirmations for outputs received from a different wallet. */205const int conf_theirs;206/** Maximum number of unconfirmed ancestors aggregated across all UTXOs in an OutputGroup. */207const uint64_t max_ancestors;208/** Maximum cluster count that a single UTXO in the OutputGroup may have. In practice, this filter also caps the209* maximum descendant count, as a transaction's descendant count is never larger than its cluster count. */210const uint64_t max_cluster_count;211/** When avoid_reuse=true and there are full groups (OUTPUT_GROUP_MAX_ENTRIES), whether or not to use any partial groups.*/212const bool m_include_partial_groups{false};214CoinEligibilityFilter() = delete;215CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_cluster_count(max_ancestors) {}216CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_cluster_count) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_cluster_count(max_cluster_count) {}217CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_cluster_count, bool include_partial) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_cluster_count(max_cluster_count), m_include_partial_groups(include_partial) {}219bool operator<(const CoinEligibilityFilter& other) const {220return std::tie(conf_mine, conf_theirs, max_ancestors, max_cluster_count, m_include_partial_groups)221< std::tie(other.conf_mine, other.conf_theirs, other.max_ancestors, other.max_cluster_count, other.m_include_partial_groups);222}223};225/** A group of UTXOs paid to the same output script. */226struct OutputGroup227{228/** The list of UTXOs contained in this output group. */229std::vector<std::shared_ptr<COutput>> m_outputs;230/** Whether the UTXOs were sent by the wallet to itself. This is relevant because we may want at231* least a certain number of confirmations on UTXOs received from outside wallets while trusting232* our own UTXOs more. */233bool m_from_me{true};234/** The total value of the UTXOs in sum. */235CAmount m_value{0};236/** The minimum number of confirmations the UTXOs in the group have. Unconfirmed is 0. */237int m_depth{999};238/** The aggregated count of unconfirmed ancestors of all UTXOs in this239* group. Not deduplicated and may overestimate when ancestors are shared. */240size_t m_ancestors{0};241/** The maximum cluster count of a single UTXO in this output group. */242size_t m_max_cluster_count{0};243/** The value of the UTXOs after deducting the cost of spending them at the effective feerate. */244CAmount effective_value{0};245/** The fee to spend these UTXOs at the effective feerate. */246CAmount fee{0};247/** The fee to spend these UTXOs at the long term feerate. */248CAmount long_term_fee{0};249/** The feerate for spending a created change output eventually (i.e. not urgently, and thus at250* a lower feerate). Calculated using long term fee estimate. This is used to decide whether
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.