Bitcoin Core  0.20.99
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 void WaitForShutdown(NodeContext& node)
32 {
33  while (!ShutdownRequested())
34  {
35  UninterruptibleSleep(std::chrono::milliseconds{200});
36  }
37  Interrupt(node);
38 }
39 
40 static bool AppInit(int argc, char* argv[])
41 {
42  NodeContext node;
43 
44  bool fRet = false;
45 
47 
48  // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
49  SetupServerArgs(node);
50  ArgsManager& args = *Assert(node.args);
51  std::string error;
52  if (!args.ParseParameters(argc, argv, error)) {
53  return InitError(Untranslated(strprintf("Error parsing command line arguments: %s\n", error)));
54  }
55 
56  // Process help and version before taking care about datadir
57  if (HelpRequested(args) || args.IsArgSet("-version")) {
58  std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n";
59 
60  if (args.IsArgSet("-version")) {
61  strUsage += FormatParagraph(LicenseInfo()) + "\n";
62  } else {
63  strUsage += "\nUsage: bitcoind [options] Start " PACKAGE_NAME "\n";
64  strUsage += "\n" + args.GetHelpMessage();
65  }
66 
67  tfm::format(std::cout, "%s", strUsage);
68  return true;
69  }
70 
71  util::Ref context{node};
72  try
73  {
74  if (!CheckDataDirOption()) {
75  return InitError(Untranslated(strprintf("Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""))));
76  }
77  if (!args.ReadConfigFiles(error, true)) {
78  return InitError(Untranslated(strprintf("Error reading configuration file: %s\n", error)));
79  }
80  // Check for chain settings (Params() calls are only valid after this clause)
81  try {
82  SelectParams(args.GetChainName());
83  } catch (const std::exception& e) {
84  return InitError(Untranslated(strprintf("%s\n", e.what())));
85  }
86 
87  // Error out when loose non-argument tokens are encountered on command line
88  for (int i = 1; i < argc; i++) {
89  if (!IsSwitchChar(argv[i][0])) {
90  return InitError(Untranslated(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i])));
91  }
92  }
93 
94  if (!args.InitSettings(error)) {
95  InitError(Untranslated(error));
96  return false;
97  }
98 
99  // -server defaults to true for bitcoind but not for the GUI so do this here
100  args.SoftSetBoolArg("-server", true);
101  // Set this early so that parameter interactions go to console
102  InitLogging(args);
104  if (!AppInitBasicSetup(args)) {
105  // InitError will have been called with detailed error, which ends up on console
106  return false;
107  }
108  if (!AppInitParameterInteraction(args)) {
109  // InitError will have been called with detailed error, which ends up on console
110  return false;
111  }
112  if (!AppInitSanityChecks())
113  {
114  // InitError will have been called with detailed error, which ends up on console
115  return false;
116  }
117  if (args.GetBoolArg("-daemon", false)) {
118 #if HAVE_DECL_DAEMON
119 #if defined(MAC_OSX)
120 #pragma GCC diagnostic push
121 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
122 #endif
123  tfm::format(std::cout, PACKAGE_NAME " starting\n");
124 
125  // Daemonize
126  if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
127  return InitError(Untranslated(strprintf("daemon() failed: %s\n", strerror(errno))));
128  }
129 #if defined(MAC_OSX)
130 #pragma GCC diagnostic pop
131 #endif
132 #else
133  return InitError(Untranslated("-daemon is not supported on this operating system\n"));
134 #endif // HAVE_DECL_DAEMON
135  }
136  // Lock data directory after daemonization
138  {
139  // If locking the data directory failed, exit immediately
140  return false;
141  }
142  fRet = AppInitInterfaces(node) && AppInitMain(context, node);
143  }
144  catch (const std::exception& e) {
145  PrintExceptionContinue(&e, "AppInit()");
146  } catch (...) {
147  PrintExceptionContinue(nullptr, "AppInit()");
148  }
149 
150  if (!fRet)
151  {
152  Interrupt(node);
153  } else {
154  WaitForShutdown(node);
155  }
156  Shutdown(node);
157 
158  return fRet;
159 }
160 
161 int main(int argc, char* argv[])
162 {
163 #ifdef WIN32
164  util::WinCmdLineArgs winArgs;
165  std::tie(argc, argv) = winArgs.get();
166 #endif
168 
169  // Connect bitcoind signal handlers
170  noui_connect();
171 
172  return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
173 }
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:830
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:370
bool ShutdownRequested()
Definition: shutdown.cpp:20
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:492
void Shutdown(NodeContext &node)
Definition: init.cpp:178
#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:1213
#define PACKAGE_NAME
NODISCARD bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:283
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:478
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:594
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:371
int main(int argc, char *argv[])
Definition: bitcoind.cpp:161
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:532
bool CheckDataDirOption()
Definition: system.cpp:736
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1219
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:162
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:601
bool InitError(const bilingual_str &str)
Show error message.
static bool AppInit(int argc, char *argv[])
Definition: bitcoind.cpp:40
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:643
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:42
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:959
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:375
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:19
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:466
bool AppInitBasicSetup(ArgsManager &args)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:917
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:917
bool IsSwitchChar(char c)
Definition: system.h:122
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1252
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1240
bool AppInitMain(const util::Ref &context, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1263
static void WaitForShutdown(NodeContext &node)
Definition: bitcoind.cpp:31
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:802
#define Assert(val)
Identity function.
Definition: check.h:57
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10