22#include <validation.h>
30#include <boost/test/unit_test.hpp>
50 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);
212 wallet->SetupLegacyScriptPubKeyMan();
213 WITH_LOCK(
wallet->cs_wallet,
wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
222 key.
pushKV(
"timestamp", 0);
240 strprintf(
"[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
241 "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
242 "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
243 "transactions and coins using this key may not appear in the wallet. This error could be caused "
244 "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
245 "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
246 "RPC).\"}},{\"success\":true}]",
260 const int64_t BLOCK_TIME =
m_node.
chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5;
262 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
263 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
269 m_coinbase_txns.emplace_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
279 auto spk_man =
wallet->GetOrCreateLegacyScriptPubKeyMan();
281 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
282 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
301 wallet->SetupLegacyScriptPubKeyMan();
316 for (
size_t i = 0; i < m_coinbase_txns.size(); ++i) {
317 bool found =
wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
318 bool expected = i >= 100;
337 wallet.SetupDescriptorScriptPubKeyMans();
366 const uint256& hash = inserted.first->first;
367 block = inserted.first->second;
368 block->
nTime = blockTime;
370 confirm = {CWalletTx::Status::CONFIRMED, block->
nHeight, hash, 0};
411 m_wallet.SetAddressUsed(batch, dest,
true);
412 m_wallet.SetAddressReceiveRequest(batch, dest,
"0",
"val_rr0");
413 m_wallet.SetAddressReceiveRequest(batch, dest,
"1",
"val_rr1");
439 if (is_pubkey_fully_valid) {
450 if (is_pubkey_fully_valid) {
459 std::vector<unsigned char> pubkey_raw(pubkey.
begin(), pubkey.
end());
460 std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
525 wallet->CommitTransaction(tx, {}, {});
535 auto it =
wallet->mapWallet.find(tx->GetHash());
538 it->second.m_confirm = confirm;
547 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
551 std::map<CTxDestination, std::vector<COutput>> list;
557 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
573 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
579 std::vector<COutput> available;
583 for (
const auto& group : list) {
584 for (
const auto& coin : group.second) {
591 std::vector<COutput> available;
602 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
610 wallet->SetupLegacyScriptPubKeyMan();
675 std::string s(e.what());
676 return s.find(
"Missing checksum") != std::string::npos;
681 std::vector<unsigned char> malformed_record;
683 vw << std::string(
"notadescriptor");
729 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet", [&](
const std::string* s) {
730 if (s) ++addtx_count;
735 bool rescan_completed =
false;
736 DebugLogHelper rescan_check(
"[default wallet] Rescan completed", [&](
const std::string* s) {
737 if (s) rescan_completed =
true;
745 std::promise<void> promise;
747 promise.get_future().wait();
750 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
752 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
787 BOOST_CHECK(rescan_completed);
788 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
790 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
832 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
839 auto block_hash = block_tx.GetHash();
840 auto prev_hash = m_coinbase_txns[0]->GetHash();
846 std::vector<uint256> vHashIn{ block_hash }, vHashOut;
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
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.
void ForceSetArg(const std::string &strArg, const std::string &strValue)
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
unsigned int nSize
number of used bytes of block file
The block chain is a tree shaped structure starting with the genesis block at the root,...
FlatFilePos GetBlockPos() const
uint256 GetBlockHash() const
int64_t GetBlockTimeMax() const
int nHeight
height of the entry in the chain. The genesis block has height 0
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 outpoint - a combination of a transaction hash and an index n into its vout.
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)
const unsigned char * end() const
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
const unsigned char * begin() const
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const uint256 & GetHash() const
const std::vector< CTxOut > vout
An input of a transaction.
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
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)
A transaction with a bunch of additional info that only the owner cares about.
void MarkDirty()
make sure balances are recalculated
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
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
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.
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
std::unique_ptr< CWallet > wallet
CWalletTx & AddTx(CRecipient recipient)
UniValue HandleRequest(const JSONRPCRequest &request) const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool push_back(const UniValue &val)
bool pushKV(const std::string &key, const UniValue &val)
Minimal stream for reading from an existing vector by reference.
Access to the wallet database.
Descriptor with some wallet metadata.
RAII object to check and reserve a wallet rescan.
BOOST_AUTO_TEST_SUITE_END()
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
std::string EncodeSecret(const CKey &key)
static std::string PathToString(const path &path)
Convert path object to byte string.
#define BOOST_FIXTURE_TEST_SUITE(a, b)
#define BOOST_CHECK_EQUAL(v1, v2)
#define BOOST_CHECK(expr)
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
uint256 GetRandHash() noexcept
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.
CAmount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, bool fUseCache)
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
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.
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
CAmount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CAmount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, FeeCalculation &fee_calc_out, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
A mutable version of CTransaction.
std::vector< CTxOut > vout
std::optional< int > last_scanned_height
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
enum CWallet::ScanResult::@17 status
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
std::unique_ptr< ChainstateManager > chainman
std::unique_ptr< interfaces::Chain > chain
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, CChainState *chainstate=nullptr)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
WalletContext struct containing references to state shared between CWallet instances,...
interfaces::Chain * chain
Testing setup and teardown for wallet.
#define ENTER_CRITICAL_SECTION(cs)
#define LEAVE_CRITICAL_SECTION(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
bool error(const char *fmt, const Args &... args)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
std::shared_ptr< CWallet > m_wallet
std::unique_ptr< CWallet > CreateSyncedWallet(interfaces::Chain &chain, CChain &cchain, const CKey &key)
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
bool AddWallet(WalletContext &context, const 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)
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
static const std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
static void PollutePubKey(CPubKey &pubkey)
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
RPCHelpMan importwallet()
static CMutableTransaction TestSimpleSpend(const CTransaction &from, uint32_t index, const CKey &key, const CScript &pubkey)
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
static void AddKey(CWallet &wallet, const CKey &key)
static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan *spk_man, const CPubKey &add_pubkey)
bool malformed_descriptor(std::ios_base::failure e)
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.