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

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