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

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