Bitcoin Core  22.99.0
P2P Digital Currency
bitcoin-wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016-2021 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 <interfaces/init.h>
13 #include <key.h>
14 #include <logging.h>
15 #include <pubkey.h>
16 #include <tinyformat.h>
17 #include <util/system.h>
18 #include <util/translation.h>
19 #include <util/url.h>
20 #include <wallet/wallettool.h>
21 
22 #include <exception>
23 #include <functional>
24 #include <string>
25 #include <tuple>
26 
27 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
28 UrlDecodeFn* const URL_DECODE = nullptr;
29 
30 static void SetupWalletToolArgs(ArgsManager& argsman)
31 {
32  SetupHelpOptions(argsman);
34 
35  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
36  argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
37  argsman.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
38  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);
39  argsman.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
40  argsman.AddArg("-descriptors", "Create descriptors wallet. Only for 'create'", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
41  argsman.AddArg("-legacy", "Create legacy wallet. Only for 'create'", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
42  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);
43  argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
44 
45  argsman.AddCommand("info", "Get wallet info");
46  argsman.AddCommand("create", "Create new wallet file");
47  argsman.AddCommand("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.");
48  argsman.AddCommand("dump", "Print out all of the wallet key-value records");
49  argsman.AddCommand("createfromdump", "Create new wallet file from dumped records");
50 }
51 
52 static bool WalletAppInit(ArgsManager& args, int argc, char* argv[])
53 {
55  std::string error_message;
56  if (!args.ParseParameters(argc, argv, error_message)) {
57  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
58  return false;
59  }
60  if (argc < 2 || HelpRequested(args) || args.IsArgSet("-version")) {
61  std::string strUsage = strprintf("%s bitcoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n";
62  if (!args.IsArgSet("-version")) {
63  strUsage += "\n"
64  "bitcoin-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n"
65  "By default bitcoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n"
66  "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n"
67  "Usage:\n"
68  " bitcoin-wallet [options] <command>\n";
69  strUsage += "\n" + args.GetHelpMessage();
70  }
71  tfm::format(std::cout, "%s", strUsage);
72  return false;
73  }
74 
75  // check for printtoconsole, allow -debug
76  LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", args.GetBoolArg("-debug", false));
77 
78  if (!CheckDataDirOption()) {
79  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""));
80  return false;
81  }
82  // Check for chain settings (Params() calls are only valid after this clause)
84 
85  return true;
86 }
87 
88 int main(int argc, char* argv[])
89 {
91 #ifdef WIN32
92  util::WinCmdLineArgs winArgs;
93  std::tie(argc, argv) = winArgs.get();
94 #endif
95 
96  int exit_status;
97  std::unique_ptr<interfaces::Init> init = interfaces::MakeWalletInit(argc, argv, exit_status);
98  if (!init) {
99  return exit_status;
100  }
101 
103  RandomInit();
104  try {
105  if (!WalletAppInit(args, argc, argv)) return EXIT_FAILURE;
106  } catch (const std::exception& e) {
107  PrintExceptionContinue(&e, "WalletAppInit()");
108  return EXIT_FAILURE;
109  } catch (...) {
110  PrintExceptionContinue(nullptr, "WalletAppInit()");
111  return EXIT_FAILURE;
112  }
113 
114  const auto command = args.GetCommand();
115  if (!command) {
116  tfm::format(std::cerr, "No method provided. Run `bitcoin-wallet -help` for valid methods.\n");
117  return EXIT_FAILURE;
118  }
119  if (command->args.size() != 0) {
120  tfm::format(std::cerr, "Error: Additional arguments provided (%s). Methods do not take arguments. Please refer to `-help`.\n", Join(command->args, ", "));
121  return EXIT_FAILURE;
122  }
123 
125  ECC_Start();
126  if (!wallet::WalletTool::ExecuteWalletToolFunc(args, command->command)) {
127  return EXIT_FAILURE;
128  }
129  ECC_Stop();
130  return EXIT_SUCCESS;
131 }
WalletAppInit
static bool WalletAppInit(ArgsManager &args, int argc, char *argv[])
Definition: bitcoin-wallet.cpp:52
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:600
tinyformat::format
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:1062
globalVerifyHandle
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: common.cpp:23
ArgsManager::GetHelpMessage
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:668
chainparamsbase.h
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
disable validation
Definition: system.h:172
SetupChainParamsBaseOptions
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
Definition: chainparamsbase.cpp:18
ArgsManager::DISALLOW_NEGATION
@ DISALLOW_NEGATION
disallow -nofoo syntax
Definition: system.h:177
ArgsManager::GetChainName
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:987
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:494
SetupEnvironment
void SetupEnvironment()
Definition: system.cpp:1301
main
int main(int argc, char *argv[])
Definition: bitcoin-wallet.cpp:88
clientversion.h
HelpRequested
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:737
bitcoin-config.h
pubkey.h
chainparams.h
SetupHelpOptions
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:742
tinyformat.h
ECC_Stop
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:408
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:354
ArgsManager::AddArg
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:640
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:588
OptionsCategory::OPTIONS
@ OPTIONS
init.h
SelectParams
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
Definition: chainparams.cpp:580
wallettool.h
ArgsManager::ParseParameters
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:297
wallet::WalletTool::ExecuteWalletToolFunc
bool ExecuteWalletToolFunc(const ArgsManager &args, const std::string &command)
Definition: wallettool.cpp:116
RandomInit
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:707
G_TRANSLATION_FUN
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-wallet.cpp:27
gArgs
ArgsManager gArgs
Definition: system.cpp:87
SetupWalletToolArgs
static void SetupWalletToolArgs(ArgsManager &argsman)
Definition: bitcoin-wallet.cpp:30
interfaces::MakeWalletInit
std::unique_ptr< Init > MakeWalletInit(int argc, char *argv[], int &exit_status)
Return implementation of Init interface for the wallet process.
Definition: bitcoin-wallet.cpp:8
CheckDataDirOption
bool CheckDataDirOption()
Definition: system.cpp:811
system.h
ECC_Start
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:391
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
key.h
Join
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
ECCVerifyHandle
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:332
ArgsManager
Definition: system.h:164
translation.h
url.h
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:94
init
Definition: bitcoin-gui.cpp:16
logging.h
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:18
UrlDecodeFn
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10
OptionsCategory::DEBUG_TEST
@ DEBUG_TEST
ArgsManager::GetCommand
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: system.cpp:465
PrintExceptionContinue
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:779
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:50
URL_DECODE
UrlDecodeFn *const URL_DECODE
Definition: bitcoin-wallet.cpp:28
ArgsManager::AddCommand
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: system.cpp:628
ArgsManager::NETWORK_ONLY
@ NETWORK_ONLY
Definition: system.h:185
args
ArgsManager args
Definition: notifications.cpp:36