6#include <chainparams.h>
14#include <validation.h>
22#include <test/util/logging.h>
23#include <test/util/setup_common.h>
26#include <boost/test/unit_test.hpp>
45 std::vector<bilingual_str> warnings;
59 wallet->m_chain_notifications_handler.reset();
64 uint32_t index,
const CKey &key,
65 const CScript &pubkey) {
69 mtx.
vin.push_back({CTxIn{from.GetId(), index}});
72 std::map<COutPoint, Coin> coins;
73 coins[mtx.
vin[0].prevout].GetTxOut() = from.vout[index];
74 std::map<int, std::string> input_errors;
81 auto spk_man =
wallet.GetOrCreateLegacyScriptPubKeyMan();
83 spk_man->AddKeyPubKey(key, key.
GetPubKey());
104 wallet.SetLastBlockProcessed(
105 m_node.chainman->ActiveHeight(),
106 m_node.chainman->ActiveTip()->GetBlockHash());
113 {} , reserver,
false );
128 wallet.SetLastBlockProcessed(
129 m_node.chainman->ActiveHeight(),
130 m_node.chainman->ActiveTip()->GetBlockHash());
150 Assert(
m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
152 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
161 wallet.SetLastBlockProcessed(
162 m_node.chainman->ActiveHeight(),
163 m_node.chainman->ActiveTip()->GetBlockHash());
181 file_number = newTip->GetBlockPos().nFile;
182 Assert(
m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
184 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
192 wallet.SetLastBlockProcessed(
193 m_node.chainman->ActiveHeight(),
194 m_node.chainman->ActiveTip()->GetBlockHash());
214 chainman.
GetMutex(),
return m_node.chainman->ActiveChain().Tip());
220 chainman.
GetMutex(),
return m_node.chainman->ActiveChain().Tip());
229 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
233 m_node.chainman->m_blockman.m_have_pruned =
true;
239 std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
241 wallet->SetupLegacyScriptPubKeyMan();
243 wallet->SetLastBlockProcessed(newTip->nHeight,
244 newTip->GetBlockHash()));
251 key.
pushKV(
"scriptPubKey",
253 key.
pushKV(
"timestamp", 0);
260 key.
pushKV(
"scriptPubKey",
274 strprintf(
"[{\"success\":false,\"error\":{\"code\":-1,\"message\":"
275 "\"Rescan failed for key with creation timestamp %d. "
276 "There was an error reading a block from time %d, which "
277 "is after or within %d seconds of key creation, and "
278 "could contain transactions pertaining to the key. As a "
279 "result, transactions and coins using this key may not "
280 "appear in the wallet. This error could be caused by "
281 "pruning or data corruption (see bitcoind log for "
282 "details) and could be dealt with by downloading and "
283 "rescanning the relevant blocks (see -reindex option "
284 "and rescanblockchain RPC).\"}},{\"success\":true}]",
298 const int64_t BLOCK_TIME =
302 m_coinbase_txns.emplace_back(
303 CreateAndProcessBlock({},
306 m_coinbase_txns.emplace_back(
307 CreateAndProcessBlock({},
315 m_coinbase_txns.emplace_back(
316 CreateAndProcessBlock({},
320 std::string backup_file =
326 std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
329 auto spk_man =
wallet->GetOrCreateLegacyScriptPubKeyMan();
331 spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()]
332 .nCreateTime = KEY_TIME;
333 spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
351 std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
354 wallet->SetupLegacyScriptPubKeyMan();
372 for (
size_t i = 0; i < m_coinbase_txns.size(); ++i) {
373 bool found =
wallet->GetWalletTx(m_coinbase_txns[i]->GetId());
374 bool expected = i >= 100;
389 auto spk_man =
wallet.GetOrCreateLegacyScriptPubKeyMan();
409 BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
414 uint32_t lockTime, int64_t mockTime, int64_t blockTime) {
422 auto inserted = chainman.
BlockIndex().emplace(
423 std::piecewise_construct, std::make_tuple(
GetRandHash()),
426 const BlockHash &hash = inserted.first->first;
427 block = &inserted.first->second;
428 block->
nTime = blockTime;
430 confirm = {CWalletTx::Status::CONFIRMED, block->
nHeight, hash, 0};
475 m_wallet.AddDestData(batch, dest,
"misc",
"val_misc");
476 m_wallet.AddDestData(batch, dest,
"rr0",
"val_rr0");
477 m_wallet.AddDestData(batch, dest,
"rr1",
"val_rr1");
479 auto values =
m_wallet.GetDestValues(
"rr");
506 if (is_pubkey_fully_valid) {
518 if (is_pubkey_fully_valid) {
528 std::vector<uint8_t> pubkey_raw(pubkey.
begin(), pubkey.
end());
529 std::fill(pubkey_raw.begin() + 1, pubkey_raw.end(), 0);
540 m_wallet.GetOrCreateLegacyScriptPubKeyMan();
573 CreateAndProcessBlock({},
575 wallet = std::make_unique<CWallet>(
m_node.chain.get(),
"",
587 m_node.chainman->ActiveChain().Genesis()->GetBlockHash(),
605 constexpr int RANDOM_CHANGE_POSITION = -1;
607 RANDOM_CHANGE_POSITION, dummy);
613 wallet->CommitTransaction(tx, {}, {});
625 wallet->SetLastBlockProcessed(
wallet->GetLastBlockHeight() + 1,
627 auto it =
wallet->mapWallet.find(tx->GetId());
632 it->second.m_confirm = confirm;
640 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
644 std::map<CTxDestination, std::vector<COutput>> list;
675 std::vector<COutput> available;
679 for (
const auto &
group : list) {
680 for (
const auto &coin :
group.second) {
682 wallet->LockCoin(COutPoint(coin.tx->GetId(), coin.i));
687 std::vector<COutput> available;
704 std::shared_ptr<CWallet>
wallet = std::make_shared<CWallet>(
706 wallet->SetupLegacyScriptPubKeyMan();
751 std::string s(e.what());
752 return s.find(
"Missing checksum") != std::string::npos;
756 std::vector<uint8_t> malformed_record;
758 vw << std::string(
"notadescriptor");
766 BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure,
801 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet",
802 [&](
const std::string *s) {
809 bool rescan_completed =
false;
810 DebugLogHelper rescan_check(
"[default wallet] Rescan completed",
811 [&](
const std::string *s) {
813 rescan_completed =
true;
821 std::promise<void> promise;
822 m_node.validation_signals->CallFunctionInValidationInterfaceQueue(
823 [&promise] { promise.get_future().wait(); });
825 m_coinbase_txns.push_back(
826 CreateAndProcessBlock({},
831 m_coinbase_txns.push_back(
832 CreateAndProcessBlock({block_tx},
855 m_node.validation_signals->SyncWithValidationInterfaceQueue();
868 context, [&](std::unique_ptr<interfaces::Wallet> wallet_param) {
870 m_coinbase_txns.push_back(
871 CreateAndProcessBlock(
876 m_coinbase_txns.push_back(
877 CreateAndProcessBlock(
886 m_node.validation_signals->SyncWithValidationInterfaceQueue();
915 m_coinbase_txns.push_back(
916 CreateAndProcessBlock({},
921 CreateAndProcessBlock({block_tx},
924 m_node.validation_signals->SyncWithValidationInterfaceQueue();
927 auto block_id = block_tx.GetId();
928 auto prev_id = m_coinbase_txns[0]->GetId();
934 std::vector<TxId> vIdIn{block_id}, vIdOut;
945BOOST_AUTO_TEST_SUITE_END()
static constexpr Amount COIN
RPCHelpMan importwallet()
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.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
The block chain is a tree shaped structure starting with the genesis block at the root,...
const BlockHash * phashBlock
pointer to the hash of the block, if any.
int64_t GetBlockTimeMax() const
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
An encapsulated secp256k1 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.
A mutable version of CTransaction.
std::vector< CTxOut > 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 uint8_t * end() const
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.
const uint8_t * begin() const
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)
Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error.
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...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
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 Config &config, const JSONRPCRequest &request) const
Signature hash type wrapper class.
Minimal stream for reading from an existing byte array by Span.
void push_back(UniValue val)
void pushKV(std::string key, UniValue val)
Minimal stream for overwriting and/or appending to an existing byte vector.
Access to the wallet database.
Descriptor with some wallet metadata.
RAII object to check and reserve a wallet rescan.
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
const Config & GetConfig()
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static std::string PathToString(const path &path)
Convert path object to byte string.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
#define BOOST_CHECK_EQUAL(v1, v2)
#define BOOST_CHECK(expr)
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigChecks, unsigned int bytes_per_sigCheck)
static CTransactionRef MakeTransactionRef()
std::shared_ptr< const CTransaction > CTransactionRef
uint256 GetRandHash() noexcept
========== CONVENIENCE FUNCTIONS FOR COMMONLY USED RANDOMNESS ==========
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.
Amount CachedTxGetImmatureCredit(const CWallet &wallet, const CWalletTx &wtx, bool fUseCache)
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
bool(* handler)(Config &config, 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.
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
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...
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const Amount nMinimumAmount, const Amount nMaximumAmount, const Amount nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
Amount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
std::optional< int > last_scanned_height
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
enum CWallet::ScanResult::@19 status
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
WalletContext struct containing references to state shared between CWallet instances,...
interfaces::Chain * chain
Testing setup and teardown for wallet.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
std::shared_ptr< CWallet > m_wallet
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
constexpr Amount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
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)
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the 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)
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
static void PollutePubKey(CPubKey &pubkey)
static size_t CalculateP2PKHInputSize(bool use_max_sig)
static void TestUnloadWallet(std::shared_ptr< CWallet > &&wallet)
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)
static std::shared_ptr< CWallet > TestLoadWallet(WalletContext &context)
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.
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS