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