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