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

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