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

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