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