Bitcoin Core  25.99.0
P2P Digital Currency
spend_tests.cpp
Go to the documentation of this file.
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 <consensus/amount.h>
6 #include <policy/fees.h>
7 #include <validation.h>
8 #include <wallet/coincontrol.h>
9 #include <wallet/spend.h>
10 #include <wallet/test/util.h>
12 
13 #include <boost/test/unit_test.hpp>
14 
15 namespace wallet {
16 BOOST_FIXTURE_TEST_SUITE(spend_tests, WalletTestingSetup)
17 
19 {
20  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
21  auto wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
22 
23  // Check that a subtract-from-recipient transaction slightly less than the
24  // coinbase input amount does not create a change output (because it would
25  // be uneconomical to add and spend the output), and make sure it pays the
26  // leftover input amount which would have been change to the recipient
27  // instead of the miner.
28  auto check_tx = [&wallet](CAmount leftover_input_amount) {
29  CRecipient recipient{GetScriptForRawPubKey({}), 50 * COIN - leftover_input_amount, /*subtract_fee=*/true};
30  constexpr int RANDOM_CHANGE_POSITION = -1;
31  CCoinControl coin_control;
32  coin_control.m_feerate.emplace(10000);
33  coin_control.fOverrideFeeRate = true;
34  // We need to use a change type with high cost of change so that the leftover amount will be dropped to fee instead of added as a change output
35  coin_control.m_change_type = OutputType::LEGACY;
36  auto res = CreateTransaction(*wallet, {recipient}, RANDOM_CHANGE_POSITION, coin_control);
37  BOOST_CHECK(res);
38  const auto& txr = *res;
39  BOOST_CHECK_EQUAL(txr.tx->vout.size(), 1);
40  BOOST_CHECK_EQUAL(txr.tx->vout[0].nValue, recipient.nAmount + leftover_input_amount - txr.fee);
41  BOOST_CHECK_GT(txr.fee, 0);
42  return txr.fee;
43  };
44 
45  // Send full input amount to recipient, check that only nonzero fee is
46  // subtracted (to_reduce == fee).
47  const CAmount fee{check_tx(0)};
48 
49  // Send slightly less than full input amount to recipient, check leftover
50  // input amount is paid to recipient not the miner (to_reduce == fee - 123)
51  BOOST_CHECK_EQUAL(fee, check_tx(123));
52 
53  // Send full input minus fee amount to recipient, check leftover input
54  // amount is paid to recipient not the miner (to_reduce == 0)
55  BOOST_CHECK_EQUAL(fee, check_tx(fee));
56 
57  // Send full input minus more than the fee amount to recipient, check
58  // leftover input amount is paid to recipient not the miner (to_reduce ==
59  // -123). This overpays the recipient instead of overpaying the miner more
60  // than double the necessary fee.
61  BOOST_CHECK_EQUAL(fee, check_tx(fee + 123));
62 }
63 
64 static void TestFillInputToWeight(int64_t additional_weight, std::vector<int64_t> expected_stack_sizes)
65 {
66  static const int64_t EMPTY_INPUT_WEIGHT = GetTransactionInputWeight(CTxIn());
67 
68  CTxIn input;
69  int64_t target_weight = EMPTY_INPUT_WEIGHT + additional_weight;
70  BOOST_CHECK(FillInputToWeight(input, target_weight));
71  BOOST_CHECK_EQUAL(GetTransactionInputWeight(input), target_weight);
72  BOOST_CHECK_EQUAL(input.scriptWitness.stack.size(), expected_stack_sizes.size());
73  for (unsigned int i = 0; i < expected_stack_sizes.size(); ++i) {
74  BOOST_CHECK_EQUAL(input.scriptWitness.stack[i].size(), expected_stack_sizes[i]);
75  }
76 }
77 
79 {
80  {
81  // Less than or equal minimum of 165 should not add any witness data
82  CTxIn input;
83  BOOST_CHECK(!FillInputToWeight(input, -1));
85  BOOST_CHECK_EQUAL(input.scriptWitness.stack.size(), 0);
86  BOOST_CHECK(!FillInputToWeight(input, 0));
88  BOOST_CHECK_EQUAL(input.scriptWitness.stack.size(), 0);
89  BOOST_CHECK(!FillInputToWeight(input, 164));
91  BOOST_CHECK_EQUAL(input.scriptWitness.stack.size(), 0);
92  BOOST_CHECK(FillInputToWeight(input, 165));
94  BOOST_CHECK_EQUAL(input.scriptWitness.stack.size(), 0);
95  }
96 
97  // Make sure we can add at least one weight
98  TestFillInputToWeight(1, {0});
99 
100  // 1 byte compact size uint boundary
101  TestFillInputToWeight(252, {251});
102  TestFillInputToWeight(253, {83, 168});
103  TestFillInputToWeight(262, {86, 174});
104  TestFillInputToWeight(263, {260});
105 
106  // 3 byte compact size uint boundary
107  TestFillInputToWeight(65535, {65532});
108  TestFillInputToWeight(65536, {21842, 43688});
109  TestFillInputToWeight(65545, {21845, 43694});
110  TestFillInputToWeight(65546, {65541});
111 
112  // Note: We don't test the next boundary because of memory allocation constraints.
113 }
114 
115 BOOST_FIXTURE_TEST_CASE(wallet_duplicated_preset_inputs_test, TestChain100Setup)
116 {
117  // Verify that the wallet's Coin Selection process does not include pre-selected inputs twice in a transaction.
118 
119  // Add 4 spendable UTXO, 50 BTC each, to the wallet (total balance 200 BTC)
120  for (int i = 0; i < 4; i++) CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
121  auto wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
122 
123  LOCK(wallet->cs_wallet);
124  auto available_coins = AvailableCoins(*wallet);
125  std::vector<COutput> coins = available_coins.All();
126  // Preselect the first 3 UTXO (150 BTC total)
127  std::set<COutPoint> preset_inputs = {coins[0].outpoint, coins[1].outpoint, coins[2].outpoint};
128 
129  // Try to create a tx that spends more than what preset inputs + wallet selected inputs are covering for.
130  // The wallet can cover up to 200 BTC, and the tx target is 299 BTC.
131  std::vector<CRecipient> recipients = {{GetScriptForDestination(*Assert(wallet->GetNewDestination(OutputType::BECH32, "dummy"))),
132  /*nAmount=*/299 * COIN, /*fSubtractFeeFromAmount=*/true}};
133  CCoinControl coin_control;
134  coin_control.m_allow_other_inputs = true;
135  for (const auto& outpoint : preset_inputs) {
136  coin_control.Select(outpoint);
137  }
138 
139  // Attempt to send 299 BTC from a wallet that only has 200 BTC. The wallet should exclude
140  // the preset inputs from the pool of available coins, realize that there is not enough
141  // money to fund the 299 BTC payment, and fail with "Insufficient funds".
142  //
143  // Even with SFFO, the wallet can only afford to send 200 BTC.
144  // If the wallet does not properly exclude preset inputs from the pool of available coins
145  // prior to coin selection, it may create a transaction that does not fund the full payment
146  // amount or, through SFFO, incorrectly reduce the recipient's amount by the difference
147  // between the original target and the wrongly counted inputs (in this case 99 BTC)
148  // so that the recipient's amount is no longer equal to the user's selected target of 299 BTC.
149 
150  // First case, use 'subtract_fee_from_outputs=true'
151  util::Result<CreatedTransactionResult> res_tx = CreateTransaction(*wallet, recipients, /*change_pos*/-1, coin_control);
152  BOOST_CHECK(!res_tx.has_value());
153 
154  // Second case, don't use 'subtract_fee_from_outputs'.
155  recipients[0].fSubtractFeeFromAmount = false;
156  res_tx = CreateTransaction(*wallet, recipients, /*change_pos*/-1, coin_control);
157  BOOST_CHECK(!res_tx.has_value());
158 }
159 
161 } // namespace wallet
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
#define Assert(val)
Identity function.
Definition: check.h:73
An input of a transaction.
Definition: transaction.h:75
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:80
bool has_value() const noexcept
std::optional methods, so functions returning optional<T> can change to return Result<T> with minimal...
Definition: result.h:52
Coin Control Features.
Definition: coincontrol.h:30
void Select(const COutPoint &output)
Lock-in the given output for spending.
Definition: coincontrol.cpp:40
std::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
Definition: coincontrol.h:35
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:40
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
Definition: coincontrol.h:44
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
Definition: coincontrol.h:46
static int64_t GetTransactionInputWeight(const CTxIn &txin)
Definition: validation.h:156
BOOST_AUTO_TEST_SUITE_END()
bool FillInputToWeight(CTxIn &txin, int64_t target_weight)
Definition: wallet.cpp:1687
static void TestFillInputToWeight(int64_t additional_weight, std::vector< int64_t > expected_stack_sizes)
Definition: spend_tests.cpp:64
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
Definition: util.cpp:19
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:1132
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CoinFilterParams &params)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
Definition: spend.cpp:203
std::shared_ptr< CWallet > wallet
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:339
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
Basic testing setup.
Definition: setup_common.h:80
std::vector< std::vector< unsigned char > > stack
Definition: script.h:566
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:129
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:56
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:59
#define LOCK(cs)
Definition: sync.h:258
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302