aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/bench/wallet_balance.cpp3
-rw-r--r--src/net_permissions.cpp8
-rw-r--r--src/net_permissions.h4
-rw-r--r--src/qt/test/addressbooktests.cpp3
-rw-r--r--src/qt/test/wallettests.cpp3
-rw-r--r--src/rpc/blockchain.cpp2
-rw-r--r--src/rpc/net.cpp2
-rw-r--r--src/rpc/rawtransaction.cpp2
-rw-r--r--src/test/fuzz/coins_view.cpp6
-rw-r--r--src/test/fuzz/i2p.cpp2
-rw-r--r--src/test/fuzz/transaction.cpp7
-rw-r--r--src/test/sock_tests.cpp4
-rw-r--r--src/util/sock.cpp4
-rw-r--r--src/util/sock.h29
-rw-r--r--src/wallet/dump.cpp3
-rw-r--r--src/wallet/load.cpp3
-rw-r--r--src/wallet/rpcwallet.cpp14
-rw-r--r--src/wallet/sqlite.cpp100
-rw-r--r--src/wallet/test/coinselector_tests.cpp3
-rw-r--r--src/wallet/test/wallet_test_fixture.cpp3
-rw-r--r--src/wallet/test/wallet_tests.cpp24
-rw-r--r--src/wallet/wallet.cpp102
-rw-r--r--src/wallet/wallet.h11
-rw-r--r--src/wallet/wallettool.cpp3
24 files changed, 187 insertions, 158 deletions
diff --git a/src/bench/wallet_balance.cpp b/src/bench/wallet_balance.cpp
index d7cc167885..362b7c1e15 100644
--- a/src/bench/wallet_balance.cpp
+++ b/src/bench/wallet_balance.cpp
@@ -22,8 +22,7 @@ static void WalletBalance(benchmark::Bench& bench, const bool set_dirty, const b
CWallet wallet{test_setup->m_node.chain.get(), "", CreateMockWalletDatabase()};
{
wallet.SetupLegacyScriptPubKeyMan();
- bool first_run;
- if (wallet.LoadWallet(first_run) != DBErrors::LOAD_OK) assert(false);
+ if (wallet.LoadWallet() != DBErrors::LOAD_OK) assert(false);
}
auto handler = test_setup->m_node.chain->handleNotifications({&wallet, [](CWallet*) {}});
diff --git a/src/net_permissions.cpp b/src/net_permissions.cpp
index 228453df20..d0a45f90fa 100644
--- a/src/net_permissions.cpp
+++ b/src/net_permissions.cpp
@@ -20,8 +20,8 @@ const std::vector<std::string> NET_PERMISSIONS_DOC{
namespace {
-// The parse the following format "perm1,perm2@xxxxxx"
-bool TryParsePermissionFlags(const std::string str, NetPermissionFlags& output, size_t& readen, bilingual_str& error)
+// Parse the following format: "perm1,perm2@xxxxxx"
+bool TryParsePermissionFlags(const std::string& str, NetPermissionFlags& output, size_t& readen, bilingual_str& error)
{
NetPermissionFlags flags = NetPermissionFlags::None;
const auto atSeparator = str.find('@');
@@ -81,7 +81,7 @@ std::vector<std::string> NetPermissions::ToStrings(NetPermissionFlags flags)
return strings;
}
-bool NetWhitebindPermissions::TryParse(const std::string str, NetWhitebindPermissions& output, bilingual_str& error)
+bool NetWhitebindPermissions::TryParse(const std::string& str, NetWhitebindPermissions& output, bilingual_str& error)
{
NetPermissionFlags flags;
size_t offset;
@@ -104,7 +104,7 @@ bool NetWhitebindPermissions::TryParse(const std::string str, NetWhitebindPermis
return true;
}
-bool NetWhitelistPermissions::TryParse(const std::string str, NetWhitelistPermissions& output, bilingual_str& error)
+bool NetWhitelistPermissions::TryParse(const std::string& str, NetWhitelistPermissions& output, bilingual_str& error)
{
NetPermissionFlags flags;
size_t offset;
diff --git a/src/net_permissions.h b/src/net_permissions.h
index 7a158aa6c5..c00689465e 100644
--- a/src/net_permissions.h
+++ b/src/net_permissions.h
@@ -74,14 +74,14 @@ public:
class NetWhitebindPermissions : public NetPermissions
{
public:
- static bool TryParse(const std::string str, NetWhitebindPermissions& output, bilingual_str& error);
+ static bool TryParse(const std::string& str, NetWhitebindPermissions& output, bilingual_str& error);
CService m_service;
};
class NetWhitelistPermissions : public NetPermissions
{
public:
- static bool TryParse(const std::string str, NetWhitelistPermissions& output, bilingual_str& error);
+ static bool TryParse(const std::string& str, NetWhitelistPermissions& output, bilingual_str& error);
CSubNet m_subnet;
};
diff --git a/src/qt/test/addressbooktests.cpp b/src/qt/test/addressbooktests.cpp
index a026069232..39c69fe184 100644
--- a/src/qt/test/addressbooktests.cpp
+++ b/src/qt/test/addressbooktests.cpp
@@ -63,8 +63,7 @@ void TestAddAddressesToSendBook(interfaces::Node& node)
node.setContext(&test.m_node);
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), "", CreateMockWalletDatabase());
wallet->SetupLegacyScriptPubKeyMan();
- bool firstRun;
- wallet->LoadWallet(firstRun);
+ wallet->LoadWallet();
auto build_address = [&wallet]() {
CKey key;
diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp
index 03460cd6eb..febfead6ad 100644
--- a/src/qt/test/wallettests.cpp
+++ b/src/qt/test/wallettests.cpp
@@ -140,8 +140,7 @@ void TestGUI(interfaces::Node& node)
}
node.setContext(&test.m_node);
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), "", CreateMockWalletDatabase());
- bool firstRun;
- wallet->LoadWallet(firstRun);
+ wallet->LoadWallet();
{
auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index f2b99579b7..63826c49e1 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -1099,7 +1099,7 @@ static RPCHelpMan gettxoutsetinfo()
"Note this call may take some time if you are not using coinstatsindex.\n",
{
{"hash_type", RPCArg::Type::STR, RPCArg::Default{"hash_serialized_2"}, "Which UTXO set hash should be calculated. Options: 'hash_serialized_2' (the legacy algorithm), 'muhash', 'none'."},
- {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The block hash or height of the target height (only available with coinstatsindex).", "", {"", "string or numeric"}},
+ {"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "The block hash or height of the target height (only available with coinstatsindex).", "", {"", "string or numeric"}},
{"use_index", RPCArg::Type::BOOL, RPCArg::Default{true}, "Use coinstatsindex, if available."},
},
RPCResult{
diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
index 07b085ce74..4999eefc24 100644
--- a/src/rpc/net.cpp
+++ b/src/rpc/net.cpp
@@ -161,7 +161,7 @@ static RPCHelpMan getpeerinfo()
"When a message type is not listed in this json object, the bytes sent are 0.\n"
"Only known message types can appear as keys in the object."}
}},
- {RPCResult::Type::OBJ, "bytesrecv_per_msg", "",
+ {RPCResult::Type::OBJ_DYN, "bytesrecv_per_msg", "",
{
{RPCResult::Type::NUM, "msg", "The total bytes received aggregated by message type\n"
"When a message type is not listed in this json object, the bytes received are 0.\n"
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index f1ab1b4687..adb8ac0595 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -1434,7 +1434,7 @@ static RPCHelpMan createpsbt()
"For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
" accepted as second parameter.",
{
- {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
+ {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
{
{"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT},
},
diff --git a/src/test/fuzz/coins_view.cpp b/src/test/fuzz/coins_view.cpp
index 21dc80cc8d..878b5a27da 100644
--- a/src/test/fuzz/coins_view.cpp
+++ b/src/test/fuzz/coins_view.cpp
@@ -6,6 +6,7 @@
#include <chainparams.h>
#include <chainparamsbase.h>
#include <coins.h>
+#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <key.h>
@@ -230,6 +231,11 @@ FUZZ_TARGET_INIT(coins_view, initialize_coins_view)
// consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
return;
}
+ TxValidationState dummy;
+ if (!CheckTransaction(transaction, dummy)) {
+ // It is not allowed to call CheckTxInputs if CheckTransaction failed
+ return;
+ }
(void)Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out);
assert(MoneyRange(tx_fee_out));
},
diff --git a/src/test/fuzz/i2p.cpp b/src/test/fuzz/i2p.cpp
index 345d68502a..e0d62fb493 100644
--- a/src/test/fuzz/i2p.cpp
+++ b/src/test/fuzz/i2p.cpp
@@ -37,7 +37,7 @@ FUZZ_TARGET_INIT(i2p, initialize_i2p)
if (sess.Listen(conn)) {
if (sess.Accept(conn)) {
try {
- conn.sock->RecvUntilTerminator('\n', 10ms, interrupt, i2p::sam::MAX_MSG_SIZE);
+ (void)conn.sock->RecvUntilTerminator('\n', 10ms, interrupt, i2p::sam::MAX_MSG_SIZE);
} catch (const std::runtime_error&) {
}
}
diff --git a/src/test/fuzz/transaction.cpp b/src/test/fuzz/transaction.cpp
index 17e4405a13..797b9cea3e 100644
--- a/src/test/fuzz/transaction.cpp
+++ b/src/test/fuzz/transaction.cpp
@@ -61,8 +61,11 @@ FUZZ_TARGET_INIT(transaction, initialize_transaction)
return;
}
- TxValidationState state_with_dupe_check;
- (void)CheckTransaction(tx, state_with_dupe_check);
+ {
+ TxValidationState state_with_dupe_check;
+ const bool res{CheckTransaction(tx, state_with_dupe_check)};
+ Assert(res == state_with_dupe_check.IsValid());
+ }
const CFeeRate dust_relay_fee{DUST_RELAY_TX_FEE};
std::string reason;
diff --git a/src/test/sock_tests.cpp b/src/test/sock_tests.cpp
index 400de875b7..9e98f4f0b1 100644
--- a/src/test/sock_tests.cpp
+++ b/src/test/sock_tests.cpp
@@ -139,7 +139,7 @@ BOOST_AUTO_TEST_CASE(wait)
Sock sock0(s[0]);
Sock sock1(s[1]);
- std::thread waiter([&sock0]() { sock0.Wait(24h, Sock::RECV); });
+ std::thread waiter([&sock0]() { (void)sock0.Wait(24h, Sock::RECV); });
BOOST_REQUIRE_EQUAL(sock1.Send("a", 1, 0), 1);
@@ -162,7 +162,7 @@ BOOST_AUTO_TEST_CASE(recv_until_terminator_limit)
// BOOST_CHECK_EXCEPTION() writes to some variables shared with the main thread which
// creates a data race. So mimic it manually.
try {
- sock_recv.RecvUntilTerminator('\n', timeout, interrupt, max_data);
+ (void)sock_recv.RecvUntilTerminator('\n', timeout, interrupt, max_data);
} catch (const std::runtime_error& e) {
threw_as_expected = HasReason("too many bytes without a terminator")(e);
}
diff --git a/src/util/sock.cpp b/src/util/sock.cpp
index 0bc9795db3..b6c2a47434 100644
--- a/src/util/sock.cpp
+++ b/src/util/sock.cpp
@@ -179,7 +179,7 @@ void Sock::SendComplete(const std::string& data,
// Wait for a short while (or the socket to become ready for sending) before retrying
// if nothing was sent.
const auto wait_time = std::min(deadline - now, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
- Wait(wait_time, SEND);
+ (void)Wait(wait_time, SEND);
}
}
@@ -262,7 +262,7 @@ std::string Sock::RecvUntilTerminator(uint8_t terminator,
// Wait for a short while (or the socket to become ready for reading) before retrying.
const auto wait_time = std::min(deadline - now, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
- Wait(wait_time, RECV);
+ (void)Wait(wait_time, RECV);
}
}
diff --git a/src/util/sock.h b/src/util/sock.h
index a4df7cd21b..59cc8c0b1d 100644
--- a/src/util/sock.h
+++ b/src/util/sock.h
@@ -64,7 +64,7 @@ public:
* Get the value of the contained socket.
* @return socket or INVALID_SOCKET if empty
*/
- virtual SOCKET Get() const;
+ [[nodiscard]] virtual SOCKET Get() const;
/**
* Get the value of the contained socket and drop ownership. It will not be closed by the
@@ -82,26 +82,29 @@ public:
* send(2) wrapper. Equivalent to `send(this->Get(), data, len, flags);`. Code that uses this
* wrapper can be unit tested if this method is overridden by a mock Sock implementation.
*/
- virtual ssize_t Send(const void* data, size_t len, int flags) const;
+ [[nodiscard]] virtual ssize_t Send(const void* data, size_t len, int flags) const;
/**
* recv(2) wrapper. Equivalent to `recv(this->Get(), buf, len, flags);`. Code that uses this
* wrapper can be unit tested if this method is overridden by a mock Sock implementation.
*/
- virtual ssize_t Recv(void* buf, size_t len, int flags) const;
+ [[nodiscard]] virtual ssize_t Recv(void* buf, size_t len, int flags) const;
/**
* connect(2) wrapper. Equivalent to `connect(this->Get(), addr, addrlen)`. Code that uses this
* wrapper can be unit tested if this method is overridden by a mock Sock implementation.
*/
- virtual int Connect(const sockaddr* addr, socklen_t addr_len) const;
+ [[nodiscard]] virtual int Connect(const sockaddr* addr, socklen_t addr_len) const;
/**
* getsockopt(2) wrapper. Equivalent to
* `getsockopt(this->Get(), level, opt_name, opt_val, opt_len)`. Code that uses this
* wrapper can be unit tested if this method is overridden by a mock Sock implementation.
*/
- virtual int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const;
+ [[nodiscard]] virtual int GetSockOpt(int level,
+ int opt_name,
+ void* opt_val,
+ socklen_t* opt_len) const;
using Event = uint8_t;
@@ -124,9 +127,9 @@ public:
* value of `true` and `occurred` being set to 0.
* @return true on success and false otherwise
*/
- virtual bool Wait(std::chrono::milliseconds timeout,
- Event requested,
- Event* occurred = nullptr) const;
+ [[nodiscard]] virtual bool Wait(std::chrono::milliseconds timeout,
+ Event requested,
+ Event* occurred = nullptr) const;
/* Higher level, convenience, methods. These may throw. */
@@ -154,17 +157,17 @@ public:
* @throws std::runtime_error if the operation cannot be completed. In this case some bytes may
* have been consumed from the socket.
*/
- virtual std::string RecvUntilTerminator(uint8_t terminator,
- std::chrono::milliseconds timeout,
- CThreadInterrupt& interrupt,
- size_t max_data) const;
+ [[nodiscard]] virtual std::string RecvUntilTerminator(uint8_t terminator,
+ std::chrono::milliseconds timeout,
+ CThreadInterrupt& interrupt,
+ size_t max_data) const;
/**
* Check if still connected.
* @param[out] errmsg The error string, if the socket has been disconnected.
* @return true if connected
*/
- virtual bool IsConnected(std::string& errmsg) const;
+ [[nodiscard]] virtual bool IsConnected(std::string& errmsg) const;
protected:
/**
diff --git a/src/wallet/dump.cpp b/src/wallet/dump.cpp
index e314107988..c39c0c7e73 100644
--- a/src/wallet/dump.cpp
+++ b/src/wallet/dump.cpp
@@ -194,8 +194,7 @@ bool CreateFromDump(const std::string& name, const fs::path& wallet_path, biling
std::shared_ptr<CWallet> wallet(new CWallet(nullptr /* chain */, name, std::move(database)), WalletToolReleaseWallet);
{
LOCK(wallet->cs_wallet);
- bool first_run = true;
- DBErrors load_wallet_ret = wallet->LoadWallet(first_run);
+ DBErrors load_wallet_ret = wallet->LoadWallet();
if (load_wallet_ret != DBErrors::LOAD_OK) {
error = strprintf(_("Error creating %s"), name);
return false;
diff --git a/src/wallet/load.cpp b/src/wallet/load.cpp
index 342a165f39..e0df96666f 100644
--- a/src/wallet/load.cpp
+++ b/src/wallet/load.cpp
@@ -105,7 +105,8 @@ bool LoadWallets(interfaces::Chain& chain)
if (!database && status == DatabaseStatus::FAILED_NOT_FOUND) {
continue;
}
- std::shared_ptr<CWallet> pwallet = database ? CWallet::Create(chain, name, std::move(database), options.create_flags, error, warnings) : nullptr;
+ chain.initMessage(_("Loading wallet...").translated);
+ std::shared_ptr<CWallet> pwallet = database ? CWallet::Create(&chain, name, std::move(database), options.create_flags, error, warnings) : nullptr;
if (!warnings.empty()) chain.initWarning(Join(warnings, Untranslated("\n")));
if (!pwallet) {
chain.initError(error);
diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
index 5567d183b6..4e3c8ce49d 100644
--- a/src/wallet/rpcwallet.cpp
+++ b/src/wallet/rpcwallet.cpp
@@ -854,7 +854,7 @@ static RPCHelpMan sendmany()
HELP_REQUIRING_PASSPHRASE,
{
{"dummy", RPCArg::Type::STR, RPCArg::Optional::NO, "Must be set to \"\" for backwards compatibility.", "\"\""},
- {"amounts", RPCArg::Type::OBJ, RPCArg::Optional::NO, "The addresses and amounts",
+ {"amounts", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::NO, "The addresses and amounts",
{
{"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The bitcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value"},
},
@@ -2568,7 +2568,7 @@ static RPCHelpMan loadwallet()
"\napplied to the new wallet (eg -rescan, etc).\n",
{
{"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet directory or .dat file."},
- {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Default{UniValue::VNULL}, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
+ {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED_NAMED_ARG, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
@@ -2696,10 +2696,10 @@ static RPCHelpMan createwallet()
{"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name for the new wallet. If this is a path, the wallet will be created at the path location."},
{"disable_private_keys", RPCArg::Type::BOOL, RPCArg::Default{false}, "Disable the possibility of private keys (only watchonlys are possible in this mode)."},
{"blank", RPCArg::Type::BOOL, RPCArg::Default{false}, "Create a blank wallet. A blank wallet has no keys or HD seed. One can be set using sethdseed."},
- {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Encrypt the wallet with this passphrase."},
+ {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Encrypt the wallet with this passphrase."},
{"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{false}, "Keep track of coin reuse, and treat dirty and clean coins differently with privacy considerations in mind."},
{"descriptors", RPCArg::Type::BOOL, RPCArg::Default{false}, "Create a native descriptor wallet. The wallet will use descriptors internally to handle address creation"},
- {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Default{UniValue::VNULL}, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
+ {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED_NAMED_ARG, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
{"external_signer", RPCArg::Type::BOOL, RPCArg::Default{false}, "Use an external signer such as a hardware wallet. Requires -signer to be configured. Wallet creation will fail if keys cannot be fetched. Requires disable_private_keys and descriptors set to true."},
},
RPCResult{
@@ -2790,7 +2790,7 @@ static RPCHelpMan unloadwallet()
"Specifying the wallet name on a wallet endpoint is invalid.",
{
{"wallet_name", RPCArg::Type::STR, RPCArg::DefaultHint{"the wallet name from the RPC endpoint"}, "The name of the wallet to unload. If provided both here and in the RPC endpoint, the two must be identical."},
- {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Default{UniValue::VNULL}, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
+ {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED_NAMED_ARG, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
},
RPCResult{RPCResult::Type::OBJ, "", "", {
{RPCResult::Type::STR, "warning", "Warning message if wallet was not unloaded cleanly."},
@@ -4021,7 +4021,7 @@ static RPCHelpMan send()
"That is, each address can only appear once and there can only be one 'data' object.\n"
"For convenience, a dictionary, which holds the key-value pairs directly, is also accepted.",
{
- {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
+ {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
{
{"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
},
@@ -4370,7 +4370,7 @@ static RPCHelpMan walletcreatefundedpsbt()
"For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
"accepted as second parameter.",
{
- {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
+ {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
{
{"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
},
diff --git a/src/wallet/sqlite.cpp b/src/wallet/sqlite.cpp
index e245a277e4..2e60aca017 100644
--- a/src/wallet/sqlite.cpp
+++ b/src/wallet/sqlite.cpp
@@ -16,6 +16,7 @@
#include <sqlite3.h>
#include <stdint.h>
+#include <optional>
#include <utility>
#include <vector>
@@ -35,6 +36,36 @@ static void ErrorLogCallback(void* arg, int code, const char* msg)
LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg);
}
+static std::optional<int> ReadPragmaInteger(sqlite3* db, const std::string& key, const std::string& description, bilingual_str& error)
+{
+ std::string stmt_text = strprintf("PRAGMA %s", key);
+ sqlite3_stmt* pragma_read_stmt{nullptr};
+ int ret = sqlite3_prepare_v2(db, stmt_text.c_str(), -1, &pragma_read_stmt, nullptr);
+ if (ret != SQLITE_OK) {
+ sqlite3_finalize(pragma_read_stmt);
+ error = Untranslated(strprintf("SQLiteDatabase: Failed to prepare the statement to fetch %s: %s", description, sqlite3_errstr(ret)));
+ return std::nullopt;
+ }
+ ret = sqlite3_step(pragma_read_stmt);
+ if (ret != SQLITE_ROW) {
+ sqlite3_finalize(pragma_read_stmt);
+ error = Untranslated(strprintf("SQLiteDatabase: Failed to fetch %s: %s", description, sqlite3_errstr(ret)));
+ return std::nullopt;
+ }
+ int result = sqlite3_column_int(pragma_read_stmt, 0);
+ sqlite3_finalize(pragma_read_stmt);
+ return result;
+}
+
+static void SetPragma(sqlite3* db, const std::string& key, const std::string& value, const std::string& err_msg)
+{
+ std::string stmt_text = strprintf("PRAGMA %s = %s", key, value);
+ int ret = sqlite3_exec(db, stmt_text.c_str(), nullptr, nullptr, nullptr);
+ if (ret != SQLITE_OK) {
+ throw std::runtime_error(strprintf("SQLiteDatabase: %s: %s\n", err_msg, sqlite3_errstr(ret)));
+ }
+}
+
SQLiteDatabase::SQLiteDatabase(const fs::path& dir_path, const fs::path& file_path, bool mock)
: WalletDatabase(), m_mock(mock), m_dir_path(dir_path.string()), m_file_path(file_path.string())
{
@@ -114,21 +145,9 @@ bool SQLiteDatabase::Verify(bilingual_str& error)
assert(m_db);
// Check the application ID matches our network magic
- sqlite3_stmt* app_id_stmt{nullptr};
- int ret = sqlite3_prepare_v2(m_db, "PRAGMA application_id", -1, &app_id_stmt, nullptr);
- if (ret != SQLITE_OK) {
- sqlite3_finalize(app_id_stmt);
- error = strprintf(_("SQLiteDatabase: Failed to prepare the statement to fetch the application id: %s"), sqlite3_errstr(ret));
- return false;
- }
- ret = sqlite3_step(app_id_stmt);
- if (ret != SQLITE_ROW) {
- sqlite3_finalize(app_id_stmt);
- error = strprintf(_("SQLiteDatabase: Failed to fetch the application id: %s"), sqlite3_errstr(ret));
- return false;
- }
- uint32_t app_id = static_cast<uint32_t>(sqlite3_column_int(app_id_stmt, 0));
- sqlite3_finalize(app_id_stmt);
+ auto read_result = ReadPragmaInteger(m_db, "application_id", "the application id", error);
+ if (!read_result.has_value()) return false;
+ uint32_t app_id = static_cast<uint32_t>(read_result.value());
uint32_t net_magic = ReadBE32(Params().MessageStart());
if (app_id != net_magic) {
error = strprintf(_("SQLiteDatabase: Unexpected application id. Expected %u, got %u"), net_magic, app_id);
@@ -136,28 +155,16 @@ bool SQLiteDatabase::Verify(bilingual_str& error)
}
// Check our schema version
- sqlite3_stmt* user_ver_stmt{nullptr};
- ret = sqlite3_prepare_v2(m_db, "PRAGMA user_version", -1, &user_ver_stmt, nullptr);
- if (ret != SQLITE_OK) {
- sqlite3_finalize(user_ver_stmt);
- error = strprintf(_("SQLiteDatabase: Failed to prepare the statement to fetch sqlite wallet schema version: %s"), sqlite3_errstr(ret));
- return false;
- }
- ret = sqlite3_step(user_ver_stmt);
- if (ret != SQLITE_ROW) {
- sqlite3_finalize(user_ver_stmt);
- error = strprintf(_("SQLiteDatabase: Failed to fetch sqlite wallet schema version: %s"), sqlite3_errstr(ret));
- return false;
- }
- int32_t user_ver = sqlite3_column_int(user_ver_stmt, 0);
- sqlite3_finalize(user_ver_stmt);
+ read_result = ReadPragmaInteger(m_db, "user_version", "sqlite wallet schema version", error);
+ if (!read_result.has_value()) return false;
+ int32_t user_ver = read_result.value();
if (user_ver != WALLET_SCHEMA_VERSION) {
error = strprintf(_("SQLiteDatabase: Unknown sqlite wallet schema version %d. Only version %d is supported"), user_ver, WALLET_SCHEMA_VERSION);
return false;
}
sqlite3_stmt* stmt{nullptr};
- ret = sqlite3_prepare_v2(m_db, "PRAGMA integrity_check", -1, &stmt, nullptr);
+ int ret = sqlite3_prepare_v2(m_db, "PRAGMA integrity_check", -1, &stmt, nullptr);
if (ret != SQLITE_OK) {
sqlite3_finalize(stmt);
error = strprintf(_("SQLiteDatabase: Failed to prepare statement to verify database: %s"), sqlite3_errstr(ret));
@@ -213,12 +220,9 @@ void SQLiteDatabase::Open()
// Acquire an exclusive lock on the database
// First change the locking mode to exclusive
- int ret = sqlite3_exec(m_db, "PRAGMA locking_mode = exclusive", nullptr, nullptr, nullptr);
- if (ret != SQLITE_OK) {
- throw std::runtime_error(strprintf("SQLiteDatabase: Unable to change database locking mode to exclusive: %s\n", sqlite3_errstr(ret)));
- }
+ SetPragma(m_db, "locking_mode", "exclusive", "Unable to change database locking mode to exclusive");
// Now begin a transaction to acquire the exclusive lock. This lock won't be released until we close because of the exclusive locking mode.
- ret = sqlite3_exec(m_db, "BEGIN EXCLUSIVE TRANSACTION", nullptr, nullptr, nullptr);
+ int ret = sqlite3_exec(m_db, "BEGIN EXCLUSIVE TRANSACTION", nullptr, nullptr, nullptr);
if (ret != SQLITE_OK) {
throw std::runtime_error("SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another bitcoind?\n");
}
@@ -228,18 +232,12 @@ void SQLiteDatabase::Open()
}
// Enable fullfsync for the platforms that use it
- ret = sqlite3_exec(m_db, "PRAGMA fullfsync = true", nullptr, nullptr, nullptr);
- if (ret != SQLITE_OK) {
- throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable fullfsync: %s\n", sqlite3_errstr(ret)));
- }
+ SetPragma(m_db, "fullfsync", "true", "Failed to enable fullfsync");
if (gArgs.GetBoolArg("-unsafesqlitesync", false)) {
// Use normal synchronous mode for the journal
LogPrintf("WARNING SQLite is configured to not wait for data to be flushed to disk. Data loss and corruption may occur.\n");
- ret = sqlite3_exec(m_db, "PRAGMA synchronous = OFF", nullptr, nullptr, nullptr);
- if (ret != SQLITE_OK) {
- throw std::runtime_error(strprintf("SQLiteDatabase: Failed to set synchronous mode to OFF: %s\n", sqlite3_errstr(ret)));
- }
+ SetPragma(m_db, "synchronous", "OFF", "Failed to set synchronous mode to OFF");
}
// Make the table for our key-value pairs
@@ -271,18 +269,12 @@ void SQLiteDatabase::Open()
// Set the application id
uint32_t app_id = ReadBE32(Params().MessageStart());
- std::string set_app_id = strprintf("PRAGMA application_id = %d", static_cast<int32_t>(app_id));
- ret = sqlite3_exec(m_db, set_app_id.c_str(), nullptr, nullptr, nullptr);
- if (ret != SQLITE_OK) {
- throw std::runtime_error(strprintf("SQLiteDatabase: Failed to set the application id: %s\n", sqlite3_errstr(ret)));
- }
+ SetPragma(m_db, "application_id", strprintf("%d", static_cast<int32_t>(app_id)),
+ "Failed to set the application id");
// Set the user version
- std::string set_user_ver = strprintf("PRAGMA user_version = %d", WALLET_SCHEMA_VERSION);
- ret = sqlite3_exec(m_db, set_user_ver.c_str(), nullptr, nullptr, nullptr);
- if (ret != SQLITE_OK) {
- throw std::runtime_error(strprintf("SQLiteDatabase: Failed to set the wallet schema version: %s\n", sqlite3_errstr(ret)));
- }
+ SetPragma(m_db, "user_version", strprintf("%d", WALLET_SCHEMA_VERSION),
+ "Failed to set the wallet schema version");
}
}
diff --git a/src/wallet/test/coinselector_tests.cpp b/src/wallet/test/coinselector_tests.cpp
index 7eff6e592d..7bca385deb 100644
--- a/src/wallet/test/coinselector_tests.cpp
+++ b/src/wallet/test/coinselector_tests.cpp
@@ -297,8 +297,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test)
empty_wallet();
{
std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", CreateMockWalletDatabase());
- bool firstRun;
- wallet->LoadWallet(firstRun);
+ wallet->LoadWallet();
wallet->SetupLegacyScriptPubKeyMan();
LOCK(wallet->cs_wallet);
add_coin(*wallet, 5 * CENT, 6 * 24, false, 0, true);
diff --git a/src/wallet/test/wallet_test_fixture.cpp b/src/wallet/test/wallet_test_fixture.cpp
index badf2eb459..fc744ebe5b 100644
--- a/src/wallet/test/wallet_test_fixture.cpp
+++ b/src/wallet/test/wallet_test_fixture.cpp
@@ -8,8 +8,7 @@ WalletTestingSetup::WalletTestingSetup(const std::string& chainName)
: TestingSetup(chainName),
m_wallet(m_node.chain.get(), "", CreateMockWalletDatabase())
{
- bool fFirstRun;
- m_wallet.LoadWallet(fFirstRun);
+ m_wallet.LoadWallet();
m_chain_notifications_handler = m_node.chain->handleNotifications({ &m_wallet, [](CWallet*) {} });
m_wallet_client->registerRpcs();
}
diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp
index c8e3c8f819..512374c34f 100644
--- a/src/wallet/test/wallet_tests.cpp
+++ b/src/wallet/test/wallet_tests.cpp
@@ -38,7 +38,7 @@ static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wa
BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
-static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain& chain)
+static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain* chain)
{
DatabaseOptions options;
DatabaseStatus status;
@@ -46,7 +46,9 @@ static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain& chain)
std::vector<bilingual_str> warnings;
auto database = MakeWalletDatabase("", options, status, error);
auto wallet = CWallet::Create(chain, "", std::move(database), options.create_flags, error, warnings);
- wallet->postInitProcess();
+ if (chain) {
+ wallet->postInitProcess();
+ }
return wallet;
}
@@ -483,8 +485,7 @@ public:
LOCK2(wallet->cs_wallet, ::cs_main);
wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
}
- bool firstRun;
- wallet->LoadWallet(firstRun);
+ wallet->LoadWallet();
AddKey(*wallet, coinbaseKey);
WalletRescanReserver reserver(*wallet);
reserver.reserve();
@@ -690,7 +691,7 @@ BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
{
gArgs.ForceSetArg("-unsafesqlitesync", "1");
// Create new wallet with known key and unload it.
- auto wallet = TestLoadWallet(*m_node.chain);
+ auto wallet = TestLoadWallet(m_node.chain.get());
CKey key;
key.MakeNewKey(true);
AddKey(*wallet, key);
@@ -730,7 +731,7 @@ BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
// Reload wallet and make sure new transactions are detected despite events
// being blocked
- wallet = TestLoadWallet(*m_node.chain);
+ wallet = TestLoadWallet(m_node.chain.get());
BOOST_CHECK(rescan_completed);
BOOST_CHECK_EQUAL(addtx_count, 2);
{
@@ -770,7 +771,7 @@ BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
ENTER_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
ENTER_CRITICAL_SECTION(cs_wallets);
});
- wallet = TestLoadWallet(*m_node.chain);
+ wallet = TestLoadWallet(m_node.chain.get());
BOOST_CHECK_EQUAL(addtx_count, 4);
{
LOCK(wallet->cs_wallet);
@@ -782,10 +783,17 @@ BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
TestUnloadWallet(std::move(wallet));
}
+BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
+{
+ auto wallet = TestLoadWallet(nullptr);
+ BOOST_CHECK(wallet);
+ UnloadWallet(std::move(wallet));
+}
+
BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup)
{
gArgs.ForceSetArg("-unsafesqlitesync", "1");
- auto wallet = TestLoadWallet(*m_node.chain);
+ auto wallet = TestLoadWallet(m_node.chain.get());
CKey key;
key.MakeNewKey(true);
AddKey(*wallet, key);
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index 456c26ea31..7cdf2fcda0 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -213,7 +213,8 @@ std::shared_ptr<CWallet> LoadWalletInternal(interfaces::Chain& chain, const std:
return nullptr;
}
- std::shared_ptr<CWallet> wallet = CWallet::Create(chain, name, std::move(database), options.create_flags, error, warnings);
+ chain.initMessage(_("Loading wallet...").translated);
+ std::shared_ptr<CWallet> wallet = CWallet::Create(&chain, name, std::move(database), options.create_flags, error, warnings);
if (!wallet) {
error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
status = DatabaseStatus::FAILED_LOAD;
@@ -292,7 +293,8 @@ std::shared_ptr<CWallet> CreateWallet(interfaces::Chain& chain, const std::strin
}
// Make the wallet
- std::shared_ptr<CWallet> wallet = CWallet::Create(chain, name, std::move(database), wallet_creation_flags, error, warnings);
+ chain.initMessage(_("Loading wallet...").translated);
+ std::shared_ptr<CWallet> wallet = CWallet::Create(&chain, name, std::move(database), wallet_creation_flags, error, warnings);
if (!wallet) {
error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
status = DatabaseStatus::FAILED_CREATE;
@@ -3247,11 +3249,10 @@ void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::ve
}
}
-DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
+DBErrors CWallet::LoadWallet()
{
LOCK(cs_wallet);
- fFirstRunRet = false;
DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{
@@ -3263,9 +3264,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
}
}
- // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
- fFirstRunRet = m_spk_managers.empty() && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
- if (fFirstRunRet) {
+ if (m_spk_managers.empty()) {
assert(m_external_spk_managers.empty());
assert(m_internal_spk_managers.empty());
}
@@ -3886,18 +3885,15 @@ std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, cons
return MakeDatabase(wallet_path, options, status, error_string);
}
-std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings)
+std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings)
{
const std::string& walletFile = database->Filename();
- chain.initMessage(_("Loading wallet…").translated);
-
int64_t nStart = GetTimeMillis();
- bool fFirstRun = true;
// TODO: Can't use std::make_shared because we need a custom deleter but
// should be possible to use std::allocate_shared.
- std::shared_ptr<CWallet> walletInstance(new CWallet(&chain, name, std::move(database)), ReleaseWallet);
- DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
+ std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), ReleaseWallet);
+ DBErrors nLoadWalletRet = walletInstance->LoadWallet();
if (nLoadWalletRet != DBErrors::LOAD_OK) {
if (nLoadWalletRet == DBErrors::CORRUPT) {
error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
@@ -3924,6 +3920,10 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
}
}
+ // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
+ const bool fFirstRun = walletInstance->m_spk_managers.empty() &&
+ !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
+ !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
if (fFirstRun)
{
// ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
@@ -3952,7 +3952,9 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
}
}
- walletInstance->chainStateFlushed(chain.getTipLocator());
+ if (chain) {
+ walletInstance->chainStateFlushed(chain->getTipLocator());
+ }
} else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
// Make it impossible to disable private keys after creation
error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
@@ -4049,9 +4051,9 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
_("This is the transaction fee you will pay if you send a transaction."));
}
walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
- if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
+ if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
- gArgs.GetArg("-paytxfee", ""), chain.relayMinFee().ToString());
+ gArgs.GetArg("-paytxfee", ""), chain->relayMinFee().ToString());
return nullptr;
}
}
@@ -4065,15 +4067,15 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
if (nMaxFee > HIGH_MAX_TX_FEE) {
warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
}
- if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
+ if (chain && CFeeRate(nMaxFee, 1000) < chain->relayMinFee()) {
error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
- gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString());
+ gArgs.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
return nullptr;
}
walletInstance->m_default_max_tx_fee = nMaxFee;
}
- if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
+ if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
_("The wallet will avoid paying less than the minimum relay fee."));
}
@@ -4089,6 +4091,35 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
LOCK(walletInstance->cs_wallet);
+ if (chain && !AttachChain(walletInstance, *chain, error, warnings)) {
+ return nullptr;
+ }
+
+ {
+ LOCK(cs_wallets);
+ for (auto& load_wallet : g_load_wallet_fns) {
+ load_wallet(interfaces::MakeWallet(walletInstance));
+ }
+ }
+
+ walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
+
+ {
+ walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
+ walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
+ walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
+ }
+
+ return walletInstance;
+}
+
+bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings)
+{
+ LOCK(walletInstance->cs_wallet);
+ // allow setting the chain if it hasn't been set already but prevent changing it
+ assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
+ walletInstance->m_chain = &chain;
+
// Register wallet with validationinterface. It's done before rescan to avoid
// missing block connections between end of rescan and validation subscribing.
// Because of wallet lock being hold, block connection notifications are going to
@@ -4122,21 +4153,21 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
if (tip_height && *tip_height != rescan_height)
{
- // We can't rescan beyond non-pruned blocks, stop and throw an error.
- // This might happen if a user uses an old wallet within a pruned node
- // or if they ran -disablewallet for a longer time, then decided to re-enable
if (chain.havePruned()) {
- // Exit early and print an error.
- // If a block is pruned after this check, we will load the wallet,
- // but fail the rescan with a generic error.
int block_height = *tip_height;
while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
--block_height;
}
if (rescan_height != block_height) {
+ // We can't rescan beyond non-pruned blocks, stop and throw an error.
+ // This might happen if a user uses an old wallet within a pruned node
+ // or if they ran -disablewallet for a longer time, then decided to re-enable
+ // Exit early and print an error.
+ // If a block is pruned after this check, we will load the wallet,
+ // but fail the rescan with a generic error.
error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)");
- return nullptr;
+ return false;
}
}
@@ -4158,29 +4189,14 @@ std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain& chain, const std::st
WalletRescanReserver reserver(*walletInstance);
if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, {} /* max height */, reserver, true /* update */).status)) {
error = _("Failed to rescan the wallet during initialization");
- return nullptr;
+ return false;
}
}
walletInstance->chainStateFlushed(chain.getTipLocator());
walletInstance->GetDatabase().IncrementUpdateCounter();
}
- {
- LOCK(cs_wallets);
- for (auto& load_wallet : g_load_wallet_fns) {
- load_wallet(interfaces::MakeWallet(walletInstance));
- }
- }
-
- walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
-
- {
- walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
- walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
- walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
- }
-
- return walletInstance;
+ return true;
}
const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index 5a36d92784..fc4edd8d20 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -763,6 +763,13 @@ private:
bool CreateTransactionInternal(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, FeeCalculation& fee_calc_out, bool sign);
+ /**
+ * Catch wallet up to current chain, scanning new blocks, updating the best
+ * block locator and m_last_block_processed, and registering for
+ * notifications about new blocks and transactions.
+ */
+ static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings);
+
public:
/**
* Main wallet lock.
@@ -1126,7 +1133,7 @@ public:
CAmount GetChange(const CTransaction& tx) const;
void chainStateFlushed(const CBlockLocator& loc) override;
- DBErrors LoadWallet(bool& fFirstRunRet);
+ DBErrors LoadWallet();
DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
@@ -1202,7 +1209,7 @@ public:
bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
/* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
- static std::shared_ptr<CWallet> Create(interfaces::Chain& chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
+ static std::shared_ptr<CWallet> Create(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
/**
* Wallet post-init setup
diff --git a/src/wallet/wallettool.cpp b/src/wallet/wallettool.cpp
index b2cb0bf479..50b6c9d29f 100644
--- a/src/wallet/wallettool.cpp
+++ b/src/wallet/wallettool.cpp
@@ -54,8 +54,7 @@ static std::shared_ptr<CWallet> MakeWallet(const std::string& name, const fs::pa
std::shared_ptr<CWallet> wallet_instance{new CWallet(nullptr /* chain */, name, std::move(database)), WalletToolReleaseWallet};
DBErrors load_wallet_ret;
try {
- bool first_run;
- load_wallet_ret = wallet_instance->LoadWallet(first_run);
+ load_wallet_ret = wallet_instance->LoadWallet();
} catch (const std::runtime_error&) {
tfm::format(std::cerr, "Error loading %s. Is wallet being used by another process?\n", name);
return nullptr;