20 #include <validation.h> 28 #include <boost/test/unit_test.hpp> 44 BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
52 std::vector<bilingual_str> warnings;
62 wallet->m_chain_notifications_handler.reset();
73 std::map<COutPoint, Coin> coins;
74 coins[mtx.
vin[0].prevout].out = from.
vout[index];
75 std::map<int, bilingual_str> input_errors;
88 if (!
wallet.AddWalletDescriptor(w_desc, provider,
"",
false))
assert(
false);
131 std::chrono::steady_clock::time_point fake_time;
132 reserver.
setNow([&] { fake_time += 60s;
return fake_time; });
236 wallet->SetupLegacyScriptPubKeyMan();
246 key.
pushKV(
"timestamp", 0);
264 strprintf(
"[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation " 265 "timestamp %d. There was an error reading a block from time %d, which is after or within %d " 266 "seconds of key creation, and could contain transactions pertaining to the key. As a result, " 267 "transactions and coins using this key may not appear in the wallet. This error could be caused " 268 "by pruning or data corruption (see bitcoind log for details) and could be dealt with by " 269 "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain " 270 "RPC).\"}},{\"success\":true}]",
286 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
287 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
293 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
295 std::string backup_file =
fs::PathToString(m_args.GetDataDirNet() /
"wallet.backup");
303 auto spk_man =
wallet->GetOrCreateLegacyScriptPubKeyMan();
305 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
306 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
326 wallet->SetupLegacyScriptPubKeyMan();
342 for (
size_t i = 0; i < m_coinbase_txns.size(); ++i) {
343 bool found =
wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
344 bool expected = i >= 100;
364 wallet.SetupDescriptorScriptPubKeyMans();
388 auto inserted = chainman.
BlockIndex().emplace(std::piecewise_construct, std::make_tuple(
GetRandHash()), std::make_tuple());
390 const uint256& hash = inserted.first->first;
391 block = &inserted.first->second;
392 block->
nTime = blockTime;
435 m_wallet.SetAddressUsed(batch, dest,
true);
436 m_wallet.SetAddressReceiveRequest(batch, dest,
"0",
"val_rr0");
437 m_wallet.SetAddressReceiveRequest(batch, dest,
"1",
"val_rr1");
463 if (is_pubkey_fully_valid) {
474 if (is_pubkey_fully_valid) {
483 std::vector<unsigned char> pubkey_raw(pubkey.
begin(), pubkey.
end());
484 std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
486 assert(!pubkey.IsFullyValid());
543 constexpr
int RANDOM_CHANGE_POSITION = -1;
548 wallet->CommitTransaction(tx, {}, {});
559 auto it =
wallet->mapWallet.find(tx->GetHash());
570 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
574 std::map<CTxDestination, std::vector<COutput>> list;
604 for (
const auto& group : list) {
605 for (
const auto& coin : group.second) {
607 wallet->LockCoin(coin.outpoint);
629 wallet->SetupLegacyScriptPubKeyMan();
662 CScript script_pubkey =
CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) <<
OP_EQUAL;
667 keystore.AddKeyPubKey(key, pubkey);
690 std::string s(e.what());
691 return s.find(
"Missing checksum") != std::string::npos;
696 std::vector<unsigned char> malformed_record;
698 vw << std::string(
"notadescriptor");
729 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
744 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet", [&](
const std::string* s) {
745 if (s) ++addtx_count;
750 bool rescan_completed =
false;
751 DebugLogHelper rescan_check(
"[default wallet] Rescan completed", [&](
const std::string* s) {
752 if (s) rescan_completed =
true;
760 std::promise<void> promise;
762 promise.get_future().wait();
765 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
767 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
806 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
808 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
836 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
846 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
853 auto block_hash = block_tx.GetHash();
854 auto prev_tx = m_coinbase_txns[0];
860 std::vector<uint256> vHashIn{ block_hash }, vHashOut;
902 bool Rewrite(
const char* pszSkip=
nullptr)
override {
return true; }
903 bool Backup(
const std::string& strDest)
const override {
return true; }
909 std::string
Filename()
override {
return "faildb"; }
910 std::string
Format()
override {
return "faildb"; }
911 std::unique_ptr<DatabaseBatch>
MakeBatch(
bool flush_on_close =
true)
override {
return std::make_unique<FailBatch>(
m_pass); }
924 wallet.SetupDescriptorScriptPubKeyMans();
929 BOOST_ASSERT(op_dest);
948 mtx.
vin.push_back(
CTxIn(tx_id_to_spend, 0));
969 mtx.
vin.push_back(
CTxIn(good_tx_id, 0));
972 HasReason(
"DB error adding transaction to wallet, write failed"));
std::shared_ptr< const CTransaction > CTransactionRef
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::@17 status
RPCHelpMan importwallet()
std::unique_ptr< interfaces::Chain > chain
void push_back(UniValue val)
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
State of transaction added to mempool.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
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.
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
bool TxnCommit() override
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
bool ReadAtCursor(CDataStream &ssKey, CDataStream &ssValue, bool &complete) override
static void AddKey(CWallet &wallet, const CKey &key)
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::optional< int > last_scanned_height
std::string Filename() override
Return path to main database file for logs and error messages.
static const std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
RecursiveMutex cs_KeyStore
CPubKey GetPubKey() const
Compute the public key from a private key.
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, ArgsManager &args, const CKey &key)
uint256 GetRandHash() noexcept
bool WriteKey(CDataStream &&key, CDataStream &&value, bool overwrite=true) override
virtual bool AddCScript(const CScript &redeemScript)
std::shared_ptr< CWallet > m_wallet
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.
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
uint256 rand256() noexcept
generate a random uint256.
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
void Close() override
Flush to the database file and close the database.
State of transaction not confirmed or conflicting with a known block and not in the mempool...
RAII object to check and reserve a wallet rescan.
bool StartCursor() override
void AddRef() override
Indicate the a new database user has began using the database.
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Double ended buffer combining vector and stream-like interfaces.
bool Backup(const std::string &strDest) const override
Back up the entire database to a file.
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Access to the wallet database.
State of transaction confirmed in a block.
bool ReadKey(CDataStream &&key, CDataStream &value) override
std::atomic< unsigned int > nUpdateCounter
bool EraseKey(CDataStream &&key) override
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
RAII class that provides access to a WalletDatabase.
const unsigned char * begin() const
std::unique_ptr< CWallet > wallet
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Minimal stream for reading from an existing byte array by Span.
A dummy WalletDatabase that does nothing, only fails if needed.
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
uint256 GetBlockHash() const
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
void IncrementUpdateCounter() override
void RemoveRef() override
Indicate that database user has stopped using the database and that it could be flushed or closed...
A transaction with a bunch of additional info that only the owner cares about.
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
void CloseCursor() override
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, Chainstate *chainstate=nullptr)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
std::unique_ptr< DatabaseBatch > MakeBatch(bool flush_on_close=true) override
Make a DatabaseBatch connected to this database.
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
static std::string PathToString(const path &path)
Convert path object to a byte string.
const unsigned char * end() const
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase(DatabaseOptions &options)
Return object for accessing temporary in-memory database.
An input of a transaction.
static void PollutePubKey(CPubKey &pubkey)
const uint256 & GetHash() const
bool HasKey(CDataStream &&key) override
BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, AvailableCoinsTestingSetup)
BOOST_AUTO_TEST_SUITE_END()
RAII class that provides access to a FailDatabase.
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
An encapsulated public key.
Fillable signing provider that keeps keys in an address->secret map.
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
const std::vector< CTxOut > vout
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
int64_t GetBlockTimeMax() const
Indicate that this wallet supports DescriptorScriptPubKeyMan.
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
bool malformed_descriptor(std::ios_base::failure e)
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
bool Rewrite(const char *pszSkip=nullptr) override
Rewrite the entire database on disk, with the exception of key pszSkip if non-zero.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
std::vector< CTxOut > vout
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
void Open() override
Open the database if it is not already opened.
Descriptor with some wallet metadata.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
static CTransactionRef MakeTransactionRef(Tx &&txIn)
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
void Flush() override
Make sure all changes are flushed to database file.
CWalletTx & AddTx(CRecipient recipient)
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
CAmount CachedTxGetAvailableCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
#define BOOST_CHECK_EQUAL(v1, v2)
The block chain is a tree shaped structure starting with the genesis block at the root...
void pushKV(std::string key, UniValue val)
Serialized script, used inside transaction inputs and outputs.
bool PeriodicFlush() override
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
A reference to a CKey: the Hash160 of its serialized public key.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
void UpdateInput(CTxIn &input, const SignatureData &data)
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
WalletContext struct containing references to state shared between CWallet instances, like the reference to the chain interface, and the list of opened wallets.
std::string Format() override
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
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...
interfaces::Chain * chain
A mutable version of CTransaction.
void ReloadDbEnv() override
An encapsulated private key.
The basic transaction that is broadcasted on the network and contained in blocks. ...
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
std::shared_ptr< CWallet > wallet
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)
BOOST_AUTO_TEST_CASE(bnb_search_test)
UniValue HandleRequest(const JSONRPCRequest &request) const
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
std::string EncodeSecret(const CKey &key)
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
bool error(const char *fmt, const Args &... args)
CoinsResult AvailableCoinsListUnspent(const CWallet &wallet, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount)
Wrapper function for AvailableCoins which skips the feerate parameter.
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
An instance of this class represents one database.
Testing setup that configures a complete environment.
std::unique_ptr< ChainstateManager > chainman
virtual bool AddKey(const CKey &key)
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
#define Assert(val)
Identity function.
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
static std::shared_ptr< CWallet > Create(WalletContext &context, const std::string &name, std::unique_ptr< WalletDatabase > database, uint64_t wallet_creation_flags, bilingual_str &error, std::vector< bilingual_str > &warnings)
#define BOOST_CHECK(expr)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
bool IsCompressed() const
Check whether this is a compressed public key.
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex