]> Git Repo - VerusCoin.git/blame - src/init.cpp
Merge pull request #3416
[VerusCoin.git] / src / init.cpp
CommitLineData
69d605f4 1// Copyright (c) 2009-2010 Satoshi Nakamoto
db0e8ccd 2// Copyright (c) 2009-2013 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
CF
6#if defined(HAVE_CONFIG_H)
7#include "bitcoin-config.h"
8#endif
9
663224c2 10#include "init.h"
51ed9ec9
BD
11
12#include "addrman.h"
51ed9ec9 13#include "checkpoints.h"
a9a37c8b 14#include "main.h"
d247a5d1 15#include "miner.h"
51ed9ec9 16#include "net.h"
a9a37c8b 17#include "rpcserver.h"
51ed9ec9 18#include "txdb.h"
ed6d0b5f 19#include "ui_interface.h"
51ed9ec9 20#include "util.h"
48ba56cd 21#ifdef ENABLE_WALLET
df840de5 22#include "db.h"
51ed9ec9
BD
23#include "wallet.h"
24#include "walletdb.h"
48ba56cd 25#endif
5350ea41 26
51ed9ec9
BD
27#include <inttypes.h>
28#include <stdint.h>
69d605f4 29
ed6d0b5f
PW
30#ifndef WIN32
31#include <signal.h>
52d3a481 32#endif
5f2e76b8 33
51ed9ec9
BD
34#include <boost/algorithm/string/predicate.hpp>
35#include <boost/filesystem.hpp>
36#include <boost/interprocess/sync/file_lock.hpp>
37#include <openssl/crypto.h>
38
69d605f4
WL
39using namespace std;
40using namespace boost;
41
48ba56cd 42#ifdef ENABLE_WALLET
674cb304 43std::string strWalletFile;
e8ef3da7 44CWallet* pwalletMain;
48ba56cd 45#endif
e8ef3da7 46
ba29a559
PW
47#ifdef WIN32
48// Win32 LevelDB doesn't use filedescriptors, and the ones used for
49// accessing block files, don't count towards to fd_set size limit
50// anyway.
51#define MIN_CORE_FILEDESCRIPTORS 0
52#else
53#define MIN_CORE_FILEDESCRIPTORS 150
54#endif
55
c73323ee
PK
56// Used to pass flags to the Bind() function
57enum BindFlags {
29e214aa
PK
58 BF_NONE = 0,
59 BF_EXPLICIT = (1U << 0),
60 BF_REPORT_ERROR = (1U << 1)
c73323ee
PK
61};
62
4751d07e 63
69d605f4
WL
64//////////////////////////////////////////////////////////////////////////////
65//
66// Shutdown
67//
68
b31499ec
GA
69//
70// Thread management and startup/shutdown:
71//
72// The network-processing threads are all part of a thread group
73// created by AppInit() or the Qt main() function.
74//
75// A clean exit happens when StartShutdown() or the SIGTERM
76// signal handler sets fRequestShutdown, which triggers
77// the DetectShutdownThread(), which interrupts the main thread group.
78// DetectShutdownThread() then exits, which causes AppInit() to
79// continue (it .joins the shutdown thread).
80// Shutdown() is then
81// called to clean up database connections, and stop other
82// threads that should only be stopped after the main network-processing
83// threads have exited.
84//
85// Note that if running -daemon the parent process returns from AppInit2
86// before adding any threads to the threadGroup, so .join_all() returns
87// immediately and the parent exits from main().
88//
89// Shutdown for Qt is very similar, only it uses a QTimer to detect
723035bb
GA
90// fRequestShutdown getting set, and then does the normal Qt
91// shutdown thing.
b31499ec
GA
92//
93
94volatile bool fRequestShutdown = false;
69d605f4 95
9247134e
PK
96void StartShutdown()
97{
b31499ec 98 fRequestShutdown = true;
9247134e 99}
723035bb
GA
100bool ShutdownRequested()
101{
102 return fRequestShutdown;
103}
9247134e 104
ae8bfd12
PW
105static CCoinsViewDB *pcoinsdbview;
106
b31499ec 107void Shutdown()
69d605f4 108{
ced3c248 109 LogPrintf("Shutdown : In progress...\n");
69d605f4 110 static CCriticalSection cs_Shutdown;
b31499ec
GA
111 TRY_LOCK(cs_Shutdown, lockShutdown);
112 if (!lockShutdown) return;
96931d6f 113
96931d6f 114 RenameThread("bitcoin-shutoff");
319b1160 115 mempool.AddTransactionsUpdated(1);
21eb5ada 116 StopRPCThreads();
d98bf10f 117 ShutdownRPCMining();
4a85e067 118#ifdef ENABLE_WALLET
b0730874
JG
119 if (pwalletMain)
120 bitdb.Flush(false);
c8b74258 121 GenerateBitcoins(false, NULL, 0);
48ba56cd 122#endif
21eb5ada 123 StopNode();
b2864d2f 124 UnregisterNodeSignals(GetNodeSignals());
69d605f4 125 {
b31499ec 126 LOCK(cs_main);
48ba56cd 127#ifdef ENABLE_WALLET
dbc6dea1 128 if (pwalletMain)
e4daecda 129 pwalletMain->SetBestChain(chainActive.GetLocator());
48ba56cd 130#endif
b31499ec
GA
131 if (pblocktree)
132 pblocktree->Flush();
133 if (pcoinsTip)
134 pcoinsTip->Flush();
135 delete pcoinsTip; pcoinsTip = NULL;
136 delete pcoinsdbview; pcoinsdbview = NULL;
137 delete pblocktree; pblocktree = NULL;
69d605f4 138 }
48ba56cd 139#ifdef ENABLE_WALLET
b0730874
JG
140 if (pwalletMain)
141 bitdb.Flush(true);
48ba56cd 142#endif
b31499ec 143 boost::filesystem::remove(GetPidFile());
e6fe8e77 144 UnregisterAllWallets();
48ba56cd 145#ifdef ENABLE_WALLET
b0730874
JG
146 if (pwalletMain)
147 delete pwalletMain;
48ba56cd 148#endif
ced3c248 149 LogPrintf("Shutdown : done\n");
69d605f4
WL
150}
151
c8c2fbe0
GA
152//
153// Signal handlers are very limited in what they are allowed to do, so:
154//
69d605f4
WL
155void HandleSIGTERM(int)
156{
157 fRequestShutdown = true;
158}
159
9af080c3
MH
160void HandleSIGHUP(int)
161{
162 fReopenDebugLog = true;
163}
69d605f4 164
ac7c7ab9
PW
165bool static InitError(const std::string &str)
166{
5350ea41 167 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
ac7c7ab9 168 return false;
ac7c7ab9
PW
169}
170
171bool static InitWarning(const std::string &str)
172{
5350ea41 173 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
ac7c7ab9
PW
174 return true;
175}
176
29e214aa 177bool static Bind(const CService &addr, unsigned int flags) {
c73323ee 178 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
8f10a288
PW
179 return false;
180 std::string strError;
587f929c 181 if (!BindListenPort(addr, strError)) {
c73323ee 182 if (flags & BF_REPORT_ERROR)
587f929c
PW
183 return InitError(strError);
184 return false;
185 }
8f10a288
PW
186 return true;
187}
188
2a03a390
WL
189// Core-specific options shared between UI, daemon and RPC client
190std::string HelpMessage(HelpMessageMode hmm)
9f5b11e6 191{
c98c88b3
CF
192 string strUsage = _("Options:") + "\n";
193 strUsage += " -? " + _("This help message") + "\n";
194 strUsage += " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n";
c98c88b3 195 strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n";
2a03a390 196 strUsage += " -testnet " + _("Use the test network") + "\n";
0b47fe6b
WL
197 strUsage += " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n";
198 strUsage += " -gen " + _("Generate coins (default: 0)") + "\n";
0b47fe6b
WL
199 strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n";
200 strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n";
b6aafca0
PK
201 strUsage += " -proxy=<ip:port> " + _("Connect through SOCKS proxy") + "\n";
202 strUsage += " -socks=<n> " + _("Select SOCKS version for -proxy (4 or 5, default: 5)") + "\n";
203 strUsage += " -onion=<ip:port> " + _("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)") + "\n";
0b47fe6b
WL
204 strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n";
205 strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n";
206 strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n";
207 strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n";
208 strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n";
209 strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n";
210 strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n";
211 strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n";
212 strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n";
213 strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n";
214 strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n";
215 strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n";
216 strUsage += " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n";
217 strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n";
218 strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n";
219 strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n";
220 strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n";
9f5b11e6
WL
221#ifdef USE_UPNP
222#if USE_UPNP
0b47fe6b 223 strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n";
9f5b11e6 224#else
0b47fe6b 225 strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n";
2a03a390 226#endif
9f5b11e6 227#endif
0b47fe6b
WL
228 strUsage += " -debug=<category> " + _("Output debugging information (default: 0, supplying <category> is optional)") + "\n";
229 strUsage += _("If <category> is not supplied, output all debugging information.") + "\n";
230 strUsage += _("<category> can be:");
231 strUsage += " addrman, alert, coindb, db, lock, rand, rpc, selectcoins, mempool, net"; // Don't translate these and qt below
3b570559
PK
232 if (hmm == HMM_BITCOIN_QT)
233 {
234 strUsage += ", qt.\n";
235 }
236 else
237 {
238 strUsage += ".\n";
239 }
0b47fe6b
WL
240 strUsage += " -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n";
241 strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n";
242 strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n";
243 strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be "
b6aafca0 244 "solved instantly. This is intended for regression testing tools and app development.") + "\n";
2a03a390
WL
245 if (hmm == HMM_BITCOIN_QT)
246 {
7f61f1ac 247 strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n";
2a03a390
WL
248 }
249
250 if (hmm == HMM_BITCOIND)
251 {
7f61f1ac 252#if !defined(WIN32)
7f61f1ac 253 strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n";
9f5b11e6 254#endif
2a03a390
WL
255 }
256
c98c88b3
CF
257 strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n";
258 strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n";
0b47fe6b 259 strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n";
0b47fe6b
WL
260 strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n";
261 strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n";
262 strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n";
0b47fe6b 263 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";
0b47fe6b 264 strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n";
0b47fe6b
WL
265 strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n";
266 strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n";
267 strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n";
268 strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n";
269 strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n";
270 strUsage += " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n";
06eb2f21
WL
271#ifdef ENABLE_WALLET
272 strUsage += "\n" + _("Wallet options:") + "\n";
273 strUsage += " -disablewallet " + _("Do not load the wallet and disable wallet RPC calls") + "\n";
274 strUsage += " -paytxfee=<amt> " + _("Fee per kB to add to transactions you send") + "\n";
275 strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n";
276 strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n";
277 strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n";
278 strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n";
279 strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n";
280#endif
0b47fe6b 281 strUsage += "\n" + _("Block creation options:") + "\n";
b6aafca0 282 strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n";
a9a37c8b
PK
283 strUsage += " -blockmaxsize=<n> " + strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE) + "\n";
284 strUsage += " -blockprioritysize=<n> " + strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE) + "\n";
9f5b11e6 285
dabd4bd4 286 strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
c98c88b3 287 strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
0b47fe6b
WL
288 strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n";
289 strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n";
290 strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n";
9f5b11e6
WL
291
292 return strUsage;
293}
294
7a5b7535
PW
295struct CImportingNow
296{
297 CImportingNow() {
298 assert(fImporting == false);
299 fImporting = true;
300 }
301
302 ~CImportingNow() {
303 assert(fImporting == true);
304 fImporting = false;
305 }
306};
307
21eb5ada
GA
308void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
309{
7a5b7535
PW
310 RenameThread("bitcoin-loadblk");
311
7fea4846
PW
312 // -reindex
313 if (fReindex) {
314 CImportingNow imp;
315 int nFile = 0;
21eb5ada 316 while (true) {
a8a4b967 317 CDiskBlockPos pos(nFile, 0);
7fea4846
PW
318 FILE *file = OpenBlockFile(pos, true);
319 if (!file)
320 break;
881a85a2 321 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
7fea4846
PW
322 LoadExternalBlockFile(file, &pos);
323 nFile++;
324 }
21eb5ada
GA
325 pblocktree->WriteReindexing(false);
326 fReindex = false;
881a85a2 327 LogPrintf("Reindexing finished\n");
21eb5ada
GA
328 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
329 InitBlockIndex();
7a5b7535
PW
330 }
331
332 // hardcoded $DATADIR/bootstrap.dat
333 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
21eb5ada 334 if (filesystem::exists(pathBootstrap)) {
7a5b7535
PW
335 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
336 if (file) {
7fea4846 337 CImportingNow imp;
7a5b7535 338 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
881a85a2 339 LogPrintf("Importing bootstrap.dat...\n");
7a5b7535
PW
340 LoadExternalBlockFile(file);
341 RenameOver(pathBootstrap, pathBootstrapOld);
342 }
343 }
344
7fea4846 345 // -loadblock=
21eb5ada 346 BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
7fea4846
PW
347 FILE *file = fopen(path.string().c_str(), "rb");
348 if (file) {
349 CImportingNow imp;
881a85a2 350 LogPrintf("Importing %s...\n", path.string().c_str());
7fea4846
PW
351 LoadExternalBlockFile(file);
352 }
353 }
7a5b7535
PW
354}
355
9f5b11e6
WL
356/** Initialize bitcoin.
357 * @pre Parameters should be parsed and config file should be read.
358 */
e30bd78f 359bool AppInit2(boost::thread_group& threadGroup, bool fForceServer)
69d605f4 360{
7d80d2e3 361 // ********************************************************* Step 1: setup
69d605f4 362#ifdef _MSC_VER
814efd6f 363 // Turn off Microsoft heap dump noise
69d605f4
WL
364 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
365 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
366#endif
367#if _MSC_VER >= 1400
814efd6f 368 // Disable confusing "helpful" text message on abort, Ctrl-C
69d605f4
WL
369 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
370#endif
3d88c9b4
PK
371#ifdef WIN32
372 // Enable Data Execution Prevention (DEP)
373 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
374 // A failure is non-critical and needs no further attention!
375#ifndef PROCESS_DEP_ENABLE
f65dddc7
PK
376 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
377 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
3d88c9b4
PK
378#define PROCESS_DEP_ENABLE 0x00000001
379#endif
380 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
381 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
382 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
d23fa49c
WL
383
384 // Initialize Windows Sockets
385 WSADATA wsadata;
386 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
110257a6 387 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
d23fa49c 388 {
110257a6 389 return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
d23fa49c 390 }
69d605f4 391#endif
6853e627 392#ifndef WIN32
3d88c9b4
PK
393 umask(077);
394
69d605f4
WL
395 // Clean shutdown on SIGTERM
396 struct sigaction sa;
397 sa.sa_handler = HandleSIGTERM;
398 sigemptyset(&sa.sa_mask);
399 sa.sa_flags = 0;
400 sigaction(SIGTERM, &sa, NULL);
401 sigaction(SIGINT, &sa, NULL);
9af080c3
MH
402
403 // Reopen debug.log on SIGHUP
404 struct sigaction sa_hup;
405 sa_hup.sa_handler = HandleSIGHUP;
406 sigemptyset(&sa_hup.sa_mask);
407 sa_hup.sa_flags = 0;
408 sigaction(SIGHUP, &sa_hup, NULL);
b34255b7 409
410#if defined (__SVR4) && defined (__sun)
411 // ignore SIGPIPE on Solaris
412 signal(SIGPIPE, SIG_IGN);
413#endif
69d605f4
WL
414#endif
415
7d80d2e3
PW
416 // ********************************************************* Step 2: parameter interactions
417
587f929c
PW
418 if (mapArgs.count("-bind")) {
419 // when specifying an explicit binding address, you want to listen on it
420 // even when -connect or -proxy is specified
7d80d2e3 421 SoftSetBoolArg("-listen", true);
587f929c 422 }
7d80d2e3 423
f161a2c2 424 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
587f929c
PW
425 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
426 SoftSetBoolArg("-dnsseed", false);
427 SoftSetBoolArg("-listen", false);
428 }
429
430 if (mapArgs.count("-proxy")) {
431 // to protect privacy, do not listen by default if a proxy server is specified
7d80d2e3 432 SoftSetBoolArg("-listen", false);
587f929c
PW
433 }
434
3bbb49de 435 if (!GetBoolArg("-listen", true)) {
587f929c 436 // do not map ports or try to retrieve public IP when not listening (pointless)
7d80d2e3
PW
437 SoftSetBoolArg("-upnp", false);
438 SoftSetBoolArg("-discover", false);
439 }
440
587f929c
PW
441 if (mapArgs.count("-externalip")) {
442 // if an explicit public IP is specified, do not try to find others
443 SoftSetBoolArg("-discover", false);
444 }
445
3260b4c0 446 if (GetBoolArg("-salvagewallet", false)) {
eed1785f
GA
447 // Rewrite just private keys: rescan to find transactions
448 SoftSetBoolArg("-rescan", true);
449 }
450
ba29a559
PW
451 // Make sure enough file descriptors are available
452 int nBind = std::max((int)mapArgs.count("-bind"), 1);
453 nMaxConnections = GetArg("-maxconnections", 125);
03f49808 454 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
ba29a559
PW
455 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
456 if (nFD < MIN_CORE_FILEDESCRIPTORS)
457 return InitError(_("Not enough file descriptors available."));
458 if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
459 nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
460
7d80d2e3
PW
461 // ********************************************************* Step 3: parameter-to-internal-flags
462
3b570559
PK
463 fDebug = !mapMultiArgs["-debug"].empty();
464 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
465 const vector<string>& categories = mapMultiArgs["-debug"];
466 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
467 fDebug = false;
468
469 // Check for -debugnet (deprecated)
470 if (GetBoolArg("-debugnet", false))
471 InitWarning(_("Warning: Deprecated argument -debugnet ignored, use -debug=net"));
472
3260b4c0 473 fBenchmark = GetBoolArg("-benchmark", false);
319b1160 474 mempool.setSanityCheck(GetBoolArg("-checkmempool", RegTest()));
60fc1b40 475 Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
d07eaba1 476
f9cae832
PW
477 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
478 nScriptCheckThreads = GetArg("-par", 0);
ebd7e8bf
DS
479 if (nScriptCheckThreads <= 0)
480 nScriptCheckThreads += boost::thread::hardware_concurrency();
69e07747 481 if (nScriptCheckThreads <= 1)
f9cae832
PW
482 nScriptCheckThreads = 0;
483 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
484 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
485
e30bd78f 486 if (fDaemon || fForceServer)
69d605f4
WL
487 fServer = true;
488 else
3260b4c0 489 fServer = GetBoolArg("-server", false);
69d605f4 490
3260b4c0 491 fPrintToConsole = GetBoolArg("-printtoconsole", false);
959e62f0 492 fLogTimestamps = GetBoolArg("-logtimestamps", true);
48ba56cd 493#ifdef ENABLE_WALLET
e6b7e3dc 494 bool fDisableWallet = GetBoolArg("-disablewallet", false);
48ba56cd 495#endif
69d605f4 496
7d80d2e3
PW
497 if (mapArgs.count("-timeout"))
498 {
499 int nNewTimeout = GetArg("-timeout", 5000);
500 if (nNewTimeout > 0 && nNewTimeout < 600000)
501 nConnectTimeout = nNewTimeout;
502 }
503
504 // Continue to put "/P2SH/" in the coinbase to monitor
505 // BIP16 support.
506 // This can be removed eventually...
507 const char* pszP2SH = "/P2SH/";
508 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
509
000dc551
GA
510 // Fee-per-kilobyte amount considered the same as "free"
511 // If you are mining, be careful setting this:
512 // if you set it to zero then
513 // a transaction spammer can cheaply fill blocks using
514 // 1-satoshi-fee transactions. It should be set above the real
515 // cost to you of processing a transaction.
516 if (mapArgs.count("-mintxfee"))
517 {
51ed9ec9 518 int64_t n = 0;
000dc551
GA
519 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
520 CTransaction::nMinTxFee = n;
521 else
522 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
523 }
524 if (mapArgs.count("-minrelaytxfee"))
525 {
51ed9ec9 526 int64_t n = 0;
000dc551
GA
527 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
528 CTransaction::nMinRelayTxFee = n;
529 else
530 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
531 }
7d80d2e3 532
cd7fa8bb 533#ifdef ENABLE_WALLET
7d80d2e3
PW
534 if (mapArgs.count("-paytxfee"))
535 {
536 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
537 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
538 if (nTransactionFee > 0.25 * COIN)
e6bc9c35 539 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
7d80d2e3
PW
540 }
541
674cb304 542 strWalletFile = GetArg("-wallet", "wallet.dat");
48ba56cd 543#endif
7d80d2e3
PW
544 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
545
22bb0490 546 std::string strDataDir = GetDataDir().string();
48ba56cd 547#ifdef ENABLE_WALLET
674cb304
NS
548 // Wallet file must be a plain filename without a directory
549 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
265e2657 550 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile.c_str(), strDataDir.c_str()));
48ba56cd 551#endif
7d80d2e3
PW
552 // Make sure only a single Bitcoin process is using the data directory.
553 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
554 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
555 if (file) fclose(file);
556 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
557 if (!lock.try_lock())
6b3783a9 558 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), strDataDir.c_str()));
7d80d2e3 559
7f1de3fe 560 if (GetBoolArg("-shrinkdebugfile", !fDebug))
69d605f4 561 ShrinkDebugFile();
881a85a2
GA
562 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
563 LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
564 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
dcb14198 565 if (!fLogTimestamps)
881a85a2
GA
566 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
567 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
568 LogPrintf("Using data directory %s\n", strDataDir.c_str());
569 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
7d80d2e3 570 std::ostringstream strErrors;
69d605f4 571
7d80d2e3
PW
572 if (fDaemon)
573 fprintf(stdout, "Bitcoin server starting\n");
574
f9cae832 575 if (nScriptCheckThreads) {
881a85a2 576 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
f9cae832 577 for (int i=0; i<nScriptCheckThreads-1; i++)
21eb5ada 578 threadGroup.create_thread(&ThreadScriptCheck);
f9cae832
PW
579 }
580
51ed9ec9 581 int64_t nStart;
7d80d2e3 582
06494cab 583 // ********************************************************* Step 5: verify wallet database integrity
48ba56cd 584#ifdef ENABLE_WALLET
e6b7e3dc 585 if (!fDisableWallet) {
f9ee7a03 586 uiInterface.InitMessage(_("Verifying wallet..."));
eed1785f 587
f9ee7a03
JG
588 if (!bitdb.Open(GetDataDir()))
589 {
590 // try moving the database env out of the way
591 boost::filesystem::path pathDatabase = GetDataDir() / "database";
592 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRId64".bak", GetTime());
593 try {
594 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
595 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
596 } catch(boost::filesystem::filesystem_error &error) {
597 // failure is ok (well, not really, but it's not worse than what we started with)
598 }
1859aafe 599
f9ee7a03
JG
600 // try again
601 if (!bitdb.Open(GetDataDir())) {
602 // if it still fails, it probably means we can't even create the database env
603 string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
604 return InitError(msg);
605 }
1859aafe 606 }
eed1785f 607
f9ee7a03
JG
608 if (GetBoolArg("-salvagewallet", false))
609 {
610 // Recover readable keypairs:
611 if (!CWalletDB::Recover(bitdb, strWalletFile, true))
612 return false;
613 }
eed1785f 614
f9ee7a03 615 if (filesystem::exists(GetDataDir() / strWalletFile))
d0b3e77a 616 {
f9ee7a03
JG
617 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover);
618 if (r == CDBEnv::RECOVER_OK)
619 {
620 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
621 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
622 " your balance or transactions are incorrect you should"
623 " restore from a backup."), strDataDir.c_str());
624 InitWarning(msg);
625 }
626 if (r == CDBEnv::RECOVER_FAIL)
627 return InitError(_("wallet.dat corrupt, salvage failed"));
d0b3e77a 628 }
e6b7e3dc 629 } // (!fDisableWallet)
48ba56cd 630#endif // ENABLE_WALLET
eed1785f 631 // ********************************************************* Step 6: network initialization
7d80d2e3 632
501da250 633 RegisterNodeSignals(GetNodeSignals());
0e4b3175 634
587f929c 635 int nSocksVersion = GetArg("-socks", 5);
7d80d2e3
PW
636 if (nSocksVersion != 4 && nSocksVersion != 5)
637 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
69d605f4 638
7d80d2e3
PW
639 if (mapArgs.count("-onlynet")) {
640 std::set<enum Network> nets;
641 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
642 enum Network net = ParseNetwork(snet);
643 if (net == NET_UNROUTABLE)
644 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
645 nets.insert(net);
646 }
647 for (int n = 0; n < NET_MAX; n++) {
648 enum Network net = (enum Network)n;
649 if (!nets.count(net))
650 SetLimited(net);
651 }
652 }
9655d73f
LD
653#if defined(USE_IPV6)
654#if ! USE_IPV6
655 else
656 SetLimited(NET_IPV6);
657#endif
658#endif
7d80d2e3 659
54ce3bad
PW
660 CService addrProxy;
661 bool fProxy = false;
587f929c 662 if (mapArgs.count("-proxy")) {
54ce3bad 663 addrProxy = CService(mapArgs["-proxy"], 9050);
587f929c
PW
664 if (!addrProxy.IsValid())
665 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
666
667 if (!IsLimited(NET_IPV4))
668 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
669 if (nSocksVersion > 4) {
670#ifdef USE_IPV6
671 if (!IsLimited(NET_IPV6))
672 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
673#endif
674 SetNameProxy(addrProxy, nSocksVersion);
675 }
54ce3bad
PW
676 fProxy = true;
677 }
678
102518fd
GM
679 // -onion can override normal proxy, -noonion disables tor entirely
680 // -tor here is a temporary backwards compatibility measure
681 if (mapArgs.count("-tor"))
682 printf("Notice: option -tor has been replaced with -onion and will be removed in a later version.\n");
683 if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") &&
684 !(mapArgs.count("-tor") && mapArgs["-tor"] == "0") &&
685 (fProxy || mapArgs.count("-onion") || mapArgs.count("-tor"))) {
54ce3bad 686 CService addrOnion;
102518fd 687 if (!mapArgs.count("-onion") && !mapArgs.count("-tor"))
54ce3bad
PW
688 addrOnion = addrProxy;
689 else
102518fd 690 addrOnion = mapArgs.count("-onion")?CService(mapArgs["-onion"], 9050):CService(mapArgs["-tor"], 9050);
54ce3bad 691 if (!addrOnion.IsValid())
102518fd 692 return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs.count("-onion")?mapArgs["-onion"].c_str():mapArgs["-tor"].c_str()));
54ce3bad
PW
693 SetProxy(NET_TOR, addrOnion, 5);
694 SetReachable(NET_TOR);
587f929c
PW
695 }
696
697 // see Step 2: parameter interactions for more information about these
698 fNoListen = !GetBoolArg("-listen", true);
699 fDiscover = GetBoolArg("-discover", true);
700 fNameLookup = GetBoolArg("-dns", true);
928d3a01 701
7d80d2e3 702 bool fBound = false;
c73323ee 703 if (!fNoListen) {
7d80d2e3
PW
704 if (mapArgs.count("-bind")) {
705 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
706 CService addrBind;
707 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
708 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
c73323ee 709 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
7d80d2e3 710 }
c73323ee
PK
711 }
712 else {
7d80d2e3
PW
713 struct in_addr inaddr_any;
714 inaddr_any.s_addr = INADDR_ANY;
7d80d2e3 715#ifdef USE_IPV6
c73323ee 716 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
7d80d2e3 717#endif
c73323ee 718 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
7d80d2e3
PW
719 }
720 if (!fBound)
587f929c 721 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
928d3a01
JG
722 }
723
c73323ee 724 if (mapArgs.count("-externalip")) {
7d80d2e3
PW
725 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
726 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
727 if (!addrLocal.IsValid())
728 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
729 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
730 }
731 }
732
587f929c
PW
733 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
734 AddOneShot(strDest);
735
729b1806 736 // ********************************************************* Step 7: load block chain
7d80d2e3 737
3260b4c0 738 fReindex = GetBoolArg("-reindex", false);
7fea4846 739
f4445f99
GA
740 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
741 filesystem::path blocksDir = GetDataDir() / "blocks";
742 if (!filesystem::exists(blocksDir))
743 {
744 filesystem::create_directories(blocksDir);
745 bool linked = false;
746 for (unsigned int i = 1; i < 10000; i++) {
747 filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
748 if (!filesystem::exists(source)) break;
749 filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
750 try {
751 filesystem::create_hard_link(source, dest);
881a85a2 752 LogPrintf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
f4445f99
GA
753 linked = true;
754 } catch (filesystem::filesystem_error & e) {
755 // Note: hardlink creation failing is not a disaster, it just means
756 // blocks will get re-downloaded from peers.
881a85a2 757 LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
f4445f99
GA
758 break;
759 }
760 }
761 if (linked)
762 {
763 fReindex = true;
764 }
765 }
766
1c83b0a3
PW
767 // cache size calculations
768 size_t nTotalCache = GetArg("-dbcache", 25) << 20;
769 if (nTotalCache < (1 << 22))
770 nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
771 size_t nBlockTreeDBCache = nTotalCache / 8;
2d1fa42e 772 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1c83b0a3
PW
773 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
774 nTotalCache -= nBlockTreeDBCache;
775 size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
776 nTotalCache -= nCoinDBCache;
777 nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
778
f7f3a96b
PW
779 bool fLoaded = false;
780 while (!fLoaded) {
781 bool fReset = fReindex;
782 std::string strLoadError;
bb41a87d 783
f7f3a96b 784 uiInterface.InitMessage(_("Loading block index..."));
ae8bfd12 785
f7f3a96b
PW
786 nStart = GetTimeMillis();
787 do {
788 try {
789 UnloadBlockIndex();
790 delete pcoinsTip;
791 delete pcoinsdbview;
792 delete pblocktree;
793
794 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
795 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
796 pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
797
798 if (fReindex)
799 pblocktree->WriteReindexing(true);
800
801 if (!LoadBlockIndex()) {
802 strLoadError = _("Error loading block database");
803 break;
804 }
805
5d274c99
PW
806 // If the loaded chain has a wrong genesis, bail out immediately
807 // (we're likely using a testnet datadir, or the other way around).
4c6d41b8 808 if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL)
5d274c99
PW
809 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
810
f7f3a96b
PW
811 // Initialize the block index (no-op if non-empty database was already loaded)
812 if (!InitBlockIndex()) {
813 strLoadError = _("Error initializing block database");
814 break;
815 }
816
067a6092
PW
817 // Check for changed -txindex state
818 if (fTxIndex != GetBoolArg("-txindex", false)) {
819 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
820 break;
821 }
822
e1ca89df 823 uiInterface.InitMessage(_("Verifying blocks..."));
168ba993 824 if (!VerifyDB(GetArg("-checklevel", 3),
d78900cc 825 GetArg("-checkblocks", 288))) {
f7f3a96b
PW
826 strLoadError = _("Corrupted block database detected");
827 break;
828 }
829 } catch(std::exception &e) {
881a85a2 830 if (fDebug) LogPrintf("%s\n", e.what());
f7f3a96b
PW
831 strLoadError = _("Error opening block database");
832 break;
833 }
1f355b66 834
f7f3a96b
PW
835 fLoaded = true;
836 } while(false);
837
838 if (!fLoaded) {
839 // first suggest a reindex
840 if (!fReset) {
841 bool fRet = uiInterface.ThreadSafeMessageBox(
0206e38d 842 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
f7f3a96b
PW
843 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
844 if (fRet) {
845 fReindex = true;
846 fRequestShutdown = false;
847 } else {
881a85a2 848 LogPrintf("Aborted block database rebuild. Exiting.\n");
f7f3a96b
PW
849 return false;
850 }
851 } else {
852 return InitError(strLoadError);
853 }
854 }
855 }
871c3557 856
46469d0f
PK
857 // As LoadBlockIndex can take several minutes, it's possible the user
858 // requested to kill the GUI during the last operation. If so, exit.
871c3557
B
859 // As the program has not fully started yet, Shutdown() is possibly overkill.
860 if (fRequestShutdown)
861 {
881a85a2 862 LogPrintf("Shutdown requested. Exiting.\n");
871c3557
B
863 return false;
864 }
51ed9ec9 865 LogPrintf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart);
69d605f4 866
3260b4c0 867 if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false))
1d740055 868 {
7d80d2e3
PW
869 PrintBlockTree();
870 return false;
871 }
872
873 if (mapArgs.count("-printblock"))
874 {
875 string strMatch = mapArgs["-printblock"];
876 int nFound = 0;
877 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1d740055 878 {
7d80d2e3
PW
879 uint256 hash = (*mi).first;
880 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
881 {
882 CBlockIndex* pindex = (*mi).second;
883 CBlock block;
7db120d5 884 ReadBlockFromDisk(block, pindex);
7d80d2e3
PW
885 block.BuildMerkleTree();
886 block.print();
881a85a2 887 LogPrintf("\n");
7d80d2e3
PW
888 nFound++;
889 }
1d740055 890 }
7d80d2e3 891 if (nFound == 0)
881a85a2 892 LogPrintf("No blocks matching %s were found\n", strMatch.c_str());
7d80d2e3 893 return false;
1d740055
PW
894 }
895
eed1785f 896 // ********************************************************* Step 8: load wallet
48ba56cd 897#ifdef ENABLE_WALLET
e6b7e3dc
JG
898 if (fDisableWallet) {
899 pwalletMain = NULL;
900 LogPrintf("Wallet disabled!\n");
901 } else {
f9ee7a03 902 uiInterface.InitMessage(_("Loading wallet..."));
bb41a87d 903
f9ee7a03
JG
904 nStart = GetTimeMillis();
905 bool fFirstRun = true;
906 pwalletMain = new CWallet(strWalletFile);
907 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
908 if (nLoadWalletRet != DB_LOAD_OK)
eed1785f 909 {
f9ee7a03
JG
910 if (nLoadWalletRet == DB_CORRUPT)
911 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
912 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
913 {
914 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
915 " or address book entries might be missing or incorrect."));
916 InitWarning(msg);
917 }
918 else if (nLoadWalletRet == DB_TOO_NEW)
919 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
920 else if (nLoadWalletRet == DB_NEED_REWRITE)
921 {
922 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
923 LogPrintf("%s", strErrors.str().c_str());
924 return InitError(strErrors.str());
925 }
926 else
927 strErrors << _("Error loading wallet.dat") << "\n";
eed1785f 928 }
f9ee7a03
JG
929
930 if (GetBoolArg("-upgradewallet", fFirstRun))
d764d916 931 {
f9ee7a03
JG
932 int nMaxVersion = GetArg("-upgradewallet", 0);
933 if (nMaxVersion == 0) // the -upgradewallet without argument case
934 {
935 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
936 nMaxVersion = CLIENT_VERSION;
937 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
938 }
939 else
940 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
941 if (nMaxVersion < pwalletMain->GetVersion())
942 strErrors << _("Cannot downgrade wallet") << "\n";
943 pwalletMain->SetMaxVersion(nMaxVersion);
d764d916 944 }
439e1497 945
f9ee7a03 946 if (fFirstRun)
439e1497 947 {
f9ee7a03
JG
948 // Create new keyUser and set as default key
949 RandAddSeedPerfmon();
950
951 CPubKey newDefaultKey;
952 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
953 pwalletMain->SetDefaultKey(newDefaultKey);
954 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
955 strErrors << _("Cannot write default address") << "\n";
956 }
439e1497 957
f9ee7a03 958 pwalletMain->SetBestChain(chainActive.GetLocator());
360cfe14 959 }
95c7db3d 960
f9ee7a03
JG
961 LogPrintf("%s", strErrors.str().c_str());
962 LogPrintf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart);
69d605f4 963
f9ee7a03 964 RegisterWallet(pwalletMain);
e8ef3da7 965
f9ee7a03
JG
966 CBlockIndex *pindexRescan = chainActive.Tip();
967 if (GetBoolArg("-rescan", false))
4c6d41b8 968 pindexRescan = chainActive.Genesis();
f9ee7a03
JG
969 else
970 {
971 CWalletDB walletdb(strWalletFile);
972 CBlockLocator locator;
973 if (walletdb.ReadBestBlock(locator))
974 pindexRescan = chainActive.FindFork(locator);
975 else
976 pindexRescan = chainActive.Genesis();
977 }
978 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
979 {
980 uiInterface.InitMessage(_("Rescanning..."));
981 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
982 nStart = GetTimeMillis();
983 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
984 LogPrintf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart);
985 pwalletMain->SetBestChain(chainActive.GetLocator());
986 nWalletDBUpdated++;
987 }
e6b7e3dc 988 } // (!fDisableWallet)
48ba56cd
WL
989#else // ENABLE_WALLET
990 LogPrintf("No wallet compiled in!\n");
991#endif // !ENABLE_WALLET
eed1785f 992 // ********************************************************* Step 9: import blocks
0fcf91ea 993
4fea06db 994 // scan for better chains in the block chain database, that are not yet connected in the active best chain
ef3988ca
PW
995 CValidationState state;
996 if (!ConnectBestBlock(state))
857c61df 997 strErrors << "Failed to connect best block";
4fea06db 998
21eb5ada 999 std::vector<boost::filesystem::path> vImportFiles;
7d80d2e3 1000 if (mapArgs.count("-loadblock"))
69d605f4 1001 {
7d80d2e3 1002 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
21eb5ada 1003 vImportFiles.push_back(strFile);
52c90a2b 1004 }
21eb5ada 1005 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
52c90a2b 1006
eed1785f 1007 // ********************************************************* Step 10: load peers
0fcf91ea 1008
7d80d2e3 1009 uiInterface.InitMessage(_("Loading addresses..."));
bb41a87d 1010
7d80d2e3 1011 nStart = GetTimeMillis();
7bf8b7c2 1012
0fcf91ea 1013 {
7d80d2e3
PW
1014 CAddrDB adb;
1015 if (!adb.Read(addrman))
881a85a2 1016 LogPrintf("Invalid or missing peers.dat; recreating\n");
0fcf91ea
GA
1017 }
1018
51ed9ec9 1019 LogPrintf("Loaded %i addresses from peers.dat %"PRId64"ms\n",
7d80d2e3 1020 addrman.size(), GetTimeMillis() - nStart);
69d605f4 1021
eed1785f 1022 // ********************************************************* Step 11: start node
69d605f4 1023
69d605f4
WL
1024 if (!CheckDiskSpace())
1025 return false;
1026
d605bc4c
GA
1027 if (!strErrors.str().empty())
1028 return InitError(strErrors.str());
1029
69d605f4
WL
1030 RandAddSeedPerfmon();
1031
7d80d2e3 1032 //// debug print
881a85a2 1033 LogPrintf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
4c6d41b8 1034 LogPrintf("nBestHeight = %d\n", chainActive.Height());
48ba56cd 1035#ifdef ENABLE_WALLET
b0730874
JG
1036 LogPrintf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1037 LogPrintf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1038 LogPrintf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
48ba56cd 1039#endif
7d80d2e3 1040
b31499ec 1041 StartNode(threadGroup);
d98bf10f
WL
1042 // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
1043 InitRPCMining();
69d605f4 1044 if (fServer)
21eb5ada 1045 StartRPCThreads();
69d605f4 1046
48ba56cd 1047#ifdef ENABLE_WALLET
a0cafb79 1048 // Generate coins in the background
b0730874 1049 if (pwalletMain)
c8b74258 1050 GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", -1));
48ba56cd 1051#endif
a0cafb79 1052
eed1785f 1053 // ********************************************************* Step 12: finished
7d80d2e3
PW
1054
1055 uiInterface.InitMessage(_("Done loading"));
7d80d2e3 1056
48ba56cd 1057#ifdef ENABLE_WALLET
b0730874
JG
1058 if (pwalletMain) {
1059 // Add wallet transactions that aren't already in a block to mapTransactions
1060 pwalletMain->ReacceptWalletTransactions();
7d80d2e3 1061
b0730874
JG
1062 // Run a thread to flush wallet periodically
1063 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1064 }
48ba56cd 1065#endif
69d605f4 1066
b31499ec 1067 return !fRequestShutdown;
69d605f4 1068}
This page took 0.327638 seconds and 4 git commands to generate.