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