Bitcoin Core  24.99.0
P2P Digital Currency
bitcoin-wallet.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 <chainparams.h>
10 #include <chainparamsbase.h>
11 #include <clientversion.h>
12 #include <common/url.h>
13 #include <compat/compat.h>
14 #include <interfaces/init.h>
15 #include <key.h>
16 #include <logging.h>
17 #include <pubkey.h>
18 #include <tinyformat.h>
19 #include <util/system.h>
20 #include <util/translation.h>
21 #include <wallet/wallettool.h>
22 
23 #include <exception>
24 #include <functional>
25 #include <string>
26 #include <tuple>
27 
28 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
29 UrlDecodeFn* const URL_DECODE = nullptr;
30 
31 static void SetupWalletToolArgs(ArgsManager& argsman)
32 {
33  SetupHelpOptions(argsman);
35 
36  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
37  argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
38  argsman.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
39  argsman.AddArg("-dumpfile=<file name>", "When used with 'dump', writes out the records to this file. When used with 'createfromdump', loads the records into a new wallet.", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);
40  argsman.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
41  argsman.AddArg("-descriptors", "Create descriptors wallet. Only for 'create'", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
42  argsman.AddArg("-legacy", "Create legacy wallet. Only for 'create'", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
43  argsman.AddArg("-format=<format>", "The format of the wallet file to create. Either \"bdb\" or \"sqlite\". Only used with 'createfromdump'", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
44  argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
45 
46  argsman.AddCommand("info", "Get wallet info");
47  argsman.AddCommand("create", "Create new wallet file");
48  argsman.AddCommand("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.");
49  argsman.AddCommand("dump", "Print out all of the wallet key-value records");
50  argsman.AddCommand("createfromdump", "Create new wallet file from dumped records");
51 }
52 
53 static std::optional<int> WalletAppInit(ArgsManager& args, int argc, char* argv[])
54 {
56  std::string error_message;
57  if (!args.ParseParameters(argc, argv, error_message)) {
58  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
59  return EXIT_FAILURE;
60  }
61  const bool missing_args{argc < 2};
62  if (missing_args || HelpRequested(args) || args.IsArgSet("-version")) {
63  std::string strUsage = strprintf("%s bitcoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n";
64 
65  if (args.IsArgSet("-version")) {
66  strUsage += FormatParagraph(LicenseInfo());
67  } else {
68  strUsage += "\n"
69  "bitcoin-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n"
70  "By default bitcoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n"
71  "To change the target wallet, use the -datadir, -wallet and -regtest/-signet/-testnet arguments.\n\n"
72  "Usage:\n"
73  " bitcoin-wallet [options] <command>\n";
74  strUsage += "\n" + args.GetHelpMessage();
75  }
76  tfm::format(std::cout, "%s", strUsage);
77  if (missing_args) {
78  tfm::format(std::cerr, "Error: too few parameters\n");
79  return EXIT_FAILURE;
80  }
81  return EXIT_SUCCESS;
82  }
83 
84  // check for printtoconsole, allow -debug
85  LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", args.GetBoolArg("-debug", false));
86 
87  if (!CheckDataDirOption()) {
88  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""));
89  return EXIT_FAILURE;
90  }
91  // Check for chain settings (Params() calls are only valid after this clause)
93 
94  return std::nullopt;
95 }
96 
98 {
100 #ifdef WIN32
101  util::WinCmdLineArgs winArgs;
102  std::tie(argc, argv) = winArgs.get();
103 #endif
104 
106  std::unique_ptr<interfaces::Init> init = interfaces::MakeWalletInit(argc, argv, exit_status);
107  if (!init) {
108  return exit_status;
109  }
110 
112  RandomInit();
113  try {
114  if (const auto maybe_exit{WalletAppInit(args, argc, argv)}) return *maybe_exit;
115  } catch (const std::exception& e) {
116  PrintExceptionContinue(&e, "WalletAppInit()");
117  return EXIT_FAILURE;
118  } catch (...) {
119  PrintExceptionContinue(nullptr, "WalletAppInit()");
120  return EXIT_FAILURE;
121  }
122 
123  const auto command = args.GetCommand();
124  if (!command) {
125  tfm::format(std::cerr, "No method provided. Run `bitcoin-wallet -help` for valid methods.\n");
126  return EXIT_FAILURE;
127  }
128  if (command->args.size() != 0) {
129  tfm::format(std::cerr, "Error: Additional arguments provided (%s). Methods do not take arguments. Please refer to `-help`.\n", Join(command->args, ", "));
130  return EXIT_FAILURE;
131  }
132 
133  ECC_Start();
135  return EXIT_FAILURE;
136  }
137  ECC_Stop();
138  return EXIT_SUCCESS;
139 }
#define PACKAGE_NAME
UrlDecodeFn *const URL_DECODE
return EXIT_SUCCESS
const auto command
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
ECC_Start()
Definition: key.cpp:391
RandomInit()
Definition: random.cpp:701
ECC_Stop()
Definition: key.cpp:408
static void SetupWalletToolArgs(ArgsManager &argsman)
SetupEnvironment()
Definition: system.cpp:1338
int exit_status
static std::optional< int > WalletAppInit(ArgsManager &args, int argc, char *argv[])
MAIN_FUNCTION
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: system.cpp:458
@ NETWORK_ONLY
Definition: system.h:186
@ ALLOW_ANY
disable validation
Definition: system.h:172
@ DISALLOW_NEGATION
disallow -nofoo syntax
Definition: system.h:177
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:287
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:726
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:487
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: system.cpp:686
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
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:698
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:1060
bool m_print_to_console
Definition: logging.h:115
std::string FormatFullVersion()
std::string LicenseInfo()
Returns licensing information (for -version)
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
std::unique_ptr< Init > MakeWalletInit(int argc, char *argv[], int &exit_status)
Return implementation of Init interface for the wallet process.
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
bool ExecuteWalletToolFunc(const ArgsManager &args, const std::string &command)
Definition: wallettool.cpp:116
ArgsManager args
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:68
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:795
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:800
bool CheckDataDirOption()
Definition: system.cpp:869
ArgsManager gArgs
Definition: system.cpp:73
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: system.cpp:837