您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  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") && gArgs.GetArgs("-connect").size() > 0) {
  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") > 0) {
  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") > 0) {
  830. const std::vector<std::string>& excludedCategories = gArgs.GetArgs("-debugexclude");
  831. for (const auto& cat : excludedCategories) {
  832. uint32_t flag = 0;
  833. if (!GetLogCategory(&flag, &cat)) {
  834. InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
  835. continue;
  836. }
  837. logCategories &= ~flag;
  838. }
  839. }
  840. // Check for -debugnet
  841. if (GetBoolArg("-debugnet", false))
  842. InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
  843. // Check for -socks - as this is a privacy risk to continue, exit here
  844. if (IsArgSet("-socks"))
  845. return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
  846. // Check for -tor - as this is a privacy risk to continue, exit here
  847. if (GetBoolArg("-tor", false))
  848. return InitError(_("Unsupported argument -tor found, use -onion."));
  849. if (GetBoolArg("-benchmark", false))
  850. InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
  851. if (GetBoolArg("-whitelistalwaysrelay", false))
  852. InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
  853. if (IsArgSet("-blockminsize"))
  854. InitWarning("Unsupported argument -blockminsize ignored.");
  855. // Checkmempool and checkblockindex default to true in regtest mode
  856. int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
  857. if (ratio != 0) {
  858. mempool.setSanityCheck(1.0 / ratio);
  859. }
  860. fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
  861. fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
  862. hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
  863. if (!hashAssumeValid.IsNull())
  864. LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
  865. else
  866. LogPrintf("Validating signatures for all blocks.\n");
  867. // mempool limits
  868. int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
  869. int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
  870. if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
  871. return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
  872. // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
  873. // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
  874. if (IsArgSet("-incrementalrelayfee"))
  875. {
  876. CAmount n = 0;
  877. if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
  878. return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
  879. incrementalRelayFee = CFeeRate(n);
  880. }
  881. // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
  882. nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
  883. if (nScriptCheckThreads <= 0)
  884. nScriptCheckThreads += GetNumCores();
  885. if (nScriptCheckThreads <= 1)
  886. nScriptCheckThreads = 0;
  887. else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
  888. nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
  889. // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
  890. int64_t nPruneArg = GetArg("-prune", 0);
  891. if (nPruneArg < 0) {
  892. return InitError(_("Prune cannot be configured with a negative value."));
  893. }
  894. nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
  895. if (nPruneArg == 1) { // manual pruning: -prune=1
  896. LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
  897. nPruneTarget = std::numeric_limits<uint64_t>::max();
  898. fPruneMode = true;
  899. } else if (nPruneTarget) {
  900. if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
  901. return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
  902. }
  903. LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
  904. fPruneMode = true;
  905. }
  906. RegisterAllCoreRPCCommands(tableRPC);
  907. #ifdef ENABLE_WALLET
  908. RegisterWalletRPCCommands(tableRPC);
  909. #endif
  910. nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
  911. if (nConnectTimeout <= 0)
  912. nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
  913. // Fee-per-kilobyte amount required for mempool acceptance and relay
  914. // If you are mining, be careful setting this:
  915. // if you set it to zero then
  916. // a transaction spammer can cheaply fill blocks using
  917. // 0-fee transactions. It should be set above the real
  918. // cost to you of processing a transaction.
  919. if (IsArgSet("-minrelaytxfee"))
  920. {
  921. CAmount n = 0;
  922. if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
  923. return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
  924. }
  925. // High fee check is done afterward in CWallet::ParameterInteraction()
  926. ::minRelayTxFee = CFeeRate(n);
  927. } else if (incrementalRelayFee > ::minRelayTxFee) {
  928. // Allow only setting incrementalRelayFee to control both
  929. ::minRelayTxFee = incrementalRelayFee;
  930. LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
  931. }
  932. // Sanity check argument for min fee for including tx in block
  933. // TODO: Harmonize which arguments need sanity checking and where that happens
  934. if (IsArgSet("-blockmintxfee"))
  935. {
  936. CAmount n = 0;
  937. if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
  938. return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
  939. }
  940. // Feerate used to define dust. Shouldn't be changed lightly as old
  941. // implementations may inadvertently create non-standard transactions
  942. if (IsArgSet("-dustrelayfee"))
  943. {
  944. CAmount n = 0;
  945. if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
  946. return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
  947. dustRelayFee = CFeeRate(n);
  948. }
  949. fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
  950. if (chainparams.RequireStandard() && !fRequireStandard)
  951. return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
  952. nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
  953. #ifdef ENABLE_WALLET
  954. if (!CWallet::ParameterInteraction())
  955. return false;
  956. #endif
  957. fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
  958. fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
  959. nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
  960. // Option to startup with mocktime set (used for regression testing):
  961. SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
  962. if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
  963. nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
  964. if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
  965. return InitError("rpcserialversion must be non-negative.");
  966. if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
  967. return InitError("unknown rpcserialversion requested.");
  968. nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
  969. fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
  970. if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
  971. // Minimal effort at forwards compatibility
  972. std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
  973. std::vector<std::string> vstrReplacementModes;
  974. boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
  975. fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
  976. }
  977. if (gArgs.IsArgSet("-bip9params")) {
  978. // Allow overriding BIP9 parameters for testing
  979. if (!chainparams.MineBlocksOnDemand()) {
  980. return InitError("BIP9 parameters may only be overridden on regtest.");
  981. }
  982. const std::vector<std::string>& deployments = gArgs.GetArgs("-bip9params");
  983. for (auto i : deployments) {
  984. std::vector<std::string> vDeploymentParams;
  985. boost::split(vDeploymentParams, i, boost::is_any_of(":"));
  986. if (vDeploymentParams.size() != 3) {
  987. return InitError("BIP9 parameters malformed, expecting deployment:start:end");
  988. }
  989. int64_t nStartTime, nTimeout;
  990. if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
  991. return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
  992. }
  993. if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
  994. return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
  995. }
  996. bool found = false;
  997. for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
  998. {
  999. if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
  1000. UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
  1001. found = true;
  1002. LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
  1003. break;
  1004. }
  1005. }
  1006. if (!found) {
  1007. return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
  1008. }
  1009. }
  1010. }
  1011. return true;
  1012. }
  1013. static bool LockDataDirectory(bool probeOnly)
  1014. {
  1015. std::string strDataDir = GetDataDir().string();
  1016. // Make sure only a single Bitcoin process is using the data directory.
  1017. fs::path pathLockFile = GetDataDir() / ".lock";
  1018. FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
  1019. if (file) fclose(file);
  1020. try {
  1021. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  1022. if (!lock.try_lock()) {
  1023. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
  1024. }
  1025. if (probeOnly) {
  1026. lock.unlock();
  1027. }
  1028. } catch(const boost::interprocess::interprocess_exception& e) {
  1029. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
  1030. }
  1031. return true;
  1032. }
  1033. bool AppInitSanityChecks()
  1034. {
  1035. // ********************************************************* Step 4: sanity checks
  1036. // Initialize elliptic curve code
  1037. ECC_Start();
  1038. globalVerifyHandle.reset(new ECCVerifyHandle());
  1039. // Sanity check
  1040. if (!InitSanityCheck())
  1041. return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
  1042. // Probe the data directory lock to give an early error message, if possible
  1043. return LockDataDirectory(true);
  1044. }
  1045. bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
  1046. {
  1047. const CChainParams& chainparams = Params();
  1048. // ********************************************************* Step 4a: application initialization
  1049. // After daemonization get the data directory lock again and hold on to it until exit
  1050. // This creates a slight window for a race condition to happen, however this condition is harmless: it
  1051. // will at most make us exit without printing a message to console.
  1052. if (!LockDataDirectory(false)) {
  1053. // Detailed error printed inside LockDataDirectory
  1054. return false;
  1055. }
  1056. #ifndef WIN32
  1057. CreatePidFile(GetPidFile(), getpid());
  1058. #endif
  1059. if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
  1060. // Do this first since it both loads a bunch of debug.log into memory,
  1061. // and because this needs to happen before any other debug.log printing
  1062. ShrinkDebugFile();
  1063. }
  1064. if (fPrintToDebugLog)
  1065. OpenDebugLog();
  1066. if (!fLogTimestamps)
  1067. LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
  1068. LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
  1069. LogPrintf("Using data directory %s\n", GetDataDir().string());
  1070. LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
  1071. LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
  1072. InitSignatureCache();
  1073. LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
  1074. if (nScriptCheckThreads) {
  1075. for (int i=0; i<nScriptCheckThreads-1; i++)
  1076. threadGroup.create_thread(&ThreadScriptCheck);
  1077. }
  1078. // Start the lightweight task scheduler thread
  1079. CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
  1080. threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
  1081. /* Start the RPC server already. It will be started in "warmup" mode
  1082. * and not really process calls already (but it will signify connections
  1083. * that the server is there and will be ready later). Warmup mode will
  1084. * be disabled when initialisation is finished.
  1085. */
  1086. if (GetBoolArg("-server", false))
  1087. {
  1088. uiInterface.InitMessage.connect(SetRPCWarmupStatus);
  1089. if (!AppInitServers(threadGroup))
  1090. return InitError(_("Unable to start HTTP server. See debug log for details."));
  1091. }
  1092. int64_t nStart;
  1093. // ********************************************************* Step 5: verify wallet database integrity
  1094. #ifdef ENABLE_WALLET
  1095. if (!CWallet::Verify())
  1096. return false;
  1097. #endif
  1098. // ********************************************************* Step 6: network initialization
  1099. // Note that we absolutely cannot open any actual connections
  1100. // until the very end ("start node") as the UTXO/block state
  1101. // is not yet setup and may end up being set up twice if we
  1102. // need to reindex later.
  1103. assert(!g_connman);
  1104. g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
  1105. CConnman& connman = *g_connman;
  1106. peerLogic.reset(new PeerLogicValidation(&connman));
  1107. RegisterValidationInterface(peerLogic.get());
  1108. RegisterNodeSignals(GetNodeSignals());
  1109. // sanitize comments per BIP-0014, format user agent and check total size
  1110. std::vector<std::string> uacomments;
  1111. if (gArgs.IsArgSet("-uacomment")) {
  1112. BOOST_FOREACH(std::string cmt, gArgs.GetArgs("-uacomment"))
  1113. {
  1114. if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
  1115. return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
  1116. uacomments.push_back(cmt);
  1117. }
  1118. }
  1119. strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
  1120. if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
  1121. return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
  1122. strSubVersion.size(), MAX_SUBVERSION_LENGTH));
  1123. }
  1124. if (gArgs.IsArgSet("-onlynet")) {
  1125. std::set<enum Network> nets;
  1126. BOOST_FOREACH(const std::string& snet, gArgs.GetArgs("-onlynet")) {
  1127. enum Network net = ParseNetwork(snet);
  1128. if (net == NET_UNROUTABLE)
  1129. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
  1130. nets.insert(net);
  1131. }
  1132. for (int n = 0; n < NET_MAX; n++) {
  1133. enum Network net = (enum Network)n;
  1134. if (!nets.count(net))
  1135. SetLimited(net);
  1136. }
  1137. }
  1138. if (gArgs.IsArgSet("-whitelist")) {
  1139. BOOST_FOREACH(const std::string& net, gArgs.GetArgs("-whitelist")) {
  1140. CSubNet subnet;
  1141. LookupSubNet(net.c_str(), subnet);
  1142. if (!subnet.IsValid())
  1143. return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
  1144. connman.AddWhitelistedRange(subnet);
  1145. }
  1146. }
  1147. // Check for host lookup allowed before parsing any network related parameters
  1148. fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
  1149. bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
  1150. // -proxy sets a proxy for all outgoing network traffic
  1151. // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
  1152. std::string proxyArg = GetArg("-proxy", "");
  1153. SetLimited(NET_TOR);
  1154. if (proxyArg != "" && proxyArg != "0") {
  1155. CService proxyAddr;
  1156. if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
  1157. return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
  1158. }
  1159. proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
  1160. if (!addrProxy.IsValid())
  1161. return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
  1162. SetProxy(NET_IPV4, addrProxy);
  1163. SetProxy(NET_IPV6, addrProxy);
  1164. SetProxy(NET_TOR, addrProxy);
  1165. SetNameProxy(addrProxy);
  1166. SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
  1167. }
  1168. // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
  1169. // -noonion (or -onion=0) disables connecting to .onion entirely
  1170. // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
  1171. std::string onionArg = GetArg("-onion", "");
  1172. if (onionArg != "") {
  1173. if (onionArg == "0") { // Handle -noonion/-onion=0
  1174. SetLimited(NET_TOR); // set onions as unreachable
  1175. } else {
  1176. CService onionProxy;
  1177. if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
  1178. return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
  1179. }
  1180. proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
  1181. if (!addrOnion.IsValid())
  1182. return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
  1183. SetProxy(NET_TOR, addrOnion);
  1184. SetLimited(NET_TOR, false);
  1185. }
  1186. }
  1187. // see Step 2: parameter interactions for more information about these
  1188. fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
  1189. fDiscover = GetBoolArg("-discover", true);
  1190. fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
  1191. if (fListen) {
  1192. bool fBound = false;
  1193. if (gArgs.IsArgSet("-bind")) {
  1194. BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-bind")) {
  1195. CService addrBind;
  1196. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  1197. return InitError(ResolveErrMsg("bind", strBind));
  1198. fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
  1199. }
  1200. }
  1201. if (gArgs.IsArgSet("-whitebind")) {
  1202. BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-whitebind")) {
  1203. CService addrBind;
  1204. if (!Lookup(strBind.c_str(), addrBind, 0, false))
  1205. return InitError(ResolveErrMsg("whitebind", strBind));
  1206. if (addrBind.GetPort() == 0)
  1207. return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
  1208. fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
  1209. }
  1210. }
  1211. if (!gArgs.IsArgSet("-bind") && !gArgs.IsArgSet("-whitebind")) {
  1212. struct in_addr inaddr_any;
  1213. inaddr_any.s_addr = INADDR_ANY;
  1214. fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
  1215. fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
  1216. }
  1217. if (!fBound)
  1218. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  1219. }
  1220. if (gArgs.IsArgSet("-externalip")) {
  1221. BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-externalip")) {
  1222. CService addrLocal;
  1223. if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
  1224. AddLocal(addrLocal, LOCAL_MANUAL);
  1225. else
  1226. return InitError(ResolveErrMsg("externalip", strAddr));
  1227. }
  1228. }
  1229. if (gArgs.IsArgSet("-seednode")) {
  1230. BOOST_FOREACH(const std::string& strDest, gArgs.GetArgs("-seednode"))
  1231. connman.AddOneShot(strDest);
  1232. }
  1233. #if ENABLE_ZMQ
  1234. pzmqNotificationInterface = CZMQNotificationInterface::Create();
  1235. if (pzmqNotificationInterface) {
  1236. RegisterValidationInterface(pzmqNotificationInterface);
  1237. }
  1238. #endif
  1239. uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
  1240. uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
  1241. if (IsArgSet("-maxuploadtarget")) {
  1242. nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
  1243. }
  1244. // ********************************************************* Step 7: load block chain
  1245. fReindex = GetBoolArg("-reindex", false);
  1246. bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
  1247. fs::create_directories(GetDataDir() / "blocks");
  1248. // cache size calculations
  1249. int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
  1250. nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
  1251. nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
  1252. int64_t nBlockTreeDBCache = nTotalCache / 8;
  1253. nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
  1254. nTotalCache -= nBlockTreeDBCache;
  1255. int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
  1256. nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
  1257. nTotalCache -= nCoinDBCache;
  1258. nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
  1259. int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
  1260. LogPrintf("Cache configuration:\n");
  1261. LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
  1262. LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
  1263. 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));
  1264. bool fLoaded = false;
  1265. while (!fLoaded) {
  1266. bool fReset = fReindex;
  1267. std::string strLoadError;
  1268. uiInterface.InitMessage(_("Loading block index..."));
  1269. nStart = GetTimeMillis();
  1270. do {
  1271. try {
  1272. UnloadBlockIndex();
  1273. delete pcoinsTip;
  1274. delete pcoinsdbview;
  1275. delete pcoinscatcher;
  1276. delete pblocktree;
  1277. pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
  1278. pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
  1279. pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
  1280. pcoinsTip = new CCoinsViewCache(pcoinscatcher);
  1281. if (fReindex) {
  1282. pblocktree->WriteReindexing(true);
  1283. //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
  1284. if (fPruneMode)
  1285. CleanupBlockRevFiles();
  1286. }
  1287. if (!LoadBlockIndex(chainparams)) {
  1288. strLoadError = _("Error loading block database");
  1289. break;
  1290. }
  1291. // If the loaded chain has a wrong genesis, bail out immediately
  1292. // (we're likely using a testnet datadir, or the other way around).
  1293. if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
  1294. return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
  1295. // Initialize the block index (no-op if non-empty database was already loaded)
  1296. if (!InitBlockIndex(chainparams)) {
  1297. strLoadError = _("Error initializing block database");
  1298. break;
  1299. }
  1300. // Check for changed -txindex state
  1301. if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
  1302. strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
  1303. break;
  1304. }
  1305. // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
  1306. // in the past, but is now trying to run unpruned.
  1307. if (fHavePruned && !fPruneMode) {
  1308. strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
  1309. break;
  1310. }
  1311. if (!fReindex && chainActive.Tip() != NULL) {
  1312. uiInterface.InitMessage(_("Rewinding blocks..."));
  1313. if (!RewindBlockIndex(chainparams)) {
  1314. strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
  1315. break;
  1316. }
  1317. }
  1318. uiInterface.InitMessage(_("Verifying blocks..."));
  1319. if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
  1320. LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
  1321. MIN_BLOCKS_TO_KEEP);
  1322. }
  1323. {
  1324. LOCK(cs_main);
  1325. CBlockIndex* tip = chainActive.Tip();
  1326. RPCNotifyBlockChange(true, tip);
  1327. if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
  1328. strLoadError = _("The block database contains a block which appears to be from the future. "
  1329. "This may be due to your computer's date and time being set incorrectly. "
  1330. "Only rebuild the block database if you are sure that your computer's date and time are correct");
  1331. break;
  1332. }
  1333. }
  1334. if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
  1335. GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
  1336. strLoadError = _("Corrupted block database detected");
  1337. break;
  1338. }
  1339. } catch (const std::exception& e) {
  1340. LogPrintf("%s\n", e.what());
  1341. strLoadError = _("Error opening block database");
  1342. break;
  1343. }
  1344. fLoaded = true;
  1345. } while(false);
  1346. if (!fLoaded) {
  1347. // first suggest a reindex
  1348. if (!fReset) {
  1349. bool fRet = uiInterface.ThreadSafeQuestion(
  1350. strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
  1351. strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
  1352. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
  1353. if (fRet) {
  1354. fReindex = true;
  1355. fRequestShutdown = false;
  1356. } else {
  1357. LogPrintf("Aborted block database rebuild. Exiting.\n");
  1358. return false;
  1359. }
  1360. } else {
  1361. return InitError(strLoadError);
  1362. }
  1363. }
  1364. }
  1365. // As LoadBlockIndex can take several minutes, it's possible the user
  1366. // requested to kill the GUI during the last operation. If so, exit.
  1367. // As the program has not fully started yet, Shutdown() is possibly overkill.
  1368. if (fRequestShutdown)
  1369. {
  1370. LogPrintf("Shutdown requested. Exiting.\n");
  1371. return false;
  1372. }
  1373. LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
  1374. fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
  1375. CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
  1376. // Allowed to fail as this file IS missing on first startup.
  1377. if (!est_filein.IsNull())
  1378. ::feeEstimator.Read(est_filein);
  1379. fFeeEstimatesInitialized = true;
  1380. // ********************************************************* Step 8: load wallet
  1381. #ifdef ENABLE_WALLET
  1382. if (!CWallet::InitLoadWallet())
  1383. return false;
  1384. #else
  1385. LogPrintf("No wallet support compiled in!\n");
  1386. #endif
  1387. // ********************************************************* Step 9: data directory maintenance
  1388. // if pruning, unset the service bit and perform the initial blockstore prune
  1389. // after any wallet rescanning has taken place.
  1390. if (fPruneMode) {
  1391. LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
  1392. nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
  1393. if (!fReindex) {
  1394. uiInterface.InitMessage(_("Pruning blockstore..."));
  1395. PruneAndFlush();
  1396. }
  1397. }
  1398. if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
  1399. // Only advertise witness capabilities if they have a reasonable start time.
  1400. // This allows us to have the code merged without a defined softfork, by setting its
  1401. // end time to 0.
  1402. // Note that setting NODE_WITNESS is never required: the only downside from not
  1403. // doing so is that after activation, no upgraded nodes will fetch from you.
  1404. nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
  1405. // Only care about others providing witness capabilities if there is a softfork
  1406. // defined.
  1407. nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
  1408. }
  1409. // ********************************************************* Step 10: import blocks
  1410. if (!CheckDiskSpace())
  1411. return false;
  1412. // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
  1413. // No locking, as this happens before any background thread is started.
  1414. if (chainActive.Tip() == NULL) {
  1415. uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
  1416. } else {
  1417. fHaveGenesis = true;
  1418. }
  1419. if (IsArgSet("-blocknotify"))
  1420. uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
  1421. std::vector<fs::path> vImportFiles;
  1422. if (gArgs.IsArgSet("-loadblock"))
  1423. {
  1424. BOOST_FOREACH(const std::string& strFile, gArgs.GetArgs("-loadblock"))
  1425. vImportFiles.push_back(strFile);
  1426. }
  1427. threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
  1428. // Wait for genesis block to be processed
  1429. {
  1430. boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
  1431. while (!fHaveGenesis) {
  1432. condvar_GenesisWait.wait(lock);
  1433. }
  1434. uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
  1435. }
  1436. // ********************************************************* Step 11: start node
  1437. //// debug print
  1438. LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
  1439. LogPrintf("nBestHeight = %d\n", chainActive.Height());
  1440. if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
  1441. StartTorControl(threadGroup, scheduler);
  1442. Discover(threadGroup);
  1443. // Map ports with UPnP
  1444. MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
  1445. std::string strNodeError;
  1446. CConnman::Options connOptions;
  1447. connOptions.nLocalServices = nLocalServices;
  1448. connOptions.nRelevantServices = nRelevantServices;
  1449. connOptions.nMaxConnections = nMaxConnections;
  1450. connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
  1451. connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
  1452. connOptions.nMaxFeeler = 1;
  1453. connOptions.nBestHeight = chainActive.Height();
  1454. connOptions.uiInterface = &uiInterface;
  1455. connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
  1456. connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
  1457. connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
  1458. connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
  1459. if (!connman.Start(scheduler, strNodeError, connOptions))
  1460. return InitError(strNodeError);
  1461. // ********************************************************* Step 12: finished
  1462. SetRPCWarmupFinished();
  1463. uiInterface.InitMessage(_("Done loading"));
  1464. #ifdef ENABLE_WALLET
  1465. if (pwalletMain)
  1466. pwalletMain->postInitProcess(scheduler);
  1467. #endif
  1468. return !fRequestShutdown;
  1469. }