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