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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  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. #if !defined(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("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
  289. -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
  290. #ifndef WIN32
  291. strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "bitcoind.pid"));
  292. #endif
  293. strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. "
  294. "Warning: Reverting this setting requires re-downloading the entire blockchain. "
  295. "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
  296. strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
  297. #if !defined(WIN32)
  298. strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
  299. #endif
  300. strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
  301. strUsage += HelpMessageGroup(_("Connection options:"));
  302. strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
  303. strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
  304. strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
  305. strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
  306. strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
  307. strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
  308. strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
  309. strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
  310. strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
  311. strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
  312. strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
  313. strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
  314. strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
  315. strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
  316. strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
  317. strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
  318. strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
  319. strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8333, 18333));
  320. strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
  321. strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
  322. strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
  323. strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
  324. #ifdef USE_UPNP
  325. #if USE_UPNP
  326. strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
  327. #else
  328. strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
  329. #endif
  330. #endif
  331. strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
  332. strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
  333. " " + _("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"));
  334. #ifdef ENABLE_WALLET
  335. strUsage += HelpMessageGroup(_("Wallet options:"));
  336. strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
  337. strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
  338. if (showDebug)
  339. strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
  340. CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
  341. strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
  342. CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
  343. strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
  344. strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
  345. strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
  346. strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
  347. 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));
  348. 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)"),
  349. CURRENCY_UNIT, FormatMoney(maxTxFee)));
  350. strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
  351. strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
  352. strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
  353. strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
  354. strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
  355. " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
  356. #endif
  357. #if ENABLE_ZMQ
  358. strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
  359. strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
  360. strUsage += HelpMessageOpt("-zmqpubhashtransaction=<address>", _("Enable publish hash transaction in <address>"));
  361. strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
  362. strUsage += HelpMessageOpt("-zmqpubrawtransaction=<address>", _("Enable publish raw transaction in <address>"));
  363. #endif
  364. strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
  365. if (showDebug)
  366. {
  367. strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
  368. strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
  369. strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
  370. strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
  371. strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
  372. strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
  373. strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
  374. strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
  375. strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
  376. 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));
  377. 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));
  378. 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));
  379. }
  380. string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, mempoolrej, net, proxy, prune, http"; // Don't translate these and qt below
  381. if (mode == HMM_BITCOIN_QT)
  382. debugCategories += ", qt";
  383. strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
  384. _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
  385. strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
  386. strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
  387. strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
  388. strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
  389. strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
  390. if (showDebug)
  391. {
  392. strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
  393. strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
  394. strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
  395. }
  396. strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
  397. CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
  398. strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
  399. if (showDebug)
  400. {
  401. strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
  402. strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
  403. strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
  404. "This is intended for regression testing tools and app development.");
  405. }
  406. strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
  407. strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
  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("-rpctimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_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("Error: Initializing networking failed");
  631. #ifndef WIN32
  632. if (GetBoolArg("-sysperms", false)) {
  633. #ifdef ENABLE_WALLET
  634. if (!GetBoolArg("-disablewallet", false))
  635. return InitError("Error: -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. #if defined (__SVR4) && defined (__sun)
  654. // ignore SIGPIPE on Solaris
  655. signal(SIGPIPE, SIG_IGN);
  656. #endif
  657. #endif
  658. // ********************************************************* Step 2: parameter interactions
  659. const CChainParams& chainparams = Params();
  660. // Set this early so that parameter interactions go to console
  661. fPrintToConsole = GetBoolArg("-printtoconsole", false);
  662. fLogTimestamps = GetBoolArg("-logtimestamps", true);
  663. fLogIPs = GetBoolArg("-logips", false);
  664. LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  665. LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
  666. // when specifying an explicit binding address, you want to listen on it
  667. // even when -connect or -proxy is specified
  668. if (mapArgs.count("-bind")) {
  669. if (SoftSetBoolArg("-listen", true))
  670. LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
  671. }
  672. if (mapArgs.count("-whitebind")) {
  673. if (SoftSetBoolArg("-listen", true))
  674. LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
  675. }
  676. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
  677. // when only connecting to trusted nodes, do not seed via DNS, or listen by default
  678. if (SoftSetBoolArg("-dnsseed", false))
  679. LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
  680. if (SoftSetBoolArg("-listen", false))
  681. LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
  682. }
  683. if (mapArgs.count("-proxy")) {
  684. // to protect privacy, do not listen by default if a default proxy server is specified
  685. if (SoftSetBoolArg("-listen", false))
  686. LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
  687. // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
  688. // to listen locally, so don't rely on this happening through -listen below.
  689. if (SoftSetBoolArg("-upnp", false))
  690. LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
  691. // to protect privacy, do not discover addresses by default
  692. if (SoftSetBoolArg("-discover", false))
  693. LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
  694. }
  695. if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
  696. // do not map ports or try to retrieve public IP when not listening (pointless)
  697. if (SoftSetBoolArg("-upnp", false))
  698. LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
  699. if (SoftSetBoolArg("-discover", false))
  700. LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
  701. }
  702. if (mapArgs.count("-externalip")) {
  703. // if an explicit public IP is specified, do not try to find others
  704. if (SoftSetBoolArg("-discover", false))
  705. LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
  706. }
  707. if (GetBoolArg("-salvagewallet", false)) {
  708. // Rewrite just private keys: rescan to find transactions
  709. if (SoftSetBoolArg("-rescan", true))
  710. LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
  711. }
  712. // -zapwallettx implies a rescan
  713. if (GetBoolArg("-zapwallettxes", false)) {
  714. if (SoftSetBoolArg("-rescan", true))
  715. LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
  716. }
  717. // if using block pruning, then disable txindex
  718. if (GetArg("-prune", 0)) {
  719. if (GetBoolArg("-txindex", false))
  720. return InitError(_("Prune mode is incompatible with -txindex."));
  721. #ifdef ENABLE_WALLET
  722. if (GetBoolArg("-rescan", false)) {
  723. return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
  724. }
  725. #endif
  726. }
  727. // Make sure enough file descriptors are available
  728. int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
  729. int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
  730. nMaxConnections = std::max(nUserMaxConnections, 0);
  731. // Trim requested connection counts, to fit into system limitations
  732. nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
  733. int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
  734. if (nFD < MIN_CORE_FILEDESCRIPTORS)
  735. return InitError(_("Not enough file descriptors available."));
  736. nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
  737. if (nMaxConnections < nUserMaxConnections)
  738. InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
  739. // ********************************************************* Step 3: parameter-to-internal-flags
  740. fDebug = !mapMultiArgs["-debug"].empty();
  741. // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
  742. const vector<string>& categories = mapMultiArgs["-debug"];
  743. if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
  744. fDebug = false;
  745. // Check for -debugnet
  746. if (GetBoolArg("-debugnet", false))
  747. InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
  748. // Check for -socks - as this is a privacy risk to continue, exit here
  749. if (mapArgs.count("-socks"))
  750. return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
  751. // Check for -tor - as this is a privacy risk to continue, exit here
  752. if (GetBoolArg("-tor", false))
  753. return InitError(_("Error: Unsupported argument -tor found, use -onion."));
  754. if (GetBoolArg("-benchmark", false))
  755. InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
  756. // Checkmempool and checkblockindex default to true in regtest mode
  757. mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks()));
  758. fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
  759. fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
  760. // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
  761. nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
  762. if (nScriptCheckThreads <= 0)
  763. nScriptCheckThreads += GetNumCores();
  764. if (nScriptCheckThreads <= 1)
  765. nScriptCheckThreads = 0;
  766. else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
  767. nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
  768. fServer = GetBoolArg("-server", false);
  769. // block pruning; get the amount of disk space (in MB) to allot for block & undo files
  770. int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
  771. if (nSignedPruneTarget < 0) {
  772. return InitError(_("Prune cannot be configured with a negative value."));
  773. }
  774. nPruneTarget = (uint64_t) nSignedPruneTarget;
  775. if (nPruneTarget) {
  776. if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
  777. return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
  778. }
  779. LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
  780. fPruneMode = true;
  781. }
  782. #ifdef ENABLE_WALLET
  783. bool fDisableWallet = GetBoolArg("-disablewallet", false);
  784. #endif
  785. nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
  786. if (nConnectTimeout <= 0)
  787. nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
  788. // Fee-per-kilobyte amount considered the same as "free"
  789. // If you are mining, be careful setting this:
  790. // if you set it to zero then
  791. // a transaction spammer can cheaply fill blocks using
  792. // 1-satoshi-fee transactions. It should be set above the real
  793. // cost to you of processing a transaction.
  794. if (mapArgs.count("-minrelaytxfee"))
  795. {
  796. CAmount n = 0;
  797. if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
  798. ::minRelayTxFee = CFeeRate(n);
  799. else
  800. return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
  801. }
  802. fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard());
  803. if (Params().RequireStandard() && !fRequireStandard)
  804. return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
  805. #ifdef ENABLE_WALLET
  806. if (mapArgs.count("-mintxfee"))
  807. {
  808. CAmount n = 0;
  809. if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
  810. CWallet::minTxFee = CFeeRate(n);
  811. else
  812. return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
  813. }
  814. if (mapArgs.count("-paytxfee"))
  815. {
  816. CAmount nFeePerK = 0;
  817. if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
  818. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
  819. if (nFeePerK > nHighTransactionFeeWarning)
  820. InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
  821. payTxFee = CFeeRate(nFeePerK, 1000);
  822. if (payTxFee < ::minRelayTxFee)
  823. {
  824. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
  825. mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
  826. }
  827. }
  828. if (mapArgs.count("-maxtxfee"))
  829. {
  830. CAmount nMaxFee = 0;
  831. if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
  832. return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
  833. if (nMaxFee > nHighTransactionMaxFeeWarning)
  834. InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
  835. maxTxFee = nMaxFee;
  836. if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
  837. {
  838. return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
  839. mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
  840. }
  841. }
  842. nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
  843. bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
  844. fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
  845. std::string strWalletFile = GetArg("-wallet", "wallet.dat");
  846. #endif // ENABLE_WALLET
  847. fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
  848. nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
  849. fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
  850. // Option to startup with mocktime set (used for regression testing):
  851. SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
  852. if (GetBoolArg("-peerbloomfilters", true))
  853. nLocalServices |= NODE_BLOOM;
  854. // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
  855. // Initialize elliptic curve code
  856. ECC_Start();
  857. // Sanity check
  858. if (!InitSanityCheck())
  859. return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
  860. std::string strDataDir = GetDataDir().string();
  861. #ifdef ENABLE_WALLET
  862. // Wallet file must be a plain filename without a directory
  863. if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
  864. return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
  865. #endif
  866. // Make sure only a single Bitcoin process is using the data directory.
  867. boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
  868. FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
  869. if (file) fclose(file);
  870. try {
  871. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  872. if (!lock.try_lock())
  873. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
  874. } catch(const boost::interprocess::interprocess_exception& e) {
  875. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running.") + " %s.", strDataDir, e.what()));
  876. }
  877. #ifndef WIN32
  878. CreatePidFile(GetPidFile(), getpid());
  879. #endif
  880. if (GetBoolArg("-shrinkdebugfile", !fDebug))
  881. ShrinkDebugFile();
  882. if (fPrintToDebugLog)
  883. OpenDebugLog();
  884. LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
  885. #ifdef ENABLE_WALLET
  886. LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
  887. #endif
  888. if (!fLogTimestamps)
  889. LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
  890. LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
  891. LogPrintf("Using data directory %s\n", strDataDir);
  892. LogPrintf("Using config file %s\n", GetConfigFile().string());
  893. LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
  894. std::ostringstream strErrors;
  895. LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
  896. if (nScriptCheckThreads) {
  897. for (int i=0; i<nScriptCheckThreads-1; i++)
  898. threadGroup.create_thread(&ThreadScriptCheck);
  899. }
  900. // Start the lightweight task scheduler thread
  901. CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
  902. threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
  903. /* Start the RPC server already. It will be started in "warmup" mode
  904. * and not really process calls already (but it will signify connections
  905. * that the server is there and will be ready later). Warmup mode will
  906. * be disabled when initialisation is finished.
  907. */
  908. if (fServer)
  909. {
  910. uiInterface.InitMessage.connect(SetRPCWarmupStatus);
  911. if (!AppInitServers(threadGroup))
  912. return InitError(_("Unable to start HTTP server. See debug log for details."));
  913. }
  914. int64_t nStart;
  915. // ********************************************************* Step 5: verify wallet database integrity
  916. #ifdef ENABLE_WALLET
  917. if (!fDisableWallet) {
  918. LogPrintf("Using wallet %s\n", strWalletFile);
  919. uiInterface.InitMessage(_("Verifying wallet..."));
  920. std::string warningString;
  921. std::string errorString;
  922. if (!CWallet::Verify(strWalletFile, warningString, errorString))
  923. return false;
  924. if (!warningString.empty())
  925. InitWarning(warningString);
  926. if (!errorString.empty())
  927. return InitError(warningString);
  928. } // (!fDisableWallet)
  929. #endif // ENABLE_WALLET
  930. // ********************************************************* Step 6: network initialization
  931. RegisterNodeSignals(GetNodeSignals());
  932. // format user agent, check total size
  933. strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, mapMultiArgs.count("-uacomment") ? mapMultiArgs["-uacomment"] : std::vector<string>());
  934. if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
  935. return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
  936. strSubVersion.size(), MAX_SUBVERSION_LENGTH));
  937. }
  938. if (mapArgs.count("-onlynet")) {
  939. std::set<enum Network> nets;
  940. BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
  941. enum Network net = ParseNetwork(snet);
  942. if (net == NET_UNROUTABLE)
  943. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
  944. nets.insert(net);
  945. }
  946. for (int n = 0; n < NET_MAX; n++) {
  947. enum Network net = (enum Network)n;
  948. if (!nets.count(net))
  949. SetLimited(net);
  950. }
  951. }
  952. if (mapArgs.count("-whitelist")) {
  953. BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
  954. CSubNet subnet(net);
  955. if (!subnet.IsValid())
  956. return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
  957. CNode::AddWhitelistedRange(subnet);
  958. }
  959. }
  960. bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
  961. // -proxy sets a proxy for all outgoing network traffic
  962. // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
  963. std::string proxyArg = GetArg("-proxy", "");
  964. if (proxyArg != "" && proxyArg != "0") {
  965. proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
  966. if (!addrProxy.IsValid())
  967. return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
  968. SetProxy(NET_IPV4, addrProxy);
  969. SetProxy(NET_IPV6, addrProxy);
  970. SetProxy(NET_TOR, addrProxy);
  971. SetNameProxy(addrProxy);
  972. SetReachable(NET_TOR); // by default, -proxy sets onion as reachable, unless -noonion later
  973. }
  974. // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
  975. // -noonion (or -onion=0) disables connecting to .onion entirely
  976. // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
  977. std::string onionArg = GetArg("-onion", "");
  978. if (onionArg != "") {
  979. if (onionArg == "0") { // Handle -noonion/-onion=0
  980. SetReachable(NET_TOR, false); // set onions as unreachable
  981. } else {
  982. proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
  983. if (!addrOnion.IsValid())
  984. return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
  985. SetProxy(NET_TOR, addrOnion);
  986. SetReachable(NET_TOR);
  987. }
  988. }
  989. // see Step 2: parameter interactions for more information about these
  990. fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
  991. fDiscover = GetBoolArg("-discover", true);
  992. fNameLookup = GetBoolArg("-dns", true);
  993. bool fBound = false;
  994. if (fListen) {
  995. if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
  996. BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
  997. CService addrBind;
  998. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  999. return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
  1000. fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
  1001. }
  1002. BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
  1003. CService addrBind;
  1004. if (!Lookup(strBind.c_str(), addrBind, 0, false))
  1005. return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
  1006. if (addrBind.GetPort() == 0)
  1007. return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
  1008. fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
  1009. }
  1010. }
  1011. else {
  1012. struct in_addr inaddr_any;
  1013. inaddr_any.s_addr = INADDR_ANY;
  1014. fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
  1015. fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
  1016. }
  1017. if (!fBound)
  1018. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  1019. }
  1020. if (mapArgs.count("-externalip")) {
  1021. BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
  1022. CService addrLocal(strAddr, GetListenPort(), fNameLookup);
  1023. if (!addrLocal.IsValid())
  1024. return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
  1025. AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
  1026. }
  1027. }
  1028. BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
  1029. AddOneShot(strDest);
  1030. #if ENABLE_ZMQ
  1031. pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
  1032. if (pzmqNotificationInterface) {
  1033. pzmqNotificationInterface->Initialize();
  1034. RegisterValidationInterface(pzmqNotificationInterface);
  1035. }
  1036. #endif
  1037. // ********************************************************* Step 7: load block chain
  1038. fReindex = GetBoolArg("-reindex", false);
  1039. // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
  1040. boost::filesystem::path blocksDir = GetDataDir() / "blocks";
  1041. if (!boost::filesystem::exists(blocksDir))
  1042. {
  1043. boost::filesystem::create_directories(blocksDir);
  1044. bool linked = false;
  1045. for (unsigned int i = 1; i < 10000; i++) {
  1046. boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
  1047. if (!boost::filesystem::exists(source)) break;
  1048. boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
  1049. try {
  1050. boost::filesystem::create_hard_link(source, dest);
  1051. LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
  1052. linked = true;
  1053. } catch (const boost::filesystem::filesystem_error& e) {
  1054. // Note: hardlink creation failing is not a disaster, it just means
  1055. // blocks will get re-downloaded from peers.
  1056. LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
  1057. break;
  1058. }
  1059. }
  1060. if (linked)
  1061. {
  1062. fReindex = true;
  1063. }
  1064. }
  1065. // cache size calculations
  1066. int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
  1067. nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
  1068. nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
  1069. int64_t nBlockTreeDBCache = nTotalCache / 8;
  1070. if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
  1071. nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
  1072. nTotalCache -= nBlockTreeDBCache;
  1073. int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
  1074. nTotalCache -= nCoinDBCache;
  1075. nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
  1076. LogPrintf("Cache configuration:\n");
  1077. LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
  1078. LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
  1079. LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
  1080. bool fLoaded = false;
  1081. while (!fLoaded) {
  1082. bool fReset = fReindex;
  1083. std::string strLoadError;
  1084. uiInterface.InitMessage(_("Loading block index..."));
  1085. nStart = GetTimeMillis();
  1086. do {
  1087. try {
  1088. UnloadBlockIndex();
  1089. delete pcoinsTip;
  1090. delete pcoinsdbview;
  1091. delete pcoinscatcher;
  1092. delete pblocktree;
  1093. pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
  1094. pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
  1095. pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
  1096. pcoinsTip = new CCoinsViewCache(pcoinscatcher);
  1097. if (fReindex) {
  1098. pblocktree->WriteReindexing(true);
  1099. //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
  1100. if (fPruneMode)
  1101. CleanupBlockRevFiles();
  1102. }
  1103. if (!LoadBlockIndex()) {
  1104. strLoadError = _("Error loading block database");
  1105. break;
  1106. }
  1107. // If the loaded chain has a wrong genesis, bail out immediately
  1108. // (we're likely using a testnet datadir, or the other way around).
  1109. if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
  1110. return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
  1111. // Initialize the block index (no-op if non-empty database was already loaded)
  1112. if (!InitBlockIndex()) {
  1113. strLoadError = _("Error initializing block database");
  1114. break;
  1115. }
  1116. // Check for changed -txindex state
  1117. if (fTxIndex != GetBoolArg("-txindex", false)) {
  1118. strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
  1119. break;
  1120. }
  1121. // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
  1122. // in the past, but is now trying to run unpruned.
  1123. if (fHavePruned && !fPruneMode) {
  1124. strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
  1125. break;
  1126. }
  1127. uiInterface.InitMessage(_("Verifying blocks..."));
  1128. if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
  1129. LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
  1130. MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
  1131. }
  1132. {
  1133. LOCK(cs_main);
  1134. CBlockIndex* tip = chainActive.Tip();
  1135. if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
  1136. strLoadError = _("The block database contains a block which appears to be from the future. "
  1137. "This may be due to your computer's date and time being set incorrectly. "
  1138. "Only rebuild the block database if you are sure that your computer's date and time are correct");
  1139. break;
  1140. }
  1141. }
  1142. if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
  1143. GetArg("-checkblocks", 288))) {
  1144. strLoadError = _("Corrupted block database detected");
  1145. break;
  1146. }
  1147. } catch (const std::exception& e) {
  1148. if (fDebug) LogPrintf("%s\n", e.what());
  1149. strLoadError = _("Error opening block database");
  1150. break;
  1151. }
  1152. fLoaded = true;
  1153. } while(false);
  1154. if (!fLoaded) {
  1155. // first suggest a reindex
  1156. if (!fReset) {
  1157. bool fRet = uiInterface.ThreadSafeMessageBox(
  1158. strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
  1159. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
  1160. if (fRet) {
  1161. fReindex = true;
  1162. fRequestShutdown = false;
  1163. } else {
  1164. LogPrintf("Aborted block database rebuild. Exiting.\n");
  1165. return false;
  1166. }
  1167. } else {
  1168. return InitError(strLoadError);
  1169. }
  1170. }
  1171. }
  1172. // As LoadBlockIndex can take several minutes, it's possible the user
  1173. // requested to kill the GUI during the last operation. If so, exit.
  1174. // As the program has not fully started yet, Shutdown() is possibly overkill.
  1175. if (fRequestShutdown)
  1176. {
  1177. LogPrintf("Shutdown requested. Exiting.\n");
  1178. return false;
  1179. }
  1180. LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
  1181. boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
  1182. CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
  1183. // Allowed to fail as this file IS missing on first startup.
  1184. if (!est_filein.IsNull())
  1185. mempool.ReadFeeEstimates(est_filein);
  1186. fFeeEstimatesInitialized = true;
  1187. // ********************************************************* Step 8: load wallet
  1188. #ifdef ENABLE_WALLET
  1189. if (fDisableWallet) {
  1190. pwalletMain = NULL;
  1191. LogPrintf("Wallet disabled!\n");
  1192. } else {
  1193. // needed to restore wallet transaction meta data after -zapwallettxes
  1194. std::vector<CWalletTx> vWtx;
  1195. if (GetBoolArg("-zapwallettxes", false)) {
  1196. uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
  1197. pwalletMain = new CWallet(strWalletFile);
  1198. DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
  1199. if (nZapWalletRet != DB_LOAD_OK) {
  1200. uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
  1201. return false;
  1202. }
  1203. delete pwalletMain;
  1204. pwalletMain = NULL;
  1205. }
  1206. uiInterface.InitMessage(_("Loading wallet..."));
  1207. nStart = GetTimeMillis();
  1208. bool fFirstRun = true;
  1209. pwalletMain = new CWallet(strWalletFile);
  1210. DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
  1211. if (nLoadWalletRet != DB_LOAD_OK)
  1212. {
  1213. if (nLoadWalletRet == DB_CORRUPT)
  1214. strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
  1215. else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
  1216. {
  1217. string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
  1218. " or address book entries might be missing or incorrect."));
  1219. InitWarning(msg);
  1220. }
  1221. else if (nLoadWalletRet == DB_TOO_NEW)
  1222. strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
  1223. else if (nLoadWalletRet == DB_NEED_REWRITE)
  1224. {
  1225. strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
  1226. LogPrintf("%s", strErrors.str());
  1227. return InitError(strErrors.str());
  1228. }
  1229. else
  1230. strErrors << _("Error loading wallet.dat") << "\n";
  1231. }
  1232. if (GetBoolArg("-upgradewallet", fFirstRun))
  1233. {
  1234. int nMaxVersion = GetArg("-upgradewallet", 0);
  1235. if (nMaxVersion == 0) // the -upgradewallet without argument case
  1236. {
  1237. LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
  1238. nMaxVersion = CLIENT_VERSION;
  1239. pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
  1240. }
  1241. else
  1242. LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
  1243. if (nMaxVersion < pwalletMain->GetVersion())
  1244. strErrors << _("Cannot downgrade wallet") << "\n";
  1245. pwalletMain->SetMaxVersion(nMaxVersion);
  1246. }
  1247. if (fFirstRun)
  1248. {
  1249. // Create new keyUser and set as default key
  1250. RandAddSeedPerfmon();
  1251. CPubKey newDefaultKey;
  1252. if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
  1253. pwalletMain->SetDefaultKey(newDefaultKey);
  1254. if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
  1255. strErrors << _("Cannot write default address") << "\n";
  1256. }
  1257. pwalletMain->SetBestChain(chainActive.GetLocator());
  1258. }
  1259. LogPrintf("%s", strErrors.str());
  1260. LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
  1261. RegisterValidationInterface(pwalletMain);
  1262. CBlockIndex *pindexRescan = chainActive.Tip();
  1263. if (GetBoolArg("-rescan", false))
  1264. pindexRescan = chainActive.Genesis();
  1265. else
  1266. {
  1267. CWalletDB walletdb(strWalletFile);
  1268. CBlockLocator locator;
  1269. if (walletdb.ReadBestBlock(locator))
  1270. pindexRescan = FindForkInGlobalIndex(chainActive, locator);
  1271. else
  1272. pindexRescan = chainActive.Genesis();
  1273. }
  1274. if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
  1275. {
  1276. //We can't rescan beyond non-pruned blocks, stop and throw an error
  1277. //this might happen if a user uses a old wallet within a pruned node
  1278. // or if he ran -disablewallet for a longer time, then decided to re-enable
  1279. if (fPruneMode)
  1280. {
  1281. CBlockIndex *block = chainActive.Tip();
  1282. while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
  1283. block = block->pprev;
  1284. if (pindexRescan != block)
  1285. return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
  1286. }
  1287. uiInterface.InitMessage(_("Rescanning..."));
  1288. LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
  1289. nStart = GetTimeMillis();
  1290. pwalletMain->ScanForWalletTransactions(pindexRescan, true);
  1291. LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
  1292. pwalletMain->SetBestChain(chainActive.GetLocator());
  1293. nWalletDBUpdated++;
  1294. // Restore wallet transaction metadata after -zapwallettxes=1
  1295. if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
  1296. {
  1297. CWalletDB walletdb(strWalletFile);
  1298. BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
  1299. {
  1300. uint256 hash = wtxOld.GetHash();
  1301. std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
  1302. if (mi != pwalletMain->mapWallet.end())
  1303. {
  1304. const CWalletTx* copyFrom = &wtxOld;
  1305. CWalletTx* copyTo = &mi->second;
  1306. copyTo->mapValue = copyFrom->mapValue;
  1307. copyTo->vOrderForm = copyFrom->vOrderForm;
  1308. copyTo->nTimeReceived = copyFrom->nTimeReceived;
  1309. copyTo->nTimeSmart = copyFrom->nTimeSmart;
  1310. copyTo->fFromMe = copyFrom->fFromMe;
  1311. copyTo->strFromAccount = copyFrom->strFromAccount;
  1312. copyTo->nOrderPos = copyFrom->nOrderPos;
  1313. copyTo->WriteToDisk(&walletdb);
  1314. }
  1315. }
  1316. }
  1317. }
  1318. pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
  1319. } // (!fDisableWallet)
  1320. #else // ENABLE_WALLET
  1321. LogPrintf("No wallet support compiled in!\n");
  1322. #endif // !ENABLE_WALLET
  1323. // ********************************************************* Step 9: data directory maintenance
  1324. // if pruning, unset the service bit and perform the initial blockstore prune
  1325. // after any wallet rescanning has taken place.
  1326. if (fPruneMode) {
  1327. uiInterface.InitMessage(_("Pruning blockstore..."));
  1328. LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
  1329. nLocalServices &= ~NODE_NETWORK;
  1330. if (!fReindex) {
  1331. PruneAndFlush();
  1332. }
  1333. }
  1334. // ********************************************************* Step 10: import blocks
  1335. if (mapArgs.count("-blocknotify"))
  1336. uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
  1337. uiInterface.InitMessage(_("Activating best chain..."));
  1338. // scan for better chains in the block chain database, that are not yet connected in the active best chain
  1339. CValidationState state;
  1340. if (!ActivateBestChain(state))
  1341. strErrors << "Failed to connect best block";
  1342. std::vector<boost::filesystem::path> vImportFiles;
  1343. if (mapArgs.count("-loadblock"))
  1344. {
  1345. BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
  1346. vImportFiles.push_back(strFile);
  1347. }
  1348. threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
  1349. if (chainActive.Tip() == NULL) {
  1350. LogPrintf("Waiting for genesis block to be imported...\n");
  1351. while (!fRequestShutdown && chainActive.Tip() == NULL)
  1352. MilliSleep(10);
  1353. }
  1354. // ********************************************************* Step 11: start node
  1355. if (!CheckDiskSpace())
  1356. return false;
  1357. if (!strErrors.str().empty())
  1358. return InitError(strErrors.str());
  1359. RandAddSeedPerfmon();
  1360. //// debug print
  1361. LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
  1362. LogPrintf("nBestHeight = %d\n", chainActive.Height());
  1363. #ifdef ENABLE_WALLET
  1364. LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
  1365. LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
  1366. LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
  1367. #endif
  1368. StartNode(threadGroup, scheduler);
  1369. // Monitor the chain, and alert if we get blocks much quicker or slower than expected
  1370. int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
  1371. CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
  1372. boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
  1373. scheduler.scheduleEvery(f, nPowTargetSpacing);
  1374. // Generate coins in the background
  1375. GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1), Params());
  1376. // ********************************************************* Step 11: finished
  1377. SetRPCWarmupFinished();
  1378. uiInterface.InitMessage(_("Done loading"));
  1379. #ifdef ENABLE_WALLET
  1380. if (pwalletMain) {
  1381. // Add wallet transactions that aren't already in a block to mapTransactions
  1382. pwalletMain->ReacceptWalletTransactions();
  1383. // Run a thread to flush wallet periodically
  1384. threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
  1385. }
  1386. #endif
  1387. return !fRequestShutdown;
  1388. }