Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

init.cpp 72KB

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