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