Bitcoin Core  0.19.99
P2P Digital Currency
bitcoind.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <noui.h>
17 #include <shutdown.h>
18 #include <ui_interface.h>
19 #include <util/strencodings.h>
20 #include <util/system.h>
21 #include <util/threadnames.h>
22 #include <util/translation.h>
23 
24 #include <functional>
25 
26 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
27 
28 static void WaitForShutdown(NodeContext& node)
29 {
30  while (!ShutdownRequested())
31  {
32  UninterruptibleSleep(std::chrono::milliseconds{200});
33  }
34  Interrupt(node);
35 }
36 
38 //
39 // Start
40 //
41 static bool AppInit(int argc, char* argv[])
42 {
43  NodeContext node;
44  node.chain = interfaces::MakeChain(node);
45 
46  bool fRet = false;
47 
49 
50  //
51  // Parameters
52  //
53  // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
55  std::string error;
56  if (!gArgs.ParseParameters(argc, argv, error)) {
57  return InitError(strprintf("Error parsing command line arguments: %s\n", error));
58  }
59 
60  // Process help and version before taking care about datadir
61  if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
62  std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n";
63 
64  if (gArgs.IsArgSet("-version"))
65  {
66  strUsage += FormatParagraph(LicenseInfo()) + "\n";
67  }
68  else
69  {
70  strUsage += "\nUsage: bitcoind [options] Start " PACKAGE_NAME "\n";
71  strUsage += "\n" + gArgs.GetHelpMessage();
72  }
73 
74  tfm::format(std::cout, "%s", strUsage);
75  return true;
76  }
77 
78  try
79  {
80  if (!CheckDataDirOption()) {
81  return InitError(strprintf("Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "")));
82  }
83  if (!gArgs.ReadConfigFiles(error, true)) {
84  return InitError(strprintf("Error reading configuration file: %s\n", error));
85  }
86  // Check for -chain, -testnet or -regtest parameter (Params() calls are only valid after this clause)
87  try {
89  } catch (const std::exception& e) {
90  return InitError(strprintf("%s\n", e.what()));
91  }
92 
93  // Error out when loose non-argument tokens are encountered on command line
94  for (int i = 1; i < argc; i++) {
95  if (!IsSwitchChar(argv[i][0])) {
96  return InitError(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i]));
97  }
98  }
99 
100  // -server defaults to true for bitcoind but not for the GUI so do this here
101  gArgs.SoftSetBoolArg("-server", true);
102  // Set this early so that parameter interactions go to console
103  InitLogging();
105  if (!AppInitBasicSetup())
106  {
107  // InitError will have been called with detailed error, which ends up on console
108  return false;
109  }
111  {
112  // InitError will have been called with detailed error, which ends up on console
113  return false;
114  }
115  if (!AppInitSanityChecks())
116  {
117  // InitError will have been called with detailed error, which ends up on console
118  return false;
119  }
120  if (gArgs.GetBoolArg("-daemon", false))
121  {
122 #if HAVE_DECL_DAEMON
123 #if defined(MAC_OSX)
124 #pragma GCC diagnostic push
125 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
126 #endif
127  tfm::format(std::cout, PACKAGE_NAME " starting\n");
128 
129  // Daemonize
130  if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
131  return InitError(strprintf("daemon() failed: %s\n", strerror(errno)));
132  }
133 #if defined(MAC_OSX)
134 #pragma GCC diagnostic pop
135 #endif
136 #else
137  return InitError("-daemon is not supported on this operating system\n");
138 #endif // HAVE_DECL_DAEMON
139  }
140  // Lock data directory after daemonization
142  {
143  // If locking the data directory failed, exit immediately
144  return false;
145  }
146  fRet = AppInitMain(node);
147  }
148  catch (const std::exception& e) {
149  PrintExceptionContinue(&e, "AppInit()");
150  } catch (...) {
151  PrintExceptionContinue(nullptr, "AppInit()");
152  }
153 
154  if (!fRet)
155  {
156  Interrupt(node);
157  } else {
158  WaitForShutdown(node);
159  }
160  Shutdown(node);
161 
162  return fRet;
163 }
164 
165 int main(int argc, char* argv[])
166 {
167 #ifdef WIN32
168  util::WinCmdLineArgs winArgs;
169  std::tie(argc, argv) = winArgs.get();
170 #endif
172 
173  // Connect bitcoind signal handlers
174  noui_connect();
175 
176  return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
177 }
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:736
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:362
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...
bool AppInitMain(NodeContext &node)
Bitcoin core main initialization.
Definition: init.cpp:1205
void InitLogging()
Initialize global loggers.
Definition: init.cpp:845
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:398
void Shutdown(NodeContext &node)
Definition: init.cpp:173
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:36
void SetupEnvironment()
Definition: system.cpp:1074
#define PACKAGE_NAME
NODISCARD bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:275
void noui_connect()
Connect all bitcoind signal handlers.
Definition: noui.cpp:62
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:384
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:889
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoind.cpp:26
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:574
int main(int argc, char *argv[])
Definition: bitcoind.cpp:165
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
Definition: chain.cpp:386
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:438
bool CheckDataDirOption()
Definition: system.cpp:642
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:776
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1172
NodeContext struct containing references to chain state and connection state.
Definition: context.h:31
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:157
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:507
static bool AppInit(int argc, char *argv[])
Definition: bitcoind.cpp:41
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:549
std::string FormatFullVersion()
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:63
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:930
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:360
bool InitError(const std::string &str)
Show error message.
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:372
ArgsManager gArgs
Definition: system.cpp:76
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:823
bool IsSwitchChar(char c)
Definition: system.h:101
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1193
static void WaitForShutdown(NodeContext &node)
Definition: bitcoind.cpp:28
bool error(const char *fmt, const Args &... args)
Definition: system.h:49