You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.cpp 79KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 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. #if defined(HAVE_CONFIG_H)
  6. #include "config/bitcoin-config.h"
  7. #endif
  8. #include "init.h"
  9. #include "addrman.h"
  10. #include "amount.h"
  11. #include "chain.h"
  12. #include "chainparams.h"
  13. #include "checkpoints.h"
  14. #include "compat/sanity.h"
  15. #include "consensus/validation.h"
  16. #include "fs.h"
  17. #include "httpserver.h"
  18. #include "httprpc.h"
  19. #include "key.h"
  20. #include "validation.h"
  21. #include "miner.h"
  22. #include "netbase.h"
  23. #include "net.h"
  24. #include "net_processing.h"
  25. #include "policy/fees.h"
  26. #include "policy/policy.h"
  27. #include "rpc/server.h"
  28. #include "rpc/register.h"
  29. #include "rpc/blockchain.h"
  30. #include "script/standard.h"
  31. #include "script/sigcache.h"
  32. #include "scheduler.h"
  33. #include "timedata.h"
  34. #include "txdb.h"
  35. #include "txmempool.h"
  36. #include "torcontrol.h"
  37. #include "ui_interface.h"
  38. #include "util.h"
  39. #include "utilmoneystr.h"
  40. #include "validationinterface.h"
  41. #ifdef ENABLE_WALLET
  42. #include "wallet/wallet.h"
  43. #endif
  44. #include "warnings.h"
  45. #include <stdint.h>
  46. #include <stdio.h>
  47. #include <memory>
  48. #ifndef WIN32
  49. #include <signal.h>
  50. #endif
  51. #include <boost/algorithm/string/classification.hpp>
  52. #include <boost/algorithm/string/predicate.hpp>
  53. #include <boost/algorithm/string/replace.hpp>
  54. #include <boost/algorithm/string/split.hpp>
  55. #include <boost/bind.hpp>
  56. #include <boost/function.hpp>
  57. #include <boost/interprocess/sync/file_lock.hpp>
  58. #include <boost/thread.hpp>
  59. #include <openssl/crypto.h>
  60. #if ENABLE_ZMQ
  61. #include "zmq/zmqnotificationinterface.h"
  62. #endif
  63. bool fFeeEstimatesInitialized = false;
  64. static const bool DEFAULT_PROXYRANDOMIZE = true;
  65. static const bool DEFAULT_REST_ENABLE = false;
  66. static const bool DEFAULT_DISABLE_SAFEMODE = false;
  67. static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
  68. std::unique_ptr<CConnman> g_connman;
  69. std::unique_ptr<PeerLogicValidation> peerLogic;
  70. #if ENABLE_ZMQ
  71. static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
  72. #endif
  73. #ifdef WIN32
  74. // Win32 LevelDB doesn't use filedescriptors, and the ones used for
  75. // accessing block files don't count towards the fd_set size limit
  76. // anyway.
  77. #define MIN_CORE_FILEDESCRIPTORS 0
  78. #else
  79. #define MIN_CORE_FILEDESCRIPTORS 150
  80. #endif
  81. /** Used to pass flags to the Bind() function */
  82. enum BindFlags {
  83. BF_NONE = 0,
  84. BF_EXPLICIT = (1U << 0),
  85. BF_REPORT_ERROR = (1U << 1),
  86. BF_WHITELIST = (1U << 2),
  87. };
  88. static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
  89. //////////////////////////////////////////////////////////////////////////////
  90. //
  91. // Shutdown
  92. //
  93. //
  94. // Thread management and startup/shutdown:
  95. //
  96. // The network-processing threads are all part of a thread group
  97. // created by AppInit() or the Qt main() function.
  98. //
  99. // A clean exit happens when StartShutdown() or the SIGTERM
  100. // signal handler sets fRequestShutdown, which triggers
  101. // the DetectShutdownThread(), which interrupts the main thread group.
  102. // DetectShutdownThread() then exits, which causes AppInit() to
  103. // continue (it .joins the shutdown thread).
  104. // Shutdown() is then
  105. // called to clean up database connections, and stop other
  106. // threads that should only be stopped after the main network-processing
  107. // threads have exited.
  108. //
  109. // Shutdown for Qt is very similar, only it uses a QTimer to detect
  110. // fRequestShutdown getting set, and then does the normal Qt
  111. // shutdown thing.
  112. //
  113. std::atomic<bool> fRequestShutdown(false);
  114. std::atomic<bool> fDumpMempoolLater(false);
  115. void StartShutdown()
  116. {
  117. fRequestShutdown = true;
  118. }
  119. bool ShutdownRequested()
  120. {
  121. return fRequestShutdown;
  122. }
  123. /**
  124. * This is a minimally invasive approach to shutdown on LevelDB read errors from the
  125. * chainstate, while keeping user interface out of the common library, which is shared
  126. * between bitcoind, and bitcoin-qt and non-server tools.
  127. */
  128. class CCoinsViewErrorCatcher : public CCoinsViewBacked
  129. {
  130. public:
  131. CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
  132. bool GetCoins(const uint256 &txid, CCoins &coins) const {
  133. try {
  134. return CCoinsViewBacked::GetCoins(txid, coins);
  135. } catch(const std::runtime_error& e) {
  136. uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
  137. LogPrintf("Error reading from database: %s\n", e.what());
  138. // Starting the shutdown sequence and returning false to the caller would be
  139. // interpreted as 'entry not found' (as opposed to unable to read data), and
  140. // could lead to invalid interpretation. Just exit immediately, as we can't
  141. // continue anyway, and all writes should be atomic.
  142. abort();
  143. }
  144. }
  145. // Writes do not need similar protection, as failure to write is handled by the caller.
  146. };
  147. static CCoinsViewDB *pcoinsdbview = NULL;
  148. static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
  149. static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
  150. void Interrupt(boost::thread_group& threadGroup)
  151. {
  152. InterruptHTTPServer();
  153. InterruptHTTPRPC();
  154. InterruptRPC();
  155. InterruptREST();
  156. InterruptTorControl();
  157. if (g_connman)
  158. g_connman->Interrupt();
  159. threadGroup.interrupt_all();
  160. }
  161. void Shutdown()
  162. {
  163. LogPrintf("%s: In progress...\n", __func__);
  164. static CCriticalSection cs_Shutdown;
  165. TRY_LOCK(cs_Shutdown, lockShutdown);
  166. if (!lockShutdown)
  167. return;
  168. /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
  169. /// for example if the data directory was found to be locked.
  170. /// Be sure that anything that writes files or flushes caches only does this if the respective
  171. /// module was initialized.
  172. RenameThread("bitcoin-shutoff");
  173. mempool.AddTransactionsUpdated(1);
  174. StopHTTPRPC();
  175. StopREST();
  176. StopRPC();
  177. StopHTTPServer();
  178. #ifdef ENABLE_WALLET
  179. if (pwalletMain)
  180. pwalletMain->Flush(false);
  181. #endif
  182. MapPort(false);
  183. UnregisterValidationInterface(peerLogic.get());
  184. peerLogic.reset();
  185. g_connman.reset();
  186. StopTorControl();
  187. UnregisterNodeSignals(GetNodeSignals());
  188. if (fDumpMempoolLater && GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
  189. DumpMempool();
  190. }
  191. if (fFeeEstimatesInitialized)
  192. {
  193. fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
  194. CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
  195. if (!est_fileout.IsNull())
  196. ::feeEstimator.Write(est_fileout);
  197. else
  198. LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
  199. fFeeEstimatesInitialized = false;
  200. }
  201. {
  202. LOCK(cs_main);
  203. if (pcoinsTip != NULL) {
  204. FlushStateToDisk();
  205. }
  206. delete pcoinsTip;
  207. pcoinsTip = NULL;
  208. delete pcoinscatcher;
  209. pcoinscatcher = NULL;
  210. delete pcoinsdbview;
  211. pcoinsdbview = NULL;
  212. delete pblocktree;
  213. pblocktree = NULL;
  214. }
  215. #ifdef ENABLE_WALLET
  216. if (pwalletMain)
  217. pwalletMain->Flush(true);
  218. #endif
  219. #if ENABLE_ZMQ
  220. if (pzmqNotificationInterface) {
  221. UnregisterValidationInterface(pzmqNotificationInterface);
  222. delete pzmqNotificationInterface;
  223. pzmqNotificationInterface = NULL;
  224. }
  225. #endif
  226. #ifndef WIN32
  227. try {
  228. fs::remove(GetPidFile());
  229. } catch (const fs::filesystem_error& e) {
  230. LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
  231. }
  232. #endif
  233. UnregisterAllValidationInterfaces();
  234. #ifdef ENABLE_WALLET
  235. delete pwalletMain;
  236. pwalletMain = NULL;
  237. #endif
  238. globalVerifyHandle.reset();
  239. ECC_Stop();
  240. LogPrintf("%s: done\n", __func__);
  241. }
  242. /**
  243. * Signal handlers are very limited in what they are allowed to do.
  244. * The execution context the handler is invoked in is not guaranteed,
  245. * so we restrict handler operations to just touching variables:
  246. */
  247. static void HandleSIGTERM(int)
  248. {
  249. fRequestShutdown = true;
  250. }
  251. static void HandleSIGHUP(int)
  252. {
  253. fReopenDebugLog = true;
  254. }
  255. #ifndef WIN32
  256. static void registerSignalHandler(int signal, void(*handler)(int))
  257. {
  258. struct sigaction sa;
  259. sa.sa_handler = handler;
  260. sigemptyset(&sa.sa_mask);
  261. sa.sa_flags = 0;
  262. sigaction(signal, &sa, NULL);
  263. }
  264. #endif
  265. bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
  266. if (!(flags & BF_EXPLICIT) && IsLimited(addr))
  267. return false;
  268. std::string strError;
  269. if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
  270. if (flags & BF_REPORT_ERROR)
  271. return InitError(strError);
  272. return false;
  273. }
  274. return true;
  275. }
  276. void OnRPCStarted()
  277. {
  278. uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
  279. }
  280. void OnRPCStopped()
  281. {
  282. uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
  283. RPCNotifyBlockChange(false, nullptr);
  284. cvBlockChange.notify_all();
  285. LogPrint(BCLog::RPC, "RPC stopped.\n");
  286. }
  287. void OnRPCPreCommand(const CRPCCommand& cmd)
  288. {
  289. // Observe safe mode
  290. std::string strWarning = GetWarnings("rpc");
  291. if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
  292. !cmd.okSafeMode)
  293. throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
  294. }
  295. std::string HelpMessage(HelpMessageMode mode)
  296. {
  297. const bool showDebug = GetBoolArg("-help-debug", false);
  298. // When adding new options to the categories, please keep and ensure alphabetical ordering.
  299. // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
  300. std::string strUsage = HelpMessageGroup(_("Options:"));
  301. strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
  302. strUsage += HelpMessageOpt("-version", _("Print version and exit"));
  303. strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
  304. strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
  305. if (showDebug)
  306. strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
  307. strUsage +=HelpMessageOpt("-assumevalid=<hex>", strprintf(_("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)"), Params(CBaseChainParams::MAIN).GetConsensus().defaultAssumeValid.GetHex(), Params(CBaseChainParams::TESTNET).GetConsensus().defaultAssumeValid.GetHex()));
  308. strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
  309. if (mode == HMM_BITCOIND)
  310. {
  311. #if HAVE_DECL_DAEMON
  312. strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
  313. #endif
  314. }
  315. strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
  316. strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
  317. if (showDebug)
  318. strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
  319. strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
  320. strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
  321. strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
  322. strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
  323. strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
  324. strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
  325. strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
  326. -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
  327. #ifndef WIN32
  328. strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
  329. #endif
  330. strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. "
  331. "Warning: Reverting this setting requires re-downloading the entire blockchain. "
  332. "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u = automatically prune block files to stay under the specified target size in MiB)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
  333. strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
  334. strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
  335. #ifndef WIN32
  336. strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
  337. #endif
  338. strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
  339. strUsage += HelpMessageGroup(_("Connection options:"));
  340. strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
  341. strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
  342. strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
  343. strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
  344. strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections"));
  345. strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
  346. strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
  347. strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
  348. strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
  349. strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
  350. strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
  351. strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
  352. strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
  353. strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
  354. strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
  355. strUsage += HelpMessageOpt("-maxtimeadjustment", strprintf(_("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT));
  356. strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
  357. strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
  358. strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
  359. strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
  360. strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
  361. strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
  362. strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
  363. strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
  364. strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
  365. strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
  366. strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
  367. #ifdef USE_UPNP
  368. #if USE_UPNP
  369. strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
  370. #else
  371. strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
  372. #endif
  373. #endif
  374. strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
  375. strUsage += HelpMessageOpt("-whitelist=<IP address or network>", _("Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.") +
  376. " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway"));
  377. strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
  378. #ifdef ENABLE_WALLET
  379. strUsage += CWallet::GetWalletHelpString(showDebug);
  380. #endif
  381. #if ENABLE_ZMQ
  382. strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
  383. strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
  384. strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
  385. strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
  386. strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
  387. #endif
  388. strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
  389. strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
  390. if (showDebug)
  391. {
  392. strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
  393. strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
  394. strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
  395. strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
  396. strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
  397. strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
  398. strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
  399. strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
  400. strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
  401. strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
  402. strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
  403. strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
  404. strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT));
  405. strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
  406. strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
  407. strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
  408. }
  409. strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
  410. _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
  411. strUsage += HelpMessageOpt("-debugexclude=<category>", strprintf(_("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories.")));
  412. strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
  413. strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
  414. strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
  415. if (showDebug)
  416. {
  417. strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
  418. strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
  419. strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
  420. strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
  421. }
  422. strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)"),
  423. CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
  424. strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
  425. if (showDebug)
  426. {
  427. strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
  428. }
  429. strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
  430. AppendParamsHelpMessages(strUsage, showDebug);
  431. strUsage += HelpMessageGroup(_("Node relay options:"));
  432. if (showDebug) {
  433. strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
  434. strUsage += HelpMessageOpt("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)));
  435. strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost about 1/3 of its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
  436. }
  437. strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
  438. strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
  439. strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
  440. strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
  441. strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
  442. CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
  443. strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
  444. strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
  445. strUsage += HelpMessageGroup(_("Block creation options:"));
  446. strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
  447. strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
  448. strUsage += HelpMessageOpt("-blockmintxfee=<amt>", strprintf(_("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)));
  449. if (showDebug)
  450. strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
  451. strUsage += HelpMessageGroup(_("RPC server options:"));
  452. strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
  453. strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
  454. strUsage += HelpMessageOpt("-rpcbind=<addr>[:port]", _("Bind to given address to listen for JSON-RPC connections. This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)"));
  455. strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
  456. strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
  457. strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
  458. strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times"));
  459. strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
  460. strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"));
  461. strUsage += HelpMessageOpt("-rpcserialversion", strprintf(_("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)"), DEFAULT_RPC_SERIALIZE_VERSION));
  462. strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
  463. if (showDebug) {
  464. strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
  465. strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
  466. }
  467. return strUsage;
  468. }
  469. std::string LicenseInfo()
  470. {
  471. const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
  472. const std::string URL_WEBSITE = "<https://bitcoincore.org>";
  473. return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
  474. "\n" +
  475. strprintf(_("Please contribute if you find %s useful. "
  476. "Visit %s for further information about the software."),
  477. PACKAGE_NAME, URL_WEBSITE) +
  478. "\n" +
  479. strprintf(_("The source code is available from %s."),
  480. URL_SOURCE_CODE) +
  481. "\n" +
  482. "\n" +
  483. _("This is experimental software.") + "\n" +
  484. strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
  485. "\n" +
  486. strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") +
  487. "\n";
  488. }
  489. static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
  490. {
  491. if (initialSync || !pBlockIndex)
  492. return;
  493. std::string strCmd = GetArg("-blocknotify", "");
  494. boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
  495. boost::thread t(runCommand, strCmd); // thread runs free
  496. }
  497. static bool fHaveGenesis = false;
  498. static boost::mutex cs_GenesisWait;
  499. static CConditionVariable condvar_GenesisWait;
  500. static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
  501. {
  502. if (pBlockIndex != NULL) {
  503. {
  504. boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
  505. fHaveGenesis = true;
  506. }
  507. condvar_GenesisWait.notify_all();
  508. }
  509. }
  510. struct CImportingNow
  511. {
  512. CImportingNow() {
  513. assert(fImporting == false);
  514. fImporting = true;
  515. }
  516. ~CImportingNow() {
  517. assert(fImporting == true);
  518. fImporting = false;
  519. }
  520. };
  521. // If we're using -prune with -reindex, then delete block files that will be ignored by the
  522. // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
  523. // is missing, do the same here to delete any later block files after a gap. Also delete all
  524. // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
  525. // is in sync with what's actually on disk by the time we start downloading, so that pruning
  526. // works correctly.
  527. void CleanupBlockRevFiles()
  528. {
  529. std::map<std::string, fs::path> mapBlockFiles;
  530. // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
  531. // Remove the rev files immediately and insert the blk file paths into an
  532. // ordered map keyed by block file index.
  533. LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
  534. fs::path blocksdir = GetDataDir() / "blocks";
  535. for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
  536. if (is_regular_file(*it) &&
  537. it->path().filename().string().length() == 12 &&
  538. it->path().filename().string().substr(8,4) == ".dat")
  539. {
  540. if (it->path().filename().string().substr(0,3) == "blk")
  541. mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
  542. else if (it->path().filename().string().substr(0,3) == "rev")
  543. remove(it->path());
  544. }
  545. }
  546. // Remove all block files that aren't part of a contiguous set starting at
  547. // zero by walking the ordered map (keys are block file indices) by
  548. // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
  549. // start removing block files.
  550. int nContigCounter = 0;
  551. BOOST_FOREACH(const PAIRTYPE(std::string, fs::path)& item, mapBlockFiles) {
  552. if (atoi(item.first) == nContigCounter) {
  553. nContigCounter++;
  554. continue;
  555. }
  556. remove(item.second);
  557. }
  558. }
  559. void ThreadImport(std::vector<fs::path> vImportFiles)
  560. {
  561. const CChainParams& chainparams = Params();
  562. RenameThread("bitcoin-loadblk");
  563. {
  564. CImportingNow imp;
  565. // -reindex
  566. if (fReindex) {
  567. int nFile = 0;
  568. while (true) {
  569. CDiskBlockPos pos(nFile, 0);
  570. if (!fs::exists(GetBlockPosFilename(pos, "blk")))
  571. break; // No block files left to reindex
  572. FILE *file = OpenBlockFile(pos, true);
  573. if (!file)
  574. break; // This error is logged in OpenBlockFile
  575. LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
  576. LoadExternalBlockFile(chainparams, file, &pos);
  577. nFile++;
  578. }
  579. pblocktree->WriteReindexing(false);
  580. fReindex = false;
  581. LogPrintf("Reindexing finished\n");
  582. // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
  583. InitBlockIndex(chainparams);
  584. }
  585. // hardcoded $DATADIR/bootstrap.dat
  586. fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
  587. if (fs::exists(pathBootstrap)) {
  588. FILE *file = fsbridge::fopen(pathBootstrap, "rb");
  589. if (file) {
  590. fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
  591. LogPrintf("Importing bootstrap.dat...\n");
  592. LoadExternalBlockFile(chainparams, file);
  593. RenameOver(pathBootstrap, pathBootstrapOld);
  594. } else {
  595. LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
  596. }
  597. }
  598. // -loadblock=
  599. BOOST_FOREACH(const fs::path& path, vImportFiles) {
  600. FILE *file = fsbridge::fopen(path, "rb");
  601. if (file) {
  602. LogPrintf("Importing blocks file %s...\n", path.string());
  603. LoadExternalBlockFile(chainparams, file);
  604. } else {
  605. LogPrintf("Warning: Could not open blocks file %s\n", path.string());
  606. }
  607. }
  608. // scan for better chains in the block chain database, that are not yet connected in the active best chain
  609. CValidationState state;
  610. if (!ActivateBestChain(state, chainparams)) {
  611. LogPrintf("Failed to connect best block");
  612. StartShutdown();
  613. }
  614. if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
  615. LogPrintf("Stopping after block import\n");
  616. StartShutdown();
  617. }
  618. } // End scope of CImportingNow
  619. if (GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
  620. LoadMempool();
  621. fDumpMempoolLater = !fRequestShutdown;
  622. }
  623. }
  624. /** Sanity checks
  625. * Ensure that Bitcoin is running in a usable environment with all
  626. * necessary library support.
  627. */
  628. bool InitSanityCheck(void)
  629. {
  630. if(!ECC_InitSanityCheck()) {
  631. InitError("Elliptic curve cryptography sanity check failure. Aborting.");
  632. return false;
  633. }
  634. if (!glibc_sanity_test() || !glibcxx_sanity_test())
  635. return false;
  636. if (!Random_SanityCheck()) {
  637. InitError("OS cryptographic RNG sanity check failure. Aborting.");
  638. return false;
  639. }
  640. return true;
  641. }
  642. bool AppInitServers(boost::thread_group& threadGroup)
  643. {
  644. RPCServer::OnStarted(&OnRPCStarted);
  645. RPCServer::OnStopped(&OnRPCStopped);
  646. RPCServer::OnPreCommand(&OnRPCPreCommand);
  647. if (!InitHTTPServer())
  648. return false;
  649. if (!StartRPC())
  650. return false;
  651. if (!StartHTTPRPC())
  652. return false;
  653. if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
  654. return false;
  655. if (!StartHTTPServer())
  656. return false;
  657. return true;
  658. }
  659. // Parameter interaction based on rules
  660. void InitParameterInteraction()
  661. {
  662. // when specifying an explicit binding address, you want to listen on it
  663. // even when -connect or -proxy is specified
  664. if (IsArgSet("-bind")) {
  665. if (SoftSetBoolArg("-listen", true))
  666. LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
  667. }
  668. if (IsArgSet("-whitebind")) {
  669. if (SoftSetBoolArg("-listen", true))
  670. LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
  671. }
  672. if (gArgs.IsArgSet("-connect")) {
  673. // when only connecting to trusted nodes, do not seed via DNS, or listen by default
  674. if (SoftSetBoolArg("-dnsseed", false))
  675. LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
  676. if (SoftSetBoolArg("-listen", false))
  677. LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
  678. }
  679. if (IsArgSet("-proxy")) {
  680. // to protect privacy, do not listen by default if a default proxy server is specified
  681. if (SoftSetBoolArg("-listen", false))
  682. LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
  683. // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
  684. // to listen locally, so don't rely on this happening through -listen below.
  685. if (SoftSetBoolArg("-upnp", false))
  686. LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
  687. // to protect privacy, do not discover addresses by default
  688. if (SoftSetBoolArg("-discover", false))
  689. LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
  690. }
  691. if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
  692. // do not map ports or try to retrieve public IP when not listening (pointless)
  693. if (SoftSetBoolArg("-upnp", false))
  694. LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
  695. if (SoftSetBoolArg("-discover", false))
  696. LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
  697. if (SoftSetBoolArg("-listenonion", false))
  698. LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
  699. }
  700. if (IsArgSet("-externalip")) {
  701. // if an explicit public IP is specified, do not try to find others
  702. if (SoftSetBoolArg("-discover", false))
  703. LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
  704. }
  705. // disable whitelistrelay in blocksonly mode
  706. if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
  707. if (SoftSetBoolArg("-whitelistrelay", false))
  708. LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
  709. }
  710. // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
  711. if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
  712. if (SoftSetBoolArg("-whitelistrelay", true))
  713. LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
  714. }
  715. }
  716. static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
  717. {
  718. return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
  719. }
  720. void InitLogging()
  721. {
  722. fPrintToConsole = GetBoolArg("-printtoconsole", false);
  723. fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
  724. fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
  725. fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
  726. LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  727. LogPrintf("Bitcoin version %s\n", FormatFullVersion());
  728. }
  729. namespace { // Variables internal to initialization process only
  730. ServiceFlags nRelevantServices = NODE_NETWORK;
  731. int nMaxConnections;
  732. int nUserMaxConnections;
  733. int nFD;
  734. ServiceFlags nLocalServices = NODE_NETWORK;
  735. }
  736. [[noreturn]] static void new_handler_terminate()
  737. {
  738. // Rather than throwing std::bad-alloc if allocation fails, terminate
  739. // immediately to (try to) avoid chain corruption.
  740. // Since LogPrintf may itself allocate memory, set the handler directly
  741. // to terminate first.
  742. std::set_new_handler(std::terminate);
  743. LogPrintf("Error: Out of memory. Terminating.\n");
  744. // The log was successful, terminate now.
  745. std::terminate();
  746. };
  747. bool AppInitBasicSetup()
  748. {
  749. // ********************************************************* Step 1: setup
  750. #ifdef _MSC_VER
  751. // Turn off Microsoft heap dump noise
  752. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  753. _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  754. #endif
  755. #if _MSC_VER >= 1400
  756. // Disable confusing "helpful" text message on abort, Ctrl-C
  757. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  758. #endif
  759. #ifdef WIN32
  760. // Enable Data Execution Prevention (DEP)
  761. // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
  762. // A failure is non-critical and needs no further attention!
  763. #ifndef PROCESS_DEP_ENABLE
  764. // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
  765. // which is not correct. Can be removed, when GCCs winbase.h is fixed!
  766. #define PROCESS_DEP_ENABLE 0x00000001
  767. #endif
  768. typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
  769. PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
  770. if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
  771. #endif
  772. if (!SetupNetworking())
  773. return InitError("Initializing networking failed");
  774. #ifndef WIN32
  775. if (!GetBoolArg("-sysperms", false)) {
  776. umask(077);
  777. }
  778. // Clean shutdown on SIGTERM
  779. registerSignalHandler(SIGTERM, HandleSIGTERM);
  780. registerSignalHandler(SIGINT, HandleSIGTERM);
  781. // Reopen debug.log on SIGHUP
  782. registerSignalHandler(SIGHUP, HandleSIGHUP);
  783. // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
  784. signal(SIGPIPE, SIG_IGN);
  785. #endif
  786. std::set_new_handler(new_handler_terminate);
  787. return true;
  788. }
  789. bool AppInitParameterInteraction()
  790. {
  791. const CChainParams& chainparams = Params();
  792. // ********************************************************* Step 2: parameter interactions
  793. // also see: InitParameterInteraction()
  794. // if using block pruning, then disallow txindex
  795. if (GetArg("-prune", 0)) {
  796. if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
  797. return InitError(_("Prune mode is incompatible with -txindex."));
  798. }
  799. // Make sure enough file descriptors are available
  800. int nBind = std::max(
  801. (gArgs.IsArgSet("-bind") ? gArgs.GetArgs("-bind").size() : 0) +
  802. (gArgs.IsArgSet("-whitebind") ? gArgs.GetArgs("-whitebind").size() : 0), size_t(1));
  803. nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
  804. nMaxConnections = std::max(nUserMaxConnections, 0);
  805. // Trim requested connection counts, to fit into system limitations
  806. nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
  807. nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
  808. if (nFD < MIN_CORE_FILEDESCRIPTORS)
  809. return InitError(_("Not enough file descriptors available."));
  810. nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
  811. if (nMaxConnections < nUserMaxConnections)
  812. InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
  813. // ********************************************************* Step 3: parameter-to-internal-flags
  814. if (gArgs.IsArgSet("-debug")) {
  815. // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
  816. const std::vector<std::string> categories = gArgs.GetArgs("-debug");
  817. if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
  818. for (const auto& cat : categories) {
  819. uint32_t flag = 0;
  820. if (!GetLogCategory(&flag, &cat)) {
  821. InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
  822. continue;
  823. }
  824. logCategories |= flag;
  825. }
  826. }
  827. }
  828. // Now remove the logging categories which were explicitly excluded
  829. if (gArgs.IsArgSet("-debugexclude")) {
  830. for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
  831. uint32_t flag = 0;
  832. if (!GetLogCategory(&flag, &cat)) {
  833. InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
  834. continue;
  835. }
  836. logCategories &= ~flag;
  837. }
  838. }
  839. // Check for -debugnet
  840. if (GetBoolArg("-debugnet", false))
  841. InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
  842. // Check for -socks - as this is a privacy risk to continue, exit here
  843. if (IsArgSet("-socks"))
  844. return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
  845. // Check for -tor - as this is a privacy risk to continue, exit here
  846. if (GetBoolArg("-tor", false))
  847. return InitError(_("Unsupported argument -tor found, use -onion."));
  848. if (GetBoolArg("-benchmark", false))
  849. InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
  850. if (GetBoolArg("-whitelistalwaysrelay", false))
  851. InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
  852. if (IsArgSet("-blockminsize"))
  853. InitWarning("Unsupported argument -blockminsize ignored.");
  854. // Checkmempool and checkblockindex default to true in regtest mode
  855. int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
  856. if (ratio != 0) {
  857. mempool.setSanityCheck(1.0 / ratio);
  858. }
  859. fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
  860. fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
  861. hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
  862. if (!hashAssumeValid.IsNull())
  863. LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
  864. else
  865. LogPrintf("Validating signatures for all blocks.\n");
  866. // mempool limits
  867. int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
  868. int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
  869. if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
  870. return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
  871. // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
  872. // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
  873. if (IsArgSet("-incrementalrelayfee"))
  874. {
  875. CAmount n = 0;
  876. if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
  877. return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
  878. incrementalRelayFee = CFeeRate(n);
  879. }
  880. // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
  881. nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
  882. if (nScriptCheckThreads <= 0)
  883. nScriptCheckThreads += GetNumCores();
  884. if (nScriptCheckThreads <= 1)
  885. nScriptCheckThreads = 0;
  886. else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
  887. nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
  888. // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
  889. int64_t nPruneArg = GetArg("-prune", 0);
  890. if (nPruneArg < 0) {
  891. return InitError(_("Prune cannot be configured with a negative value."));
  892. }
  893. nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
  894. if (nPruneArg == 1) { // manual pruning: -prune=1
  895. LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
  896. nPruneTarget = std::numeric_limits<uint64_t>::max();
  897. fPruneMode = true;
  898. } else if (nPruneTarget) {
  899. if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
  900. return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
  901. }
  902. LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
  903. fPruneMode = true;
  904. }
  905. RegisterAllCoreRPCCommands(tableRPC);
  906. #ifdef ENABLE_WALLET
  907. RegisterWalletRPCCommands(tableRPC);
  908. #endif
  909. nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
  910. if (nConnectTimeout <= 0)
  911. nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
  912. // Fee-per-kilobyte amount required for mempool acceptance and relay
  913. // If you are mining, be careful setting this:
  914. // if you set it to zero then
  915. // a transaction spammer can cheaply fill blocks using
  916. // 0-fee transactions. It should be set above the real
  917. // cost to you of processing a transaction.
  918. if (IsArgSet("-minrelaytxfee"))
  919. {
  920. CAmount n = 0;
  921. if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
  922. return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
  923. }
  924. // High fee check is done afterward in CWallet::ParameterInteraction()
  925. ::minRelayTxFee = CFeeRate(n);
  926. } else if (incrementalRelayFee > ::minRelayTxFee) {
  927. // Allow only setting incrementalRelayFee to control both
  928. ::minRelayTxFee = incrementalRelayFee;
  929. LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
  930. }
  931. // Sanity check argument for min fee for including tx in block
  932. // TODO: Harmonize which arguments need sanity checking and where that happens
  933. if (IsArgSet("-blockmintxfee"))
  934. {
  935. CAmount n = 0;
  936. if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
  937. return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
  938. }
  939. // Feerate used to define dust. Shouldn't be changed lightly as old
  940. // implementations may inadvertently create non-standard transactions
  941. if (IsArgSet("-dustrelayfee"))
  942. {
  943. CAmount n = 0;
  944. if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
  945. return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
  946. dustRelayFee = CFeeRate(n);
  947. }
  948. fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
  949. if (chainparams.RequireStandard() && !fRequireStandard)
  950. return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
  951. nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
  952. #ifdef ENABLE_WALLET
  953. if (!CWallet::ParameterInteraction())
  954. return false;
  955. #endif
  956. fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
  957. fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
  958. nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
  959. // Option to startup with mocktime set (used for regression testing):
  960. SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
  961. if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
  962. nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
  963. if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
  964. return InitError("rpcserialversion must be non-negative.");
  965. if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
  966. return InitError("unknown rpcserialversion requested.");
  967. nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
  968. fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
  969. if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
  970. // Minimal effort at forwards compatibility
  971. std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
  972. std::vector<std::string> vstrReplacementModes;
  973. boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
  974. fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
  975. }
  976. if (gArgs.IsArgSet("-bip9params")) {
  977. // Allow overriding BIP9 parameters for testing
  978. if (!chainparams.MineBlocksOnDemand()) {
  979. return InitError("BIP9 parameters may only be overridden on regtest.");
  980. }
  981. for (const std::string& strDeployment : gArgs.GetArgs("-bip9params")) {
  982. std::vector<std::string> vDeploymentParams;
  983. boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
  984. if (vDeploymentParams.size() != 3) {
  985. return InitError("BIP9 parameters malformed, expecting deployment:start:end");
  986. }
  987. int64_t nStartTime, nTimeout;
  988. if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
  989. return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
  990. }
  991. if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
  992. return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
  993. }
  994. bool found = false;
  995. for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
  996. {
  997. if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
  998. UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
  999. found = true;
  1000. LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
  1001. break;
  1002. }
  1003. }
  1004. if (!found) {
  1005. return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
  1006. }
  1007. }
  1008. }
  1009. return true;
  1010. }
  1011. static bool LockDataDirectory(bool probeOnly)
  1012. {
  1013. std::string strDataDir = GetDataDir().string();
  1014. // Make sure only a single Bitcoin process is using the data directory.
  1015. fs::path pathLockFile = GetDataDir() / ".lock";
  1016. FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
  1017. if (file) fclose(file);
  1018. try {
  1019. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  1020. if (!lock.try_lock()) {
  1021. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
  1022. }
  1023. if (probeOnly) {
  1024. lock.unlock();
  1025. }
  1026. } catch(const boost::interprocess::interprocess_exception& e) {
  1027. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
  1028. }
  1029. return true;
  1030. }
  1031. bool AppInitSanityChecks()
  1032. {
  1033. // ********************************************************* Step 4: sanity checks
  1034. // Initialize elliptic curve code
  1035. ECC_Start();
  1036. globalVerifyHandle.reset(new ECCVerifyHandle());
  1037. // Sanity check
  1038. if (!InitSanityCheck())
  1039. return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
  1040. // Probe the data directory lock to give an early error message, if possible
  1041. return LockDataDirectory(true);
  1042. }
  1043. bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
  1044. {
  1045. const CChainParams& chainparams = Params();
  1046. // ********************************************************* Step 4a: application initialization
  1047. // After daemonization get the data directory lock again and hold on to it until exit
  1048. // This creates a slight window for a race condition to happen, however this condition is harmless: it
  1049. // will at most make us exit without printing a message to console.
  1050. if (!LockDataDirectory(false)) {
  1051. // Detailed error printed inside LockDataDirectory
  1052. return false;
  1053. }
  1054. #ifndef WIN32
  1055. CreatePidFile(GetPidFile(), getpid());
  1056. #endif
  1057. if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
  1058. // Do this first since it both loads a bunch of debug.log into memory,
  1059. // and because this needs to happen before any other debug.log printing
  1060. ShrinkDebugFile();
  1061. }
  1062. if (fPrintToDebugLog)
  1063. OpenDebugLog();
  1064. if (!fLogTimestamps)
  1065. LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
  1066. LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
  1067. LogPrintf("Using data directory %s\n", GetDataDir().string());
  1068. LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
  1069. LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
  1070. InitSignatureCache();
  1071. LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
  1072. if (nScriptCheckThreads) {
  1073. for (int i=0; i<nScriptCheckThreads-1; i++)
  1074. threadGroup.create_thread(&ThreadScriptCheck);
  1075. }
  1076. // Start the lightweight task scheduler thread
  1077. CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
  1078. threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
  1079. /* Start the RPC server already. It will be started in "warmup" mode
  1080. * and not really process calls already (but it will signify connections
  1081. * that the server is there and will be ready later). Warmup mode will
  1082. * be disabled when initialisation is finished.
  1083. */
  1084. if (GetBoolArg("-server", false))
  1085. {
  1086. uiInterface.InitMessage.connect(SetRPCWarmupStatus);
  1087. if (!AppInitServers(threadGroup))
  1088. return InitError(_("Unable to start HTTP server. See debug log for details."));
  1089. }
  1090. int64_t nStart;
  1091. // ********************************************************* Step 5: verify wallet database integrity
  1092. #ifdef ENABLE_WALLET
  1093. if (!CWallet::Verify())
  1094. return false;
  1095. #endif
  1096. // ********************************************************* Step 6: network initialization
  1097. // Note that we absolutely cannot open any actual connections
  1098. // until the very end ("start node") as the UTXO/block state
  1099. // is not yet setup and may end up being set up twice if we
  1100. // need to reindex later.
  1101. assert(!g_connman);
  1102. g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
  1103. CConnman& connman = *g_connman;
  1104. peerLogic.reset(new PeerLogicValidation(&connman));
  1105. RegisterValidationInterface(peerLogic.get());
  1106. RegisterNodeSignals(GetNodeSignals());
  1107. // sanitize comments per BIP-0014, format user agent and check total size
  1108. std::vector<std::string> uacomments;
  1109. if (gArgs.IsArgSet("-uacomment")) {
  1110. BOOST_FOREACH(std::string cmt, gArgs.GetArgs("-uacomment"))
  1111. {
  1112. if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
  1113. return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
  1114. uacomments.push_back(cmt);
  1115. }
  1116. }
  1117. strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
  1118. if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
  1119. return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
  1120. strSubVersion.size(), MAX_SUBVERSION_LENGTH));
  1121. }
  1122. if (gArgs.IsArgSet("-onlynet")) {
  1123. std::set<enum Network> nets;
  1124. BOOST_FOREACH(const std::string& snet, gArgs.GetArgs("-onlynet")) {
  1125. enum Network net = ParseNetwork(snet);
  1126. if (net == NET_UNROUTABLE)
  1127. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
  1128. nets.insert(net);
  1129. }
  1130. for (int n = 0; n < NET_MAX; n++) {
  1131. enum Network net = (enum Network)n;
  1132. if (!nets.count(net))
  1133. SetLimited(net);
  1134. }
  1135. }
  1136. if (gArgs.IsArgSet("-whitelist")) {
  1137. BOOST_FOREACH(const std::string& net, gArgs.GetArgs("-whitelist")) {
  1138. CSubNet subnet;
  1139. LookupSubNet(net.c_str(), subnet);
  1140. if (!subnet.IsValid())
  1141. return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
  1142. connman.AddWhitelistedRange(subnet);
  1143. }
  1144. }
  1145. // Check for host lookup allowed before parsing any network related parameters
  1146. fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
  1147. bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
  1148. // -proxy sets a proxy for all outgoing network traffic
  1149. // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
  1150. std::string proxyArg = GetArg("-proxy", "");
  1151. SetLimited(NET_TOR);
  1152. if (proxyArg != "" && proxyArg != "0") {
  1153. CService proxyAddr;
  1154. if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
  1155. return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
  1156. }
  1157. proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
  1158. if (!addrProxy.IsValid())
  1159. return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
  1160. SetProxy(NET_IPV4, addrProxy);
  1161. SetProxy(NET_IPV6, addrProxy);
  1162. SetProxy(NET_TOR, addrProxy);
  1163. SetNameProxy(addrProxy);
  1164. SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
  1165. }
  1166. // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
  1167. // -noonion (or -onion=0) disables connecting to .onion entirely
  1168. // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
  1169. std::string onionArg = GetArg("-onion", "");
  1170. if (onionArg != "") {
  1171. if (onionArg == "0") { // Handle -noonion/-onion=0
  1172. SetLimited(NET_TOR); // set onions as unreachable
  1173. } else {
  1174. CService onionProxy;
  1175. if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
  1176. return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
  1177. }
  1178. proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
  1179. if (!addrOnion.IsValid())
  1180. return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
  1181. SetProxy(NET_TOR, addrOnion);
  1182. SetLimited(NET_TOR, false);
  1183. }
  1184. }
  1185. // see Step 2: parameter interactions for more information about these
  1186. fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
  1187. fDiscover = GetBoolArg("-discover", true);
  1188. fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
  1189. if (fListen) {
  1190. bool fBound = false;
  1191. if (gArgs.IsArgSet("-bind")) {
  1192. BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-bind")) {
  1193. CService addrBind;
  1194. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  1195. return InitError(ResolveErrMsg("bind", strBind));
  1196. fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
  1197. }
  1198. }
  1199. if (gArgs.IsArgSet("-whitebind")) {
  1200. BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-whitebind")) {
  1201. CService addrBind;
  1202. if (!Lookup(strBind.c_str(), addrBind, 0, false))
  1203. return InitError(ResolveErrMsg("whitebind", strBind));
  1204. if (addrBind.GetPort() == 0)
  1205. return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
  1206. fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
  1207. }
  1208. }
  1209. if (!gArgs.IsArgSet("-bind") && !gArgs.IsArgSet("-whitebind")) {
  1210. struct in_addr inaddr_any;
  1211. inaddr_any.s_addr = INADDR_ANY;
  1212. fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
  1213. fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
  1214. }
  1215. if (!fBound)
  1216. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  1217. }
  1218. if (gArgs.IsArgSet("-externalip")) {
  1219. BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-externalip")) {
  1220. CService addrLocal;
  1221. if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
  1222. AddLocal(addrLocal, LOCAL_MANUAL);
  1223. else
  1224. return InitError(ResolveErrMsg("externalip", strAddr));
  1225. }
  1226. }
  1227. if (gArgs.IsArgSet("-seednode")) {
  1228. BOOST_FOREACH(const std::string& strDest, gArgs.GetArgs("-seednode"))
  1229. connman.AddOneShot(strDest);
  1230. }
  1231. #if ENABLE_ZMQ
  1232. pzmqNotificationInterface = CZMQNotificationInterface::Create();
  1233. if (pzmqNotificationInterface) {
  1234. RegisterValidationInterface(pzmqNotificationInterface);
  1235. }
  1236. #endif
  1237. uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
  1238. uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
  1239. if (IsArgSet("-maxuploadtarget")) {
  1240. nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
  1241. }
  1242. // ********************************************************* Step 7: load block chain
  1243. fReindex = GetBoolArg("-reindex", false);
  1244. bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
  1245. fs::create_directories(GetDataDir() / "blocks");
  1246. // cache size calculations
  1247. int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
  1248. nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
  1249. nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
  1250. int64_t nBlockTreeDBCache = nTotalCache / 8;
  1251. nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
  1252. nTotalCache -= nBlockTreeDBCache;
  1253. int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
  1254. nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
  1255. nTotalCache -= nCoinDBCache;
  1256. nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
  1257. int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
  1258. LogPrintf("Cache configuration:\n");
  1259. LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
  1260. LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
  1261. LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
  1262. bool fLoaded = false;
  1263. while (!fLoaded) {
  1264. bool fReset = fReindex;
  1265. std::string strLoadError;
  1266. uiInterface.InitMessage(_("Loading block index..."));
  1267. nStart = GetTimeMillis();
  1268. do {
  1269. try {
  1270. UnloadBlockIndex();
  1271. delete pcoinsTip;
  1272. delete pcoinsdbview;
  1273. delete pcoinscatcher;
  1274. delete pblocktree;
  1275. pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
  1276. pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
  1277. pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
  1278. pcoinsTip = new CCoinsViewCache(pcoinscatcher);
  1279. if (fReindex) {
  1280. pblocktree->WriteReindexing(true);
  1281. //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
  1282. if (fPruneMode)
  1283. CleanupBlockRevFiles();
  1284. }
  1285. if (!LoadBlockIndex(chainparams)) {
  1286. strLoadError = _("Error loading block database");
  1287. break;
  1288. }
  1289. // If the loaded chain has a wrong genesis, bail out immediately
  1290. // (we're likely using a testnet datadir, or the other way around).
  1291. if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
  1292. return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
  1293. // Initialize the block index (no-op if non-empty database was already loaded)
  1294. if (!InitBlockIndex(chainparams)) {
  1295. strLoadError = _("Error initializing block database");
  1296. break;
  1297. }
  1298. // Check for changed -txindex state
  1299. if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
  1300. strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
  1301. break;
  1302. }
  1303. // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
  1304. // in the past, but is now trying to run unpruned.
  1305. if (fHavePruned && !fPruneMode) {
  1306. strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
  1307. break;
  1308. }
  1309. if (!fReindex && chainActive.Tip() != NULL) {
  1310. uiInterface.InitMessage(_("Rewinding blocks..."));
  1311. if (!RewindBlockIndex(chainparams)) {
  1312. strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
  1313. break;
  1314. }
  1315. }
  1316. uiInterface.InitMessage(_("Verifying blocks..."));
  1317. if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
  1318. LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
  1319. MIN_BLOCKS_TO_KEEP);
  1320. }
  1321. {
  1322. LOCK(cs_main);
  1323. CBlockIndex* tip = chainActive.Tip();
  1324. RPCNotifyBlockChange(true, tip);
  1325. if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
  1326. strLoadError = _("The block database contains a block which appears to be from the future. "
  1327. "This may be due to your computer's date and time being set incorrectly. "
  1328. "Only rebuild the block database if you are sure that your computer's date and time are correct");
  1329. break;
  1330. }
  1331. }
  1332. if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
  1333. GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
  1334. strLoadError = _("Corrupted block database detected");
  1335. break;
  1336. }
  1337. } catch (const std::exception& e) {
  1338. LogPrintf("%s\n", e.what());
  1339. strLoadError = _("Error opening block database");
  1340. break;
  1341. }
  1342. fLoaded = true;
  1343. } while(false);
  1344. if (!fLoaded) {
  1345. // first suggest a reindex
  1346. if (!fReset) {
  1347. bool fRet = uiInterface.ThreadSafeQuestion(
  1348. strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
  1349. strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
  1350. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
  1351. if (fRet) {
  1352. fReindex = true;
  1353. fRequestShutdown = false;
  1354. } else {
  1355. LogPrintf("Aborted block database rebuild. Exiting.\n");
  1356. return false;
  1357. }
  1358. } else {
  1359. return InitError(strLoadError);
  1360. }
  1361. }
  1362. }
  1363. // As LoadBlockIndex can take several minutes, it's possible the user
  1364. // requested to kill the GUI during the last operation. If so, exit.
  1365. // As the program has not fully started yet, Shutdown() is possibly overkill.
  1366. if (fRequestShutdown)
  1367. {
  1368. LogPrintf("Shutdown requested. Exiting.\n");
  1369. return false;
  1370. }
  1371. LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
  1372. fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
  1373. CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
  1374. // Allowed to fail as this file IS missing on first startup.
  1375. if (!est_filein.IsNull())
  1376. ::feeEstimator.Read(est_filein);
  1377. fFeeEstimatesInitialized = true;
  1378. // ********************************************************* Step 8: load wallet
  1379. #ifdef ENABLE_WALLET
  1380. if (!CWallet::InitLoadWallet())
  1381. return false;
  1382. #else
  1383. LogPrintf("No wallet support compiled in!\n");
  1384. #endif
  1385. // ********************************************************* Step 9: data directory maintenance
  1386. // if pruning, unset the service bit and perform the initial blockstore prune
  1387. // after any wallet rescanning has taken place.
  1388. if (fPruneMode) {
  1389. LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
  1390. nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
  1391. if (!fReindex) {
  1392. uiInterface.InitMessage(_("Pruning blockstore..."));
  1393. PruneAndFlush();
  1394. }
  1395. }
  1396. if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
  1397. // Only advertise witness capabilities if they have a reasonable start time.
  1398. // This allows us to have the code merged without a defined softfork, by setting its
  1399. // end time to 0.
  1400. // Note that setting NODE_WITNESS is never required: the only downside from not
  1401. // doing so is that after activation, no upgraded nodes will fetch from you.
  1402. nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
  1403. // Only care about others providing witness capabilities if there is a softfork
  1404. // defined.
  1405. nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
  1406. }
  1407. // ********************************************************* Step 10: import blocks
  1408. if (!CheckDiskSpace())
  1409. return false;
  1410. // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
  1411. // No locking, as this happens before any background thread is started.
  1412. if (chainActive.Tip() == NULL) {
  1413. uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
  1414. } else {
  1415. fHaveGenesis = true;
  1416. }
  1417. if (IsArgSet("-blocknotify"))
  1418. uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
  1419. std::vector<fs::path> vImportFiles;
  1420. if (gArgs.IsArgSet("-loadblock"))
  1421. {
  1422. BOOST_FOREACH(const std::string& strFile, gArgs.GetArgs("-loadblock"))
  1423. vImportFiles.push_back(strFile);
  1424. }
  1425. threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
  1426. // Wait for genesis block to be processed
  1427. {
  1428. boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
  1429. while (!fHaveGenesis) {
  1430. condvar_GenesisWait.wait(lock);
  1431. }
  1432. uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
  1433. }
  1434. // ********************************************************* Step 11: start node
  1435. //// debug print
  1436. LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
  1437. LogPrintf("nBestHeight = %d\n", chainActive.Height());
  1438. if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
  1439. StartTorControl(threadGroup, scheduler);
  1440. Discover(threadGroup);
  1441. // Map ports with UPnP
  1442. MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
  1443. std::string strNodeError;
  1444. CConnman::Options connOptions;
  1445. connOptions.nLocalServices = nLocalServices;
  1446. connOptions.nRelevantServices = nRelevantServices;
  1447. connOptions.nMaxConnections = nMaxConnections;
  1448. connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
  1449. connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
  1450. connOptions.nMaxFeeler = 1;
  1451. connOptions.nBestHeight = chainActive.Height();
  1452. connOptions.uiInterface = &uiInterface;
  1453. connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
  1454. connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
  1455. connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
  1456. connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
  1457. if (!connman.Start(scheduler, strNodeError, connOptions))
  1458. return InitError(strNodeError);
  1459. // ********************************************************* Step 12: finished
  1460. SetRPCWarmupFinished();
  1461. uiInterface.InitMessage(_("Done loading"));
  1462. #ifdef ENABLE_WALLET
  1463. if (pwalletMain)
  1464. pwalletMain->postInitProcess(scheduler);
  1465. #endif
  1466. return !fRequestShutdown;
  1467. }