Bitcoin Core  21.99.0
P2P Digital Currency
bitcoind.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
8 #endif
9 
10 #include <chainparams.h>
11 #include <clientversion.h>
12 #include <compat.h>
13 #include <init.h>
14 #include <interfaces/chain.h>
15 #include <node/context.h>
16 #include <node/ui_interface.h>
17 #include <noui.h>
18 #include <shutdown.h>
19 #include <util/ref.h>
20 #include <util/strencodings.h>
21 #include <util/system.h>
22 #include <util/threadnames.h>
23 #include <util/translation.h>
24 #include <util/url.h>
25 
26 #include <functional>
27 
28 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
30 
31 static bool AppInit(int argc, char* argv[])
32 {
34 
35  bool fRet = false;
36 
38 
39  // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
40  SetupServerArgs(node);
41  ArgsManager& args = *Assert(node.args);
42  std::string error;
43  if (!args.ParseParameters(argc, argv, error)) {
44  return InitError(Untranslated(strprintf("Error parsing command line arguments: %s\n", error)));
45  }
46 
47  // Process help and version before taking care about datadir
48  if (HelpRequested(args) || args.IsArgSet("-version")) {
49  std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n";
50 
51  if (!args.IsArgSet("-version")) {
52  strUsage += FormatParagraph(LicenseInfo()) + "\n"
53  "\nUsage: bitcoind [options] Start " PACKAGE_NAME "\n"
54  "\n";
55  strUsage += args.GetHelpMessage();
56  }
57 
58  tfm::format(std::cout, "%s", strUsage);
59  return true;
60  }
61 
62  util::Ref context{node};
63  try
64  {
65  if (!CheckDataDirOption()) {
66  return InitError(Untranslated(strprintf("Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""))));
67  }
68  if (!args.ReadConfigFiles(error, true)) {
69  return InitError(Untranslated(strprintf("Error reading configuration file: %s\n", error)));
70  }
71  // Check for chain settings (Params() calls are only valid after this clause)
72  try {
73  SelectParams(args.GetChainName());
74  } catch (const std::exception& e) {
75  return InitError(Untranslated(strprintf("%s\n", e.what())));
76  }
77 
78  // Error out when loose non-argument tokens are encountered on command line
79  for (int i = 1; i < argc; i++) {
80  if (!IsSwitchChar(argv[i][0])) {
81  return InitError(Untranslated(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i])));
82  }
83  }
84 
85  if (!args.InitSettings(error)) {
86  InitError(Untranslated(error));
87  return false;
88  }
89 
90  // -server defaults to true for bitcoind but not for the GUI so do this here
91  args.SoftSetBoolArg("-server", true);
92  // Set this early so that parameter interactions go to console
93  InitLogging(args);
95  if (!AppInitBasicSetup(args)) {
96  // InitError will have been called with detailed error, which ends up on console
97  return false;
98  }
99  if (!AppInitParameterInteraction(args)) {
100  // InitError will have been called with detailed error, which ends up on console
101  return false;
102  }
103  if (!AppInitSanityChecks())
104  {
105  // InitError will have been called with detailed error, which ends up on console
106  return false;
107  }
108  if (args.GetBoolArg("-daemon", false)) {
109 #if HAVE_DECL_DAEMON
110 #if defined(MAC_OSX)
111 #pragma GCC diagnostic push
112 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
113 #endif
114  tfm::format(std::cout, PACKAGE_NAME " starting\n");
115 
116  // Daemonize
117  if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
118  return InitError(Untranslated(strprintf("daemon() failed: %s\n", strerror(errno))));
119  }
120 #if defined(MAC_OSX)
121 #pragma GCC diagnostic pop
122 #endif
123 #else
124  return InitError(Untranslated("-daemon is not supported on this operating system\n"));
125 #endif // HAVE_DECL_DAEMON
126  }
127  // Lock data directory after daemonization
129  {
130  // If locking the data directory failed, exit immediately
131  return false;
132  }
133  fRet = AppInitInterfaces(node) && AppInitMain(context, node);
134  }
135  catch (const std::exception& e) {
136  PrintExceptionContinue(&e, "AppInit()");
137  } catch (...) {
138  PrintExceptionContinue(nullptr, "AppInit()");
139  }
140 
141  if (fRet) {
142  WaitForShutdown();
143  }
144  Interrupt(node);
145  Shutdown(node);
146 
147  return fRet;
148 }
149 
150 int main(int argc, char* argv[])
151 {
152 #ifdef WIN32
153  util::WinCmdLineArgs winArgs;
154  std::tie(argc, argv) = winArgs.get();
155 #endif
157 
158  // Connect bitcoind signal handlers
159  noui_connect();
160 
161  return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
162 }
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:845
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:371
std::string FormatParagraph(const std::string &in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line...
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:871
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:493
void Shutdown(NodeContext &node)
Definition: init.cpp:176
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
UrlDecodeFn urlDecode
Definition: url.h:11
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
void SetupEnvironment()
Definition: system.cpp:1237
#define PACKAGE_NAME
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:284
void noui_connect()
Connect all bitcoind signal handlers.
Definition: noui.cpp:59
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:479
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoind.cpp:28
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:588
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:361
int main(int argc, char *argv[])
Definition: bitcoind.cpp:150
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:917
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:533
bool CheckDataDirOption()
Definition: system.cpp:751
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1222
NodeContext struct containing references to chain state and connection state.
Definition: context.h:37
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:160
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
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
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:602
bool InitError(const bilingual_str &str)
Show error message.
static bool AppInit(int argc, char *argv[])
Definition: bitcoind.cpp:31
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:644
std::string FormatFullVersion()
Type-safe dynamic reference.
Definition: ref.h:21
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:63
ArgsManager * args
Definition: context.h:44
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:962
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:376
void WaitForShutdown()
Wait for StartShutdown to be called in any thread.
Definition: shutdown.cpp:93
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:467
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:932
bool IsSwitchChar(char c)
Definition: system.h:134
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1255
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1243
bool AppInitMain(const util::Ref &context, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1266
UrlDecodeFn *const URL_DECODE
Definition: bitcoind.cpp:29
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:796
#define Assert(val)
Identity function.
Definition: check.h:57
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10