23#include <validation.h>
32#include <boost/test/unit_test.hpp>
50 mtx.
vin.push_back({
CTxIn{from.GetHash(), index}});
53 std::map<COutPoint, Coin> coins;
54 coins[mtx.
vin[0].prevout].out = from.vout[index];
55 std::map<int, bilingual_str> input_errors;
67 auto& desc = descs.at(0);
69 auto spk_manager = *
Assert(
wallet.AddWalletDescriptor(w_desc, provider,
"",
false));
113 std::chrono::steady_clock::time_point fake_time;
114 reserver.
setNow([&] { fake_time += 60
s;
return fake_time; });
170 file_number = newTip->GetBlockPos().nFile;
201 const auto NUM_WALLETS{5};
204 BOOST_REQUIRE(chain->getRwSetting(
"wallet").isNull());
206 const auto& check_concurrent_wallet = [&](
const auto& settings_function,
int num_expected_wallets) {
207 std::vector<std::thread> threads;
208 threads.reserve(NUM_WALLETS);
209 for (
auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
210 for (
auto&
t : threads)
t.join();
212 auto wallets = chain->getRwSetting(
"wallet");
217 check_concurrent_wallet([&chain](
int i) {
223 check_concurrent_wallet([&chain](
int i) {
243 wallet.SetupDescriptorScriptPubKeyMans();
267 auto inserted = chainman.
BlockIndex().emplace(std::piecewise_construct, std::make_tuple(
GetRandHash()), std::make_tuple());
269 const uint256& hash = inserted.first->first;
270 block = &inserted.first->second;
271 block->
nTime = blockTime;
317 std::vector<bilingual_str> warnings;
319 auto wallet{std::make_shared<CWallet>(chain.get(),
"", std::move(database))};
329 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
330 WalletBatch batch{wallet->GetDatabase()};
340 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
341 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
342 auto requests = wallet->GetAddressReceiveRequests();
343 auto erequests = {
"val_rr11",
"val_rr20"};
344 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
346 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
347 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
352 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
353 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
354 auto requests = wallet->GetAddressReceiveRequests();
355 auto erequests = {
"val_rr11"};
356 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
384 wallet->CommitTransaction(tx, {}, {});
395 auto it =
wallet->mapWallet.find(tx->GetHash());
406 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
410 std::map<CTxDestination, std::vector<COutput>> list;
416 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
432 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
440 for (
const auto&
group : list) {
441 for (
const auto& coin :
group.second) {
443 wallet->LockCoin(coin.outpoint);
457 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
462 std::map<OutputType, size_t>& expected_coins_sizes)
464 LOCK(context.wallet->cs_wallet);
471 for (uint32_t i = 0; i < wtx.
tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
472 for (
const auto& [type, size] : expected_coins_sizes)
BOOST_CHECK_EQUAL(size, available_coins.
coins[type].size());
477 std::map<OutputType, size_t> expected_coins_sizes;
478 for (
const auto& out_type :
OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
496 expected_coins_sizes[out_type] = 2U;
555 std::string
s(e.what());
556 return s.find(
"Missing checksum") != std::string::npos;
561 std::vector<unsigned char> malformed_record;
563 vw << std::string(
"notadescriptor");
594 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
597 context.
args = &m_args;
608 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet", [&](
const std::string*
s) {
609 if (
s) ++addtx_count;
614 bool rescan_completed =
false;
615 DebugLogHelper rescan_check(
"[default wallet] Rescan completed", [&](
const std::string*
s) {
616 if (
s) rescan_completed =
true;
624 std::promise<void> promise;
626 promise.get_future().wait();
629 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
631 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
671 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
673 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
695 context.
args = &m_args;
703 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
705 context.
args = &m_args;
712 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
719 auto block_hash = block_tx.GetHash();
720 auto prev_tx = m_coinbase_txns[0];
726 std::vector<uint256> vHashIn{ block_hash };
746 wallet.SetupDescriptorScriptPubKeyMans();
769 mtx.
vin.emplace_back(tx_id_to_spend, 0);
771 const auto good_tx_id{mtx.
GetHash()};
790 mtx.
vin.emplace_back(good_tx_id, 0);
793 HasReason(
"DB error adding transaction to wallet, write failed"));
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
#define Assert(val)
Identity function.
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
An encapsulated private key.
CPubKey GetPubKey() const
Compute the public key from a private key.
An encapsulated public key.
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
An input of a transaction.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool AddCScript(const CScript &redeemScript)
virtual bool AddKey(const CKey &key)
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Minimal stream for reading from an existing byte array by std::span.
constexpr bool IsNull() const
constexpr unsigned char * end()
constexpr unsigned char * begin()
static transaction_identifier FromUint256(const uint256 &id)
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
A transaction with a bunch of additional info that only the owner cares about.
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
Descriptor with some wallet metadata.
RAII object to check and reserve a wallet rescan.
bool reserve(bool with_passphrase=false)
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
CKey GenerateRandomKey(bool compressed) noexcept
std::string EncodeSecret(const CKey &key)
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
CAmount CachedTxGetAvailableCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
void TestLoadWallet(const std::string &name, DatabaseFormat format, std::function< void(std::shared_ptr< CWallet >)> f)
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned 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...
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
static const DatabaseFormat DATABASE_FORMATS[]
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
static void AddTx(CWallet &wallet)
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
MockableDatabase & GetMockableDatabase(CWallet &wallet)
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
BOOST_AUTO_TEST_CASE(bnb_test)
CoinsResult AvailableCoinsListUnspent(const CWallet &wallet, const CCoinControl *coinControl, CoinFilterParams params)
Wrapper function for AvailableCoins which skips the feerate and CoinFilterParams::only_spendable para...
static void AddKey(CWallet &wallet, const CKey &key)
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marke...
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
bool malformed_descriptor(std::ios_base::failure e)
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
void TestCoinsResult(ListCoinsTest &context, OutputType out_type, CAmount amount, std::map< OutputType, size_t > &expected_coins_sizes)
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
#define BOOST_CHECK_EQUAL(v1, v2)
#define BOOST_CHECK(expr)
static constexpr auto OUTPUT_TYPES
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
uint256 GetRandHash() noexcept
Generate a random uint256.
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
void UpdateInput(CTxIn &input, const SignatureData &data)
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
A mutable version of CTransaction.
std::vector< CTxOut > vout
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Testing setup that configures a complete environment.
NodeContext struct containing references to chain state and connection state.
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
std::unique_ptr< ChainstateManager > chainman
std::unique_ptr< interfaces::Chain > chain
std::optional< int > last_scanned_height
enum wallet::CWallet::ScanResult::@19 status
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
COutputs available for spending, stored by OutputType.
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
std::map< OutputType, std::vector< COutput > > coins
std::optional< DatabaseFormat > require_format
State of transaction confirmed in a block.
State of transaction added to mempool.
State of transaction not confirmed or conflicting with a known block and not in the mempool.
WalletContext struct containing references to state shared between CWallet instances,...
interfaces::Chain * chain
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
std::shared_ptr< CWallet > m_wallet
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)