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