Bitcoin Core  22.99.0
P2P Digital Currency
bitcoin-wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016-2020 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 <logging.h>
12 #include <util/system.h>
13 #include <util/translation.h>
14 #include <util/url.h>
15 #include <wallet/wallettool.h>
16 
17 #include <functional>
18 
19 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
20 UrlDecodeFn* const URL_DECODE = nullptr;
21 
22 static void SetupWalletToolArgs(ArgsManager& argsman)
23 {
24  SetupHelpOptions(argsman);
26 
27  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
28  argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
29  argsman.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
30  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_STRING, OptionsCategory::OPTIONS);
31  argsman.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
32  argsman.AddArg("-descriptors", "Create descriptors wallet. Only for 'create'", ArgsManager::ALLOW_BOOL, OptionsCategory::OPTIONS);
33  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);
34  argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
35 
36  argsman.AddCommand("info", "Get wallet info");
37  argsman.AddCommand("create", "Create new wallet file");
38  argsman.AddCommand("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.");
39  argsman.AddCommand("dump", "Print out all of the wallet key-value records");
40  argsman.AddCommand("createfromdump", "Create new wallet file from dumped records");
41 }
42 
43 static bool WalletAppInit(ArgsManager& args, int argc, char* argv[])
44 {
45  SetupWalletToolArgs(args);
46  std::string error_message;
47  if (!args.ParseParameters(argc, argv, error_message)) {
48  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
49  return false;
50  }
51  if (argc < 2 || HelpRequested(args) || args.IsArgSet("-version")) {
52  std::string strUsage = strprintf("%s bitcoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n";
53  if (!args.IsArgSet("-version")) {
54  strUsage += "\n"
55  "bitcoin-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n"
56  "By default bitcoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n"
57  "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n"
58  "Usage:\n"
59  " bitcoin-wallet [options] <command>\n";
60  strUsage += "\n" + args.GetHelpMessage();
61  }
62  tfm::format(std::cout, "%s", strUsage);
63  return false;
64  }
65 
66  // check for printtoconsole, allow -debug
67  LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", args.GetBoolArg("-debug", false));
68 
69  if (!CheckDataDirOption()) {
70  tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""));
71  return false;
72  }
73  // Check for chain settings (Params() calls are only valid after this clause)
74  SelectParams(args.GetChainName());
75 
76  return true;
77 }
78 
79 int main(int argc, char* argv[])
80 {
81  ArgsManager& args = gArgs;
82 #ifdef WIN32
83  util::WinCmdLineArgs winArgs;
84  std::tie(argc, argv) = winArgs.get();
85 #endif
87  RandomInit();
88  try {
89  if (!WalletAppInit(args, argc, argv)) return EXIT_FAILURE;
90  } catch (const std::exception& e) {
91  PrintExceptionContinue(&e, "WalletAppInit()");
92  return EXIT_FAILURE;
93  } catch (...) {
94  PrintExceptionContinue(nullptr, "WalletAppInit()");
95  return EXIT_FAILURE;
96  }
97 
98  const auto command = args.GetCommand();
99  if (!command) {
100  tfm::format(std::cerr, "No method provided. Run `bitcoin-wallet -help` for valid methods.\n");
101  return EXIT_FAILURE;
102  }
103  if (command->args.size() != 0) {
104  tfm::format(std::cerr, "Error: Additional arguments provided (%s). Methods do not take arguments. Please refer to `-help`.\n", Join(command->args, ", "));
105  return EXIT_FAILURE;
106  }
107 
109  ECC_Start();
110  if (!WalletTool::ExecuteWalletToolFunc(args, command->command)) {
111  return EXIT_FAILURE;
112  }
113  ECC_Stop();
114  return EXIT_SUCCESS;
115 }
WalletAppInit
static bool WalletAppInit(ArgsManager &args, int argc, char *argv[])
Definition: bitcoin-wallet.cpp:43
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
Definition: system.h:166
SetupChainParamsBaseOptions
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
Definition: chainparamsbase.cpp:18
ArgsManager::GetChainName
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:988
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:492
SetupEnvironment
void SetupEnvironment()
Definition: system.cpp:1295
main
int main(int argc, char *argv[])
Definition: bitcoin-wallet.cpp:79
HelpRequested
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:737
bitcoin-config.h
chainparams.h
SetupHelpOptions
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:742
ECC_Stop
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:387
ArgsManager::ALLOW_STRING
@ ALLOW_STRING
Definition: system.h:165
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:362
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
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:304
RandomInit
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:710
G_TRANSLATION_FUN
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-wallet.cpp:19
gArgs
ArgsManager gArgs
Definition: system.cpp:84
SetupWalletToolArgs
static void SetupWalletToolArgs(ArgsManager &argsman)
Definition: bitcoin-wallet.cpp:22
CheckDataDirOption
bool CheckDataDirOption()
Definition: system.cpp:811
system.h
ECC_Start
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:370
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
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:315
ArgsManager
Definition: system.h:158
translation.h
url.h
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:91
WalletTool::ExecuteWalletToolFunc
bool ExecuteWalletToolFunc(const ArgsManager &args, const std::string &command)
Definition: wallettool.cpp:105
logging.h
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:17
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:463
ArgsManager::ALLOW_BOOL
@ ALLOW_BOOL
Definition: system.h:163
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:20
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:173