LCOV - code coverage report
Current view: top level - src/wallet - spend.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 603 736 81.9 %
Date: 2023-11-10 23:46:46 Functions: 36 48 75.0 %
Branches: 644 1339 48.1 %

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

Generated by: LCOV version 1.14