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

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