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