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 84KB

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