25#include <validation.h>
34#include <boost/test/unit_test.hpp>
52 mtx.
vin.push_back({CTxIn{from.GetHash(), index}});
55 std::map<COutPoint, Coin> coins;
56 coins[mtx.vin[0].prevout].out = from.vout[index];
57 std::map<int, bilingual_str> input_errors;
69 auto& desc = descs.at(0);
85 auto& desc{descs.at(0)};
108 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
129 wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
133 std::chrono::steady_clock::time_point fake_time;
134 reserver.
setNow([&] { fake_time += 60s;
return fake_time; });
140 BOOST_REQUIRE(!locator.
IsNull());
154 BOOST_REQUIRE(!locator.
IsNull());
164 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
166 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
176 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
192 file_number = newTip->GetBlockPos().nFile;
193 Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
195 m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
204 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
226 wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
227 genesis_hash = m_node.chainman->ActiveChain().Genesis()->GetBlockHash();
252 auto chain = m_node.chain.get();
253 const auto NUM_WALLETS{5};
256 BOOST_REQUIRE(chain->getRwSetting(
"wallet").isNull());
258 const auto& check_concurrent_wallet = [&](
const auto& settings_function,
int num_expected_wallets) {
259 std::vector<std::thread> threads;
260 threads.reserve(NUM_WALLETS);
261 for (
auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
262 for (
auto&
t : threads)
t.join();
264 auto wallets = chain->getRwSetting(
"wallet");
269 check_concurrent_wallet([&chain](
int i) {
275 check_concurrent_wallet([&chain](
int i) {
290 auto inserted = chainman.
BlockIndex().emplace(std::piecewise_construct, std::make_tuple(
GetRandHash()), std::make_tuple());
292 const uint256& hash = inserted.first->first;
293 block = &inserted.first->second;
294 block->
nTime = blockTime;
298 return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](
CWalletTx& wtx,
bool ) {
340 std::vector<bilingual_str> warnings;
342 auto wallet{std::make_shared<CWallet>(chain.get(),
"", std::move(database))};
350 const std::string name{
strprintf(
"receive-requests-%i", format)};
352 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
353 WalletBatch batch{wallet->GetDatabase()};
363 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
364 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
365 auto requests = wallet->GetAddressReceiveRequests();
366 auto erequests = {
"val_rr11",
"val_rr20"};
369 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
370 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
375 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
376 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
377 auto requests = wallet->GetAddressReceiveRequests();
378 auto erequests = {
"val_rr11"};
407 wallet->CommitTransaction(tx);
417 wallet->SetLastBlockProcessed(
wallet->GetLastBlockHeight() + 1,
m_node.chainman->ActiveChain().Tip()->GetBlockHash());
418 auto it =
wallet->mapWallet.find(tx->GetHash());
420 it->second.m_state =
TxStateConfirmed{
m_node.chainman->ActiveChain().Tip()->GetBlockHash(),
m_node.chainman->ActiveChain().Height(), 1};
429 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
433 std::map<CTxDestination, std::vector<COutput>> list;
439 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
455 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
463 for (
const auto& group : list) {
464 for (
const auto& coin : group.second) {
466 wallet->LockCoin(coin.outpoint,
false);
480 BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
485 std::map<OutputType, size_t>& expected_coins_sizes)
487 LOCK(context.wallet->cs_wallet);
494 for (uint32_t i = 0; i < wtx.
GetTx()->vout.size(); i++) context.wallet->LockCoin({wtx.
GetHash(), i},
false);
495 for (
const auto& [type, size] : expected_coins_sizes)
BOOST_CHECK_EQUAL(size, available_coins.
coins[type].size());
500 std::map<OutputType, size_t> expected_coins_sizes;
501 for (
const auto& out_type :
OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
519 expected_coins_sizes[out_type] = 2U;
577 std::string s(e.what());
578 return s.find(
"Missing checksum") != std::string::npos;
583 std::vector<unsigned char> malformed_record;
585 vw << std::string(
"notadescriptor");
592 std::optional<WalletDescriptor> w_desc;
616 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
619 context.
args = &m_args;
620 context.
chain = m_node.chain.get();
630 DebugLogHelper addtx_counter(
"[default wallet] AddToWallet", [&](
const std::string* s) {
631 if (s) ++addtx_count;
636 bool rescan_completed =
false;
637 DebugLogHelper rescan_check(
"[default wallet] Rescan completed", [&](
const std::string* s) {
638 if (s) rescan_completed =
true;
646 std::promise<void> promise;
647 m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
648 promise.get_future().wait();
651 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
653 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
675 m_node.validation_signals->SyncWithValidationInterfaceQueue();
693 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
695 m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
698 m_node.validation_signals->SyncWithValidationInterfaceQueue();
717 context.
args = &m_args;
725 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
727 context.
args = &m_args;
728 context.
chain = m_node.chain.get();
733 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
737 m_node.validation_signals->SyncWithValidationInterfaceQueue();
740 auto block_hash = block_tx.GetHash();
741 auto prev_tx = m_coinbase_txns[0];
747 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.
constexpr unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?
#define Assert(val)
Identity function.
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() 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)
Access to the wallet database.
bool ReadBestBlock(CBlockLocator &locator)
Descriptor with some wallet metadata.
static WalletDescriptor FromStream(deserialize_type, Stream &s)
RAII object to check and reserve a wallet rescan.
bool reserve(bool with_passphrase=false)
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_EXCEPTION(req.LoadBody(reader), std::runtime_error, HasReason{"Cannot parse Content-Length value"})
CKey GenerateRandomKey(bool compressed) noexcept
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?
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)
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.
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase()
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
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
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)
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::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
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)
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CoinFilterParams ¶ms)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
#define BOOST_CHECK_EQUAL(v1, v2)
#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.
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.
std::vector< std::unique_ptr< Descriptor > > Parse(std::string_view descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
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.
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
A mutable version of CTransaction.
std::vector< CTxOut > vout
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
TestChain100Setup(ChainType chain_type=ChainType::REGTEST, TestOpts={})
Testing setup that configures a complete environment.
std::optional< int > last_scanned_height
uint256 last_scanned_block
uint256 last_failed_block
enum wallet::CWallet::ScanResult::@273233031336335332015254221053060000163044056224 status
COutputs available for spending, stored by OutputType.
CAmount GetTotalAmount() const
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.
interfaces::Chain * chain
Testing setup and teardown for wallet.
#define WITH_LOCK(cs, code)
FuzzedDataProvider provider
#define EXCLUSIVE_LOCKS_REQUIRED(...)
BOOST_CHECK_EQUAL_COLLECTIONS(R1L.begin(), R1L.end(), R1Array, R1Array+uint256::size())