Bitcoin ABC  0.26.3
P2P Digital Currency
load.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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/string.h>
12 #include <util/system.h>
13 #include <util/translation.h>
14 #include <wallet/wallet.h>
15 #include <wallet/walletdb.h>
16 
17 #include <univalue.h>
18 
20  if (gArgs.IsArgSet("-walletdir")) {
21  fs::path wallet_dir =
22  fs::PathFromString(gArgs.GetArg("-walletdir", ""));
23  boost::system::error_code error;
24  // The canonical path cleans the path, preventing >1 Berkeley
25  // environment instances for the same directory
26  fs::path canonical_wallet_dir =
27  fs::canonical(wallet_dir, error).remove_trailing_separator();
28  if (error || !fs::exists(wallet_dir)) {
29  chain.initError(
30  strprintf(_("Specified -walletdir \"%s\" does not exist"),
31  fs::PathToString(wallet_dir)));
32  return false;
33  } else if (!fs::is_directory(wallet_dir)) {
34  chain.initError(
35  strprintf(_("Specified -walletdir \"%s\" is not a directory"),
36  fs::PathToString(wallet_dir)));
37  return false;
38  // The canonical path transforms relative paths into absolute ones,
39  // so we check the non-canonical version
40  } else if (!wallet_dir.is_absolute()) {
41  chain.initError(
42  strprintf(_("Specified -walletdir \"%s\" is a relative path"),
43  fs::PathToString(wallet_dir)));
44  return false;
45  }
46  gArgs.ForceSetArg("-walletdir", fs::PathToString(canonical_wallet_dir));
47  }
48 
49  LogPrintf("Using wallet directory %s\n", fs::PathToString(GetWalletDir()));
50 
51  chain.initMessage(_("Verifying wallet(s)...").translated);
52 
53  // For backwards compatibility if an unnamed top level wallet exists in the
54  // wallets directory, include it in the default list of wallets to load.
55  if (!gArgs.IsArgSet("wallet")) {
56  DatabaseOptions options;
57  DatabaseStatus status;
58  bilingual_str error_string;
59  options.require_existing = true;
60  options.verify = false;
61  if (MakeWalletDatabase("", options, status, error_string)) {
62  gArgs.LockSettings([&](util::Settings &settings) {
64  // Default wallet name is ""
65  wallets.push_back("");
66  settings.rw_settings["wallet"] = wallets;
67  });
68  }
69  }
70 
71  // Keep track of each wallet absolute path to detect duplicates.
72  std::set<fs::path> wallet_paths;
73 
74  for (const auto &wallet_file : gArgs.GetArgs("-wallet")) {
75  const fs::path path = fsbridge::AbsPathJoin(
76  GetWalletDir(), fs::PathFromString(wallet_file));
77 
78  if (!wallet_paths.insert(path).second) {
79  chain.initWarning(
80  strprintf(_("Ignoring duplicate -wallet %s."), wallet_file));
81  continue;
82  }
83 
84  DatabaseOptions options;
85  DatabaseStatus status;
86  options.verify = true;
87  bilingual_str error_string;
88  if (!MakeWalletDatabase(wallet_file, options, status, error_string)) {
89  chain.initError(error_string);
90  return false;
91  }
92  }
93 
94  return true;
95 }
96 
98  try {
99  std::set<fs::path> wallet_paths;
100  for (const std::string &name : gArgs.GetArgs("-wallet")) {
101  if (!wallet_paths.insert(fs::PathFromString(name)).second) {
102  continue;
103  }
104  DatabaseOptions options;
105  DatabaseStatus status;
106  // No need to verify, assuming verified earlier in VerifyWallets()
107  options.verify = false;
109  std::vector<bilingual_str> warnings;
110  std::unique_ptr<WalletDatabase> database =
111  MakeWalletDatabase(name, options, status, error);
112  std::shared_ptr<CWallet> pwallet =
113  database
114  ? CWallet::Create(chain, name, std::move(database),
115  options.create_flags, error, warnings)
116  : nullptr;
117 
118  if (!warnings.empty()) {
119  chain.initWarning(Join(warnings, Untranslated("\n")));
120  }
121  if (!pwallet) {
122  chain.initError(error);
123  return false;
124  }
125  AddWallet(pwallet);
126  }
127  return true;
128  } catch (const std::runtime_error &e) {
129  chain.initError(Untranslated(e.what()));
130  return false;
131  }
132 }
133 
134 void StartWallets(CScheduler &scheduler, const ArgsManager &args) {
135  for (const std::shared_ptr<CWallet> &pwallet : GetWallets()) {
136  pwallet->postInitProcess();
137  }
138 
139  // Schedule periodic wallet flushes and tx rebroadcasts
140  if (args.GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET)) {
141  scheduler.scheduleEvery(
142  [] {
144  return true;
145  },
146  std::chrono::milliseconds{500});
147  }
148  scheduler.scheduleEvery(
149  [] {
151  return true;
152  },
153  std::chrono::milliseconds{1000});
154 }
155 
156 void FlushWallets() {
157  for (const std::shared_ptr<CWallet> &pwallet : GetWallets()) {
158  pwallet->Flush();
159  }
160 }
161 
162 void StopWallets() {
163  for (const std::shared_ptr<CWallet> &pwallet : GetWallets()) {
164  pwallet->Close();
165  }
166 }
167 
169  auto wallets = GetWallets();
170  while (!wallets.empty()) {
171  auto wallet = wallets.back();
172  wallets.pop_back();
173  std::vector<bilingual_str> warnings;
174  RemoveWallet(wallet, std::nullopt, warnings);
175  UnloadWallet(std::move(wallet));
176  }
177 }
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:628
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:474
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: system.h:416
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:484
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:584
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:603
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:36
void scheduleEvery(Predicate p, std::chrono::milliseconds delta)
Repeat p until it return false.
Definition: scheduler.cpp:114
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)
Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error.
Definition: wallet.cpp:4263
@ VARR
Definition: univalue.h:27
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:123
virtual void initMessage(const std::string &message)=0
Send init message.
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
void StartWallets(CScheduler &scheduler, const ArgsManager &args)
Complete startup of wallets.
Definition: load.cpp:134
bool VerifyWallets(interfaces::Chain &chain)
Responsible for reading and validating the -wallet arguments and verifying the wallet database.
Definition: load.cpp:19
void UnloadWallets()
Close all wallets.
Definition: load.cpp:168
void FlushWallets()
Flush all wallets in preparation for shutdown.
Definition: load.cpp:156
void StopWallets()
Stop all wallets. Wallets will be flushed first.
Definition: load.cpp:162
bool LoadWallets(interfaces::Chain &chain)
Load wallet databases.
Definition: load.cpp:97
#define LogPrintf(...)
Definition: logging.h:204
static bool exists(const path &p)
Definition: fs.h:94
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:134
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:147
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:36
const char * name
Definition: rest.cpp:50
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
bool verify
Definition: db.h:226
uint64_t create_flags
Definition: db.h:224
bool require_existing
Definition: db.h:222
Bilingual messages:
Definition: translation.h:17
Stored settings.
Definition: settings.h:31
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
Definition: settings.h:37
ArgsManager gArgs
Definition: system.cpp:77
bool error(const char *fmt, const Args &...args)
Definition: system.h:46
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
DatabaseStatus
Definition: db.h:229
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:119
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2403
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:200
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:4233
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:149
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:105
void MaybeCompactWalletDB()
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:1044
static const bool DEFAULT_FLUSHWALLET
Overview of wallet database classes:
Definition: walletdb.h:33
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:10