Bitcoin ABC 0.32.4
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 <common/args.h>
9#include <interfaces/chain.h>
10#include <logging.h>
11#include <scheduler.h>
12#include <util/fs.h>
13#include <util/string.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#include <system_error>
23
25 interfaces::Chain &chain = *context.chain;
26 if (gArgs.IsArgSet("-walletdir")) {
27 const fs::path wallet_dir{gArgs.GetPathArg("-walletdir")};
28 std::error_code error;
29 // The canonical path cleans the path, preventing >1 Berkeley
30 // environment instances for the same directory
31 fs::path canonical_wallet_dir = fs::canonical(wallet_dir, error);
32 if (error || !fs::exists(canonical_wallet_dir)) {
33 chain.initError(
34 strprintf(_("Specified -walletdir \"%s\" does not exist"),
35 fs::PathToString(wallet_dir)));
36 return false;
37 } else if (!fs::is_directory(canonical_wallet_dir)) {
38 chain.initError(
39 strprintf(_("Specified -walletdir \"%s\" is not a directory"),
40 fs::PathToString(wallet_dir)));
41 return false;
42 // The canonical path transforms relative paths into absolute ones,
43 // so we check the non-canonical version
44 } else if (!wallet_dir.is_absolute()) {
45 chain.initError(
46 strprintf(_("Specified -walletdir \"%s\" is a relative path"),
47 fs::PathToString(wallet_dir)));
48 return false;
49 }
50 gArgs.ForceSetArg("-walletdir", fs::PathToString(canonical_wallet_dir));
51 }
52
53 LogPrintf("Using wallet directory %s\n", fs::PathToString(GetWalletDir()));
54
55 chain.initMessage(_("Verifying wallet(s)...").translated);
56
57 // For backwards compatibility if an unnamed top level wallet exists in the
58 // wallets directory, include it in the default list of wallets to load.
59 if (!gArgs.IsArgSet("wallet")) {
60 DatabaseOptions options;
61 DatabaseStatus status;
62 bilingual_str error_string;
63 options.require_existing = true;
64 options.verify = false;
65 if (MakeWalletDatabase("", options, status, error_string)) {
67 wallets.push_back(""); // Default wallet name is ""
68 // Pass write=false because no need to write file and probably
69 // better not to. If unnamed wallet needs to be added next startup
70 // and the setting is empty, this code will just run again.
71 chain.updateRwSetting("wallet", wallets, /* write= */ false);
72 }
73 }
74
75 // Keep track of each wallet absolute path to detect duplicates.
76 std::set<fs::path> wallet_paths;
77
78 for (const auto &wallet : chain.getSettingsList("wallet")) {
79 const auto &wallet_file = wallet.get_str();
81 GetWalletDir(), fs::PathFromString(wallet_file));
82
83 if (!wallet_paths.insert(path).second) {
84 chain.initWarning(
85 strprintf(_("Ignoring duplicate -wallet %s."), wallet_file));
86 continue;
87 }
88
89 DatabaseOptions options;
90 DatabaseStatus status;
91 options.require_existing = true;
92 options.verify = true;
93 bilingual_str error_string;
94 if (!MakeWalletDatabase(wallet_file, options, status, error_string)) {
97 strprintf("Skipping -wallet path that doesn't exist. %s\n",
98 error_string.original)));
99 } else {
100 chain.initError(error_string);
101 return false;
102 }
103 }
104 }
105
106 return true;
107}
108
110 interfaces::Chain &chain = *context.chain;
111 try {
112 std::set<fs::path> wallet_paths;
113 for (const auto &wallet : chain.getSettingsList("wallet")) {
114 const auto &name = wallet.get_str();
115 if (!wallet_paths.insert(fs::PathFromString(name)).second) {
116 continue;
117 }
118 DatabaseOptions options;
119 DatabaseStatus status;
120 options.require_existing = true;
121 // No need to verify, assuming verified earlier in VerifyWallets()
122 options.verify = false;
123 bilingual_str error;
124 std::vector<bilingual_str> warnings;
125 std::unique_ptr<WalletDatabase> database =
126 MakeWalletDatabase(name, options, status, error);
127 if (!database && status == DatabaseStatus::FAILED_NOT_FOUND) {
128 continue;
129 }
130 chain.initMessage(_("Loading wallet...").translated);
131 std::shared_ptr<CWallet> pwallet =
132 database
133 ? CWallet::Create(context, name, std::move(database),
134 options.create_flags, error, warnings)
135 : nullptr;
136
137 if (!warnings.empty()) {
138 chain.initWarning(Join(warnings, Untranslated("\n")));
139 }
140 if (!pwallet) {
141 chain.initError(error);
142 return false;
143 }
144
145 NotifyWalletLoaded(context, pwallet);
146 AddWallet(context, pwallet);
147 }
148 return true;
149 } catch (const std::runtime_error &e) {
150 chain.initError(Untranslated(e.what()));
151 return false;
152 }
153}
154
155void StartWallets(WalletContext &context, CScheduler &scheduler) {
156 for (const std::shared_ptr<CWallet> &pwallet : GetWallets(context)) {
157 pwallet->postInitProcess();
158 }
159
160 // Schedule periodic wallet flushes and tx rebroadcasts
161 if (context.args->GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET)) {
162 scheduler.scheduleEvery(
163 [&context] {
164 MaybeCompactWalletDB(context);
165 return true;
166 },
167 std::chrono::milliseconds{500});
168 }
169 scheduler.scheduleEvery(
170 [&context] {
171 MaybeResendWalletTxs(context);
172 return true;
173 },
174 std::chrono::milliseconds{1000});
175}
176
178 for (const std::shared_ptr<CWallet> &pwallet : GetWallets(context)) {
179 pwallet->Flush();
180 }
181}
182
184 for (const std::shared_ptr<CWallet> &pwallet : GetWallets(context)) {
185 pwallet->Close();
186 }
187}
188
190 auto wallets = GetWallets(context);
191 while (!wallets.empty()) {
192 auto wallet = wallets.back();
193 wallets.pop_back();
194 std::vector<bilingual_str> warnings;
195 RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt, warnings);
196 UnloadWallet(std::move(wallet));
197 }
198}
ArgsManager gArgs
Definition: args.cpp:40
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: args.cpp:566
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:372
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:525
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:286
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
Definition: scheduler.cpp:114
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)
Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error.
Definition: wallet.cpp:2768
void push_back(UniValue val)
Definition: univalue.cpp:96
@ VARR
Definition: univalue.h:32
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:136
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
virtual void initMessage(const std::string &message)=0
Send init message.
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual std::vector< util::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
void FlushWallets(WalletContext &context)
Flush all wallets in preparation for shutdown.
Definition: load.cpp:177
void StopWallets(WalletContext &context)
Stop all wallets. Wallets will be flushed first.
Definition: load.cpp:183
void StartWallets(WalletContext &context, CScheduler &scheduler)
Complete startup of wallets.
Definition: load.cpp:155
bool LoadWallets(WalletContext &context)
Load wallet databases.
Definition: load.cpp:109
bool VerifyWallets(WalletContext &context)
Responsible for reading and validating the -wallet arguments and verifying.
Definition: load.cpp:24
void UnloadWallets(WalletContext &context)
Close all wallets.
Definition: load.cpp:189
#define LogPrintf(...)
Definition: logging.h:424
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:170
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:39
const char * name
Definition: rest.cpp:47
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:63
bool verify
Definition: db.h:224
uint64_t create_flags
Definition: db.h:222
bool require_existing
Definition: db.h:220
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
ArgsManager * args
Definition: context.h:38
interfaces::Chain * chain
Definition: context.h:36
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
DatabaseStatus
Definition: db.h:227
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2736
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:119
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:211
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:2063
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:105
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:151
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:178
void MaybeCompactWalletDB(WalletContext &context)
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:1048
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:13