49#include <boost/test/unit_test.hpp>
64 mtx.vin.push_back({
CTxIn{from.GetHash(), index}});
67 std::map<COutPoint, Coin> coins;
68 coins[
mtx.vin[0].prevout].out = from.vout[index];
101 std::pair{std::pair<int64_t, int64_t>{2, 1},
"Range specified as [begin,end] must not have begin after end"},
102 std::pair{std::pair<int64_t, int64_t>{std::numeric_limits<int64_t>::max(), 0},
"Range specified as [begin,end] must not have begin after end"},
103 std::pair{std::pair<int64_t, int64_t>{-1, 10},
"Range should be greater or equal than 0"},
104 std::pair{std::pair<int64_t, int64_t>{0, 1'000'000},
"Range is too large"},
105 std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()},
"End of range is too high"},
106 std::pair{std::pair<int64_t, int64_t>{0, 1LL << 31},
"End of range is too high"},
115 .internal = std::nullopt,
117 .next_index = std::nullopt,
135 EncryptionFailureSetup()
138 m_args.ForceSetArg(
"-keypool",
"1");
146 auto database{std::make_unique<FaultInjectingDatabase>()};
160 for (
bool success : {
false,
true}) {
195 for (
bool success : {
false,
true}) {
210 for (
bool success : {
false,
true}) {
229 const auto changed{
wallet->ChangeWalletPassphrase(
"old_pass",
"new_pass")};
232 BOOST_CHECK_EQUAL(
changed.error().message.original,
"Error: Writing the new encryption key to the wallet database failed");
264 for (
auto failure : {Failure::PlaintextWrite, Failure::EncryptedWrite, Failure::Erase, Failure::Commit}) {
265 const bool encrypted{failure != Failure::PlaintextWrite};
272 provider.keys.emplace(key.GetPubKey().GetID(), key);
275 return wallet->AddWalletDescriptor(descriptor,
provider,
"",
false);
279 return wallet->GetKey(key.GetPubKey().GetID()).has_value();
288 if (failure == Failure::Erase) {
290 }
else if (failure == Failure::Commit) {
315 auto& desc{
descs.at(0)};
335 std::vector<std::thread>
threads;
340 auto wallets = chain->getRwSetting(
"wallet");
416 std::vector<bilingual_str> warnings;
418 auto wallet{std::make_shared<CWallet>(chain.get(),
"", std::move(
database))};
426 const std::string
name{
strprintf(
"receive-requests-%i", format)};
428 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
429 WalletBatch batch{wallet->GetDatabase()};
439 BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
440 BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
441 auto requests = wallet->GetAddressReceiveRequests();
442 auto erequests = {
"val_rr11",
"val_rr20"};
445 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
446 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
451 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
452 BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
453 auto requests = wallet->GetAddressReceiveRequests();
454 auto erequests = {
"val_rr11"};
483 wallet->CommitTransaction(tx);
494 auto it =
wallet->mapWallet.find(tx->GetHash());
505 std::string
coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
509 std::map<CTxDestination, std::vector<COutput>> list;
539 for (
const auto& group : list) {
540 for (
const auto& coin : group.second) {
542 wallet->LockCoin(coin.outpoint,
false);
653 std::string s(
e.what());
654 return s.find(
"Missing checksum") != std::string::npos;
661 vw << std::string(
"notadescriptor");
668 std::optional<WalletDescriptor>
w_desc;
692 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
727 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey()),
false).vtx[0]);
768 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
800 m_args.ForceSetArg(
"-unsafesqlitesync",
"1");
808 m_coinbase_txns.push_back(CreateAndProcessBlock({},
GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
815 auto block_hash =
block_tx.GetHash();
816 auto prev_tx = m_coinbase_txns[0];
822 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.
BOOST_FIXTURE_TEST_CASE(util_CheckValue, CheckValueTest)
static void AddTx(const CTransactionRef &tx, const CAmount &fee, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
#define Assert(val)
Identity function.
The block chain is a tree shaped structure starting with the genesis block at the root,...
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
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
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.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
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 AddKey(const CKey &key)
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Minimal stream for reading from an existing byte array by std::span.
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &max_tx_fee, const CFeeRate &max_tx_fee_rate, node::TxBroadcast broadcast_method, std::string &err_string)=0
Process a local transaction, optionally adding it to the mempool and optionally broadcasting it to th...
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
void FailNextWrite(std::string record_type, size_t match_skip_count=0)
bool HasRecordType(const std::string &record_type)
std::optional< SerializeData > GetRecordValue(const std::string &record_type)
void FailNextErase(std::string record_type)
CWalletTx & AddTx(CRecipient recipient)
std::unique_ptr< CWallet > wallet
Access to the wallet database.
Descriptor with some wallet metadata.
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.
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
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.
const std::string WALLETDESCRIPTORCKEY
const std::string WALLETDESCRIPTORKEY
const std::string MASTER_KEY
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)
wallet::DescriptorScriptPubKeyMan * CreateDescriptor(CWallet &keystore, const std::string &desc_str, const bool success)
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
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.
@ PassphraseIncorrect
The passphrase does not decrypt the wallet. Callers may ask the user to enter it again.
@ GenericError
Generic wallet error.
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[]
void AddKey(CWallet &wallet, const CKey &key)
std::shared_ptr< CWallet > TestLoadWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context)
static bool BroadcastTestSimpleSpend(interfaces::Chain &chain, ChainstateManager &chainman, const CMutableTransaction &tx, std::string &error)
std::shared_ptr< CWallet > TestCreateWallet(std::unique_ptr< WalletDatabase > database, WalletContext &context, uint64_t create_flags)
bool malformed_descriptor(std::ios_base::failure e)
constexpr CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
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
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
is a home for public enum and struct type definitions that are used internally by node code,...
#define BOOST_CHECK_EQUAL(v1, v2)
#define BOOST_CHECK(expr)
constexpr auto OUTPUT_TYPES
unsigned int nBytesPerSigOp
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
constexpr script_verify_flags STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
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.
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.
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.
std::optional< DatabaseFormat > require_format
Information about a descriptor to be imported.
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,...
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
FuzzedDataProvider provider
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
BOOST_CHECK_EQUAL_COLLECTIONS(R1L.begin(), R1L.end(), R1Array, R1Array+uint256::size())
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
std::shared_ptr< CWallet > m_wallet
static void AvailableCoins(benchmark::Bench &bench, const std::vector< OutputType > &output_type)
FaultInjectingDatabase * fail_db