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

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