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

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