20#include <blockfilter.h>
49#include <boost/test/unit_test.hpp>
67 mtx.
vin.push_back({
CTxIn{from.GetHash(), index}});
70 std::map<COutPoint, Coin> coins;
71 coins[mtx.
vin[0].prevout].out = from.vout[index];
72 std::map<int, bilingual_str> input_errors;
84 auto& desc = descs.at(0);
99 ext_key.
SetSeed(std::array<std::byte, 32>{});
100 const std::string descriptor_without_checksum{
"wpkh(" +
EncodeExtKey(ext_key) +
"/*)"};
101 const std::string descriptor{descriptor_without_checksum +
"#" +
GetDescriptorChecksum(descriptor_without_checksum)};
103 const std::array invalid_ranges{
104 std::pair{std::pair<int64_t, int64_t>{2, 1},
"Range specified as [begin,end] must not have begin after end"},
105 std::pair{std::pair<int64_t, int64_t>{-1, 10},
"Range should be greater or equal than 0"},
106 std::pair{std::pair<int64_t, int64_t>{0, 1'000'000},
"Range is too large"},
107 std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()},
"End of range is too high"},
108 std::pair{std::pair<int64_t, int64_t>{0, 1LL << 31},
"End of range is too high"},
111 for (
const auto& [range, expected_error] : invalid_ranges) {
117 .internal = std::nullopt,
119 .next_index = std::nullopt,
122 BOOST_REQUIRE_EQUAL(results.size(), 1U);
123 BOOST_REQUIRE(results.front().error.has_value());
125 BOOST_CHECK_EQUAL(results.front().error->wallet_error.message.original, expected_error);
126 BOOST_CHECK(!results.front().error->is_general_error);
141 auto& desc{descs.at(0)};
185 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
189 std::chrono::steady_clock::time_point fake_time;
190 reserver.
setNow([&] { fake_time += 60
s;
return fake_time; });
196 BOOST_REQUIRE(!locator.
IsNull());
210 BOOST_REQUIRE(!locator.
IsNull());
248 file_number = newTip->GetBlockPos().nFile;
278 BOOST_REQUIRE(filter_index.Init());
286 const int stale_height{stale_block->
nHeight};
288 BOOST_REQUIRE(
m_node.
chainman->ActiveChainstate().InvalidateBlock(state, stale_block));
290 CreateAndProcessBlock({}, replacement_script);
291 CreateAndProcessBlock({}, replacement_script);
292 BOOST_REQUIRE(filter_index.BlockUntilSyncedToCurrentChain());
295 BOOST_REQUIRE(!
m_node.
chainman->ActiveChain().Contains(*stale_block));
296 BOOST_REQUIRE_EQUAL(
m_node.
chainman->ActiveChain().Height(), stale_height + 1);
301 BOOST_REQUIRE(filter_index.LookupFilter(stale_block, filter));
315 ScanResult result =
wallet.Scanner().Scan(stale_hash, stale_height, {}, reserver,
false);
334 ScanResult result =
wallet.Scanner().Scan(stale_hash, stale_height, {}, reserver,
false);
362 ScanResult result =
wallet.Scanner().Scan(stale_hash, stale_height, {}, reserver,
false);
383 genesis_hash =
m_node.
chainman->ActiveChain().Genesis()->GetBlockHash();
397 ScanResult result =
wallet.Scanner().Scan(genesis_hash, 0, {}, reserver,
false);
439 uint256 genesis_hash, max_hash, tip_hash;
440 int max_height, tip_height;
443 genesis_hash =
m_node.
chainman->ActiveChain().Genesis()->GetBlockHash();
446 max_height = tip_height - 2;
447 max_hash =
m_node.
chainman->ActiveChain()[max_height]->GetBlockHash();
457 wallet.SetLastBlockProcessed(tip_height, tip_hash);
462 ScanResult result =
wallet.Scanner().Scan(genesis_hash, 0, max_height, reserver,
false);
478 wallet.SetLastBlockProcessed(tip_height, tip_hash);
483 ScanResult result =
wallet.Scanner().Scan(tip_hash, tip_height, tip_height, reserver,
false);
496 int start_tip_height{0};
502 wallet.SetLastBlockProcessed(start_tip_height,
m_node.
chainman->ActiveChain().Tip()->GetBlockHash());
503 genesis_hash =
m_node.
chainman->ActiveChain().Genesis()->GetBlockHash();
512 bool extended{
false};
513 auto handler =
wallet.ShowProgress.connect([&](
const std::string&,
int) {
514 if (extended)
return;
521 wallet.SetLastBlockProcessed(new_tip->
nHeight, new_tip_hash);
526 ScanResult result =
wallet.Scanner().Scan(genesis_hash, 0, {}, reserver,
false);
536 uint256 genesis_hash, tip_hash;
544 genesis_hash =
m_node.
chainman->ActiveChain().Genesis()->GetBlockHash();
552 std::chrono::steady_clock::time_point fake_time;
553 reserver.
setNow([&] { fake_time += 60
s;
return fake_time; });
556 ScanResult result =
wallet.Scanner().Scan(genesis_hash, 0, max_height, reserver,
false);
603 bool scan_logged{
false};
604 DebugLogHelper scan_check{
"Rescan started from block", [&](
const std::string*
s) {
605 if (
s) scan_logged =
true;
621 BOOST_REQUIRE(filter_index.Init());
625 uint256 genesis_hash, tip_hash;
631 genesis_hash =
m_node.
chainman->ActiveChain().Genesis()->GetBlockHash();
634 tip_hash = tip->GetBlockHash();
635 wallet.SetLastBlockProcessed(tip_height, tip_hash);
637 BOOST_REQUIRE(!filter_index.LookupFilter(tip, filter));
642 bool fast_scan_logged{
false};
643 DebugLogHelper scan_check{
"fast variant using block filters", [&](
const std::string*
s) {
644 if (
s) fast_scan_logged =
true;
647 ScanResult result =
wallet.Scanner().Scan(genesis_hash, 0, {}, reserver,
false);
648 BOOST_REQUIRE(fast_scan_logged);
667 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
671 context.
args = &m_args;
678 constexpr int NEW_BLOCKS{5};
679 for (
int i = 0; i < NEW_BLOCKS; ++i) {
710 const auto NUM_WALLETS{5};
713 BOOST_REQUIRE(chain->getRwSetting(
"wallet").isNull());
715 const auto& check_concurrent_wallet = [&](
const auto& settings_function,
int num_expected_wallets) {
716 std::vector<std::thread> threads;
717 threads.reserve(NUM_WALLETS);
718 for (
auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
719 for (
auto&
t : threads)
t.join();
721 auto wallets = chain->getRwSetting(
"wallet");
726 check_concurrent_wallet([&chain](
int i) {
732 check_concurrent_wallet([&chain](
int i) {
747 auto inserted = chainman.
BlockIndex().emplace(std::piecewise_construct, std::make_tuple(
GetRandHash()), std::make_tuple());
749 const uint256& hash = inserted.first->first;
750 block = &inserted.first->second;
751 block->
nTime = blockTime;
797 std::vector<bilingual_str> warnings;
799 auto wallet{std::make_shared<CWallet>(chain.get(),
"", std::move(database))};
809 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
810 WalletBatch batch{wallet->GetDatabase()};
820 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
821 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
822 auto requests = wallet->GetAddressReceiveRequests();
823 auto erequests = {
"val_rr11",
"val_rr20"};
824 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
826 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
827 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
832 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
833 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
834 auto requests = wallet->GetAddressReceiveRequests();
835 auto erequests = {
"val_rr11"};
836 BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
864 wallet->CommitTransaction(tx);
875 auto it =
wallet->mapWallet.find(tx->GetHash());
886 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
890 std::map<CTxDestination, std::vector<COutput>> list;
896 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
912 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
920 for (
const auto&
group : list) {
921 for (
const auto& coin :
group.second) {
923 wallet->LockCoin(coin.outpoint,
false);
937 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
942 std::map<OutputType, size_t>& expected_coins_sizes)
944 LOCK(context.wallet->cs_wallet);
951 for (uint32_t i = 0; i < wtx.
GetTx()->vout.size(); i++) context.wallet->LockCoin({wtx.
GetHash(), i},
false);
952 for (
const auto& [type, size] : expected_coins_sizes)
BOOST_CHECK_EQUAL(size, available_coins.
coins[type].size());
957 std::map<OutputType, size_t> expected_coins_sizes;
958 for (
const auto& out_type :
OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
976 expected_coins_sizes[out_type] = 2U;
1002 CScript inner_script =
CScript() << OP_0 << std::vector<unsigned char>(key_hash.
begin(), key_hash.
end());
1034 std::string
s(e.what());
1035 return s.find(
"Missing checksum") != std::string::npos;
1040 std::vector<unsigned char> malformed_record;
1042 vw << std::string(
"notadescriptor");
1049 std::optional<WalletDescriptor> w_desc;
1073 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
1076 context.
args = &m_args;
1086 int addtx_count = 0;
1087 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet", [&](
const std::string*
s) {
1088 if (
s) ++addtx_count;
1093 bool rescan_completed =
false;
1094 DebugLogHelper rescan_check(
"[default wallet] Rescan completed", [&](
const std::string*
s) {
1095 if (
s) rescan_completed =
true;
1103 std::promise<void> promise;
1105 promise.get_future().wait();
1108 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1110 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1131 promise.set_value();
1150 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1152 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1174 context.
args = &m_args;
1182 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
1184 context.
args = &m_args;
1190 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
1197 auto block_hash = block_tx.GetHash();
1198 auto prev_tx = m_coinbase_txns[0];
1204 std::vector<Txid> vHashIn{ block_hash };
int64_t CAmount
Amount in satoshis (Can be negative)
constexpr CAmount COIN
The amount of satoshis in one BTC.
bool DestroyBlockFilterIndex(BlockFilterType filter_type)
Destroy the block filter index with the given type.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
bool InitBlockFilterIndex(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
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.
Complete block filter struct as defined in BIP 157.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
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.
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.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
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)
Minimal stream for reading from an existing byte array by std::span.
constexpr bool IsNull() const
constexpr unsigned char * end()
constexpr unsigned char * begin()
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.
const Txid & GetHash() const LIFETIMEBOUND
CTransactionRef GetTx() const
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, ParamFormat format=ParamFormat::JSON)
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.
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
CKey GenerateRandomKey(bool compressed) noexcept
std::string EncodeExtKey(const CExtKey &key)
std::string EncodeSecret(const CKey &key)
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
@ MEMPOOL_NO_BROADCAST
Add the transaction to the mempool, but don't broadcast to anybody.
constexpr unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
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)
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase()
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::vector< ImportResult > ProcessDescriptorsImport(CWallet &wallet, std::vector< ImportDescriptorRequest > &requests)
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)
constexpr CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
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)
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
BOOST_AUTO_TEST_CASE(bnb_test)
constexpr DatabaseFormat DATABASE_FORMATS[]
static void AddKey(CWallet &wallet, const CKey &key)
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context)
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse, bool include_nonmempool)
std::shared_ptr< CWallet > TestCreateWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
static int64_t AddTx(ChainstateManager &chainman, CWallet &wallet, uint32_t lockTime, std::chrono::seconds mock_time, int64_t blockTime)
bool malformed_descriptor(std::ios_base::failure e)
constexpr CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
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)
BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
is a home for public enum and struct type definitions that are used internally by node code,...
#define BOOST_CHECK(expr)
constexpr auto OUTPUT_TYPES
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
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)
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
constexpr deserialize_type deserialize
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.
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
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...
std::vector< uint256 > vHave
void SetSeed(std::span< const std::byte > seed)
A mutable version of CTransaction.
std::vector< CTxOut > vout
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
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
Information about a descriptor to be imported.
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
enum wallet::ScanResult::@19 status
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.
State of transaction confirmed in a block.
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.
FuzzedDataProvider provider
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::shared_ptr< CWallet > m_wallet
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)