23#include <validation.h>
32#include <boost/test/unit_test.hpp>
47BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
53 mtx.
vin.push_back({CTxIn{from.GetHash(), index}});
56 std::map<COutPoint, Coin> coins;
57 coins[mtx.vin[0].prevout].out = from.vout[index];
58 std::map<int, bilingual_str> input_errors;
68 std::unique_ptr<Descriptor> desc =
Parse(
"combo(" +
EncodeSecret(key) +
")", provider, error,
false);
71 if (!
wallet.AddWalletDescriptor(w_desc, provider,
"",
false))
assert(
false);
88 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
109 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
114 std::chrono::steady_clock::time_point fake_time;
115 reserver.
setNow([&] { fake_time += 60s;
return fake_time; });
154 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
171 file_number = newTip->GetBlockPos().nFile;
182 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
218 const std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
m_node.
chain.get(),
"", CreateMockableWalletDatabase());
219 wallet->SetupLegacyScriptPubKeyMan();
220 WITH_LOCK(
wallet->cs_wallet,
wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
222 context.
args = &m_args;
223 AddWallet(context,
wallet);
229 key.
pushKV(
"timestamp", 0);
246 strprintf(
"[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
247 "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
248 "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
249 "transactions and coins using this key may not appear in the wallet. This error could be caused "
250 "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
251 "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
252 "RPC).\"}},{\"success\":true}]",
254 RemoveWallet(context,
wallet, std::nullopt);
268 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
269 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
275 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
277 std::string backup_file =
fs::PathToString(m_args.GetDataDirNet() /
"wallet.backup");
282 context.
args = &m_args;
283 const std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
m_node.
chain.get(),
"", CreateMockableWalletDatabase());
285 auto spk_man =
wallet->GetOrCreateLegacyScriptPubKeyMan();
287 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
288 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
290 AddWallet(context,
wallet);
300 RemoveWallet(context,
wallet, std::nullopt);
306 const std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
m_node.
chain.get(),
"", CreateMockableWalletDatabase());
308 wallet->SetupLegacyScriptPubKeyMan();
311 context.
args = &m_args;
316 AddWallet(context,
wallet);
320 RemoveWallet(context,
wallet, std::nullopt);
324 for (
size_t i = 0; i < m_coinbase_txns.size(); ++i) {
325 bool found =
wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
326 bool expected = i >= 100;
338 const auto NUM_WALLETS{5};
343 const auto& check_concurrent_wallet = [&](
const auto& settings_function,
int num_expected_wallets) {
344 std::vector<std::thread> threads;
345 threads.reserve(NUM_WALLETS);
346 for (
auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
347 for (
auto&
t : threads)
t.join();
354 check_concurrent_wallet([&context](
int i) {
360 check_concurrent_wallet([&context](
int i) {
379 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
380 wallet.SetupDescriptorScriptPubKeyMans();
404 auto inserted = chainman.
BlockIndex().emplace(std::piecewise_construct, std::make_tuple(
GetRandHash()), std::make_tuple());
406 const uint256& hash = inserted.first->first;
407 block = &inserted.first->second;
408 block->
nTime = blockTime;
454 std::vector<bilingual_str> warnings;
456 auto wallet{std::make_shared<CWallet>(chain.get(),
"", std::move(database))};
464 const std::string
name{
strprintf(
"receive-requests-%i", format)};
466 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
467 WalletBatch batch{wallet->GetDatabase()};
477 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
478 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
479 auto requests = wallet->GetAddressReceiveRequests();
480 auto erequests = {
"val_rr11",
"val_rr20"};
483 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
484 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
489 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
490 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
491 auto requests = wallet->GetAddressReceiveRequests();
492 auto erequests = {
"val_rr11"};
516 if (is_pubkey_fully_valid) {
527 if (is_pubkey_fully_valid) {
537 std::vector<unsigned char> pubkey_raw;
538 pubkey_raw.push_back(pubkey[0]);
539 pubkey_raw.insert(pubkey_raw.end(), pubkey.
size() - 1, 0);
602 wallet->CommitTransaction(tx, {}, {});
613 auto it =
wallet->mapWallet.find(tx->GetHash());
624 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
628 std::map<CTxDestination, std::vector<COutput>> list;
634 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
650 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
658 for (
const auto& group : list) {
659 for (
const auto& coin : group.second) {
661 wallet->LockCoin(coin.outpoint);
675 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
680 std::map<OutputType, size_t>& expected_coins_sizes)
682 LOCK(context.wallet->cs_wallet);
689 for (uint32_t i = 0; i < wtx.
tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
690 for (
const auto& [type, size] : expected_coins_sizes)
BOOST_CHECK_EQUAL(size, available_coins.
coins[type].size());
695 std::map<OutputType, size_t> expected_coins_sizes;
696 for (
const auto& out_type :
OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
714 expected_coins_sizes[out_type] = 2U;
722 const std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
m_node.
chain.get(),
"", CreateMockableWalletDatabase());
723 wallet->SetupLegacyScriptPubKeyMan();
725 wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
730 const std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
m_node.
chain.get(),
"", CreateMockableWalletDatabase());
732 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
734 wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
783 std::string s(e.what());
784 return s.find(
"Missing checksum") != std::string::npos;
789 std::vector<unsigned char> malformed_record;
791 vw << std::string(
"notadescriptor");
822 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
825 context.
args = &m_args;
836 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet", [&](
const std::string* s) {
837 if (s) ++addtx_count;
842 bool rescan_completed =
false;
843 DebugLogHelper rescan_check(
"[default wallet] Rescan completed", [&](
const std::string* s) {
844 if (s) rescan_completed =
true;
852 std::promise<void> promise;
854 promise.get_future().wait();
857 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
859 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
899 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
901 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
923 context.
args = &m_args;
931 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
933 context.
args = &m_args;
940 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
947 auto block_hash = block_tx.GetHash();
948 auto prev_tx = m_coinbase_txns[0];
954 std::vector<uint256> vHashIn{ block_hash };
973 wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
974 wallet.SetupDescriptorScriptPubKeyMans();
997 mtx.
vin.emplace_back(tx_id_to_spend, 0);
999 const auto good_tx_id{mtx.
GetHash()};
1004 const CWalletTx* new_wtx =
wallet.GetWalletTx(good_tx_id.ToUint256());
1018 mtx.
vin.emplace_back(good_tx_id, 0);
1021 HasReason(
"DB error adding transaction to wallet, write failed"));
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
BOOST_AUTO_TEST_CASE(addrman_simple)
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
BOOST_FIXTURE_TEST_CASE(util_CheckValue, CheckValueTest)
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
#define Assert(val)
Identity function.
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() const
int64_t GetBlockTimeMax() 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.
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
CPubKey GetPubKey() const
Compute the public key from a private key.
A reference to a CKey: the Hash160 of its serialized public key.
An encapsulated public key.
bool IsCompressed() const
Check whether this is a compressed public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
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)
RecursiveMutex cs_KeyStore
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
UniValue HandleRequest(const JSONRPCRequest &request) const
uint256 rand256() noexcept
generate a random uint256.
Minimal stream for reading from an existing byte array by Span.
void push_back(UniValue val)
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void pushKV(std::string key, UniValue val)
constexpr bool IsNull() const
constexpr unsigned char * end()
constexpr unsigned char * begin()
virtual common::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
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.
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
bool ReadBestBlock(CBlockLocator &locator)
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_AUTO_TEST_SUITE_END()
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
CKey GenerateRandomKey(bool compressed) noexcept
std::string EncodeSecret(const CKey &key)
static void AddTx(const CTransactionRef &tx, const CAmount &nFee, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
static std::string PathToString(const path &path)
Convert path object to a byte string.
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 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)
bool RunWithinTxn(WalletDatabase &database, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Executes the provided function 'func' within a database transaction context.
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...
static void PollutePubKey(CPubKey &pubkey)
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
RPCHelpMan importwallet()
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.
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)
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
MockableDatabase & GetMockableDatabase(CWallet &wallet)
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
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
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
bool malformed_descriptor(std::ios_base::failure e)
void TestCoinsResult(ListCoinsTest &context, OutputType out_type, CAmount amount, std::map< OutputType, size_t > &expected_coins_sizes)
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
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.
enum wallet::CWallet::ScanResult::@18 status
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.
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
BOOST_CHECK_EQUAL_COLLECTIONS(R1L.begin(), R1L.end(), R1Array, R1Array+uint256::size())
std::shared_ptr< CWallet > m_wallet
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)