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