Bitcoin Core  29.1.0
P2P Digital Currency
bitcoin-wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016-present 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 #include <bitcoin-build-config.h> // IWYU pragma: keep
6 
7 #include <chainparams.h>
8 #include <chainparamsbase.h>
9 #include <clientversion.h>
10 #include <common/args.h>
11 #include <common/system.h>
12 #include <compat/compat.h>
13 #include <interfaces/init.h>
14 #include <key.h>
15 #include <logging.h>
16 #include <pubkey.h>
17 #include <tinyformat.h>
18 #include <util/exception.h>
19 #include <util/translation.h>
20 #include <wallet/wallettool.h>
21 
22 #include <exception>
23 #include <functional>
24 #include <string>
25 #include <tuple>
26 
27 using util::Join;
28 
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 | ArgsManager::DISALLOW_NEGATION, 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  argsman.AddArg("-withinternalbdb", "Use the internal Berkeley DB parser when dumping a Berkeley DB wallet file (default: false)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
46 
47  argsman.AddCommand("info", "Get wallet info");
48  argsman.AddCommand("create", "Create new wallet file");
49  argsman.AddCommand("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.");
50  argsman.AddCommand("dump", "Print out all of the wallet key-value records");
51  argsman.AddCommand("createfromdump", "Create new wallet file from dumped records");
52 }
53 
54 static std::optional<int> WalletAppInit(ArgsManager& args, int argc, char* argv[])
55 {
57  std::string error_message;
58  if (!args.ParseParameters(argc, argv, error_message)) {
59  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
60  return EXIT_FAILURE;
61  }
62  const bool missing_args{argc < 2};
63  if (missing_args || HelpRequested(args) || args.GetBoolArg("-version", false)) {
64  std::string strUsage = strprintf("%s bitcoin-wallet utility version", CLIENT_NAME) + " " + FormatFullVersion() + "\n";
65 
66  if (args.GetBoolArg("-version", false)) {
67  strUsage += FormatParagraph(LicenseInfo());
68  } else {
69  strUsage += "\n"
70  "bitcoin-wallet is an offline tool for creating and interacting with " CLIENT_NAME " wallet files.\n\n"
71  "By default bitcoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n\n"
72  "To change the target wallet, use the -datadir, -wallet and (test)chain selection arguments.\n"
73  "\n"
74  "Usage: bitcoin-wallet [options] <command>\n"
75  "\n";
76  strUsage += "\n" + args.GetHelpMessage();
77  }
78  tfm::format(std::cout, "%s", strUsage);
79  if (missing_args) {
80  tfm::format(std::cerr, "Error: too few parameters\n");
81  return EXIT_FAILURE;
82  }
83  return EXIT_SUCCESS;
84  }
85 
86  // check for printtoconsole, allow -debug
87  LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", args.GetBoolArg("-debug", false));
88 
89  if (!CheckDataDirOption(args)) {
90  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""));
91  return EXIT_FAILURE;
92  }
93  // Check for chain settings (Params() calls are only valid after this clause)
95 
96  return std::nullopt;
97 }
98 
100 {
102 #ifdef WIN32
103  common::WinCmdLineArgs winArgs;
104  std::tie(argc, argv) = winArgs.get();
105 #endif
106 
108  std::unique_ptr<interfaces::Init> init = interfaces::MakeWalletInit(argc, argv, exit_status);
109  if (!init) {
110  return exit_status;
111  }
112 
114  RandomInit();
115  try {
116  if (const auto maybe_exit{WalletAppInit(args, argc, argv)}) return *maybe_exit;
117  } catch (const std::exception& e) {
118  PrintExceptionContinue(&e, "WalletAppInit()");
119  return EXIT_FAILURE;
120  } catch (...) {
121  PrintExceptionContinue(nullptr, "WalletAppInit()");
122  return EXIT_FAILURE;
123  }
124 
125  const auto command = args.GetCommand();
126  if (!command) {
127  tfm::format(std::cerr, "No method provided. Run `bitcoin-wallet -help` for valid methods.\n");
128  return EXIT_FAILURE;
129  }
130  if (command->args.size() != 0) {
131  tfm::format(std::cerr, "Error: Additional arguments provided (%s). Methods do not take arguments. Please refer to `-help`.\n", Join(command->args, ", "));
132  return EXIT_FAILURE;
133  }
134 
137  return EXIT_FAILURE;
138  }
139  return EXIT_SUCCESS;
140 }
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
return EXIT_SUCCESS
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
std::unique_ptr< Init > MakeWalletInit(int argc, char *argv[], int &exit_status)
Return implementation of Init interface for the wallet process.
RAII class initializing and deinitializing global state for elliptic curve support.
Definition: key.h:321
static std::optional< int > WalletAppInit(ArgsManager &args, int argc, char *argv[])
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
ECC_Context ecc_context
MAIN_FUNCTION
disallow -nofoo syntax
Definition: args.h:111
bool m_print_to_console
Definition: logging.h:221
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:179
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:507
std::string LicenseInfo()
Returns licensing information (for -version)
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: exception.cpp:36
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:774
disable validation
Definition: args.h:106
std::string GetHelpMessage() const
Get the help string.
Definition: args.cpp:609
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: args.cpp:552
const TranslateFn G_TRANSLATION_FUN
Translate string to current locale using Qt.
ArgsManager & args
Definition: bitcoind.cpp:277
std::function< std::string(const char *)> TranslateFn
Translate a message to the native language of the user.
Definition: translation.h:16
bool ExecuteWalletToolFunc(const ArgsManager &args, const std::string &command)
Definition: wallettool.cpp:113
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:564
SetupEnvironment()
Definition: system.cpp:59
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...
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: args.cpp:342
std::string FormatFullVersion()
ArgsManager gArgs
Definition: args.cpp:42
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:689
const auto command
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:457
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:684
static void SetupWalletToolArgs(ArgsManager &argsman)
int exit_status
RandomInit()
Definition: random.cpp:698
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:192
void SelectParams(const ChainType chain)
Sets the params returned by Params() to those for the given chain type.
bool CheckDataDirOption(const ArgsManager &args)
Definition: args.cpp:755