Bitcoin Core  22.99.0
P2P Digital Currency
load.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <wallet/load.h>
7 
8 #include <fs.h>
9 #include <interfaces/chain.h>
10 #include <scheduler.h>
11 #include <util/check.h>
12 #include <util/string.h>
13 #include <util/system.h>
14 #include <util/translation.h>
15 #include <wallet/context.h>
16 #include <wallet/spend.h>
17 #include <wallet/wallet.h>
18 #include <wallet/walletdb.h>
19 
20 #include <univalue.h>
21 
22 namespace wallet {
24 {
27 
28  if (args.IsArgSet("-walletdir")) {
29  fs::path wallet_dir = fs::PathFromString(args.GetArg("-walletdir", ""));
30  boost::system::error_code error;
31  // The canonical path cleans the path, preventing >1 Berkeley environment instances for the same directory
32  fs::path canonical_wallet_dir = fs::canonical(wallet_dir, error).remove_trailing_separator();
33  if (error || !fs::exists(wallet_dir)) {
34  chain.initError(strprintf(_("Specified -walletdir \"%s\" does not exist"), fs::PathToString(wallet_dir)));
35  return false;
36  } else if (!fs::is_directory(wallet_dir)) {
37  chain.initError(strprintf(_("Specified -walletdir \"%s\" is not a directory"), fs::PathToString(wallet_dir)));
38  return false;
39  // The canonical path transforms relative paths into absolute ones, so we check the non-canonical version
40  } else if (!wallet_dir.is_absolute()) {
41  chain.initError(strprintf(_("Specified -walletdir \"%s\" is a relative path"), fs::PathToString(wallet_dir)));
42  return false;
43  }
44  args.ForceSetArg("-walletdir", fs::PathToString(canonical_wallet_dir));
45  }
46 
47  LogPrintf("Using wallet directory %s\n", fs::PathToString(GetWalletDir()));
48 
49  chain.initMessage(_("Verifying wallet(s)…").translated);
50 
51  // For backwards compatibility if an unnamed top level wallet exists in the
52  // wallets directory, include it in the default list of wallets to load.
53  if (!args.IsArgSet("wallet")) {
54  DatabaseOptions options;
55  DatabaseStatus status;
56  bilingual_str error_string;
57  options.require_existing = true;
58  options.verify = false;
59  if (MakeWalletDatabase("", options, status, error_string)) {
61  wallets.push_back(""); // Default wallet name is ""
62  // Pass write=false because no need to write file and probably
63  // better not to. If unnamed wallet needs to be added next startup
64  // and the setting is empty, this code will just run again.
65  chain.updateRwSetting("wallet", wallets, /* write= */ false);
66  }
67  }
68 
69  // Keep track of each wallet absolute path to detect duplicates.
70  std::set<fs::path> wallet_paths;
71 
72  for (const auto& wallet : chain.getSettingsList("wallet")) {
73  const auto& wallet_file = wallet.get_str();
74  const fs::path path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(wallet_file));
75 
76  if (!wallet_paths.insert(path).second) {
77  chain.initWarning(strprintf(_("Ignoring duplicate -wallet %s."), wallet_file));
78  continue;
79  }
80 
81  DatabaseOptions options;
82  DatabaseStatus status;
83  options.require_existing = true;
84  options.verify = true;
85  bilingual_str error_string;
86  if (!MakeWalletDatabase(wallet_file, options, status, error_string)) {
87  if (status == DatabaseStatus::FAILED_NOT_FOUND) {
88  chain.initWarning(Untranslated(strprintf("Skipping -wallet path that doesn't exist. %s", error_string.original)));
89  } else {
90  chain.initError(error_string);
91  return false;
92  }
93  }
94  }
95 
96  return true;
97 }
98 
100 {
101  interfaces::Chain& chain = *context.chain;
102  try {
103  std::set<fs::path> wallet_paths;
104  for (const auto& wallet : chain.getSettingsList("wallet")) {
105  const auto& name = wallet.get_str();
106  if (!wallet_paths.insert(fs::PathFromString(name)).second) {
107  continue;
108  }
109  DatabaseOptions options;
110  DatabaseStatus status;
111  options.require_existing = true;
112  options.verify = false; // No need to verify, assuming verified earlier in VerifyWallets()
114  std::vector<bilingual_str> warnings;
115  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
116  if (!database && status == DatabaseStatus::FAILED_NOT_FOUND) {
117  continue;
118  }
119  chain.initMessage(_("Loading wallet…").translated);
120  std::shared_ptr<CWallet> pwallet = database ? CWallet::Create(context, name, std::move(database), options.create_flags, error, warnings) : nullptr;
121  if (!warnings.empty()) chain.initWarning(Join(warnings, Untranslated("\n")));
122  if (!pwallet) {
123  chain.initError(error);
124  return false;
125  }
126  AddWallet(context, pwallet);
127  }
128  return true;
129  } catch (const std::runtime_error& e) {
130  chain.initError(Untranslated(e.what()));
131  return false;
132  }
133 }
134 
136 {
137  for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
138  pwallet->postInitProcess();
139  }
140 
141  // Schedule periodic wallet flushes and tx rebroadcasts
142  if (context.args->GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET)) {
143  scheduler.scheduleEvery([&context] { MaybeCompactWalletDB(context); }, std::chrono::milliseconds{500});
144  }
145  scheduler.scheduleEvery([&context] { MaybeResendWalletTxs(context); }, std::chrono::milliseconds{1000});
146 }
147 
149 {
150  for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
151  pwallet->Flush();
152  }
153 }
154 
156 {
157  for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
158  pwallet->Close();
159  }
160 }
161 
163 {
164  auto wallets = GetWallets(context);
165  while (!wallets.empty()) {
166  auto wallet = wallets.back();
167  wallets.pop_back();
168  std::vector<bilingual_str> warnings;
169  RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt, warnings);
170  UnloadWallet(std::move(wallet));
171  }
172 }
173 } // namespace wallet
wallet::StartWallets
void StartWallets(WalletContext &context, CScheduler &scheduler)
Complete startup of wallets.
Definition: load.cpp:135
CScheduler
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:33
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:597
fs::exists
static bool exists(const path &p)
Definition: fs.h:77
_
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
check.h
wallet.h
wallet::AddWallet
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:110
wallet::UnloadWallets
void UnloadWallets(WalletContext &context)
Close all wallets.
Definition: load.cpp:162
fs.h
wallet::DatabaseStatus
DatabaseStatus
Definition: db.h:213
string.h
bilingual_str
Bilingual messages:
Definition: translation.h:16
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:491
wallet::MaybeResendWalletTxs
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:1854
interfaces::Chain::getSettingsList
virtual std::vector< util::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
fsbridge::AbsPathJoin
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:35
wallet
Definition: node.h:38
fs::PathToString
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
wallet::DatabaseOptions::require_existing
bool require_existing
Definition: db.h:205
chain.h
Assert
#define Assert(val)
Identity function.
Definition: check.h:57
scheduler.h
UniValue
Definition: univalue.h:17
wallet::FlushWallets
void FlushWallets(WalletContext &context)
Flush all wallets in preparation for shutdown.
Definition: load.cpp:148
wallet::GetWallets
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:148
load.h
interfaces::Chain
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:94
wallet::WalletContext::args
ArgsManager * args
Definition: context.h:37
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
wallet::MakeWalletDatabase
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2595
fs::path
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
wallet::DatabaseOptions::verify
bool verify
Definition: db.h:210
univalue.h
wallet::LoadWallets
bool LoadWallets(WalletContext &context)
Load wallet databases.
Definition: load.cpp:99
ArgsManager::ForceSetArg
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:619
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:585
LogPrintf
#define LogPrintf(...)
Definition: logging.h:187
context
WalletContext context
Definition: notifications.cpp:37
CScheduler::scheduleEvery
void scheduleEvery(Function f, std::chrono::milliseconds delta)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:112
fs::PathFromString
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:143
interfaces::Chain::updateRwSetting
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
wallet::DatabaseStatus::FAILED_NOT_FOUND
@ FAILED_NOT_FOUND
bilingual_str::original
std::string original
Definition: translation.h:17
name
const char * name
Definition: rest.cpp:52
interfaces::Chain::initWarning
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
wallet::VerifyWallets
bool VerifyWallets(WalletContext &context)
Responsible for reading and validating the -wallet arguments and verifying the wallet database.
Definition: load.cpp:23
system.h
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
Join
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:44
wallet::DEFAULT_FLUSHWALLET
static const bool DEFAULT_FLUSHWALLET
Overview of wallet database classes:
Definition: walletdb.h:42
ArgsManager
Definition: system.h:158
translation.h
wallet::GetWalletDir
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:11
interfaces::Chain::initMessage
virtual void initMessage(const std::string &message)=0
Send init message.
wallet::CWallet::Create
static std::shared_ptr< CWallet > Create(WalletContext &context, const std::string &name, std::unique_ptr< WalletDatabase > database, uint64_t wallet_creation_flags, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:2619
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
context.h
walletdb.h
interfaces::Chain::initError
virtual void initError(const bilingual_str &message)=0
Send init error.
wallet::WalletContext
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
wallet::UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:194
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
UniValue::VARR
@ VARR
Definition: univalue.h:19
wallet::MaybeCompactWalletDB
void MaybeCompactWalletDB(WalletContext &context)
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:1041
wallet::WalletContext::chain
interfaces::Chain * chain
Definition: context.h:36
wallet::DatabaseOptions
Definition: db.h:204
wallet::RemoveWallet
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:122
wallet::StopWallets
void StopWallets(WalletContext &context)
Stop all wallets. Wallets will be flushed first.
Definition: load.cpp:155
wallet::DatabaseOptions::create_flags
uint64_t create_flags
Definition: db.h:208
spend.h
args
ArgsManager args
Definition: notifications.cpp:36