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 
41 //
42 // Start
43 //
44 static bool AppInit(int argc, char* argv[])
45 {
46  NodeContext node;
47  node.chain = interfaces::MakeChain(node);
48 
49  bool fRet = false;
50 
52 
53  //
54  // Parameters
55  //
56  // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
57  SetupServerArgs(node);
58  std::string error;
59  if (!gArgs.ParseParameters(argc, argv, error)) {
60  return InitError(Untranslated(strprintf("Error parsing command line arguments: %s\n", error)));
61  }
62 
63  // Process help and version before taking care about datadir
64  if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
65  std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n";
66 
67  if (gArgs.IsArgSet("-version"))
68  {
69  strUsage += FormatParagraph(LicenseInfo()) + "\n";
70  }
71  else
72  {
73  strUsage += "\nUsage: bitcoind [options] Start " PACKAGE_NAME "\n";
74  strUsage += "\n" + gArgs.GetHelpMessage();
75  }
76 
77  tfm::format(std::cout, "%s", strUsage);
78  return true;
79  }
80 
81  util::Ref context{node};
82  try
83  {
84  if (!CheckDataDirOption()) {
85  return InitError(Untranslated(strprintf("Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", ""))));
86  }
87  if (!gArgs.ReadConfigFiles(error, true)) {
88  return InitError(Untranslated(strprintf("Error reading configuration file: %s\n", error)));
89  }
90  // Check for -chain, -testnet or -regtest parameter (Params() calls are only valid after this clause)
91  try {
93  } catch (const std::exception& e) {
94  return InitError(Untranslated(strprintf("%s\n", e.what())));
95  }
96 
97  // Error out when loose non-argument tokens are encountered on command line
98  for (int i = 1; i < argc; i++) {
99  if (!IsSwitchChar(argv[i][0])) {
100  return InitError(Untranslated(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i])));
101  }
102  }
103 
104  // -server defaults to true for bitcoind but not for the GUI so do this here
105  gArgs.SoftSetBoolArg("-server", true);
106  // Set this early so that parameter interactions go to console
107  InitLogging();
109  if (!AppInitBasicSetup())
110  {
111  // InitError will have been called with detailed error, which ends up on console
112  return false;
113  }
115  {
116  // InitError will have been called with detailed error, which ends up on console
117  return false;
118  }
119  if (!AppInitSanityChecks())
120  {
121  // InitError will have been called with detailed error, which ends up on console
122  return false;
123  }
124  if (gArgs.GetBoolArg("-daemon", false))
125  {
126 #if HAVE_DECL_DAEMON
127 #if defined(MAC_OSX)
128 #pragma GCC diagnostic push
129 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
130 #endif
131  tfm::format(std::cout, PACKAGE_NAME " starting\n");
132 
133  // Daemonize
134  if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
135  return InitError(Untranslated(strprintf("daemon() failed: %s\n", strerror(errno))));
136  }
137 #if defined(MAC_OSX)
138 #pragma GCC diagnostic pop
139 #endif
140 #else
141  return InitError(Untranslated("-daemon is not supported on this operating system\n"));
142 #endif // HAVE_DECL_DAEMON
143  }
144  // Lock data directory after daemonization
146  {
147  // If locking the data directory failed, exit immediately
148  return false;
149  }
150  fRet = AppInitMain(context, node);
151  }
152  catch (const std::exception& e) {
153  PrintExceptionContinue(&e, "AppInit()");
154  } catch (...) {
155  PrintExceptionContinue(nullptr, "AppInit()");
156  }
157 
158  if (!fRet)
159  {
160  Interrupt(node);
161  } else {
162  WaitForShutdown(node);
163  }
164  Shutdown(node);
165 
166  return fRet;
167 }
168 
169 int main(int argc, char* argv[])
170 {
171 #ifdef WIN32
172  util::WinCmdLineArgs winArgs;
173  std::tie(argc, argv) = winArgs.get();
174 #endif
176 
177  // Connect bitcoind signal handlers
178  noui_connect();
179 
180  return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
181 }
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:744
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()
Initialize global loggers.
Definition: init.cpp:862
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:406
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
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:41
void SetupEnvironment()
Definition: system.cpp:1082
#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:392
bool AppInitMain(const util::Ref &context, NodeContext &node)
Bitcoin core main initialization.
Definition: init.cpp:1242
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:908
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:580
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:368
int main(int argc, char *argv[])
Definition: bitcoind.cpp:169
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:446
bool CheckDataDirOption()
Definition: system.cpp:650
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:793
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1209
NodeContext struct containing references to chain state and connection state.
Definition: context.h:34
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:515
bool InitError(const bilingual_str &str)
Show error message.
static bool AppInit(int argc, char *argv[])
Definition: bitcoind.cpp:44
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:557
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
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:950
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:380
ArgsManager gArgs
Definition: system.cpp:77
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:831
bool IsSwitchChar(char c)
Definition: system.h:109
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1230
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:49
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10