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