LCOV - code coverage report
Current view: top level - src/wallet - spend.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 96.5 % 714 689
Test Date: 2025-06-01 06:26:32 Functions: 100.0 % 41 41
Branches: 67.0 % 1160 777

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2021-2022 The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <algorithm>
       6                 :             : #include <common/args.h>
       7                 :             : #include <common/messages.h>
       8                 :             : #include <common/system.h>
       9                 :             : #include <consensus/amount.h>
      10                 :             : #include <consensus/validation.h>
      11                 :             : #include <interfaces/chain.h>
      12                 :             : #include <node/types.h>
      13                 :             : #include <numeric>
      14                 :             : #include <policy/policy.h>
      15                 :             : #include <primitives/transaction.h>
      16                 :             : #include <script/script.h>
      17                 :             : #include <script/signingprovider.h>
      18                 :             : #include <script/solver.h>
      19                 :             : #include <util/check.h>
      20                 :             : #include <util/moneystr.h>
      21                 :             : #include <util/rbf.h>
      22                 :             : #include <util/trace.h>
      23                 :             : #include <util/translation.h>
      24                 :             : #include <util/transaction_identifier.h>
      25                 :             : #include <wallet/coincontrol.h>
      26                 :             : #include <wallet/fees.h>
      27                 :             : #include <wallet/receive.h>
      28                 :             : #include <wallet/spend.h>
      29                 :             : #include <wallet/transaction.h>
      30                 :             : #include <wallet/wallet.h>
      31                 :             : 
      32                 :             : #include <cmath>
      33                 :             : 
      34                 :             : using common::StringForFeeReason;
      35                 :             : using common::TransactionErrorString;
      36                 :             : using interfaces::FoundBlock;
      37                 :             : using node::TransactionError;
      38                 :             : 
      39                 :             : TRACEPOINT_SEMAPHORE(coin_selection, selected_coins);
      40                 :             : TRACEPOINT_SEMAPHORE(coin_selection, normal_create_tx_internal);
      41                 :             : TRACEPOINT_SEMAPHORE(coin_selection, attempting_aps_create_tx);
      42                 :             : TRACEPOINT_SEMAPHORE(coin_selection, aps_create_tx_internal);
      43                 :             : 
      44                 :             : namespace wallet {
      45                 :             : static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES{100};
      46                 :             : 
      47                 :             : /** Whether the descriptor represents, directly or not, a witness program. */
      48                 :      211772 : static bool IsSegwit(const Descriptor& desc) {
      49         [ +  + ]:      211772 :     if (const auto typ = desc.GetOutputType()) return *typ != OutputType::LEGACY;
      50                 :             :     return false;
      51                 :             : }
      52                 :             : 
      53                 :             : /** Whether to assume ECDSA signatures' will be high-r. */
      54                 :      200172 : static bool UseMaxSig(const std::optional<CTxIn>& txin, const CCoinControl* coin_control) {
      55                 :             :     // Use max sig if watch only inputs were used or if this particular input is an external input
      56                 :             :     // to ensure a sufficient fee is attained for the requested feerate.
      57   [ +  +  +  +  :      200172 :     return coin_control && (coin_control->fAllowWatchOnly || (txin && coin_control->IsExternalSelected(txin->prevout)));
             +  +  +  + ]
      58                 :             : }
      59                 :             : 
      60                 :             : /** Get the size of an input (in witness units) once it's signed.
      61                 :             :  *
      62                 :             :  * @param desc The output script descriptor of the coin spent by this input.
      63                 :             :  * @param txin Optionally the txin to estimate the size of. Used to determine the size of ECDSA signatures.
      64                 :             :  * @param coin_control Information about the context to determine the size of ECDSA signatures.
      65                 :             :  * @param tx_is_segwit Whether the transaction has at least a single input spending a segwit coin.
      66                 :             :  * @param can_grind_r Whether the signer will be able to grind the R of the signature.
      67                 :             :  */
      68                 :      200186 : static std::optional<int64_t> MaxInputWeight(const Descriptor& desc, const std::optional<CTxIn>& txin,
      69                 :             :                                              const CCoinControl* coin_control, const bool tx_is_segwit,
      70                 :             :                                              const bool can_grind_r) {
      71   [ +  +  +  +  :      200917 :     if (const auto sat_weight = desc.MaxSatisfactionWeight(!can_grind_r || UseMaxSig(txin, coin_control))) {
                   +  + ]
      72         [ +  - ]:      200183 :         if (const auto elems_count = desc.MaxSatisfactionElems()) {
      73                 :      200183 :             const bool is_segwit = IsSegwit(desc);
      74                 :             :             // Account for the size of the scriptsig and the number of elements on the witness stack. Note
      75                 :             :             // that if any input in the transaction is spending a witness program, we need to specify the
      76                 :             :             // witness stack size for every input regardless of whether it is segwit itself.
      77                 :             :             // NOTE: this also works in case of mixed scriptsig-and-witness such as in p2sh-wrapped segwit v0
      78                 :             :             // outputs. In this case the size of the scriptsig length will always be one (since the redeemScript
      79                 :             :             // is always a push of the witness program in this case, which is smaller than 253 bytes).
      80   [ +  +  +  + ]:      200183 :             const int64_t scriptsig_len = is_segwit ? 1 : GetSizeOfCompactSize(*sat_weight / WITNESS_SCALE_FACTOR);
      81   [ -  +  +  + ]:      200183 :             const int64_t witstack_len = is_segwit ? GetSizeOfCompactSize(*elems_count) : (tx_is_segwit ? 1 : 0);
      82                 :             :             // previous txid + previous vout + sequence + scriptsig len + witstack size + scriptsig or witness
      83                 :             :             // NOTE: sat_weight already accounts for the witness discount accordingly.
      84                 :      200183 :             return (32 + 4 + 4 + scriptsig_len) * WITNESS_SCALE_FACTOR + witstack_len + *sat_weight;
      85                 :             :         }
      86                 :             :     }
      87                 :             : 
      88                 :           3 :     return {};
      89                 :             : }
      90                 :             : 
      91                 :      295394 : int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* provider, bool can_grind_r, const CCoinControl* coin_control)
      92                 :             : {
      93         [ +  + ]:      295394 :     if (!provider) return -1;
      94                 :             : 
      95         [ +  - ]:      185327 :     if (const auto desc = InferDescriptor(txout.scriptPubKey, *provider)) {
      96   [ +  -  +  + ]:      370654 :         if (const auto weight = MaxInputWeight(*desc, {}, coin_control, true, can_grind_r)) {
      97         [ +  - ]:      185324 :             return static_cast<int>(GetVirtualTransactionSize(*weight, 0, 0));
      98                 :             :         }
      99                 :      185324 :     }
     100                 :             : 
     101                 :           3 :     return -1;
     102                 :             : }
     103                 :             : 
     104                 :      122282 : int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, const CCoinControl* coin_control)
     105                 :             : {
     106                 :      122282 :     const std::unique_ptr<SigningProvider> provider = wallet->GetSolvingProvider(txout.scriptPubKey);
     107   [ +  -  +  - ]:      244564 :     return CalculateMaximumSignedInputSize(txout, COutPoint(), provider.get(), wallet->CanGrindR(), coin_control);
     108                 :      122282 : }
     109                 :             : 
     110                 :             : /** Infer a descriptor for the given output script. */
     111                 :       26448 : static std::unique_ptr<Descriptor> GetDescriptor(const CWallet* wallet, const CCoinControl* coin_control,
     112                 :             :                                                  const CScript script_pubkey)
     113                 :             : {
     114                 :       26448 :     MultiSigningProvider providers;
     115   [ +  -  +  + ]:       52840 :     for (const auto spkman: wallet->GetScriptPubKeyMans(script_pubkey)) {
     116   [ +  -  +  - ]:       26392 :         providers.AddProvider(spkman->GetSolvingProvider(script_pubkey));
     117                 :           0 :     }
     118         [ +  + ]:       26448 :     if (coin_control) {
     119   [ +  -  +  -  :       23851 :         providers.AddProvider(std::make_unique<FlatSigningProvider>(coin_control->m_external_provider));
                   -  + ]
     120                 :             :     }
     121         [ +  - ]:       26448 :     return InferDescriptor(script_pubkey, providers);
     122                 :       26448 : }
     123                 :             : 
     124                 :             : /** Infer the maximum size of this input after it will be signed. */
     125                 :       16362 : static std::optional<int64_t> GetSignedTxinWeight(const CWallet* wallet, const CCoinControl* coin_control,
     126                 :             :                                                   const CTxIn& txin, const CTxOut& txo, const bool tx_is_segwit,
     127                 :             :                                                   const bool can_grind_r)
     128                 :             : {
     129                 :             :     // If weight was provided, use that.
     130                 :       16362 :     std::optional<int64_t> weight;
     131   [ +  +  +  + ]:       16362 :     if (coin_control && (weight = coin_control->GetInputWeight(txin.prevout))) {
     132                 :        1503 :         return weight.value();
     133                 :             :     }
     134                 :             : 
     135                 :             :     // Otherwise, use the maximum satisfaction size provided by the descriptor.
     136         [ +  - ]:       14859 :     std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
     137   [ +  -  +  -  :       29718 :     if (desc) return MaxInputWeight(*desc, {txin}, coin_control, tx_is_segwit, can_grind_r);
                   +  - ]
     138                 :             : 
     139                 :           0 :     return {};
     140                 :       14859 : }
     141                 :             : 
     142                 :             : // txouts needs to be in the order of tx.vin
     143                 :        3434 : TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control)
     144                 :             : {
     145                 :             :     // version + nLockTime + input count + output count
     146   [ +  +  +  + ]:        3438 :     int64_t weight = (4 + 4 + GetSizeOfCompactSize(tx.vin.size()) + GetSizeOfCompactSize(tx.vout.size())) * WITNESS_SCALE_FACTOR;
     147                 :             :     // Whether any input spends a witness program. Necessary to run before the next loop over the
     148                 :             :     // inputs in order to accurately compute the compactSize length for the witness data per input.
     149                 :        3434 :     bool is_segwit = std::any_of(txouts.begin(), txouts.end(), [&](const CTxOut& txo) {
     150         [ +  - ]:       11589 :         std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
     151   [ +  -  +  - ]:       11589 :         if (desc) return IsSegwit(*desc);
     152                 :             :         return false;
     153                 :       11589 :     });
     154                 :             :     // Segwit marker and flag
     155         [ +  + ]:        3434 :     if (is_segwit) weight += 2;
     156                 :             : 
     157                 :             :     // Add the size of the transaction outputs.
     158         [ +  + ]:       46677 :     for (const auto& txo : tx.vout) weight += GetSerializeSize(txo) * WITNESS_SCALE_FACTOR;
     159                 :             : 
     160                 :             :     // Add the size of the transaction inputs as if they were signed.
     161         [ +  + ]:       19796 :     for (uint32_t i = 0; i < txouts.size(); i++) {
     162                 :       16362 :         const auto txin_weight = GetSignedTxinWeight(wallet, coin_control, tx.vin[i], txouts[i], is_segwit, wallet->CanGrindR());
     163         [ -  + ]:       16362 :         if (!txin_weight) return TxSize{-1, -1};
     164         [ -  + ]:       16362 :         assert(*txin_weight > -1);
     165                 :       16362 :         weight += *txin_weight;
     166                 :             :     }
     167                 :             : 
     168                 :             :     // It's ok to use 0 as the number of sigops since we never create any pathological transaction.
     169                 :        3434 :     return TxSize{GetVirtualTransactionSize(weight, 0, 0), weight};
     170                 :             : }
     171                 :             : 
     172                 :        3434 : TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const CCoinControl* coin_control)
     173                 :             : {
     174                 :        3434 :     std::vector<CTxOut> txouts;
     175                 :             :     // Look up the inputs. The inputs are either in the wallet, or in coin_control.
     176         [ +  + ]:       19796 :     for (const CTxIn& input : tx.vin) {
     177         [ +  - ]:       16362 :         const auto mi = wallet->mapWallet.find(input.prevout.hash);
     178                 :             :         // Can not estimate size without knowing the input details
     179         [ +  + ]:       16362 :         if (mi != wallet->mapWallet.end()) {
     180         [ -  + ]:       16326 :             assert(input.prevout.n < mi->second.tx->vout.size());
     181   [ +  -  +  - ]:       16326 :             txouts.emplace_back(mi->second.tx->vout.at(input.prevout.n));
     182         [ +  - ]:          36 :         } else if (coin_control) {
     183         [ +  - ]:          36 :             const auto& txout{coin_control->GetExternalOutput(input.prevout)};
     184         [ -  + ]:          36 :             if (!txout) return TxSize{-1, -1};
     185         [ +  - ]:          36 :             txouts.emplace_back(*txout);
     186                 :          36 :         } else {
     187                 :           0 :             return TxSize{-1, -1};
     188                 :             :         }
     189                 :             :     }
     190         [ +  - ]:        3434 :     return CalculateMaximumSignedTxSize(tx, wallet, txouts, coin_control);
     191                 :        3434 : }
     192                 :             : 
     193                 :        1483 : size_t CoinsResult::Size() const
     194                 :             : {
     195                 :        1483 :     size_t size{0};
     196         [ +  + ]:        3784 :     for (const auto& it : coins) {
     197                 :        2301 :         size += it.second.size();
     198                 :             :     }
     199                 :        1483 :     return size;
     200                 :             : }
     201                 :             : 
     202                 :        2661 : std::vector<COutput> CoinsResult::All() const
     203                 :             : {
     204                 :        2661 :     std::vector<COutput> all;
     205         [ +  - ]:        2661 :     all.reserve(coins.size());
     206         [ +  + ]:        5422 :     for (const auto& it : coins) {
     207         [ +  - ]:        2761 :         all.insert(all.end(), it.second.begin(), it.second.end());
     208                 :             :     }
     209                 :        2661 :     return all;
     210                 :           0 : }
     211                 :             : 
     212                 :         707 : void CoinsResult::Clear() {
     213                 :         707 :     coins.clear();
     214                 :         707 : }
     215                 :             : 
     216                 :           4 : void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher>& coins_to_remove)
     217                 :             : {
     218         [ +  + ]:           8 :     for (auto& [type, vec] : coins) {
     219                 :           4 :         auto remove_it = std::remove_if(vec.begin(), vec.end(), [&](const COutput& coin) {
     220                 :             :             // remove it if it's on the set
     221         [ +  + ]:          17 :             if (coins_to_remove.count(coin.outpoint) == 0) return false;
     222                 :             : 
     223                 :             :             // update cached amounts
     224                 :           5 :             total_amount -= coin.txout.nValue;
     225         [ +  - ]:           5 :             if (coin.HasEffectiveValue()) total_effective_amount = *total_effective_amount - coin.GetEffectiveValue();
     226                 :             :             return true;
     227                 :             :         });
     228                 :           4 :         vec.erase(remove_it, vec.end());
     229                 :             :     }
     230                 :           4 : }
     231                 :             : 
     232                 :          20 : void CoinsResult::Shuffle(FastRandomContext& rng_fast)
     233                 :             : {
     234         [ +  + ]:          56 :     for (auto& it : coins) {
     235                 :          36 :         std::shuffle(it.second.begin(), it.second.end(), rng_fast);
     236                 :             :     }
     237                 :          20 : }
     238                 :             : 
     239                 :      289408 : void CoinsResult::Add(OutputType type, const COutput& out)
     240                 :             : {
     241                 :      289408 :     coins[type].emplace_back(out);
     242                 :      289408 :     total_amount += out.txout.nValue;
     243         [ +  + ]:      289408 :     if (out.HasEffectiveValue()) {
     244         [ +  - ]:      510558 :         total_effective_amount = total_effective_amount.has_value() ?
     245                 :      510558 :                 *total_effective_amount + out.GetEffectiveValue() : out.GetEffectiveValue();
     246                 :             :     }
     247                 :      289408 : }
     248                 :             : 
     249                 :      173093 : static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
     250                 :             : {
     251   [ +  +  +  + ]:      173093 :     switch (type) {
     252                 :             :         case TxoutType::WITNESS_V1_TAPROOT:
     253                 :             :             return OutputType::BECH32M;
     254                 :      130690 :         case TxoutType::WITNESS_V0_KEYHASH:
     255                 :      130690 :         case TxoutType::WITNESS_V0_SCRIPTHASH:
     256         [ +  + ]:      130690 :             if (is_from_p2sh) return OutputType::P2SH_SEGWIT;
     257                 :      116799 :             else return OutputType::BECH32;
     258                 :       39418 :         case TxoutType::SCRIPTHASH:
     259                 :       39418 :         case TxoutType::PUBKEYHASH:
     260                 :       39418 :             return OutputType::LEGACY;
     261                 :          33 :         default:
     262                 :          33 :             return OutputType::UNKNOWN;
     263                 :             :     }
     264                 :             : }
     265                 :             : 
     266                 :             : // Fetch and validate the coin control selected inputs.
     267                 :             : // Coins could be internal (from the wallet) or external.
     268                 :         453 : util::Result<PreSelectedInputs> FetchSelectedInputs(const CWallet& wallet, const CCoinControl& coin_control,
     269                 :             :                                             const CoinSelectionParams& coin_selection_params)
     270                 :             : {
     271         [ +  - ]:         453 :     PreSelectedInputs result;
     272         [ +  - ]:         453 :     const bool can_grind_r = wallet.CanGrindR();
     273   [ +  -  +  - ]:         453 :     std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(coin_control.ListSelected(), coin_selection_params.m_effective_feerate);
     274   [ +  -  +  + ]:        6083 :     for (const COutPoint& outpoint : coin_control.ListSelected()) {
     275   [ +  -  +  + ]:        5633 :         int64_t input_bytes = coin_control.GetInputWeight(outpoint).value_or(-1);
     276         [ +  - ]:        2503 :         if (input_bytes != -1) {
     277         [ +  - ]:        2503 :             input_bytes = GetVirtualTransactionSize(input_bytes, 0, 0);
     278                 :             :         }
     279                 :        5633 :         CTxOut txout;
     280   [ +  -  +  + ]:        5633 :         if (auto ptr_wtx = wallet.GetWalletTx(outpoint.hash)) {
     281                 :             :             // Clearly invalid input, fail
     282         [ -  + ]:        5593 :             if (ptr_wtx->tx->vout.size() <= outpoint.n) {
     283   [ #  #  #  # ]:           0 :                 return util::Error{strprintf(_("Invalid pre-selected input %s"), outpoint.ToString())};
     284                 :             :             }
     285         [ +  - ]:        5593 :             txout = ptr_wtx->tx->vout.at(outpoint.n);
     286         [ +  + ]:        5593 :             if (input_bytes == -1) {
     287         [ +  - ]:        3115 :                 input_bytes = CalculateMaximumSignedInputSize(txout, &wallet, &coin_control);
     288                 :             :             }
     289                 :             :         } else {
     290                 :             :             // The input is external. We did not find the tx in mapWallet.
     291         [ +  - ]:          40 :             const auto out{coin_control.GetExternalOutput(outpoint)};
     292         [ -  + ]:          40 :             if (!out) {
     293   [ #  #  #  # ]:           0 :                 return util::Error{strprintf(_("Not found pre-selected input %s"), outpoint.ToString())};
     294                 :             :             }
     295                 :             : 
     296                 :          40 :             txout = *out;
     297                 :          40 :         }
     298                 :             : 
     299         [ +  + ]:        3155 :         if (input_bytes == -1) {
     300         [ +  - ]:          19 :             input_bytes = CalculateMaximumSignedInputSize(txout, outpoint, &coin_control.m_external_provider, can_grind_r, &coin_control);
     301                 :             :         }
     302                 :             : 
     303         [ +  + ]:          19 :         if (input_bytes == -1) {
     304   [ +  -  +  - ]:           9 :             return util::Error{strprintf(_("Not solvable pre-selected input %s"), outpoint.ToString())}; // Not solvable, can't estimate size for fee
     305                 :             :         }
     306                 :             : 
     307                 :             :         /* Set some defaults for depth, spendable, solvable, safe, time, and from_me as these don't matter for preset inputs since no selection is being done. */
     308         [ +  - ]:        5630 :         COutput output(outpoint, txout, /*depth=*/ 0, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, coin_selection_params.m_effective_feerate);
     309         [ +  - ]:        5630 :         output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
     310         [ +  - ]:        5630 :         result.Insert(output, coin_selection_params.m_subtract_fee_outputs);
     311                 :        5633 :     }
     312                 :         450 :     return result;
     313                 :         453 : }
     314                 :             : 
     315                 :        3720 : CoinsResult AvailableCoins(const CWallet& wallet,
     316                 :             :                            const CCoinControl* coinControl,
     317                 :             :                            std::optional<CFeeRate> feerate,
     318                 :             :                            const CoinFilterParams& params)
     319                 :             : {
     320                 :        3720 :     AssertLockHeld(wallet.cs_wallet);
     321                 :             : 
     322         [ +  - ]:        3720 :     CoinsResult result;
     323                 :             :     // Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we always allow), or we default to avoiding, and only in the case where
     324                 :             :     // a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
     325   [ +  -  +  +  :        3720 :     bool allow_used_addresses = !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
             +  -  +  + ]
     326         [ +  + ]:        3686 :     const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
     327                 :        7431 :     const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
     328         [ +  + ]:        3711 :     const bool only_safe = {coinControl ? !coinControl->m_include_unsafe_inputs : true};
     329         [ +  - ]:        3720 :     const bool can_grind_r = wallet.CanGrindR();
     330                 :        3720 :     std::vector<COutPoint> outpoints;
     331                 :             : 
     332                 :        3720 :     std::set<Txid> trusted_parents;
     333   [ +  +  +  - ]:      659346 :     for (const auto& entry : wallet.mapWallet)
     334                 :             :     {
     335                 :      655626 :         const Txid& txid = entry.first;
     336                 :      655626 :         const CWalletTx& wtx = entry.second;
     337                 :             : 
     338   [ +  +  +  +  :      655626 :         if (wallet.IsTxImmatureCoinBase(wtx) && !params.include_immature_coinbase)
                   +  - ]
     339                 :      220915 :             continue;
     340                 :             : 
     341         [ +  - ]:      434711 :         int nDepth = wallet.GetTxDepthInMainChain(wtx);
     342         [ +  + ]:      434711 :         if (nDepth < 0)
     343                 :        4277 :             continue;
     344                 :             : 
     345                 :             :         // We should not consider coins which aren't at least in our mempool
     346                 :             :         // It's possible for these to be conflicted via ancestors which we may never be able to detect
     347   [ +  +  +  -  :      430434 :         if (nDepth == 0 && !wtx.InMempool())
                   +  + ]
     348                 :        4592 :             continue;
     349                 :             : 
     350         [ +  - ]:      425842 :         bool safeTx = CachedTxIsTrusted(wallet, wtx, trusted_parents);
     351                 :             : 
     352                 :             :         // We should not consider coins from transactions that are replacing
     353                 :             :         // other transactions.
     354                 :             :         //
     355                 :             :         // Example: There is a transaction A which is replaced by bumpfee
     356                 :             :         // transaction B. In this case, we want to prevent creation of
     357                 :             :         // a transaction B' which spends an output of B.
     358                 :             :         //
     359                 :             :         // Reason: If transaction A were initially confirmed, transactions B
     360                 :             :         // and B' would no longer be valid, so the user would have to create
     361                 :             :         // a new transaction C to replace B'. However, in the case of a
     362                 :             :         // one-block reorg, transactions B' and C might BOTH be accepted,
     363                 :             :         // when the user only wanted one of them. Specifically, there could
     364                 :             :         // be a 1-block reorg away from the chain where transactions A and C
     365                 :             :         // were accepted to another chain where B, B', and C were all
     366                 :             :         // accepted.
     367   [ +  +  +  -  :      496158 :         if (nDepth == 0 && wtx.mapValue.count("replaces_txid")) {
             +  +  +  + ]
     368                 :         148 :             safeTx = false;
     369                 :             :         }
     370                 :             : 
     371                 :             :         // Similarly, we should not consider coins from transactions that
     372                 :             :         // have been replaced. In the example above, we would want to prevent
     373                 :             :         // creation of a transaction A' spending an output of A, because if
     374                 :             :         // transaction B were initially confirmed, conflicting with A and
     375                 :             :         // A', we wouldn't want to the user to create a transaction D
     376                 :             :         // intending to replace A', but potentially resulting in a scenario
     377                 :             :         // where A, A', and D could all be accepted (instead of just B and
     378                 :             :         // D, or just A and A' like the user would want).
     379   [ +  +  +  -  :      496158 :         if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
             +  +  +  + ]
     380                 :           1 :             safeTx = false;
     381                 :             :         }
     382                 :             : 
     383         [ +  + ]:      425842 :         if (only_safe && !safeTx) {
     384                 :        1963 :             continue;
     385                 :             :         }
     386                 :             : 
     387         [ +  + ]:      423879 :         if (nDepth < min_depth || nDepth > max_depth) {
     388                 :        3947 :             continue;
     389                 :             :         }
     390                 :             : 
     391         [ +  - ]:      419932 :         bool tx_from_me = CachedTxIsFromMe(wallet, wtx, ISMINE_ALL);
     392                 :             : 
     393         [ +  + ]:     1563558 :         for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
     394         [ +  + ]:     1143626 :             const CTxOut& output = wtx.tx->vout[i];
     395         [ +  + ]:     1143626 :             const COutPoint outpoint(txid, i);
     396                 :             : 
     397   [ +  +  -  + ]:     1143626 :             if (output.nValue < params.min_amount || output.nValue > params.max_amount)
     398                 :      153878 :                 continue;
     399                 :             : 
     400                 :             :             // Skip manually selected coins (the caller can fetch them directly)
     401   [ +  +  +  -  :      989748 :             if (coinControl && coinControl->HasSelected() && coinControl->IsSelected(outpoint))
          +  +  +  -  +  
                      + ]
     402                 :        4010 :                 continue;
     403                 :             : 
     404   [ +  -  +  +  :      985738 :             if (wallet.IsLockedCoin(outpoint) && params.skip_locked)
                   +  + ]
     405                 :         376 :                 continue;
     406                 :             : 
     407   [ +  -  +  + ]:      985362 :             if (wallet.IsSpent(outpoint))
     408                 :      462953 :                 continue;
     409                 :             : 
     410         [ +  - ]:      522409 :             isminetype mine = wallet.IsMine(output);
     411                 :             : 
     412         [ +  + ]:      522409 :             if (mine == ISMINE_NO) {
     413                 :      349316 :                 continue;
     414                 :             :             }
     415                 :             : 
     416   [ +  +  +  -  :      173093 :             if (!allow_used_addresses && wallet.IsSpentKey(output.scriptPubKey)) {
                   +  - ]
     417                 :           0 :                 continue;
     418                 :             :             }
     419                 :             : 
     420         [ +  - ]:      173093 :             std::unique_ptr<SigningProvider> provider = wallet.GetSolvingProvider(output.scriptPubKey);
     421                 :             : 
     422         [ +  - ]:      173093 :             int input_bytes = CalculateMaximumSignedInputSize(output, COutPoint(), provider.get(), can_grind_r, coinControl);
     423                 :             :             // Because CalculateMaximumSignedInputSize infers a solvable descriptor to get the satisfaction size,
     424                 :             :             // it is safe to assume that this input is solvable if input_bytes is greater than -1.
     425                 :      173093 :             bool solvable = input_bytes > -1;
     426   [ -  +  -  -  :      173093 :             bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
          -  -  -  -  -  
                      - ]
     427                 :             : 
     428                 :             :             // Filter by spendable outputs only
     429         [ #  # ]:           0 :             if (!spendable && params.only_spendable) continue;
     430                 :             : 
     431                 :             :             // Obtain script type
     432                 :      173093 :             std::vector<std::vector<uint8_t>> script_solutions;
     433         [ +  - ]:      173093 :             TxoutType type = Solver(output.scriptPubKey, script_solutions);
     434                 :             : 
     435                 :             :             // If the output is P2SH and solvable, we want to know if it is
     436                 :             :             // a P2SH (legacy) or one of P2SH-P2WPKH, P2SH-P2WSH (P2SH-Segwit). We can determine
     437                 :             :             // this from the redeemScript. If the output is not solvable, it will be classified
     438                 :             :             // as a P2SH (legacy), since we have no way of knowing otherwise without the redeemScript
     439                 :      173093 :             bool is_from_p2sh{false};
     440         [ +  + ]:      173093 :             if (type == TxoutType::SCRIPTHASH && solvable) {
     441                 :       13908 :                 CScript script;
     442   [ +  -  -  + ]:       13908 :                 if (!provider->GetCScript(CScriptID(uint160(script_solutions[0])), script)) continue;
     443         [ +  - ]:       13908 :                 type = Solver(script, script_solutions);
     444                 :       13908 :                 is_from_p2sh = true;
     445                 :       13908 :             }
     446                 :             : 
     447         [ +  - ]:      173093 :             result.Add(GetOutputType(type, is_from_p2sh),
     448   [ +  -  +  - ]:      173093 :                        COutput(outpoint, output, nDepth, input_bytes, spendable, solvable, safeTx, wtx.GetTxTime(), tx_from_me, feerate));
     449                 :             : 
     450         [ +  - ]:      173093 :             outpoints.push_back(outpoint);
     451                 :             : 
     452                 :             :             // Checks the sum amount of all UTXO's.
     453         [ -  + ]:      173093 :             if (params.min_sum_amount != MAX_MONEY) {
     454         [ #  # ]:           0 :                 if (result.GetTotalAmount() >= params.min_sum_amount) {
     455                 :             :                     return result;
     456                 :             :                 }
     457                 :             :             }
     458                 :             : 
     459                 :             :             // Checks the maximum number of UTXO's.
     460   [ -  +  -  -  :      173093 :             if (params.max_count > 0 && result.Size() >= params.max_count) {
                   -  - ]
     461                 :             :                 return result;
     462                 :             :             }
     463                 :      173093 :         }
     464                 :             :     }
     465                 :             : 
     466         [ +  + ]:        3720 :     if (feerate.has_value()) {
     467         [ +  - ]:        3342 :         std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(outpoints, feerate.value());
     468                 :             : 
     469         [ +  + ]:        8488 :         for (auto& [_, outputs] : result.coins) {
     470         [ +  + ]:      144110 :             for (auto& output : outputs) {
     471         [ +  - ]:      138964 :                 output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
     472                 :             :             }
     473                 :             :         }
     474                 :        3342 :     }
     475                 :             : 
     476                 :             :     return result;
     477                 :        3720 : }
     478                 :             : 
     479                 :         368 : CoinsResult AvailableCoinsListUnspent(const CWallet& wallet, const CCoinControl* coinControl, CoinFilterParams params)
     480                 :             : {
     481                 :         368 :     params.only_spendable = false;
     482                 :         368 :     return AvailableCoins(wallet, coinControl, /*feerate=*/ std::nullopt, params);
     483                 :             : }
     484                 :             : 
     485                 :           5 : const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const COutPoint& outpoint)
     486                 :             : {
     487                 :           5 :     AssertLockHeld(wallet.cs_wallet);
     488                 :           5 :     const CWalletTx* wtx{Assert(wallet.GetWalletTx(outpoint.hash))};
     489                 :             : 
     490                 :           5 :     const CTransaction* ptx = wtx->tx.get();
     491                 :           5 :     int n = outpoint.n;
     492   [ +  -  +  - ]:           7 :     while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
     493                 :           7 :         const COutPoint& prevout = ptx->vin[0].prevout;
     494                 :           7 :         const CWalletTx* it = wallet.GetWalletTx(prevout.hash);
     495   [ +  -  +  -  :           9 :         if (!it || it->tx->vout.size() <= prevout.n ||
                   +  + ]
     496                 :           2 :             !wallet.IsMine(it->tx->vout[prevout.n])) {
     497                 :             :             break;
     498                 :             :         }
     499                 :           2 :         ptx = it->tx.get();
     500                 :           2 :         n = prevout.n;
     501                 :             :     }
     502                 :           5 :     return ptx->vout[n];
     503                 :             : }
     504                 :             : 
     505                 :           3 : std::map<CTxDestination, std::vector<COutput>> ListCoins(const CWallet& wallet)
     506                 :             : {
     507                 :           3 :     AssertLockHeld(wallet.cs_wallet);
     508                 :             : 
     509         [ +  - ]:           3 :     std::map<CTxDestination, std::vector<COutput>> result;
     510                 :             : 
     511         [ +  - ]:           3 :     CCoinControl coin_control;
     512                 :           3 :     CoinFilterParams coins_params;
     513                 :           3 :     coins_params.only_spendable = false;
     514                 :           3 :     coins_params.skip_locked = false;
     515   [ +  -  +  -  :           8 :     for (const COutput& coin : AvailableCoins(wallet, &coin_control, /*feerate=*/std::nullopt, coins_params).All()) {
                   +  + ]
     516                 :           5 :         CTxDestination address;
     517   [ -  +  -  -  :           5 :         if ((coin.spendable || (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && coin.solvable))) {
             -  -  -  - ]
     518   [ +  -  +  -  :           5 :             if (!ExtractDestination(FindNonChangeParentOutput(wallet, coin.outpoint).scriptPubKey, address)) {
                   +  - ]
     519                 :             :                 // For backwards compatibility, we convert P2PK output scripts into PKHash destinations
     520         [ -  + ]:           5 :                 if (auto pk_dest = std::get_if<PubKeyDestination>(&address)) {
     521         [ +  - ]:           5 :                     address = PKHash(pk_dest->GetPubKey());
     522                 :             :                 } else {
     523                 :           0 :                     continue;
     524                 :             :                 }
     525                 :             :             }
     526   [ +  -  +  - ]:           5 :             result[address].emplace_back(coin);
     527                 :             :         }
     528                 :           8 :     }
     529                 :           3 :     return result;
     530                 :           3 : }
     531                 :             : 
     532                 :        6503 : FilteredOutputGroups GroupOutputs(const CWallet& wallet,
     533                 :             :                           const CoinsResult& coins,
     534                 :             :                           const CoinSelectionParams& coin_sel_params,
     535                 :             :                           const std::vector<SelectionFilter>& filters,
     536                 :             :                           std::vector<OutputGroup>& ret_discarded_groups)
     537                 :             : {
     538         [ +  + ]:        6503 :     FilteredOutputGroups filtered_groups;
     539                 :             : 
     540         [ +  + ]:        6503 :     if (!coin_sel_params.m_avoid_partial_spends) {
     541                 :             :         // Allowing partial spends means no grouping. Each COutput gets its own OutputGroup
     542         [ +  + ]:       10762 :         for (const auto& [type, outputs] : coins.coins) {
     543         [ +  + ]:      522550 :             for (const COutput& output : outputs) {
     544                 :             :                 // Get mempool info
     545                 :      516804 :                 size_t ancestors, descendants;
     546         [ +  - ]:      516804 :                 wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, descendants);
     547                 :             : 
     548                 :             :                 // Create a new group per output and add it to the all groups vector
     549         [ +  - ]:      516804 :                 OutputGroup group(coin_sel_params);
     550   [ +  -  +  - ]:      516804 :                 group.Insert(std::make_shared<COutput>(output), ancestors, descendants);
     551                 :             : 
     552                 :             :                 // Each filter maps to a different set of groups
     553                 :      516804 :                 bool accepted = false;
     554         [ +  + ]:     1839178 :                 for (const auto& sel_filter : filters) {
     555                 :     1322374 :                     const auto& filter = sel_filter.filter;
     556   [ +  -  +  + ]:     1322374 :                     if (!group.EligibleForSpending(filter)) continue;
     557   [ +  -  +  - ]:     1265379 :                     filtered_groups[filter].Push(group, type, /*insert_positive=*/true, /*insert_mixed=*/true);
     558                 :             :                     accepted = true;
     559                 :             :                 }
     560   [ +  +  +  - ]:      516804 :                 if (!accepted) ret_discarded_groups.emplace_back(group);
     561                 :      516804 :             }
     562                 :             :         }
     563                 :             :         return filtered_groups;
     564                 :             :     }
     565                 :             : 
     566                 :             :     // We want to combine COutputs that have the same scriptPubKey into single OutputGroups
     567                 :             :     // except when there are more than OUTPUT_GROUP_MAX_ENTRIES COutputs grouped in an OutputGroup.
     568                 :             :     // To do this, we maintain a map where the key is the scriptPubKey and the value is a vector of OutputGroups.
     569                 :             :     // For each COutput, we check if the scriptPubKey is in the map, and if it is, the COutput is added
     570                 :             :     // to the last OutputGroup in the vector for the scriptPubKey. When the last OutputGroup has
     571                 :             :     // OUTPUT_GROUP_MAX_ENTRIES COutputs, a new OutputGroup is added to the end of the vector.
     572                 :        1487 :     typedef std::map<std::pair<CScript, OutputType>, std::vector<OutputGroup>> ScriptPubKeyToOutgroup;
     573                 :      121549 :     const auto& insert_output = [&](
     574                 :             :             const std::shared_ptr<COutput>& output, OutputType type, size_t ancestors, size_t descendants,
     575                 :             :             ScriptPubKeyToOutgroup& groups_map) {
     576         [ +  - ]:      120062 :         std::vector<OutputGroup>& groups = groups_map[std::make_pair(output->txout.scriptPubKey,type)];
     577                 :             : 
     578         [ +  + ]:      120062 :         if (groups.size() == 0) {
     579                 :             :             // No OutputGroups for this scriptPubKey yet, add one
     580                 :       75610 :             groups.emplace_back(coin_sel_params);
     581                 :             :         }
     582                 :             : 
     583                 :             :         // Get the last OutputGroup in the vector so that we can add the COutput to it
     584                 :             :         // A pointer is used here so that group can be reassigned later if it is full.
     585                 :      120062 :         OutputGroup* group = &groups.back();
     586                 :             : 
     587                 :             :         // Check if this OutputGroup is full. We limit to OUTPUT_GROUP_MAX_ENTRIES when using -avoidpartialspends
     588                 :             :         // to avoid surprising users with very high fees.
     589         [ +  + ]:      120062 :         if (group->m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
     590                 :             :             // The last output group is full, add a new group to the vector and use that group for the insertion
     591                 :         228 :             groups.emplace_back(coin_sel_params);
     592                 :         228 :             group = &groups.back();
     593                 :             :         }
     594                 :             : 
     595                 :      120062 :         group->Insert(output, ancestors, descendants);
     596                 :      120062 :     };
     597                 :             : 
     598                 :        1487 :     ScriptPubKeyToOutgroup spk_to_groups_map;
     599                 :        1487 :     ScriptPubKeyToOutgroup spk_to_positive_groups_map;
     600         [ +  + ]:        3792 :     for (const auto& [type, outs] : coins.coins) {
     601         [ +  + ]:       62345 :         for (const COutput& output : outs) {
     602                 :       60040 :             size_t ancestors, descendants;
     603         [ +  - ]:       60040 :             wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, descendants);
     604                 :             : 
     605         [ +  - ]:       60040 :             const auto& shared_output = std::make_shared<COutput>(output);
     606                 :             :             // Filter for positive only before adding the output
     607         [ +  + ]:       60040 :             if (output.GetEffectiveValue() > 0) {
     608         [ +  - ]:       60022 :                 insert_output(shared_output, type, ancestors, descendants, spk_to_positive_groups_map);
     609                 :             :             }
     610                 :             : 
     611                 :             :             // 'All' groups
     612         [ +  - ]:       60040 :             insert_output(shared_output, type, ancestors, descendants, spk_to_groups_map);
     613                 :       60040 :         }
     614                 :             :     }
     615                 :             : 
     616                 :             :     // Now we go through the entire maps and pull out the OutputGroups
     617                 :        4461 :     const auto& push_output_groups = [&](const ScriptPubKeyToOutgroup& groups_map, bool positive_only) {
     618         [ +  + ]:       78584 :         for (const auto& [script, groups] : groups_map) {
     619                 :             :             // Go through the vector backwards. This allows for the first item we deal with being the partial group.
     620         [ +  + ]:      151448 :             for (auto group_it = groups.rbegin(); group_it != groups.rend(); group_it++) {
     621                 :       75838 :                 const OutputGroup& group = *group_it;
     622                 :             : 
     623                 :             :                 // Each filter maps to a different set of groups
     624                 :       75838 :                 bool accepted = false;
     625         [ +  + ]:      530704 :                 for (const auto& sel_filter : filters) {
     626                 :      454866 :                     const auto& filter = sel_filter.filter;
     627         [ +  + ]:      454866 :                     if (!group.EligibleForSpending(filter)) continue;
     628                 :             : 
     629                 :             :                     // Don't include partial groups if there are full groups too and we don't want partial groups
     630   [ +  +  +  +  :      350106 :                     if (group_it == groups.rbegin() && groups.size() > 1 && !filter.m_include_partial_groups) {
                   +  + ]
     631                 :         124 :                         continue;
     632                 :             :                     }
     633                 :             : 
     634                 :      349982 :                     OutputType type = script.second;
     635                 :             :                     // Either insert the group into the positive-only groups or the mixed ones.
     636                 :      349982 :                     filtered_groups[filter].Push(group, type, positive_only, /*insert_mixed=*/!positive_only);
     637                 :      349982 :                     accepted = true;
     638                 :             :                 }
     639         [ +  + ]:       75838 :                 if (!accepted) ret_discarded_groups.emplace_back(group);
     640                 :             :             }
     641                 :             :         }
     642                 :        4461 :     };
     643                 :             : 
     644         [ +  - ]:        1487 :     push_output_groups(spk_to_groups_map, /*positive_only=*/ false);
     645         [ +  - ]:        1487 :     push_output_groups(spk_to_positive_groups_map, /*positive_only=*/ true);
     646                 :             : 
     647                 :        1487 :     return filtered_groups;
     648                 :        1487 : }
     649                 :             : 
     650                 :        3427 : FilteredOutputGroups GroupOutputs(const CWallet& wallet,
     651                 :             :                                   const CoinsResult& coins,
     652                 :             :                                   const CoinSelectionParams& params,
     653                 :             :                                   const std::vector<SelectionFilter>& filters)
     654                 :             : {
     655                 :        3427 :     std::vector<OutputGroup> unused;
     656         [ +  - ]:        6854 :     return GroupOutputs(wallet, coins, params, filters, unused);
     657                 :        3427 : }
     658                 :             : 
     659                 :             : // Returns true if the result contains an error and the message is not empty
     660                 :       11392 : static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
     661                 :             : 
     662                 :        3507 : util::Result<SelectionResult> AttemptSelection(interfaces::Chain& chain, const CAmount& nTargetValue, OutputGroupTypeMap& groups,
     663                 :             :                                const CoinSelectionParams& coin_selection_params, bool allow_mixed_output_types)
     664                 :             : {
     665                 :             :     // Run coin selection on each OutputType and compute the Waste Metric
     666                 :        3507 :     std::vector<SelectionResult> results;
     667   [ +  -  +  + ]:        8462 :     for (auto& [type, group] : groups.groups_by_type) {
     668         [ +  - ]:        5007 :         auto result{ChooseSelectionResult(chain, nTargetValue, group, coin_selection_params)};
     669                 :             :         // If any specific error message appears here, then something particularly wrong happened.
     670   [ +  -  +  + ]:        5007 :         if (HasErrorMsg(result)) return result; // So let's return the specific error.
     671                 :             :         // Append the favorable result.
     672   [ +  +  +  - ]:        4955 :         if (result) results.push_back(*result);
     673                 :        4955 :     }
     674                 :             :     // If we have at least one solution for funding the transaction without mixing, choose the minimum one according to waste metric
     675                 :             :     // and return the result
     676   [ +  +  +  -  :        6454 :     if (results.size() > 0) return *std::min_element(results.begin(), results.end());
                   +  - ]
     677                 :             : 
     678                 :             :     // If we can't fund the transaction from any individual OutputType, run coin selection one last time
     679                 :             :     // over all available coins, which would allow mixing.
     680                 :             :     // If TypesCount() <= 1, there is nothing to mix.
     681   [ +  +  +  + ]:         456 :     if (allow_mixed_output_types && groups.TypesCount() > 1) {
     682         [ +  - ]:          68 :         return ChooseSelectionResult(chain, nTargetValue, groups.all_groups, coin_selection_params);
     683                 :             :     }
     684                 :             :     // Either mixing is not allowed and we couldn't find a solution from any single OutputType, or mixing was allowed and we still couldn't
     685                 :             :     // find a solution using all available coins
     686                 :         776 :     return util::Error();
     687                 :        3507 : };
     688                 :             : 
     689                 :        5075 : util::Result<SelectionResult> ChooseSelectionResult(interfaces::Chain& chain, const CAmount& nTargetValue, Groups& groups, const CoinSelectionParams& coin_selection_params)
     690                 :             : {
     691                 :             :     // Vector of results. We will choose the best one based on waste.
     692                 :        5075 :     std::vector<SelectionResult> results;
     693                 :        5075 :     std::vector<util::Result<SelectionResult>> errors;
     694                 :       11018 :     auto append_error = [&] (util::Result<SelectionResult>&& result) {
     695                 :             :         // If any specific error message appears here, then something different from a simple "no selection found" happened.
     696                 :             :         // Let's save it, so it can be retrieved to the user if no other selection algorithm succeeded.
     697         [ +  + ]:        5943 :         if (HasErrorMsg(result)) {
     698                 :          91 :             errors.emplace_back(std::move(result));
     699                 :             :         }
     700                 :       11018 :     };
     701                 :             : 
     702                 :             :     // Maximum allowed weight for selected coins.
     703         [ +  + ]:        5075 :     int max_transaction_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
     704                 :        5075 :     int tx_weight_no_input = coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR;
     705                 :        5075 :     int max_selection_weight = max_transaction_weight - tx_weight_no_input;
     706         [ +  + ]:        5075 :     if (max_selection_weight <= 0) {
     707         [ +  - ]:          36 :         return util::Error{_("Maximum transaction weight is less than transaction weight without inputs")};
     708                 :             :     }
     709                 :             : 
     710                 :             :     // SFFO frequently causes issues in the context of changeless input sets: skip BnB when SFFO is active
     711         [ +  + ]:        5063 :     if (!coin_selection_params.m_subtract_fee_outputs) {
     712   [ +  -  +  + ]:        3621 :         if (auto bnb_result{SelectCoinsBnB(groups.positive_group, nTargetValue, coin_selection_params.m_cost_of_change, max_selection_weight)}) {
     713         [ +  - ]:         114 :             results.push_back(*bnb_result);
     714         [ +  - ]:        7128 :         } else append_error(std::move(bnb_result));
     715                 :             :     }
     716                 :             : 
     717                 :             :     // Deduct change weight because remaining Coin Selection algorithms can create change output
     718                 :        5063 :     int change_outputs_weight = coin_selection_params.change_output_size * WITNESS_SCALE_FACTOR;
     719                 :        5063 :     max_selection_weight -= change_outputs_weight;
     720   [ +  +  +  - ]:        5063 :     if (max_selection_weight < 0 && results.empty()) {
     721         [ +  - ]:          18 :         return util::Error{_("Maximum transaction weight is too low, can not accommodate change output")};
     722                 :             :     }
     723                 :             : 
     724                 :             :     // The knapsack solver has some legacy behavior where it will spend dust outputs. We retain this behavior, so don't filter for positive only here.
     725   [ +  -  +  + ]:        5057 :     if (auto knapsack_result{KnapsackSolver(groups.mixed_group, nTargetValue, coin_selection_params.m_min_change_target, coin_selection_params.rng_fast, max_selection_weight)}) {
     726         [ +  - ]:        4032 :         results.push_back(*knapsack_result);
     727         [ +  - ]:        1025 :     } else append_error(std::move(knapsack_result));
     728                 :             : 
     729         [ +  + ]:        5057 :     if (coin_selection_params.m_effective_feerate > CFeeRate{3 * coin_selection_params.m_long_term_feerate}) { // Minimize input set for feerates of at least 3×LTFRE (default: 30 ṩ/vB+)
     730   [ +  -  +  + ]:         812 :         if (auto cg_result{CoinGrinder(groups.positive_group, nTargetValue, coin_selection_params.m_min_change_target, max_selection_weight)}) {
     731         [ +  - ]:         476 :             cg_result->RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
     732         [ +  - ]:         476 :             results.push_back(*cg_result);
     733                 :             :         } else {
     734         [ +  - ]:         336 :             append_error(std::move(cg_result));
     735                 :         812 :         }
     736                 :             :     }
     737                 :             : 
     738   [ +  -  +  + ]:        5057 :     if (auto srd_result{SelectCoinsSRD(groups.positive_group, nTargetValue, coin_selection_params.m_change_fee, coin_selection_params.rng_fast, max_selection_weight)}) {
     739         [ +  - ]:        3982 :         results.push_back(*srd_result);
     740         [ +  - ]:        1075 :     } else append_error(std::move(srd_result));
     741                 :             : 
     742         [ +  + ]:        5057 :     if (results.empty()) {
     743                 :             :         // No solution found, retrieve the first explicit error (if any).
     744                 :             :         // future: add 'severity level' to errors so the worst one can be retrieved instead of the first one.
     745         [ +  + ]:        2016 :         return errors.empty() ? util::Error() : std::move(errors.front());
     746                 :             :     }
     747                 :             : 
     748                 :             :     // If the chosen input set has unconfirmed inputs, check for synergies from overlapping ancestry
     749         [ +  + ]:       12636 :     for (auto& result : results) {
     750                 :        8604 :         std::vector<COutPoint> outpoints;
     751   [ +  -  +  - ]:        8604 :         std::set<std::shared_ptr<COutput>> coins = result.GetInputSet();
     752                 :        8604 :         CAmount summed_bump_fees = 0;
     753         [ +  + ]:      175882 :         for (auto& coin : coins) {
     754         [ +  + ]:      167278 :             if (coin->depth > 0) continue; // Bump fees only exist for unconfirmed inputs
     755         [ +  - ]:        1713 :             outpoints.push_back(coin->outpoint);
     756                 :        1713 :             summed_bump_fees += coin->ancestor_bump_fees;
     757                 :             :         }
     758         [ +  - ]:        8604 :         std::optional<CAmount> combined_bump_fee = chain.calculateCombinedBumpFee(outpoints, coin_selection_params.m_effective_feerate);
     759         [ -  + ]:        8604 :         if (!combined_bump_fee.has_value()) {
     760         [ #  # ]:           0 :             return util::Error{_("Failed to calculate bump fees, because unconfirmed UTXOs depend on enormous cluster of unconfirmed transactions.")};
     761                 :             :         }
     762         [ +  + ]:        8604 :         CAmount bump_fee_overestimate = summed_bump_fees - combined_bump_fee.value();
     763         [ +  + ]:        8604 :         if (bump_fee_overestimate) {
     764         [ +  - ]:          14 :             result.SetBumpFeeDiscount(bump_fee_overestimate);
     765                 :             :         }
     766         [ +  - ]:        8604 :         result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
     767                 :        8604 :     }
     768                 :             : 
     769                 :             :     // Choose the result with the least waste
     770                 :             :     // If the waste is the same, choose the one which spends more inputs.
     771   [ +  -  +  - ]:        8064 :     return *std::min_element(results.begin(), results.end());
     772                 :        5075 : }
     773                 :             : 
     774                 :        3457 : util::Result<SelectionResult> SelectCoins(const CWallet& wallet, CoinsResult& available_coins, const PreSelectedInputs& pre_set_inputs,
     775                 :             :                                           const CAmount& nTargetValue, const CCoinControl& coin_control,
     776                 :             :                                           const CoinSelectionParams& coin_selection_params)
     777                 :             : {
     778                 :             :     // Deduct preset inputs amount from the search target
     779                 :        3457 :     CAmount selection_target = nTargetValue - pre_set_inputs.total_amount;
     780                 :             : 
     781                 :             :     // Return if automatic coin selection is disabled, and we don't cover the selection target
     782   [ +  +  +  + ]:        3457 :     if (!coin_control.m_allow_other_inputs && selection_target > 0) {
     783                 :          24 :         return util::Error{_("The preselected coins total amount does not cover the transaction target. "
     784                 :          12 :                              "Please allow other inputs to be automatically selected or include more coins manually")};
     785                 :             :     }
     786                 :             : 
     787                 :             :     // Return if we can cover the target only with the preset inputs
     788         [ +  + ]:        3445 :     if (selection_target <= 0) {
     789         [ +  - ]:         355 :         SelectionResult result(nTargetValue, SelectionAlgorithm::MANUAL);
     790         [ +  - ]:         355 :         result.AddInputs(pre_set_inputs.coins, coin_selection_params.m_subtract_fee_outputs);
     791         [ +  - ]:         355 :         result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
     792                 :         355 :         return result;
     793                 :         355 :     }
     794                 :             : 
     795                 :             :     // Return early if we cannot cover the target with the wallet's UTXO.
     796                 :             :     // We use the total effective value if we are not subtracting fee from outputs and 'available_coins' contains the data.
     797         [ +  + ]:        3090 :     CAmount available_coins_total_amount = coin_selection_params.m_subtract_fee_outputs ? available_coins.GetTotalAmount() :
     798         [ +  - ]:        2470 :             (available_coins.GetEffectiveTotalAmount().has_value() ? *available_coins.GetEffectiveTotalAmount() : 0);
     799         [ +  + ]:        3090 :     if (selection_target > available_coins_total_amount) {
     800                 :          28 :         return util::Error(); // Insufficient funds
     801                 :             :     }
     802                 :             : 
     803                 :             :     // Start wallet Coin Selection procedure
     804                 :        3076 :     auto op_selection_result = AutomaticCoinSelection(wallet, available_coins, selection_target, coin_selection_params);
     805         [ +  + ]:        3076 :     if (!op_selection_result) return op_selection_result;
     806                 :             : 
     807                 :             :     // If needed, add preset inputs to the automatic coin selection result
     808         [ +  + ]:        3065 :     if (!pre_set_inputs.coins.empty()) {
     809         [ +  - ]:          80 :         SelectionResult preselected(pre_set_inputs.total_amount, SelectionAlgorithm::MANUAL);
     810         [ +  - ]:          80 :         preselected.AddInputs(pre_set_inputs.coins, coin_selection_params.m_subtract_fee_outputs);
     811         [ +  - ]:          80 :         op_selection_result->Merge(preselected);
     812                 :          80 :         op_selection_result->RecalculateWaste(coin_selection_params.min_viable_change,
     813                 :          80 :                                                 coin_selection_params.m_cost_of_change,
     814         [ +  - ]:          80 :                                                 coin_selection_params.m_change_fee);
     815                 :             : 
     816                 :             :         // Verify we haven't exceeded the maximum allowed weight
     817         [ +  + ]:          80 :         int max_inputs_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT) - (coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR);
     818         [ +  + ]:          80 :         if (op_selection_result->GetWeight() > max_inputs_weight) {
     819         [ +  - ]:           4 :             return util::Error{_("The combination of the pre-selected inputs and the wallet automatic inputs selection exceeds the transaction maximum weight. "
     820                 :           2 :                                  "Please try sending a smaller amount or manually consolidating your wallet's UTXOs")};
     821                 :             :         }
     822                 :          80 :     }
     823                 :        3063 :     return op_selection_result;
     824                 :        3076 : }
     825                 :             : 
     826                 :        3076 : util::Result<SelectionResult> AutomaticCoinSelection(const CWallet& wallet, CoinsResult& available_coins, const CAmount& value_to_select, const CoinSelectionParams& coin_selection_params)
     827                 :             : {
     828                 :        3076 :     unsigned int limit_ancestor_count = 0;
     829                 :        3076 :     unsigned int limit_descendant_count = 0;
     830                 :        3076 :     wallet.chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
     831         [ -  + ]:        3076 :     const size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
     832         [ -  + ]:        3076 :     const size_t max_descendants = (size_t)std::max<int64_t>(1, limit_descendant_count);
     833         [ +  - ]:        3076 :     const bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
     834                 :             : 
     835                 :             :     // Cases where we have 101+ outputs all pointing to the same destination may result in
     836                 :             :     // privacy leaks as they will potentially be deterministically sorted. We solve that by
     837                 :             :     // explicitly shuffling the outputs before processing
     838   [ +  +  +  + ]:        3076 :     if (coin_selection_params.m_avoid_partial_spends && available_coins.Size() > OUTPUT_GROUP_MAX_ENTRIES) {
     839                 :          20 :         available_coins.Shuffle(coin_selection_params.rng_fast);
     840                 :             :     }
     841                 :             : 
     842                 :             :     // Coin Selection attempts to select inputs from a pool of eligible UTXOs to fund the
     843                 :             :     // transaction at a target feerate. If an attempt fails, more attempts may be made using a more
     844                 :             :     // permissive CoinEligibilityFilter.
     845                 :        3076 :     {
     846                 :             :         // Place coins eligibility filters on a scope increasing order.
     847                 :        3076 :         std::vector<SelectionFilter> ordered_filters{
     848                 :             :                 // If possible, fund the transaction with confirmed UTXOs only. Prefer at least six
     849                 :             :                 // confirmations on outputs received from other wallets and only spend confirmed change.
     850                 :             :                 {CoinEligibilityFilter(1, 6, 0), /*allow_mixed_output_types=*/false},
     851                 :             :                 {CoinEligibilityFilter(1, 1, 0)},
     852                 :        3076 :         };
     853                 :             :         // Fall back to using zero confirmation change (but with as few ancestors in the mempool as
     854                 :             :         // possible) if we cannot fund the transaction otherwise.
     855         [ +  + ]:        3076 :         if (wallet.m_spend_zero_conf_change) {
     856         [ +  - ]:        3074 :             ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
     857   [ +  +  +  +  :        9180 :             ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min(size_t{4}, max_ancestors/3), std::min(size_t{4}, max_descendants/3))});
                   +  - ]
     858         [ +  - ]:        3074 :             ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2)});
     859                 :             :             // If partial groups are allowed, relax the requirement of spending OutputGroups (groups
     860                 :             :             // of UTXOs sent to the same address, which are obviously controlled by a single wallet)
     861                 :             :             // in their entirety.
     862         [ +  - ]:        3074 :             ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1, /*include_partial=*/true)});
     863                 :             :             // Try with unsafe inputs if they are allowed. This may spend unconfirmed outputs
     864                 :             :             // received from other wallets.
     865         [ +  + ]:        3074 :             if (coin_selection_params.m_include_unsafe_inputs) {
     866         [ +  - ]:           7 :                 ordered_filters.push_back({CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs*/0, max_ancestors-1, max_descendants-1, /*include_partial=*/true)});
     867                 :             :             }
     868                 :             :             // Try with unlimited ancestors/descendants. The transaction will still need to meet
     869                 :             :             // mempool ancestor/descendant policy to be accepted to mempool and broadcasted, but
     870                 :             :             // OutputGroups use heuristics that may overestimate ancestor/descendant counts.
     871         [ +  + ]:        3074 :             if (!fRejectLongChains) {
     872         [ +  - ]:          58 :                 ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max(),
     873                 :             :                                                                    std::numeric_limits<uint64_t>::max(),
     874                 :             :                                                                    /*include_partial=*/true)});
     875                 :             :             }
     876                 :             :         }
     877                 :             : 
     878                 :             :         // Group outputs and map them by coin eligibility filter
     879                 :        3076 :         std::vector<OutputGroup> discarded_groups;
     880         [ +  - ]:        3076 :         FilteredOutputGroups filtered_groups = GroupOutputs(wallet, available_coins, coin_selection_params, ordered_filters, discarded_groups);
     881                 :             : 
     882                 :             :         // Check if we still have enough balance after applying filters (some coins might be discarded)
     883                 :        3076 :         CAmount total_discarded = 0;
     884                 :        3076 :         CAmount total_unconf_long_chain = 0;
     885         [ +  + ]:        3106 :         for (const auto& group : discarded_groups) {
     886         [ +  - ]:          30 :             total_discarded += group.GetSelectionAmount();
     887   [ +  +  +  +  :          30 :             if (group.m_ancestors >= max_ancestors || group.m_descendants >= max_descendants) total_unconf_long_chain += group.GetSelectionAmount();
                   +  - ]
     888                 :             :         }
     889                 :             : 
     890         [ +  + ]:        3076 :         if (CAmount total_amount = available_coins.GetTotalAmount() - total_discarded < value_to_select) {
     891                 :             :             // Special case, too-long-mempool cluster.
     892         [ +  + ]:           2 :             if (total_amount + total_unconf_long_chain > value_to_select) {
     893         [ +  - ]:           3 :                 return util::Error{_("Unconfirmed UTXOs are available, but spending them creates a chain of transactions that will be rejected by the mempool")};
     894                 :             :             }
     895                 :           2 :             return util::Error{}; // General "Insufficient Funds"
     896                 :             :         }
     897                 :             : 
     898                 :             :         // Walk-through the filters until the solution gets found.
     899                 :             :         // If no solution is found, return the first detailed error (if any).
     900                 :             :         // future: add "error level" so the worst one can be picked instead.
     901                 :        3074 :         std::vector<util::Result<SelectionResult>> res_detailed_errors;
     902         [ +  + ]:        5207 :         for (const auto& select_filter : ordered_filters) {
     903                 :        5198 :             auto it = filtered_groups.find(select_filter.filter);
     904         [ +  + ]:        5198 :             if (it == filtered_groups.end()) continue;
     905                 :        7014 :             if (auto res{AttemptSelection(wallet.chain(), value_to_select, it->second,
     906   [ +  -  +  + ]:        3507 :                                           coin_selection_params, select_filter.allow_mixed_output_types)}) {
     907                 :        3065 :                 return res; // result found
     908                 :             :             } else {
     909                 :             :                 // If any specific error message appears here, then something particularly wrong might have happened.
     910                 :             :                 // Save the error and continue the selection process. So if no solutions gets found, we can return
     911                 :             :                 // the detailed error to the upper layers.
     912   [ +  -  +  +  :         442 :                 if (HasErrorMsg(res)) res_detailed_errors.emplace_back(std::move(res));
                   +  - ]
     913                 :        3507 :             }
     914                 :             :         }
     915                 :             : 
     916                 :             :         // Return right away if we have a detailed error
     917         [ +  - ]:           9 :         if (!res_detailed_errors.empty()) return std::move(res_detailed_errors.front());
     918                 :             : 
     919                 :             : 
     920                 :             :         // General "Insufficient Funds"
     921                 :           0 :         return util::Error{};
     922                 :        6150 :     }
     923                 :             : }
     924                 :             : 
     925                 :        2606 : static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
     926                 :             : {
     927         [ +  - ]:        2606 :     if (chain.isInitialBlockDownload()) {
     928                 :             :         return false;
     929                 :             :     }
     930                 :        2606 :     constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
     931                 :        2606 :     int64_t block_time;
     932                 :        2606 :     CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
     933         [ +  + ]:        2606 :     if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
     934                 :           8 :         return false;
     935                 :             :     }
     936                 :             :     return true;
     937                 :             : }
     938                 :             : 
     939                 :             : /**
     940                 :             :  * Set a height-based locktime for new transactions (uses the height of the
     941                 :             :  * current chain tip unless we are not synced with the current chain
     942                 :             :  */
     943                 :        2606 : static void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast,
     944                 :             :                                  interfaces::Chain& chain, const uint256& block_hash, int block_height)
     945                 :             : {
     946                 :             :     // All inputs must be added by now
     947         [ -  + ]:        2606 :     assert(!tx.vin.empty());
     948                 :             :     // Discourage fee sniping.
     949                 :             :     //
     950                 :             :     // For a large miner the value of the transactions in the best block and
     951                 :             :     // the mempool can exceed the cost of deliberately attempting to mine two
     952                 :             :     // blocks to orphan the current best block. By setting nLockTime such that
     953                 :             :     // only the next block can include the transaction, we discourage this
     954                 :             :     // practice as the height restricted and limited blocksize gives miners
     955                 :             :     // considering fee sniping fewer options for pulling off this attack.
     956                 :             :     //
     957                 :             :     // A simple way to think about this is from the wallet's point of view we
     958                 :             :     // always want the blockchain to move forward. By setting nLockTime this
     959                 :             :     // way we're basically making the statement that we only want this
     960                 :             :     // transaction to appear in the next block; we don't want to potentially
     961                 :             :     // encourage reorgs by allowing transactions to appear at lower heights
     962                 :             :     // than the next block in forks of the best chain.
     963                 :             :     //
     964                 :             :     // Of course, the subsidy is high enough, and transaction volume low
     965                 :             :     // enough, that fee sniping isn't a problem yet, but by implementing a fix
     966                 :             :     // now we ensure code won't be written that makes assumptions about
     967                 :             :     // nLockTime that preclude a fix later.
     968         [ +  + ]:        2606 :     if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
     969                 :        2598 :         tx.nLockTime = block_height;
     970                 :             : 
     971                 :             :         // Secondly occasionally randomly pick a nLockTime even further back, so
     972                 :             :         // that transactions that are delayed after signing for whatever reason,
     973                 :             :         // e.g. high-latency mix networks and some CoinJoin implementations, have
     974                 :             :         // better privacy.
     975         [ +  + ]:        5196 :         if (rng_fast.randrange(10) == 0) {
     976         [ -  + ]:         500 :             tx.nLockTime = std::max(0, int(tx.nLockTime) - int(rng_fast.randrange(100)));
     977                 :             :         }
     978                 :             :     } else {
     979                 :             :         // If our chain is lagging behind, we can't discourage fee sniping nor help
     980                 :             :         // the privacy of high-latency transactions. To avoid leaking a potentially
     981                 :             :         // unique "nLockTime fingerprint", set nLockTime to a constant.
     982                 :           8 :         tx.nLockTime = 0;
     983                 :             :     }
     984                 :             :     // Sanity check all values
     985         [ -  + ]:        2606 :     assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Type must be block height
     986         [ -  + ]:        2606 :     assert(tx.nLockTime <= uint64_t(block_height));
     987         [ +  + ]:       11218 :     for (const auto& in : tx.vin) {
     988                 :             :         // Can not be FINAL for locktime to work
     989         [ -  + ]:        8612 :         assert(in.nSequence != CTxIn::SEQUENCE_FINAL);
     990                 :             :         // May be MAX NONFINAL to disable both BIP68 and BIP125
     991         [ +  + ]:        8612 :         if (in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL) continue;
     992                 :             :         // May be MAX BIP125 to disable BIP68 and enable BIP125
     993         [ +  - ]:        8405 :         if (in.nSequence == MAX_BIP125_RBF_SEQUENCE) continue;
     994                 :             :         // The wallet does not support any other sequence-use right now.
     995                 :           0 :         assert(false);
     996                 :             :     }
     997                 :        2606 : }
     998                 :             : 
     999                 :       39913 : size_t GetSerializeSizeForRecipient(const CRecipient& recipient)
    1000                 :             : {
    1001         [ +  - ]:       39913 :     return ::GetSerializeSize(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)));
    1002                 :             : }
    1003                 :             : 
    1004                 :       39913 : bool IsDust(const CRecipient& recipient, const CFeeRate& dustRelayFee)
    1005                 :             : {
    1006   [ +  -  +  - ]:       39913 :     return ::IsDust(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)), dustRelayFee);
    1007                 :             : }
    1008                 :             : 
    1009                 :        3381 : static util::Result<CreatedTransactionResult> CreateTransactionInternal(
    1010                 :             :         CWallet& wallet,
    1011                 :             :         const std::vector<CRecipient>& vecSend,
    1012                 :             :         std::optional<unsigned int> change_pos,
    1013                 :             :         const CCoinControl& coin_control,
    1014                 :             :         bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
    1015                 :             : {
    1016                 :        3381 :     AssertLockHeld(wallet.cs_wallet);
    1017                 :             : 
    1018                 :        3381 :     FastRandomContext rng_fast;
    1019         [ +  - ]:        3381 :     CMutableTransaction txNew; // The resulting transaction that we make
    1020                 :             : 
    1021         [ +  + ]:        3381 :     if (coin_control.m_version) {
    1022                 :         761 :         txNew.version = coin_control.m_version.value();
    1023                 :             :     }
    1024                 :             : 
    1025         [ +  + ]:        3381 :     CoinSelectionParams coin_selection_params{rng_fast}; // Parameters for coin selection, init with dummy
    1026                 :        3381 :     coin_selection_params.m_avoid_partial_spends = coin_control.m_avoid_partial_spends;
    1027                 :        3381 :     coin_selection_params.m_include_unsafe_inputs = coin_control.m_include_unsafe_inputs;
    1028   [ +  +  +  - ]:        3390 :     coin_selection_params.m_max_tx_weight = coin_control.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
    1029                 :        3381 :     int minimum_tx_weight = MIN_STANDARD_TX_NONWITNESS_SIZE * WITNESS_SCALE_FACTOR;
    1030   [ +  -  +  +  :        3381 :     if (coin_selection_params.m_max_tx_weight.value() < minimum_tx_weight || coin_selection_params.m_max_tx_weight.value() > MAX_STANDARD_TX_WEIGHT) {
                   +  + ]
    1031         [ +  - ]:           9 :         return util::Error{strprintf(_("Maximum transaction weight must be between %d and %d"), minimum_tx_weight, MAX_STANDARD_TX_WEIGHT)};
    1032                 :             :     }
    1033                 :             :     // Set the long term feerate estimate to the wallet's consolidate feerate
    1034                 :        3378 :     coin_selection_params.m_long_term_feerate = wallet.m_consolidate_feerate;
    1035                 :             :     // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
    1036         [ +  + ]:        3378 :     coin_selection_params.tx_noinputs_size = 10 + GetSizeOfCompactSize(vecSend.size()); // bytes for output count
    1037                 :             : 
    1038                 :        3378 :     CAmount recipients_sum = 0;
    1039   [ +  +  +  - ]:        3378 :     const OutputType change_type = wallet.TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : wallet.m_default_change_type, vecSend);
    1040                 :        3378 :     ReserveDestination reservedest(&wallet, change_type);
    1041                 :        3378 :     unsigned int outputs_to_subtract_fee_from = 0; // The number of outputs which we are subtracting the fee from
    1042         [ +  + ]:       43291 :     for (const auto& recipient : vecSend) {
    1043   [ +  -  +  -  :       39913 :         if (IsDust(recipient, wallet.chain().relayDustFee())) {
                   -  + ]
    1044         [ #  # ]:           0 :             return util::Error{_("Transaction amount too small")};
    1045                 :             :         }
    1046                 :             : 
    1047                 :             :         // Include the fee cost for outputs.
    1048         [ +  - ]:       39913 :         coin_selection_params.tx_noinputs_size += GetSerializeSizeForRecipient(recipient);
    1049                 :       39913 :         recipients_sum += recipient.nAmount;
    1050                 :             : 
    1051         [ +  + ]:       39913 :         if (recipient.fSubtractFeeFromAmount) {
    1052                 :         640 :             outputs_to_subtract_fee_from++;
    1053                 :         640 :             coin_selection_params.m_subtract_fee_outputs = true;
    1054                 :             :         }
    1055                 :             :     }
    1056                 :             : 
    1057                 :             :     // Create change script that will be used if we need change
    1058                 :        3378 :     CScript scriptChange;
    1059         [ +  - ]:        3378 :     bilingual_str error; // possible error str
    1060                 :             : 
    1061                 :             :     // coin control: send change to custom address
    1062         [ +  - ]:        3378 :     if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
    1063         [ +  - ]:        3382 :         scriptChange = GetScriptForDestination(coin_control.destChange);
    1064                 :             :     } else { // no coin control: send change to newly generated address
    1065                 :             :         // Note: We use a new key here to keep it from being obvious which side is the change.
    1066                 :             :         //  The drawback is that by not reusing a previous key, the change may be lost if a
    1067                 :             :         //  backup is restored, if the backup doesn't have the new private key for the change.
    1068                 :             :         //  If we reused the old key, it would be possible to add code to look for and
    1069                 :             :         //  rediscover unknown transactions that were written with keys of ours to recover
    1070                 :             :         //  post-backup change.
    1071                 :             : 
    1072                 :             :         // Reserve a new key pair from key pool. If it fails, provide a dummy
    1073                 :             :         // destination in case we don't need change.
    1074                 :        1687 :         CTxDestination dest;
    1075         [ +  - ]:        1687 :         auto op_dest = reservedest.GetReservedDestination(true);
    1076         [ +  + ]:        1687 :         if (!op_dest) {
    1077   [ +  -  +  -  :          84 :             error = _("Transaction needs a change address, but we can't generate it.") + Untranslated(" ") + util::ErrorString(op_dest);
             +  -  +  - ]
    1078                 :             :         } else {
    1079         [ +  - ]:        1673 :             dest = *op_dest;
    1080         [ +  - ]:        3346 :             scriptChange = GetScriptForDestination(dest);
    1081                 :             :         }
    1082                 :             :         // A valid destination implies a change script (and
    1083                 :             :         // vice-versa). An empty change script will abort later, if the
    1084                 :             :         // change keypool ran out, but change is required.
    1085   [ +  -  +  +  :        2011 :         CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
                   +  - ]
    1086                 :        1687 :     }
    1087         [ +  - ]:        3378 :     CTxOut change_prototype_txout(0, scriptChange);
    1088                 :        3378 :     coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
    1089                 :             : 
    1090                 :             :     // Get size of spending the change output
    1091         [ +  - ]:        3378 :     int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, &wallet, /*coin_control=*/nullptr);
    1092                 :             :     // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
    1093                 :             :     // as lower-bound to allow BnB to do it's thing
    1094         [ +  + ]:        3378 :     if (change_spend_size == -1) {
    1095                 :          24 :         coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
    1096                 :             :     } else {
    1097                 :        3354 :         coin_selection_params.change_spend_size = change_spend_size;
    1098                 :             :     }
    1099                 :             : 
    1100                 :             :     // Set discard feerate
    1101         [ +  - ]:        3378 :     coin_selection_params.m_discard_feerate = GetDiscardRate(wallet);
    1102                 :             : 
    1103                 :             :     // Get the fee rate to use effective values in coin selection
    1104                 :        3378 :     FeeCalculation feeCalc;
    1105         [ +  - ]:        3378 :     coin_selection_params.m_effective_feerate = GetMinimumFeeRate(wallet, coin_control, &feeCalc);
    1106                 :             :     // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
    1107                 :             :     // provided one
    1108   [ +  +  +  + ]:        3378 :     if (coin_control.m_feerate && coin_selection_params.m_effective_feerate > *coin_control.m_feerate) {
    1109   [ +  -  +  -  :          63 :         return util::Error{strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)"), coin_control.m_feerate->ToString(FeeEstimateMode::SAT_VB), coin_selection_params.m_effective_feerate.ToString(FeeEstimateMode::SAT_VB))};
                   +  - ]
    1110                 :             :     }
    1111   [ +  +  +  + ]:        3357 :     if (feeCalc.reason == FeeReason::FALLBACK && !wallet.m_allow_fallback_fee) {
    1112                 :             :         // eventually allow a fallback fee
    1113         [ +  - ]:           9 :         return util::Error{strprintf(_("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable %s."), "-fallbackfee")};
    1114                 :             :     }
    1115                 :             : 
    1116                 :             :     // Calculate the cost of change
    1117                 :             :     // Cost of change is the cost of creating the change output + cost of spending the change output in the future.
    1118                 :             :     // For creating the change output now, we use the effective feerate.
    1119                 :             :     // For spending the change output in the future, we use the discard feerate for now.
    1120                 :             :     // So cost of change = (change output size * effective feerate) + (size of spending change output * discard feerate)
    1121         [ +  - ]:        3354 :     coin_selection_params.m_change_fee = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.change_output_size);
    1122         [ +  - ]:        3354 :     coin_selection_params.m_cost_of_change = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size) + coin_selection_params.m_change_fee;
    1123                 :             : 
    1124         [ +  - ]:        3354 :     coin_selection_params.m_min_change_target = GenerateChangeTarget(std::floor(recipients_sum / vecSend.size()), coin_selection_params.m_change_fee, rng_fast);
    1125                 :             : 
    1126                 :             :     // The smallest change amount should be:
    1127                 :             :     // 1. at least equal to dust threshold
    1128                 :             :     // 2. at least 1 sat greater than fees to spend it at m_discard_feerate
    1129         [ +  - ]:        3354 :     const auto dust = GetDustThreshold(change_prototype_txout, coin_selection_params.m_discard_feerate);
    1130         [ +  - ]:        3354 :     const auto change_spend_fee = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size);
    1131         [ +  + ]:        3354 :     coin_selection_params.min_viable_change = std::max(change_spend_fee + 1, dust);
    1132                 :             : 
    1133                 :             :     // Include the fees for things that aren't inputs, excluding the change output
    1134   [ +  +  +  - ]:        3354 :     const CAmount not_input_fees = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.m_subtract_fee_outputs ? 0 : coin_selection_params.tx_noinputs_size);
    1135                 :        3354 :     CAmount selection_target = recipients_sum + not_input_fees;
    1136                 :             : 
    1137                 :             :     // This can only happen if feerate is 0, and requested destinations are value of 0 (e.g. OP_RETURN)
    1138                 :             :     // and no pre-selected inputs. This will result in 0-input transaction, which is consensus-invalid anyways
    1139   [ +  +  +  -  :        3354 :     if (selection_target == 0 && !coin_control.HasSelected()) {
                   -  + ]
    1140         [ +  - ]:           3 :         return util::Error{_("Transaction requires one destination of non-zero value, a non-zero feerate, or a pre-selected input")};
    1141                 :             :     }
    1142                 :             : 
    1143                 :             :     // Fetch manually selected coins
    1144         [ +  - ]:        3353 :     PreSelectedInputs preset_inputs;
    1145   [ +  -  +  + ]:        3353 :     if (coin_control.HasSelected()) {
    1146         [ +  - ]:         452 :         auto res_fetch_inputs = FetchSelectedInputs(wallet, coin_control, coin_selection_params);
    1147   [ +  +  +  - ]:         458 :         if (!res_fetch_inputs) return util::Error{util::ErrorString(res_fetch_inputs)};
    1148         [ +  - ]:         449 :         preset_inputs = *res_fetch_inputs;
    1149                 :         452 :     }
    1150                 :             : 
    1151                 :             :     // Fetch wallet available coins if "other inputs" are
    1152                 :             :     // allowed (coins automatically selected by the wallet)
    1153         [ +  + ]:        3350 :     CoinsResult available_coins;
    1154         [ +  + ]:        3350 :     if (coin_control.m_allow_other_inputs) {
    1155         [ +  - ]:        6524 :         available_coins = AvailableCoins(wallet, &coin_control, coin_selection_params.m_effective_feerate);
    1156                 :             :     }
    1157                 :             : 
    1158                 :             :     // Choose coins to use
    1159         [ +  - ]:        3350 :     auto select_coins_res = SelectCoins(wallet, available_coins, preset_inputs, /*nTargetValue=*/selection_target, coin_control, coin_selection_params);
    1160         [ +  + ]:        3350 :     if (!select_coins_res) {
    1161                 :             :         // 'SelectCoins' either returns a specific error message or, if empty, means a general "Insufficient funds".
    1162         [ +  - ]:          37 :         const bilingual_str& err = util::ErrorString(select_coins_res);
    1163   [ +  +  +  -  :         111 :         return util::Error{err.empty() ?_("Insufficient funds") : err};
                   +  - ]
    1164                 :          37 :     }
    1165                 :        3313 :     const SelectionResult& result = *select_coins_res;
    1166                 :             :     TRACEPOINT(coin_selection, selected_coins,
    1167                 :             :            wallet.GetName().c_str(),
    1168                 :             :            GetAlgorithmName(result.GetAlgo()).c_str(),
    1169                 :             :            result.GetTarget(),
    1170                 :             :            result.GetWaste(),
    1171                 :        3313 :            result.GetSelectedValue());
    1172                 :             : 
    1173                 :             :     // vouts to the payees
    1174         [ +  - ]:        3313 :     txNew.vout.reserve(vecSend.size() + 1); // + 1 because of possible later insert
    1175         [ +  + ]:       43156 :     for (const auto& recipient : vecSend)
    1176                 :             :     {
    1177   [ +  -  +  - ]:       79686 :         txNew.vout.emplace_back(recipient.nAmount, GetScriptForDestination(recipient.dest));
    1178                 :             :     }
    1179         [ +  - ]:        3313 :     const CAmount change_amount = result.GetChange(coin_selection_params.min_viable_change, coin_selection_params.m_change_fee);
    1180         [ +  + ]:        3313 :     if (change_amount > 0) {
    1181         [ +  - ]:        3243 :         CTxOut newTxOut(change_amount, scriptChange);
    1182         [ +  + ]:        3243 :         if (!change_pos) {
    1183                 :             :             // Insert change txn at random position:
    1184                 :        3175 :             change_pos = rng_fast.randrange(txNew.vout.size() + 1);
    1185         [ -  + ]:          68 :         } else if ((unsigned int)*change_pos > txNew.vout.size()) {
    1186         [ #  # ]:           0 :             return util::Error{_("Transaction change output index out of range")};
    1187                 :             :         }
    1188         [ +  - ]:        3243 :         txNew.vout.insert(txNew.vout.begin() + *change_pos, newTxOut);
    1189                 :        3243 :     } else {
    1190         [ +  + ]:          70 :         change_pos = std::nullopt;
    1191                 :             :     }
    1192                 :             : 
    1193                 :             :     // Shuffle selected coins and fill in final vin
    1194         [ +  - ]:        3313 :     std::vector<std::shared_ptr<COutput>> selected_coins = result.GetShuffledInputVector();
    1195                 :             : 
    1196   [ +  -  +  +  :        3313 :     if (coin_control.HasSelected() && coin_control.HasSelectedOrder()) {
                   +  + ]
    1197                 :             :         // When there are preselected inputs, we need to move them to be the first UTXOs
    1198                 :             :         // and have them be in the order selected. We can use stable_sort for this, where we
    1199                 :             :         // compare with the positions stored in coin_control. The COutputs that have positions
    1200                 :             :         // will be placed before those that don't, and those positions will be in order.
    1201         [ +  - ]:         430 :         std::stable_sort(selected_coins.begin(), selected_coins.end(),
    1202                 :       15306 :             [&coin_control](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) {
    1203                 :       15306 :                 auto a_pos = coin_control.GetSelectionPos(a->outpoint);
    1204                 :       15306 :                 auto b_pos = coin_control.GetSelectionPos(b->outpoint);
    1205   [ +  +  +  + ]:       15306 :                 if (a_pos.has_value() && b_pos.has_value()) {
    1206                 :       14781 :                     return a_pos.value() < b_pos.value();
    1207   [ +  +  +  - ]:         525 :                 } else if (a_pos.has_value() && !b_pos.has_value()) {
    1208                 :          89 :                     return true;
    1209                 :             :                 } else {
    1210                 :             :                     return false;
    1211                 :             :                 }
    1212                 :             :             });
    1213                 :             :     }
    1214                 :             : 
    1215                 :             :     // The sequence number is set to non-maxint so that DiscourageFeeSniping
    1216                 :             :     // works.
    1217                 :             :     //
    1218                 :             :     // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
    1219                 :             :     // we use the highest possible value in that range (maxint-2)
    1220                 :             :     // to avoid conflicting with other possible uses of nSequence,
    1221                 :             :     // and in the spirit of "smallest possible change from prior
    1222                 :             :     // behavior."
    1223                 :        3313 :     bool use_anti_fee_sniping = true;
    1224   [ +  +  +  + ]:        6626 :     const uint32_t default_sequence{coin_control.m_signal_bip125_rbf.value_or(wallet.m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : CTxIn::MAX_SEQUENCE_NONFINAL};
    1225         [ +  - ]:        3313 :     txNew.vin.reserve(selected_coins.size());
    1226         [ +  + ]:       17170 :     for (const auto& coin : selected_coins) {
    1227         [ +  - ]:       13857 :         std::optional<uint32_t> sequence = coin_control.GetSequence(coin->outpoint);
    1228         [ +  + ]:       13857 :         if (sequence) {
    1229                 :             :             // If an input has a preset sequence, we can't do anti-fee-sniping
    1230                 :        1757 :             use_anti_fee_sniping = false;
    1231                 :             :         }
    1232   [ +  +  +  - ]:       15614 :         txNew.vin.emplace_back(coin->outpoint, CScript{}, sequence.value_or(default_sequence));
    1233                 :             : 
    1234         [ +  - ]:       13857 :         auto scripts = coin_control.GetScripts(coin->outpoint);
    1235         [ +  + ]:       13857 :         if (scripts.first) {
    1236                 :        1757 :             txNew.vin.back().scriptSig = *scripts.first;
    1237                 :             :         }
    1238         [ +  + ]:       13857 :         if (scripts.second) {
    1239         [ +  - ]:       13857 :             txNew.vin.back().scriptWitness = *scripts.second;
    1240                 :             :         }
    1241                 :       13857 :     }
    1242         [ +  + ]:        3313 :     if (coin_control.m_locktime) {
    1243                 :         707 :         txNew.nLockTime = coin_control.m_locktime.value();
    1244                 :             :         // If we have a locktime set, we can't use anti-fee-sniping
    1245                 :         707 :         use_anti_fee_sniping = false;
    1246                 :             :     }
    1247         [ +  - ]:        3313 :     if (use_anti_fee_sniping) {
    1248         [ +  - ]:        2606 :         DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight());
    1249                 :             :     }
    1250                 :             : 
    1251                 :             :     // Calculate the transaction fee
    1252   [ +  -  +  - ]:        3313 :     TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
    1253                 :        3313 :     int nBytes = tx_sizes.vsize;
    1254         [ -  + ]:        3313 :     if (nBytes == -1) {
    1255         [ #  # ]:           0 :         return util::Error{_("Missing solving data for estimating transaction size")};
    1256                 :             :     }
    1257   [ +  -  +  - ]:        3313 :     CAmount fee_needed = coin_selection_params.m_effective_feerate.GetFee(nBytes) + result.GetTotalBumpFees();
    1258                 :        3313 :     const CAmount output_value = CalculateOutputValue(txNew);
    1259                 :        3313 :     Assume(recipients_sum + change_amount == output_value);
    1260         [ +  - ]:        3313 :     CAmount current_fee = result.GetSelectedValue() - output_value;
    1261                 :             : 
    1262                 :             :     // Sanity check that the fee cannot be negative as that means we have more output value than input value
    1263         [ -  + ]:        3313 :     if (current_fee < 0) {
    1264   [ #  #  #  # ]:           0 :         return util::Error{Untranslated(STR_INTERNAL_BUG("Fee paid < 0"))};
    1265                 :             :     }
    1266                 :             : 
    1267                 :             :     // If there is a change output and we overpay the fees then increase the change to match the fee needed
    1268   [ +  +  +  + ]:        3313 :     if (change_pos && fee_needed < current_fee) {
    1269         [ +  - ]:         996 :         auto& change = txNew.vout.at(*change_pos);
    1270                 :         996 :         change.nValue += current_fee - fee_needed;
    1271         [ +  - ]:         996 :         current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
    1272         [ -  + ]:         996 :         if (fee_needed != current_fee) {
    1273   [ #  #  #  # ]:           0 :             return util::Error{Untranslated(STR_INTERNAL_BUG("Change adjustment: Fee needed != fee paid"))};
    1274                 :             :         }
    1275                 :             :     }
    1276                 :             : 
    1277                 :             :     // Reduce output values for subtractFeeFromAmount
    1278         [ +  + ]:        3313 :     if (coin_selection_params.m_subtract_fee_outputs) {
    1279                 :         628 :         CAmount to_reduce = fee_needed - current_fee;
    1280                 :         628 :         unsigned int i = 0;
    1281                 :         628 :         bool fFirst = true;
    1282         [ +  + ]:        1267 :         for (const auto& recipient : vecSend)
    1283                 :             :         {
    1284   [ +  +  +  + ]:         640 :             if (change_pos && i == *change_pos) {
    1285                 :         307 :                 ++i;
    1286                 :             :             }
    1287         [ +  + ]:         640 :             CTxOut& txout = txNew.vout[i];
    1288                 :             : 
    1289         [ +  + ]:         640 :             if (recipient.fSubtractFeeFromAmount)
    1290                 :             :             {
    1291                 :         638 :                 txout.nValue -= to_reduce / outputs_to_subtract_fee_from; // Subtract fee equally from each selected recipient
    1292                 :             : 
    1293         [ +  + ]:         638 :                 if (fFirst) // first receiver pays the remainder not divisible by output count
    1294                 :             :                 {
    1295                 :         628 :                     fFirst = false;
    1296                 :         628 :                     txout.nValue -= to_reduce % outputs_to_subtract_fee_from;
    1297                 :             :                 }
    1298                 :             : 
    1299                 :             :                 // Error if this output is reduced to be below dust
    1300   [ +  -  +  -  :         638 :                 if (IsDust(txout, wallet.chain().relayDustFee())) {
                   +  + ]
    1301         [ +  - ]:           1 :                     if (txout.nValue < 0) {
    1302         [ +  - ]:           3 :                         return util::Error{_("The transaction amount is too small to pay the fee")};
    1303                 :             :                     } else {
    1304         [ #  # ]:           0 :                         return util::Error{_("The transaction amount is too small to send after the fee has been deducted")};
    1305                 :             :                     }
    1306                 :             :                 }
    1307                 :             :             }
    1308                 :         639 :             ++i;
    1309                 :             :         }
    1310         [ +  - ]:         627 :         current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
    1311         [ -  + ]:         627 :         if (fee_needed != current_fee) {
    1312   [ #  #  #  # ]:           0 :             return util::Error{Untranslated(STR_INTERNAL_BUG("SFFO: Fee needed != fee paid"))};
    1313                 :             :         }
    1314                 :             :     }
    1315                 :             : 
    1316                 :             :     // fee_needed should now always be less than or equal to the current fees that we pay.
    1317                 :             :     // If it is not, it is a bug.
    1318         [ -  + ]:        3312 :     if (fee_needed > current_fee) {
    1319   [ #  #  #  # ]:           0 :         return util::Error{Untranslated(STR_INTERNAL_BUG("Fee needed > fee paid"))};
    1320                 :             :     }
    1321                 :             : 
    1322                 :             :     // Give up if change keypool ran out and change is required
    1323   [ +  +  +  +  :        3962 :     if (scriptChange.empty() && change_pos) {
                   +  + ]
    1324         [ +  - ]:           6 :         return util::Error{error};
    1325                 :             :     }
    1326                 :             : 
    1327   [ +  +  +  -  :        3310 :     if (sign && !wallet.SignTransaction(txNew)) {
                   +  - ]
    1328         [ #  # ]:           0 :         return util::Error{_("Signing transaction failed")};
    1329                 :             :     }
    1330                 :             : 
    1331                 :             :     // Return the constructed transaction data.
    1332         [ +  - ]:        3310 :     CTransactionRef tx = MakeTransactionRef(std::move(txNew));
    1333                 :             : 
    1334                 :             :     // Limit size
    1335   [ +  +  -  + ]:        3310 :     if ((sign && GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT) ||
    1336         [ +  + ]:         918 :         (!sign && tx_sizes.weight > MAX_STANDARD_TX_WEIGHT))
    1337                 :             :     {
    1338         [ +  - ]:           6 :         return util::Error{_("Transaction too large")};
    1339                 :             :     }
    1340                 :             : 
    1341         [ +  + ]:        3308 :     if (current_fee > wallet.m_default_max_tx_fee) {
    1342         [ +  - ]:          57 :         return util::Error{TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED)};
    1343                 :             :     }
    1344                 :             : 
    1345   [ +  -  +  -  :        3289 :     if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
                   +  + ]
    1346                 :             :         // Lastly, ensure this tx will pass the mempool's chain limits
    1347         [ +  - ]:        3227 :         auto result = wallet.chain().checkChainLimits(tx);
    1348         [ +  + ]:        3227 :         if (!result) {
    1349         [ +  - ]:           3 :             return util::Error{util::ErrorString(result)};
    1350                 :             :         }
    1351                 :        3227 :     }
    1352                 :             : 
    1353                 :             :     // Before we return success, we assume any change key will be used to prevent
    1354                 :             :     // accidental reuse.
    1355         [ +  - ]:        3288 :     reservedest.KeepDestination();
    1356                 :             : 
    1357   [ +  -  +  -  :        3288 :     wallet.WalletLogPrintf("Coin Selection: Algorithm:%s, Waste Metric Score:%d\n", GetAlgorithmName(result.GetAlgo()), result.GetWaste());
                   +  - ]
    1358         [ +  - ]:        3288 :     wallet.WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
    1359                 :           0 :               current_fee, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
    1360                 :             :               feeCalc.est.pass.start, feeCalc.est.pass.end,
    1361         [ +  - ]:        3288 :               (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool) > 0.0 ? 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool) : 0.0,
    1362                 :             :               feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
    1363                 :             :               feeCalc.est.fail.start, feeCalc.est.fail.end,
    1364   [ +  +  +  + ]:        3288 :               (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) > 0.0 ? 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) : 0.0,
    1365                 :             :               feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
    1366   [ +  -  -  +  :        9864 :     return CreatedTransactionResult(tx, current_fee, change_pos, feeCalc);
                   +  - ]
    1367                 :       23531 : }
    1368                 :             : 
    1369                 :        1765 : util::Result<CreatedTransactionResult> CreateTransaction(
    1370                 :             :         CWallet& wallet,
    1371                 :             :         const std::vector<CRecipient>& vecSend,
    1372                 :             :         std::optional<unsigned int> change_pos,
    1373                 :             :         const CCoinControl& coin_control,
    1374                 :             :         bool sign)
    1375                 :             : {
    1376         [ -  + ]:        1765 :     if (vecSend.empty()) {
    1377                 :           0 :         return util::Error{_("Transaction must have at least one recipient")};
    1378                 :             :     }
    1379                 :             : 
    1380   [ -  +  -  +  :        8505 :     if (std::any_of(vecSend.cbegin(), vecSend.cend(), [](const auto& recipient){ return recipient.nAmount < 0; })) {
          -  +  -  +  -  
          +  -  +  -  +  
                   -  + ]
    1381                 :           0 :         return util::Error{_("Transaction amounts must not be negative")};
    1382                 :             :     }
    1383                 :             : 
    1384                 :        1765 :     LOCK(wallet.cs_wallet);
    1385                 :             : 
    1386         [ +  - ]:        1765 :     auto res = CreateTransactionInternal(wallet, vecSend, change_pos, coin_control, sign);
    1387                 :             :     TRACEPOINT(coin_selection, normal_create_tx_internal,
    1388                 :             :            wallet.GetName().c_str(),
    1389                 :             :            bool(res),
    1390                 :             :            res ? res->fee : 0,
    1391                 :        1765 :            res && res->change_pos.has_value() ? int32_t(*res->change_pos) : -1);
    1392         [ +  + ]:        1765 :     if (!res) return res;
    1393                 :        1676 :     const auto& txr_ungrouped = *res;
    1394                 :             :     // try with avoidpartialspends unless it's enabled already
    1395   [ +  +  +  -  :        1676 :     if (txr_ungrouped.fee > 0 /* 0 means non-functional fee rate estimation */ && wallet.m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
                   +  + ]
    1396                 :        1616 :         TRACEPOINT(coin_selection, attempting_aps_create_tx, wallet.GetName().c_str());
    1397         [ +  - ]:        1616 :         CCoinControl tmp_cc = coin_control;
    1398                 :        1616 :         tmp_cc.m_avoid_partial_spends = true;
    1399                 :             : 
    1400                 :             :         // Reuse the change destination from the first creation attempt to avoid skipping BIP44 indexes
    1401         [ +  + ]:        1616 :         if (txr_ungrouped.change_pos) {
    1402         [ +  - ]:        1581 :             ExtractDestination(txr_ungrouped.tx->vout[*txr_ungrouped.change_pos].scriptPubKey, tmp_cc.destChange);
    1403                 :             :         }
    1404                 :             : 
    1405         [ +  - ]:        1616 :         auto txr_grouped = CreateTransactionInternal(wallet, vecSend, change_pos, tmp_cc, sign);
    1406                 :             :         // if fee of this alternative one is within the range of the max fee, we use this one
    1407         [ +  + ]:        3228 :         const bool use_aps{txr_grouped.has_value() ? (txr_grouped->fee <= txr_ungrouped.fee + wallet.m_max_aps_fee) : false};
    1408                 :             :         TRACEPOINT(coin_selection, aps_create_tx_internal,
    1409                 :             :                wallet.GetName().c_str(),
    1410                 :             :                use_aps,
    1411                 :             :                txr_grouped.has_value(),
    1412                 :             :                txr_grouped.has_value() ? txr_grouped->fee : 0,
    1413                 :        1616 :                txr_grouped.has_value() && txr_grouped->change_pos.has_value() ? int32_t(*txr_grouped->change_pos) : -1);
    1414         [ +  + ]:        1616 :         if (txr_grouped) {
    1415                 :        3224 :             wallet.WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n",
    1416   [ +  +  +  - ]:        1866 :                 txr_ungrouped.fee, txr_grouped->fee, use_aps ? "grouped" : "non-grouped");
    1417         [ +  + ]:        1612 :             if (use_aps) return txr_grouped;
    1418                 :             :         }
    1419                 :        1616 :     }
    1420                 :         318 :     return res;
    1421         [ +  - ]:        3530 : }
    1422                 :             : 
    1423                 :         428 : util::Result<CreatedTransactionResult> FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const std::vector<CRecipient>& vecSend, std::optional<unsigned int> change_pos, bool lockUnspents, CCoinControl coinControl)
    1424                 :             : {
    1425                 :             :     // We want to make sure tx.vout is not used now that we are passing outputs as a vector of recipients.
    1426                 :             :     // This sets us up to remove tx completely in a future PR in favor of passing the inputs directly.
    1427         [ -  + ]:         428 :     assert(tx.vout.empty());
    1428                 :             : 
    1429                 :             :     // Set the user desired locktime
    1430                 :         428 :     coinControl.m_locktime = tx.nLockTime;
    1431                 :             : 
    1432                 :             :     // Set the user desired version
    1433                 :         428 :     coinControl.m_version = tx.version;
    1434                 :             : 
    1435                 :             :     // Acquire the locks to prevent races to the new locked unspents between the
    1436                 :             :     // CreateTransaction call and LockCoin calls (when lockUnspents is true).
    1437                 :         428 :     LOCK(wallet.cs_wallet);
    1438                 :             : 
    1439                 :             :     // Fetch specified UTXOs from the UTXO set to get the scriptPubKeys and values of the outputs being selected
    1440                 :             :     // and to match with the given solving_data. Only used for non-wallet outputs.
    1441                 :         428 :     std::map<COutPoint, Coin> coins;
    1442         [ +  + ]:        3093 :     for (const CTxIn& txin : tx.vin) {
    1443         [ +  - ]:        2665 :         coins[txin.prevout]; // Create empty map entry keyed by prevout.
    1444                 :             :     }
    1445         [ +  - ]:         428 :     wallet.chain().findCoins(coins);
    1446                 :             : 
    1447         [ +  + ]:        3092 :     for (const CTxIn& txin : tx.vin) {
    1448                 :        2665 :         const auto& outPoint = txin.prevout;
    1449         [ +  - ]:        2665 :         PreselectedInput& preset_txin = coinControl.Select(outPoint);
    1450   [ +  -  +  + ]:        2665 :         if (!wallet.IsMine(outPoint)) {
    1451   [ +  -  +  + ]:          24 :             if (coins[outPoint].out.IsNull()) {
    1452         [ +  - ]:           3 :                 return util::Error{_("Unable to find UTXO for external input")};
    1453                 :             :             }
    1454                 :             : 
    1455                 :             :             // The input was not in the wallet, but is in the UTXO set, so select as external
    1456   [ +  -  +  - ]:          23 :             preset_txin.SetTxOut(coins[outPoint].out);
    1457                 :             :         }
    1458         [ +  - ]:        2664 :         preset_txin.SetSequence(txin.nSequence);
    1459         [ +  - ]:        2664 :         preset_txin.SetScriptSig(txin.scriptSig);
    1460         [ +  - ]:        2664 :         preset_txin.SetScriptWitness(txin.scriptWitness);
    1461                 :             :     }
    1462                 :             : 
    1463         [ +  - ]:         427 :     auto res = CreateTransaction(wallet, vecSend, change_pos, coinControl, false);
    1464         [ +  + ]:         427 :     if (!res) {
    1465                 :          68 :         return res;
    1466                 :             :     }
    1467                 :             : 
    1468         [ +  + ]:         359 :     if (lockUnspents) {
    1469         [ +  + ]:           8 :         for (const CTxIn& txin : res->tx->vin) {
    1470         [ +  - ]:           4 :             wallet.LockCoin(txin.prevout);
    1471                 :             :         }
    1472                 :             :     }
    1473                 :             : 
    1474                 :         359 :     return res;
    1475         [ +  - ]:        1283 : }
    1476                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1