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