Reorganize at startup to best known block
[novacoin.git] / src / init.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include "db.h"
6 #include "walletdb.h"
7 #include "bitcoinrpc.h"
8 #include "net.h"
9 #include "init.h"
10 #include "util.h"
11 #include "ui_interface.h"
12 #include "checkpoints.h"
13 #include "zerocoin/ZeroTest.h"
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/filesystem/convenience.hpp>
17 #include <boost/interprocess/sync/file_lock.hpp>
18 #include <boost/algorithm/string/predicate.hpp>
19 #include <openssl/crypto.h>
20
21 #ifndef WIN32
22 #include <signal.h>
23 #endif
24
25
26 using namespace std;
27 using namespace boost;
28
29 CWallet* pwalletMain;
30 CClientUIInterface uiInterface;
31 std::string strWalletFileName;
32 unsigned int nNodeLifespan;
33 unsigned int nDerivationMethodIndex;
34 unsigned int nMinerSleep;
35 bool fUseFastIndex;
36 bool fUseFastStakeMiner;
37 enum Checkpoints::CPMode CheckpointsMode;
38
39 //////////////////////////////////////////////////////////////////////////////
40 //
41 // Shutdown
42 //
43
44 void ExitTimeout(void* parg)
45 {
46 #ifdef WIN32
47     Sleep(5000);
48     ExitProcess(0);
49 #endif
50 }
51
52 void StartShutdown()
53 {
54 #ifdef QT_GUI
55     // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
56     uiInterface.QueueShutdown();
57 #else
58     // Without UI, Shutdown() can simply be started in a new thread
59     NewThread(Shutdown, NULL);
60 #endif
61 }
62
63 static CCoinsViewDB *pcoinsdbview;
64
65 void Shutdown(void* parg)
66 {
67     static CCriticalSection cs_Shutdown;
68     static bool fTaken;
69
70     // Make this thread recognisable as the shutdown thread
71     RenameThread("bitcoin-shutoff");
72
73     bool fFirstThread = false;
74     {
75         TRY_LOCK(cs_Shutdown, lockShutdown);
76         if (lockShutdown)
77         {
78             fFirstThread = !fTaken;
79             fTaken = true;
80         }
81     }
82     static bool fExit;
83     if (fFirstThread)
84     {
85         fShutdown = true;
86         nTransactionsUpdated++;
87         bitdb.Flush(false);
88         StopNode();
89         {
90             LOCK(cs_main);
91             pcoinsTip->Flush();
92             delete pcoinsTip;
93             delete pcoinsdbview;
94         }
95         bitdb.Flush(true);
96         boost::filesystem::remove(GetPidFile());
97         UnregisterWallet(pwalletMain);
98         delete pwalletMain;
99         NewThread(ExitTimeout, NULL);
100         Sleep(50);
101         printf("NovaCoin exited\n\n");
102         fExit = true;
103 #ifndef QT_GUI
104         // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
105         exit(0);
106 #endif
107     }
108     else
109     {
110         while (!fExit)
111             Sleep(500);
112         Sleep(100);
113         ExitThread(0);
114     }
115 }
116
117 void HandleSIGTERM(int)
118 {
119     fRequestShutdown = true;
120 }
121
122 void HandleSIGHUP(int)
123 {
124     fReopenDebugLog = true;
125 }
126
127
128
129
130
131 //////////////////////////////////////////////////////////////////////////////
132 //
133 // Start
134 //
135 #if !defined(QT_GUI)
136 bool AppInit(int argc, char* argv[])
137 {
138     bool fRet = false;
139     try
140     {
141         //
142         // Parameters
143         //
144         // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
145         ParseParameters(argc, argv);
146         if (!boost::filesystem::is_directory(GetDataDir(false)))
147         {
148             fprintf(stderr, "Error: Specified directory does not exist\n");
149             Shutdown(NULL);
150         }
151         ReadConfigFile(mapArgs, mapMultiArgs);
152
153         if (mapArgs.count("-?") || mapArgs.count("--help"))
154         {
155             // First part of help message is specific to bitcoind / RPC client
156             std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
157                 _("Usage:") + "\n" +
158                   "  novacoind [options]                     " + "\n" +
159                   "  novacoind [options] <command> [params]  " + _("Send command to -server or novacoind") + "\n" +
160                   "  novacoind [options] help                " + _("List commands") + "\n" +
161                   "  novacoind [options] help <command>      " + _("Get help for a command") + "\n";
162
163             strUsage += "\n" + HelpMessage();
164
165             fprintf(stdout, "%s", strUsage.c_str());
166             return false;
167         }
168
169         // Command-line RPC
170         for (int i = 1; i < argc; i++)
171             if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
172                 fCommandLine = true;
173
174         if (fCommandLine)
175         {
176             int ret = CommandLineRPC(argc, argv);
177             exit(ret);
178         }
179
180         fRet = AppInit2();
181     }
182     catch (std::exception& e) {
183         PrintException(&e, "AppInit()");
184     } catch (...) {
185         PrintException(NULL, "AppInit()");
186     }
187     if (!fRet)
188         Shutdown(NULL);
189     return fRet;
190 }
191
192 extern void noui_connect();
193 int main(int argc, char* argv[])
194 {
195     bool fRet = false;
196
197     // Connect bitcoind signal handlers
198     noui_connect();
199
200     fRet = AppInit(argc, argv);
201
202     if (fRet && fDaemon)
203         return 0;
204
205     return 1;
206 }
207 #endif
208
209 bool static InitError(const std::string &str)
210 {
211     uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
212     return false;
213 }
214
215 bool static InitWarning(const std::string &str)
216 {
217     uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
218     return true;
219 }
220
221
222 bool static Bind(const CService &addr, bool fError = true) {
223     if (IsLimited(addr))
224         return false;
225     std::string strError;
226     if (!BindListenPort(addr, strError)) {
227         if (fError)
228             return InitError(strError);
229         return false;
230     }
231     return true;
232 }
233
234 // Core-specific options shared between UI and daemon
235 std::string HelpMessage()
236 {
237     string strUsage = _("Options:") + "\n" +
238         "  -?                     " + _("This help message") + "\n" +
239         "  -conf=<file>           " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
240         "  -pid=<file>            " + _("Specify pid file (default: novacoind.pid)") + "\n" +
241         "  -datadir=<dir>         " + _("Specify data directory") + "\n" +
242         "  -wallet=<dir>          " + _("Specify wallet file (within data directory)") + "\n" +
243         "  -dbcache=<n>           " + _("Set database cache size in megabytes (default: 25)") + "\n" +
244         "  -dblogsize=<n>         " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
245         "  -timeout=<n>           " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
246         "  -proxy=<ip:port>       " + _("Connect through socks proxy") + "\n" +
247         "  -socks=<n>             " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
248         "  -tor=<ip:port>         " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
249         "  -dns                   " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
250         "  -port=<port>           " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
251         "  -maxconnections=<n>    " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
252         "  -addnode=<ip>          " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
253         "  -connect=<ip>          " + _("Connect only to the specified node(s)") + "\n" +
254         "  -seednode=<ip>         " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
255         "  -externalip=<ip>       " + _("Specify your own public address") + "\n" +
256         "  -onlynet=<net>         " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
257         "  -discover              " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
258         "  -irc                   " + _("Find peers using internet relay chat (default: 1)") + "\n" +
259         "  -listen                " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
260         "  -bind=<addr>           " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
261         "  -dnsseed               " + _("Find peers using DNS lookup (default: 1)") + "\n" +
262         "  -cppolicy              " + _("Sync checkpoints policy (default: strict)") + "\n" +
263         "  -banscore=<n>          " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
264         "  -bantime=<n>           " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
265         "  -maxreceivebuffer=<n>  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
266         "  -maxsendbuffer=<n>     " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
267 #ifdef USE_UPNP
268 #if USE_UPNP
269         "  -upnp                  " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
270 #else
271         "  -upnp                  " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
272 #endif
273 #endif
274         "  -detachdb              " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
275         "  -paytxfee=<amt>        " + _("Fee per KB to add to transactions you send") + "\n" +
276         "  -mininput=<amt>        " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
277 #ifdef QT_GUI
278         "  -server                " + _("Accept command line and JSON-RPC commands") + "\n" +
279 #endif
280 #if !defined(WIN32) && !defined(QT_GUI)
281         "  -daemon                " + _("Run in the background as a daemon and accept commands") + "\n" +
282 #endif
283         "  -testnet               " + _("Use the test network") + "\n" +
284         "  -debug                 " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
285         "  -debugnet              " + _("Output extra network debugging information") + "\n" +
286         "  -logtimestamps         " + _("Prepend debug output with timestamp") + "\n" +
287         "  -shrinkdebugfile       " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
288         "  -printtoconsole        " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
289 #ifdef WIN32
290         "  -printtodebugger       " + _("Send trace/debug info to debugger") + "\n" +
291 #endif
292         "  -rpcuser=<user>        " + _("Username for JSON-RPC connections") + "\n" +
293         "  -rpcpassword=<pw>      " + _("Password for JSON-RPC connections") + "\n" +
294         "  -rpcport=<port>        " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
295         "  -rpcallowip=<ip>       " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
296         "  -rpcconnect=<ip>       " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
297         "  -blocknotify=<cmd>     " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
298         "  -walletnotify=<cmd>    " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
299         "  -upgradewallet         " + _("Upgrade wallet to latest format") + "\n" +
300         "  -keypool=<n>           " + _("Set key pool size to <n> (default: 100)") + "\n" +
301         "  -rescan                " + _("Rescan the block chain for missing wallet transactions") + "\n" +
302         "  -salvagewallet         " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
303         "  -checkblocks=<n>       " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
304         "  -checklevel=<n>        " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
305         "  -loadblock=<file>      " + _("Imports blocks from external blk000?.dat file") + "\n" +
306
307         "\n" + _("Block creation options:") + "\n" +
308         "  -blockminsize=<n>      "   + _("Set minimum block size in bytes (default: 0)") + "\n" +
309         "  -blockmaxsize=<n>      "   + _("Set maximum block size in bytes (default: 250000)") + "\n" +
310         "  -blockprioritysize=<n> "   + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
311
312         "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
313         "  -rpcssl                                  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
314         "  -rpcsslcertificatechainfile=<file.cert>  " + _("Server certificate file (default: server.cert)") + "\n" +
315         "  -rpcsslprivatekeyfile=<file.pem>         " + _("Server private key (default: server.pem)") + "\n" +
316         "  -rpcsslciphers=<ciphers>                 " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
317
318     return strUsage;
319 }
320
321 /** Initialize bitcoin.
322  *  @pre Parameters should be parsed and config file should be read.
323  */
324 bool AppInit2()
325 {
326     // ********************************************************* Step 1: setup
327 #ifdef _MSC_VER
328     // Turn off Microsoft heap dump noise
329     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
330     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
331 #endif
332 #if _MSC_VER >= 1400
333     // Disable confusing "helpful" text message on abort, Ctrl-C
334     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
335 #endif
336 #ifdef WIN32
337     // Enable Data Execution Prevention (DEP)
338     // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
339     // A failure is non-critical and needs no further attention!
340 #ifndef PROCESS_DEP_ENABLE
341 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
342 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
343 #define PROCESS_DEP_ENABLE 0x00000001
344 #endif
345     typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
346     PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
347     if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
348 #endif
349 #ifndef WIN32
350     umask(077);
351
352     // Clean shutdown on SIGTERM
353     struct sigaction sa;
354     sa.sa_handler = HandleSIGTERM;
355     sigemptyset(&sa.sa_mask);
356     sa.sa_flags = 0;
357     sigaction(SIGTERM, &sa, NULL);
358     sigaction(SIGINT, &sa, NULL);
359
360     // Reopen debug.log on SIGHUP
361     struct sigaction sa_hup;
362     sa_hup.sa_handler = HandleSIGHUP;
363     sigemptyset(&sa_hup.sa_mask);
364     sa_hup.sa_flags = 0;
365     sigaction(SIGHUP, &sa_hup, NULL);
366 #endif
367
368     // ********************************************************* Step 2: parameter interactions
369
370     nNodeLifespan = GetArg("-addrlifespan", 7);
371     fUseFastIndex = GetBoolArg("-fastindex", true);
372     nMinerSleep = GetArg("-minersleep", 500);
373
374     CheckpointsMode = Checkpoints::STRICT;
375     std::string strCpMode = GetArg("-cppolicy", "strict");
376
377     if(strCpMode == "strict")
378         CheckpointsMode = Checkpoints::STRICT;
379
380     if(strCpMode == "advisory")
381         CheckpointsMode = Checkpoints::ADVISORY;
382
383     if(strCpMode == "permissive")
384         CheckpointsMode = Checkpoints::PERMISSIVE;
385
386     nDerivationMethodIndex = 0;
387
388     fTestNet = GetBoolArg("-testnet");
389     if (fTestNet) {
390         SoftSetBoolArg("-irc", true);
391     }
392
393     if (mapArgs.count("-bind")) {
394         // when specifying an explicit binding address, you want to listen on it
395         // even when -connect or -proxy is specified
396         SoftSetBoolArg("-listen", true);
397     }
398
399     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
400         // when only connecting to trusted nodes, do not seed via DNS, or listen by default
401         SoftSetBoolArg("-dnsseed", false);
402         SoftSetBoolArg("-listen", false);
403     }
404
405     if (mapArgs.count("-proxy")) {
406         // to protect privacy, do not listen by default if a proxy server is specified
407         SoftSetBoolArg("-listen", false);
408     }
409
410     if (!GetBoolArg("-listen", true)) {
411         // do not map ports or try to retrieve public IP when not listening (pointless)
412         SoftSetBoolArg("-upnp", false);
413         SoftSetBoolArg("-discover", false);
414     }
415
416     if (mapArgs.count("-externalip")) {
417         // if an explicit public IP is specified, do not try to find others
418         SoftSetBoolArg("-discover", false);
419     }
420
421     if (GetBoolArg("-salvagewallet")) {
422         // Rewrite just private keys: rescan to find transactions
423         SoftSetBoolArg("-rescan", true);
424     }
425
426     // ********************************************************* Step 3: parameter-to-internal-flags
427
428     fDebug = GetBoolArg("-debug");
429
430     // -debug implies fDebug*
431     if (fDebug)
432         fDebugNet = true;
433     else
434         fDebugNet = GetBoolArg("-debugnet");
435
436     bitdb.SetDetach(GetBoolArg("-detachdb", false));
437
438 #if !defined(WIN32) && !defined(QT_GUI)
439     fDaemon = GetBoolArg("-daemon");
440 #else
441     fDaemon = false;
442 #endif
443
444     if (fDaemon)
445         fServer = true;
446     else
447         fServer = GetBoolArg("-server");
448
449     /* force fServer when running without GUI */
450 #if !defined(QT_GUI)
451     fServer = true;
452 #endif
453     fPrintToConsole = GetBoolArg("-printtoconsole");
454     fPrintToDebugger = GetBoolArg("-printtodebugger");
455     fLogTimestamps = GetBoolArg("-logtimestamps");
456
457     if (mapArgs.count("-timeout"))
458     {
459         int nNewTimeout = GetArg("-timeout", 5000);
460         if (nNewTimeout > 0 && nNewTimeout < 600000)
461             nConnectTimeout = nNewTimeout;
462     }
463
464     // Continue to put "/P2SH/" in the coinbase to monitor
465     // BIP16 support.
466     // This can be removed eventually...
467     const char* pszP2SH = "/P2SH/";
468     COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
469
470
471     if (mapArgs.count("-paytxfee"))
472     {
473         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
474             return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
475         if (nTransactionFee > 0.25 * COIN)
476             InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
477     }
478
479     if (mapArgs.count("-mininput"))
480     {
481         if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
482             return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
483     }
484
485     // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
486
487     std::string strDataDir = GetDataDir().string();
488     std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
489
490     // strWalletFileName must be a plain filename without a directory
491     if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
492         return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
493
494     // Make sure only a single Bitcoin process is using the data directory.
495     boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
496     FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
497     if (file) fclose(file);
498     static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
499     if (!lock.try_lock())
500         return InitError(strprintf(_("Cannot obtain a lock on data directory %s.  NovaCoin is probably already running."), strDataDir.c_str()));
501
502 #if !defined(WIN32) && !defined(QT_GUI)
503     if (fDaemon)
504     {
505         // Daemonize
506         pid_t pid = fork();
507         if (pid < 0)
508         {
509             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
510             return false;
511         }
512         if (pid > 0)
513         {
514             CreatePidFile(GetPidFile(), pid);
515             return true;
516         }
517
518         pid_t sid = setsid();
519         if (sid < 0)
520             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
521     }
522 #endif
523
524     if (GetBoolArg("-shrinkdebugfile", !fDebug))
525         ShrinkDebugFile();
526     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
527     printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
528     printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
529     if (!fLogTimestamps)
530         printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
531     printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
532     printf("Used data directory %s\n", strDataDir.c_str());
533     std::ostringstream strErrors;
534
535     if (fDaemon)
536         fprintf(stdout, "NovaCoin server starting\n");
537
538     int64 nStart;
539
540     // ********************************************************* Step 5: verify database integrity
541
542     uiInterface.InitMessage(_("Verifying database integrity..."));
543
544     if (!bitdb.Open(GetDataDir()))
545     {
546         string msg = strprintf(_("Error initializing database environment %s!"
547                                  " To recover, BACKUP THAT DIRECTORY, then remove"
548                                  " everything from it except for wallet.dat."), strDataDir.c_str());
549         return InitError(msg);
550     }
551
552     if (GetBoolArg("-salvagewallet"))
553     {
554         // Recover readable keypairs:
555         if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
556             return false;
557     }
558
559     if (filesystem::exists(GetDataDir() / strWalletFileName))
560     {
561         CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
562         if (r == CDBEnv::RECOVER_OK)
563         {
564             string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
565                                      " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
566                                      " your balance or transactions are incorrect you should"
567                                      " restore from a backup."), strDataDir.c_str());
568             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
569         }
570         if (r == CDBEnv::RECOVER_FAIL)
571             return InitError(_("wallet.dat corrupt, salvage failed"));
572     }
573
574     // ********************************************************* Step 6: network initialization
575
576     int nSocksVersion = GetArg("-socks", 5);
577
578     if (nSocksVersion != 4 && nSocksVersion != 5)
579         return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
580
581     if (mapArgs.count("-onlynet")) {
582         std::set<enum Network> nets;
583         BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
584             enum Network net = ParseNetwork(snet);
585             if (net == NET_UNROUTABLE)
586                 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
587             nets.insert(net);
588         }
589         for (int n = 0; n < NET_MAX; n++) {
590             enum Network net = (enum Network)n;
591             if (!nets.count(net))
592                 SetLimited(net);
593         }
594     }
595 #if defined(USE_IPV6)
596 #if ! USE_IPV6
597     else
598         SetLimited(NET_IPV6);
599 #endif
600 #endif
601
602     CService addrProxy;
603     bool fProxy = false;
604     if (mapArgs.count("-proxy")) {
605         addrProxy = CService(mapArgs["-proxy"], 9050);
606         if (!addrProxy.IsValid())
607             return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
608
609         if (!IsLimited(NET_IPV4))
610             SetProxy(NET_IPV4, addrProxy, nSocksVersion);
611         if (nSocksVersion > 4) {
612 #ifdef USE_IPV6
613             if (!IsLimited(NET_IPV6))
614                 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
615 #endif
616             SetNameProxy(addrProxy, nSocksVersion);
617         }
618         fProxy = true;
619     }
620
621     // -tor can override normal proxy, -notor disables tor entirely
622     if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
623         CService addrOnion;
624         if (!mapArgs.count("-tor"))
625             addrOnion = addrProxy;
626         else
627             addrOnion = CService(mapArgs["-tor"], 9050);
628         if (!addrOnion.IsValid())
629             return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
630         SetProxy(NET_TOR, addrOnion, 5);
631         SetReachable(NET_TOR);
632     }
633
634     // see Step 2: parameter interactions for more information about these
635     fNoListen = !GetBoolArg("-listen", true);
636     fDiscover = GetBoolArg("-discover", true);
637     fNameLookup = GetBoolArg("-dns", true);
638 #ifdef USE_UPNP
639     fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
640 #endif
641
642     bool fBound = false;
643     if (!fNoListen)
644     {
645         std::string strError;
646         if (mapArgs.count("-bind")) {
647             BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
648                 CService addrBind;
649                 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
650                     return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
651                 fBound |= Bind(addrBind);
652             }
653         } else {
654             struct in_addr inaddr_any;
655             inaddr_any.s_addr = INADDR_ANY;
656 #ifdef USE_IPV6
657             if (!IsLimited(NET_IPV6))
658                 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
659 #endif
660             if (!IsLimited(NET_IPV4))
661                 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
662         }
663         if (!fBound)
664             return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
665     }
666
667     if (mapArgs.count("-externalip"))
668     {
669         BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
670             CService addrLocal(strAddr, GetListenPort(), fNameLookup);
671             if (!addrLocal.IsValid())
672                 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
673             AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
674         }
675     }
676
677     if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
678     {
679         int64 nReserveBalance = 0;
680         if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
681         {
682             InitError(_("Invalid amount for -reservebalance=<amount>"));
683             return false;
684         }
685     }
686
687     if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
688     {
689         if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
690             InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
691     }
692
693     BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
694         AddOneShot(strDest);
695
696     // ********************************************************* Step 7: load blockchain
697
698     if (!bitdb.Open(GetDataDir()))
699     {
700         string msg = strprintf(_("Error initializing database environment %s!"
701                                  " To recover, BACKUP THAT DIRECTORY, then remove"
702                                  " everything from it except for wallet.dat."), strDataDir.c_str());
703         return InitError(msg);
704     }
705
706     uiInterface.InitMessage(_("Loading block index..."));
707     printf("Loading block index...\n");
708     nStart = GetTimeMillis();
709     pcoinsdbview = new CCoinsViewDB();
710     pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
711
712     if (!LoadBlockIndex())
713         return InitError(_("Error loading blkindex.dat"));
714
715     // as LoadBlockIndex can take several minutes, it's possible the user
716     // requested to kill bitcoin-qt during the last operation. If so, exit.
717     // As the program has not fully started yet, Shutdown() is possibly overkill.
718     if (fRequestShutdown)
719     {
720         printf("Shutdown requested. Exiting.\n");
721         return false;
722     }
723     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
724
725     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
726     {
727         PrintBlockTree();
728         return false;
729     }
730
731     if (mapArgs.count("-printblock"))
732     {
733         string strMatch = mapArgs["-printblock"];
734         int nFound = 0;
735         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
736         {
737             uint256 hash = (*mi).first;
738             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
739             {
740                 CBlockIndex* pindex = (*mi).second;
741                 CBlock block;
742                 block.ReadFromDisk(pindex);
743                 block.BuildMerkleTree();
744                 block.print();
745                 printf("\n");
746                 nFound++;
747             }
748         }
749         if (nFound == 0)
750             printf("No blocks matching %s were found\n", strMatch.c_str());
751         return false;
752     }
753
754     // ********************************************************* Testing Zerocoin
755
756
757     if (GetBoolArg("-zerotest", false))
758     {
759         printf("\n=== ZeroCoin tests start ===\n");
760         Test_RunAllTests();
761         printf("=== ZeroCoin tests end ===\n\n");
762     }
763
764     // ********************************************************* Step 8: load wallet
765
766     uiInterface.InitMessage(_("Loading wallet..."));
767     printf("Loading wallet...\n");
768     nStart = GetTimeMillis();
769     bool fFirstRun = true;
770     pwalletMain = new CWallet(strWalletFileName);
771     DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
772     if (nLoadWalletRet != DB_LOAD_OK)
773     {
774         if (nLoadWalletRet == DB_CORRUPT)
775             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
776         else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
777         {
778             string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
779                          " or address book entries might be missing or incorrect."));
780             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
781         }
782         else if (nLoadWalletRet == DB_TOO_NEW)
783             strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
784         else if (nLoadWalletRet == DB_NEED_REWRITE)
785         {
786             strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
787             printf("%s", strErrors.str().c_str());
788             return InitError(strErrors.str());
789         }
790         else
791             strErrors << _("Error loading wallet.dat") << "\n";
792     }
793
794     if (GetBoolArg("-upgradewallet", fFirstRun))
795     {
796         int nMaxVersion = GetArg("-upgradewallet", 0);
797         if (nMaxVersion == 0) // the -upgradewallet without argument case
798         {
799             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
800             nMaxVersion = CLIENT_VERSION;
801             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
802         }
803         else
804             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
805         if (nMaxVersion < pwalletMain->GetVersion())
806             strErrors << _("Cannot downgrade wallet") << "\n";
807         pwalletMain->SetMaxVersion(nMaxVersion);
808     }
809
810     if (fFirstRun)
811     {
812         // Create new keyUser and set as default key
813         RandAddSeedPerfmon();
814
815         CPubKey newDefaultKey;
816         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
817             strErrors << _("Cannot initialize keypool") << "\n";
818         pwalletMain->SetDefaultKey(newDefaultKey);
819         if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
820             strErrors << _("Cannot write default address") << "\n";
821     }
822
823     printf("%s", strErrors.str().c_str());
824     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
825
826     RegisterWallet(pwalletMain);
827
828     CBlockIndex *pindexRescan = pindexBest;
829     if (GetBoolArg("-rescan"))
830         pindexRescan = pindexGenesisBlock;
831     else
832     {
833         CWalletDB walletdb(strWalletFileName);
834         CBlockLocator locator;
835         if (walletdb.ReadBestBlock(locator))
836             pindexRescan = locator.GetBlockIndex();
837     }
838     if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
839     {
840         uiInterface.InitMessage(_("Rescanning..."));
841         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
842         nStart = GetTimeMillis();
843         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
844         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
845     }
846
847     // ********************************************************* Step 9: import blocks
848
849     // scan for better chains in the block chain database, that are not yet connected in the active best chain
850     CBlockIndex *pindexFoundBest = pindexBest;
851     for (std::map<uint256,CBlockIndex*>::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
852         CBlockIndex *pindex = it->second;
853         if (pindexFoundBest==NULL || pindex->nChainTrust > pindexFoundBest->nChainTrust)
854             pindexFoundBest = pindex;
855     }
856     if (pindexFoundBest != pindexBest) {
857         uiInterface.InitMessage(_("Importing blocks from block database..."));
858         uint64 nTxs = 0;
859         uint64 nBlocks = 0;
860         std::vector<CBlockIndex*> vAttach;
861         vAttach.reserve(pindexFoundBest->nHeight - (pindexBest==NULL ? 0 : pindexBest->nHeight));
862         while (pindexFoundBest && pindexFoundBest->nChainTrust > (pindexBest==NULL ? 0 : pindexBest->nChainTrust)) {
863             vAttach.push_back(pindexFoundBest);
864             pindexFoundBest = pindexFoundBest->pprev;
865         }
866         for (std::vector<CBlockIndex*>::reverse_iterator it = vAttach.rbegin(); it != vAttach.rend(); it++) {
867             CBlockIndex *pindex = *it;
868             CBlock block;
869             if (!block.ReadFromDisk(pindex))
870                 break;
871             nTxs += block.vtx.size();
872             nBlocks++;
873             if (pindex->nHeight == 0 || nTxs + nBlocks*3 > 500) {
874                 nTxs=0;
875                 nBlocks=0;
876                 block.SetBestChain(pindex);
877             }
878             if (fRequestShutdown)
879                 break;
880         }
881     }
882
883     if (mapArgs.count("-loadblock"))
884     {
885         uiInterface.InitMessage(_("Importing blockchain data file."));
886
887         BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
888         {
889             FILE *file = fopen(strFile.c_str(), "rb");
890             if (file)
891                 LoadExternalBlockFile(file);
892         }
893         exit(0);
894     }
895
896     filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
897     if (filesystem::exists(pathBootstrap)) {
898         uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
899
900         FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
901         if (file) {
902             filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
903             LoadExternalBlockFile(file);
904             RenameOver(pathBootstrap, pathBootstrapOld);
905         }
906     }
907
908     // ********************************************************* Step 10: load peers
909
910     uiInterface.InitMessage(_("Loading addresses..."));
911     printf("Loading addresses...\n");
912     nStart = GetTimeMillis();
913
914     {
915         CAddrDB adb;
916         if (!adb.Read(addrman))
917             printf("Invalid or missing peers.dat; recreating\n");
918     }
919
920     printf("Loaded %i addresses from peers.dat  %"PRI64d"ms\n",
921            addrman.size(), GetTimeMillis() - nStart);
922
923     // ********************************************************* Step 11: start node
924
925     if (!CheckDiskSpace())
926         return false;
927
928     RandAddSeedPerfmon();
929
930     //// debug print
931     printf("mapBlockIndex.size() = %"PRIszu"\n",   mapBlockIndex.size());
932     printf("nBestHeight = %d\n",            nBestHeight);
933     printf("setKeyPool.size() = %"PRIszu"\n",      pwalletMain->setKeyPool.size());
934     printf("mapWallet.size() = %"PRIszu"\n",       pwalletMain->mapWallet.size());
935     printf("mapAddressBook.size() = %"PRIszu"\n",  pwalletMain->mapAddressBook.size());
936
937     if (!NewThread(StartNode, NULL))
938         InitError(_("Error: could not start node"));
939
940     if (fServer)
941         NewThread(ThreadRPCServer, NULL);
942
943     // ********************************************************* Step 12: finished
944
945     uiInterface.InitMessage(_("Done loading"));
946     printf("Done loading\n");
947
948     if (!strErrors.str().empty())
949         return InitError(strErrors.str());
950
951      // Add wallet transactions that aren't already in a block to mapTransactions
952     pwalletMain->ReacceptWalletTransactions();
953
954 #if !defined(QT_GUI)
955     // Loop until process is exit()ed from shutdown() function,
956     // called from ThreadRPCServer thread when a "stop" command is received.
957     while (1)
958         Sleep(5000);
959 #endif
960
961     return true;
962 }