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

init.cpp 79KB

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