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