Bitcoin Core  24.99.0
P2P Digital Currency
wallettool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <wallet/wallettool.h>
10 
11 #include <fs.h>
12 #include <util/system.h>
13 #include <util/translation.h>
14 #include <wallet/dump.h>
15 #include <wallet/salvage.h>
16 #include <wallet/wallet.h>
17 #include <wallet/walletutil.h>
18 
19 namespace wallet {
20 namespace WalletTool {
21 
22 // The standard wallet deleter function blocks on the validation interface
23 // queue, which doesn't exist for the bitcoin-wallet. Define our own
24 // deleter here.
26 {
27  wallet->WalletLogPrintf("Releasing wallet\n");
28  wallet->Close();
29  delete wallet;
30 }
31 
32 static void WalletCreate(CWallet* wallet_instance, uint64_t wallet_creation_flags)
33 {
34  LOCK(wallet_instance->cs_wallet);
35 
36  wallet_instance->SetMinVersion(FEATURE_LATEST);
37  wallet_instance->InitWalletFlags(wallet_creation_flags);
38 
39  if (!wallet_instance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
40  auto spk_man = wallet_instance->GetOrCreateLegacyScriptPubKeyMan();
41  spk_man->SetupGeneration(false);
42  } else {
43  wallet_instance->SetupDescriptorScriptPubKeyMans();
44  }
45 
46  tfm::format(std::cout, "Topping up keypool...\n");
47  wallet_instance->TopUpKeyPool();
48 }
49 
50 static std::shared_ptr<CWallet> MakeWallet(const std::string& name, const fs::path& path, const ArgsManager& args, DatabaseOptions options)
51 {
52  DatabaseStatus status;
54  std::unique_ptr<WalletDatabase> database = MakeDatabase(path, options, status, error);
55  if (!database) {
56  tfm::format(std::cerr, "%s\n", error.original);
57  return nullptr;
58  }
59 
60  // dummy chain interface
61  std::shared_ptr<CWallet> wallet_instance{new CWallet(/*chain=*/nullptr, name, args, std::move(database)), WalletToolReleaseWallet};
62  DBErrors load_wallet_ret;
63  try {
64  load_wallet_ret = wallet_instance->LoadWallet();
65  } catch (const std::runtime_error&) {
66  tfm::format(std::cerr, "Error loading %s. Is wallet being used by another process?\n", name);
67  return nullptr;
68  }
69 
70  if (load_wallet_ret != DBErrors::LOAD_OK) {
71  wallet_instance = nullptr;
72  if (load_wallet_ret == DBErrors::CORRUPT) {
73  tfm::format(std::cerr, "Error loading %s: Wallet corrupted", name);
74  return nullptr;
75  } else if (load_wallet_ret == DBErrors::NONCRITICAL_ERROR) {
76  tfm::format(std::cerr, "Error reading %s! All keys read correctly, but transaction data"
77  " or address book entries might be missing or incorrect.",
78  name);
79  } else if (load_wallet_ret == DBErrors::TOO_NEW) {
80  tfm::format(std::cerr, "Error loading %s: Wallet requires newer version of %s",
82  return nullptr;
83  } else if (load_wallet_ret == DBErrors::NEED_REWRITE) {
84  tfm::format(std::cerr, "Wallet needed to be rewritten: restart %s to complete", PACKAGE_NAME);
85  return nullptr;
86  } else if (load_wallet_ret == DBErrors::NEED_RESCAN) {
87  tfm::format(std::cerr, "Error reading %s! Some transaction data might be missing or"
88  " incorrect. Wallet requires a rescan.",
89  name);
90  } else {
91  tfm::format(std::cerr, "Error loading %s", name);
92  return nullptr;
93  }
94  }
95 
96  if (options.require_create) WalletCreate(wallet_instance.get(), options.create_flags);
97 
98  return wallet_instance;
99 }
100 
101 static void WalletShowInfo(CWallet* wallet_instance)
102 {
103  LOCK(wallet_instance->cs_wallet);
104 
105  tfm::format(std::cout, "Wallet info\n===========\n");
106  tfm::format(std::cout, "Name: %s\n", wallet_instance->GetName());
107  tfm::format(std::cout, "Format: %s\n", wallet_instance->GetDatabase().Format());
108  tfm::format(std::cout, "Descriptors: %s\n", wallet_instance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) ? "yes" : "no");
109  tfm::format(std::cout, "Encrypted: %s\n", wallet_instance->IsCrypted() ? "yes" : "no");
110  tfm::format(std::cout, "HD (hd seed available): %s\n", wallet_instance->IsHDEnabled() ? "yes" : "no");
111  tfm::format(std::cout, "Keypool Size: %u\n", wallet_instance->GetKeyPoolSize());
112  tfm::format(std::cout, "Transactions: %zu\n", wallet_instance->mapWallet.size());
113  tfm::format(std::cout, "Address Book: %zu\n", wallet_instance->m_address_book.size());
114 }
115 
116 bool ExecuteWalletToolFunc(const ArgsManager& args, const std::string& command)
117 {
118  if (args.IsArgSet("-format") && command != "createfromdump") {
119  tfm::format(std::cerr, "The -format option can only be used with the \"createfromdump\" command.\n");
120  return false;
121  }
122  if (args.IsArgSet("-dumpfile") && command != "dump" && command != "createfromdump") {
123  tfm::format(std::cerr, "The -dumpfile option can only be used with the \"dump\" and \"createfromdump\" commands.\n");
124  return false;
125  }
126  if (args.IsArgSet("-descriptors") && command != "create") {
127  tfm::format(std::cerr, "The -descriptors option can only be used with the 'create' command.\n");
128  return false;
129  }
130  if (args.IsArgSet("-legacy") && command != "create") {
131  tfm::format(std::cerr, "The -legacy option can only be used with the 'create' command.\n");
132  return false;
133  }
134  if (command == "create" && !args.IsArgSet("-wallet")) {
135  tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n");
136  return false;
137  }
138  const std::string name = args.GetArg("-wallet", "");
140 
141  if (command == "create") {
142  DatabaseOptions options;
143  ReadDatabaseArgs(args, options);
144  options.require_create = true;
145  // If -legacy is set, use it. Otherwise default to false.
146  bool make_legacy = args.GetBoolArg("-legacy", false);
147  // If neither -legacy nor -descriptors is set, default to true. If -descriptors is set, use its value.
148  bool make_descriptors = (!args.IsArgSet("-descriptors") && !args.IsArgSet("-legacy")) || (args.IsArgSet("-descriptors") && args.GetBoolArg("-descriptors", true));
149  if (make_legacy && make_descriptors) {
150  tfm::format(std::cerr, "Only one of -legacy or -descriptors can be set to true, not both\n");
151  return false;
152  }
153  if (!make_legacy && !make_descriptors) {
154  tfm::format(std::cerr, "One of -legacy or -descriptors must be set to true (or omitted)\n");
155  return false;
156  }
157  if (make_descriptors) {
160  }
161 
162  const std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, args, options);
163  if (wallet_instance) {
164  WalletShowInfo(wallet_instance.get());
165  wallet_instance->Close();
166  }
167  } else if (command == "info") {
168  DatabaseOptions options;
169  ReadDatabaseArgs(args, options);
170  options.require_existing = true;
171  const std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, args, options);
172  if (!wallet_instance) return false;
173  WalletShowInfo(wallet_instance.get());
174  wallet_instance->Close();
175  } else if (command == "salvage") {
176 #ifdef USE_BDB
178  std::vector<bilingual_str> warnings;
179  bool ret = RecoverDatabaseFile(args, path, error, warnings);
180  if (!ret) {
181  for (const auto& warning : warnings) {
182  tfm::format(std::cerr, "%s\n", warning.original);
183  }
184  if (!error.empty()) {
185  tfm::format(std::cerr, "%s\n", error.original);
186  }
187  }
188  return ret;
189 #else
190  tfm::format(std::cerr, "Salvage command is not available as BDB support is not compiled");
191  return false;
192 #endif
193  } else if (command == "dump") {
194  DatabaseOptions options;
195  ReadDatabaseArgs(args, options);
196  options.require_existing = true;
197  const std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, args, options);
198  if (!wallet_instance) return false;
200  bool ret = DumpWallet(args, *wallet_instance, error);
201  if (!ret && !error.empty()) {
202  tfm::format(std::cerr, "%s\n", error.original);
203  return ret;
204  }
205  tfm::format(std::cout, "The dumpfile may contain private keys. To ensure the safety of your Bitcoin, do not share the dumpfile.\n");
206  return ret;
207  } else if (command == "createfromdump") {
209  std::vector<bilingual_str> warnings;
210  bool ret = CreateFromDump(args, name, path, error, warnings);
211  for (const auto& warning : warnings) {
212  tfm::format(std::cout, "%s\n", warning.original);
213  }
214  if (!ret && !error.empty()) {
215  tfm::format(std::cerr, "%s\n", error.original);
216  }
217  return ret;
218  } else {
219  tfm::format(std::cerr, "Invalid command: %s\n", command);
220  return false;
221  }
222 
223  return true;
224 }
225 } // namespace WalletTool
226 } // namespace wallet
int ret
#define PACKAGE_NAME
const auto command
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:487
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:591
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:641
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:237
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:369
bool IsCrypted() const
Definition: wallet.cpp:3389
WalletDatabase & GetDatabase() const override
Definition: wallet.h:361
void SetupDescriptorScriptPubKeyMans(const CExtKey &master_key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Create new DescriptorScriptPubKeyMans and add them to the wallet.
Definition: wallet.cpp:3574
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:359
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3525
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
virtual std::string Format()=0
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2482
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2471
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:605
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1608
bool IsHDEnabled() const
Definition: wallet.cpp:1557
void InitWalletFlags(uint64_t flags)
overwrite all flags by the given uint64_t flags must be uninitialised (or 0) only known flags may be ...
Definition: wallet.cpp:1625
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:173
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:35
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1060
static std::shared_ptr< CWallet > MakeWallet(const std::string &name, const fs::path &path, const ArgsManager &args, DatabaseOptions options)
Definition: wallettool.cpp:50
static void WalletShowInfo(CWallet *wallet_instance)
Definition: wallettool.cpp:101
static void WalletToolReleaseWallet(CWallet *wallet)
Definition: wallettool.cpp:25
bool ExecuteWalletToolFunc(const ArgsManager &args, const std::string &command)
Definition: wallettool.cpp:116
static void WalletCreate(CWallet *wallet_instance, uint64_t wallet_creation_flags)
Definition: wallettool.cpp:32
Definition: node.h:39
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:46
void ReadDatabaseArgs(const ArgsManager &args, DatabaseOptions &options)
Definition: db.cpp:142
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1156
bool CreateFromDump(const ArgsManager &args, const std::string &name, const fs::path &wallet_path, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: dump.cpp:118
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:11
bool DumpWallet(const ArgsManager &args, CWallet &wallet, bilingual_str &error)
Definition: dump.cpp:22
@ FEATURE_LATEST
Definition: walletutil.h:30
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
bool RecoverDatabaseFile(const ArgsManager &args, const fs::path &file_path, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: salvage.cpp:26
DatabaseStatus
Definition: db.h:239
std::shared_ptr< CWallet > wallet
ArgsManager args
const char * name
Definition: rest.cpp:46
Bilingual messages:
Definition: translation.h:18
bool require_existing
Definition: db.h:226
std::optional< DatabaseFormat > require_format
Definition: db.h:228
uint64_t create_flags
Definition: db.h:229
#define LOCK(cs)
Definition: sync.h:258
bool error(const char *fmt, const Args &... args)
Definition: system.h:48