90bf8de066f2720ed55afb3a34294e7af5afc426
[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 socks proxy") + "\n" +
243         "  -socks=<n>             " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
244         "  -tor=<ip:port>         " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
245         "  -torname=<host.onion>  " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
246         "  -dns                   " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
247         "  -port=<port>           " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
248         "  -maxconnections=<n>    " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
249         "  -addnode=<ip>          " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
250         "  -connect=<ip>          " + _("Connect only to the specified node(s)") + "\n" +
251         "  -seednode=<ip>         " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
252         "  -externalip=<ip>       " + _("Specify your own public address") + "\n" +
253         "  -onlynet=<net>         " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
254         "  -discover              " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
255         "  -irc                   " + _("Find peers using internet relay chat (default: 1)") + "\n" +
256         "  -listen                " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
257         "  -bind=<addr>           " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
258         "  -dnsseed               " + _("Find peers using DNS lookup (default: 1)") + "\n" +
259         "  -cppolicy              " + _("Sync checkpoints policy (default: strict)") + "\n" +
260         "  -banscore=<n>          " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
261         "  -bantime=<n>           " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
262         "  -maxreceivebuffer=<n>  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
263         "  -maxsendbuffer=<n>     " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
264         "  -detachdb              " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\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>        " + ((string)("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: 192, 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         "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
312         "  -rpcssl                                  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
313         "  -rpcsslcertificatechainfile=<file.cert>  " + _("Server certificate file (default: server.cert)") + "\n" +
314         "  -rpcsslprivatekeyfile=<file.pem>         " + _("Server private key (default: server.pem)") + "\n" +
315         "  -rpcsslciphers=<ciphers>                 " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
316
317     return strUsage;
318 }
319
320 bool DropBlockIndex()
321 {
322     try
323     {
324 #ifdef USE_LEVELDB
325         filesystem::path directory = GetDataDir() / "txleveldb";
326         filesystem::remove_all(directory); // remove directory
327 #else
328         filesystem::path indexFile = GetDataDir() / "blkindex.dat";
329         filesystem::remove(indexFile); // remove index file
330 #endif
331
332         unsigned int nFile = 1;
333         for ( ; ; )
334         {
335             filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
336             // Break if no such file
337             if( !filesystem::exists( strBlockFile ) )
338                 break;
339             filesystem::remove(strBlockFile);
340             nFile++;
341         }
342         return true;
343     }
344     catch(const std::exception&)
345     {
346         // TODO: report error here
347         return false;
348     }
349 }
350
351 // Initialize bitcoin.
352 //  @pre Parameters should be parsed and config file should be read.
353 bool AppInit2()
354 {
355     // ********************************************************* Step 1: setup
356 #ifdef _MSC_VER
357     // Turn off Microsoft heap dump noise
358     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
359     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
360 #endif
361 #if _MSC_VER >= 1400
362     // Disable confusing "helpful" text message on abort, Ctrl-C
363     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
364 #endif
365 #ifdef WIN32
366     // Enable Data Execution Prevention (DEP)
367     // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
368     // A failure is non-critical and needs no further attention!
369 #ifndef PROCESS_DEP_ENABLE
370 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
371 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
372 #define PROCESS_DEP_ENABLE 0x00000001
373 #endif
374     typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
375     PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
376     if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
377
378     // Initialize Windows Sockets
379     WSADATA wsadata;
380     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
381     if (ret != NO_ERROR)
382     {
383         return InitError(strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret));
384     }
385 #endif
386 #ifndef WIN32
387     umask(077);
388
389     // Clean shutdown on SIGTERM
390     struct sigaction sa;
391     sa.sa_handler = HandleSIGTERM;
392     sigemptyset(&sa.sa_mask);
393     sa.sa_flags = 0;
394     sigaction(SIGTERM, &sa, NULL);
395     sigaction(SIGINT, &sa, NULL);
396
397     // Reopen debug.log on SIGHUP
398     struct sigaction sa_hup;
399     sa_hup.sa_handler = HandleSIGHUP;
400     sigemptyset(&sa_hup.sa_mask);
401     sa_hup.sa_flags = 0;
402     sigaction(SIGHUP, &sa_hup, NULL);
403 #endif
404
405     // ********************************************************* Step 2: parameter interactions
406
407     nNodeLifespan = GetArgUInt("-addrlifespan", 7);
408     fUseFastIndex = GetBoolArg("-fastindex", true);
409     fUseMemoryLog = GetBoolArg("-memorylog", true);
410
411     // Ping and address broadcast intervals
412     nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
413
414     CheckpointsMode = Checkpoints::CP_STRICT;
415     auto strCpMode = GetArg("-cppolicy", "strict");
416
417     if(strCpMode == "strict") {
418         CheckpointsMode = Checkpoints::CP_STRICT;
419     }
420
421     if(strCpMode == "advisory") {
422         CheckpointsMode = Checkpoints::CP_ADVISORY;
423     }
424
425     if(strCpMode == "permissive") {
426         CheckpointsMode = Checkpoints::CP_PERMISSIVE;
427     }
428
429     fTestNet = GetBoolArg("-testnet");
430     if (fTestNet) {
431         SoftSetBoolArg("-irc", true);
432     }
433
434     if (mapArgs.count("-bind")) {
435         // when specifying an explicit binding address, you want to listen on it
436         // even when -connect or -proxy is specified
437         SoftSetBoolArg("-listen", true);
438     }
439
440     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
441         // when only connecting to trusted nodes, do not seed via DNS, or listen by default
442         SoftSetBoolArg("-dnsseed", false);
443         SoftSetBoolArg("-listen", false);
444     }
445
446     if (mapArgs.count("-proxy")) {
447         // to protect privacy, do not listen by default if a proxy server is specified
448         SoftSetBoolArg("-listen", false);
449     }
450
451     if (!GetBoolArg("-listen", true)) {
452         // do not map ports or try to retrieve public IP when not listening (pointless)
453         SoftSetBoolArg("-discover", false);
454     }
455
456     if (mapArgs.count("-externalip")) {
457         // if an explicit public IP is specified, do not try to find others
458         SoftSetBoolArg("-discover", false);
459     }
460
461     if (GetBoolArg("-salvagewallet")) {
462         // Rewrite just private keys: rescan to find transactions
463         SoftSetBoolArg("-rescan", true);
464     }
465
466     if (GetBoolArg("-zapwallettxes", false)) {
467         // -zapwallettx implies a rescan
468         if (SoftSetBoolArg("-rescan", true))
469             printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
470     }
471
472     // ********************************************************* Step 3: parameter-to-internal-flags
473
474     // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
475     nScriptCheckThreads = GetArgInt("-par", 0);
476     if (nScriptCheckThreads == 0)
477         nScriptCheckThreads = boost::thread::hardware_concurrency();
478     if (nScriptCheckThreads <= 1) 
479         nScriptCheckThreads = 0;
480     else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
481         nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
482
483     fDebug = GetBoolArg("-debug");
484
485     // -debug implies fDebug*
486     if (fDebug)
487         fDebugNet = true;
488     else
489         fDebugNet = GetBoolArg("-debugnet");
490
491     bitdb.SetDetach(GetBoolArg("-detachdb", false));
492
493 #if !defined(WIN32) && !defined(QT_GUI)
494     fDaemon = GetBoolArg("-daemon");
495 #else
496     fDaemon = false;
497 #endif
498
499     if (fDaemon)
500         fServer = true;
501     else
502         fServer = GetBoolArg("-server");
503
504     /* force fServer when running without GUI */
505 #if !defined(QT_GUI)
506     fServer = true;
507 #endif
508     fPrintToConsole = GetBoolArg("-printtoconsole");
509     fPrintToDebugger = GetBoolArg("-printtodebugger");
510     fLogTimestamps = GetBoolArg("-logtimestamps");
511
512     if (mapArgs.count("-timeout"))
513     {
514         int nNewTimeout = GetArgInt("-timeout", 5000);
515         if (nNewTimeout > 0 && nNewTimeout < 600000)
516             nConnectTimeout = nNewTimeout;
517     }
518
519     // Put client version data into coinbase flags.
520     COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
521
522     if (mapArgs.count("-paytxfee"))
523     {
524         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
525             return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
526         if (nTransactionFee > 0.25 * COIN)
527             InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
528     }
529
530     fConfChange = GetBoolArg("-confchange", false);
531
532     if (mapArgs.count("-mininput"))
533     {
534         if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
535             return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
536     }
537
538     // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
539
540     auto strDataDir = GetDataDir().string();
541     strWalletFileName = GetArg("-wallet", "wallet.dat");
542
543     // strWalletFileName must be a plain filename without a directory
544     if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
545         return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
546
547     // Make sure only a single Bitcoin process is using the data directory.
548     boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
549     FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
550     if (file) fclose(file);
551     static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
552     if (!lock.try_lock())
553         return InitError(strprintf(_("Cannot obtain a lock on data directory %s.  NovaCoin is probably already running."), strDataDir.c_str()));
554
555 #if !defined(WIN32) && !defined(QT_GUI)
556     if (fDaemon)
557     {
558         // Daemonize
559         pid_t pid = fork();
560         if (pid < 0)
561         {
562             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
563             return false;
564         }
565         if (pid > 0)
566         {
567             CreatePidFile(GetPidFile(), pid);
568             return true;
569         }
570
571         pid_t sid = setsid();
572         if (sid < 0)
573             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
574     }
575 #endif
576
577     if (GetBoolArg("-shrinkdebugfile", !fDebug))
578         ShrinkDebugFile();
579     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
580     printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
581     printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
582     if (!fLogTimestamps)
583         printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
584     printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
585     printf("Used data directory %s\n", strDataDir.c_str());
586
587     if (fDaemon)
588         fprintf(stdout, "NovaCoin server starting\n");
589
590     if (nScriptCheckThreads) {
591         printf("Using %u threads for script verification\n", nScriptCheckThreads);
592         for (int i=0; i<nScriptCheckThreads-1; i++)
593             NewThread(ThreadScriptCheck, NULL);
594     }
595
596     // ********************************************************* Step 5: verify database integrity
597
598     uiInterface.InitMessage(_("Verifying database integrity..."));
599
600     if (!bitdb.Open(GetDataDir()))
601     {
602         string msg = strprintf(_("Error initializing database environment %s!"
603                                  " To recover, BACKUP THAT DIRECTORY, then remove"
604                                  " everything from it except for wallet.dat."), strDataDir.c_str());
605         return InitError(msg);
606     }
607
608     if (GetBoolArg("-salvagewallet"))
609     {
610         // Recover readable keypairs:
611         if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
612             return false;
613     }
614
615     if (filesystem::exists(GetDataDir() / strWalletFileName))
616     {
617         CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
618         if (r == CDBEnv::RECOVER_OK)
619         {
620             string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
621                                      " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
622                                      " your balance or transactions are incorrect you should"
623                                      " restore from a backup."), strDataDir.c_str());
624             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
625         }
626         if (r == CDBEnv::RECOVER_FAIL)
627             return InitError(_("wallet.dat corrupt, salvage failed"));
628     }
629
630     // ********************************************************* Step 6: network initialization
631
632     int nSocksVersion = GetArgInt("-socks", 5);
633
634     if (nSocksVersion != 4 && nSocksVersion != 5)
635         return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
636
637     if (mapArgs.count("-onlynet")) {
638         std::set<enum Network> nets;
639         for(std::string snet :  mapMultiArgs["-onlynet"]) {
640             enum Network net = ParseNetwork(snet);
641             if (net == NET_UNROUTABLE)
642                 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
643             nets.insert(net);
644         }
645         for (int n = 0; n < NET_MAX; n++) {
646             enum Network net = (enum Network)n;
647             if (!nets.count(net))
648                 SetLimited(net);
649         }
650     }
651 #if defined(USE_IPV6)
652 #if ! USE_IPV6
653     else
654         SetLimited(NET_IPV6);
655 #endif
656 #endif
657
658     CService addrProxy;
659     bool fProxy = false;
660     if (mapArgs.count("-proxy")) {
661         addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
662         if (!addrProxy.IsValid())
663             return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
664
665         if (!IsLimited(NET_IPV4))
666             SetProxy(NET_IPV4, addrProxy, nSocksVersion);
667         if (nSocksVersion > 4) {
668 #ifdef USE_IPV6
669             if (!IsLimited(NET_IPV6))
670                 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
671 #endif
672             SetNameProxy(addrProxy, nSocksVersion);
673         }
674         fProxy = true;
675     }
676
677     // -tor can override normal proxy, -notor disables tor entirely
678     if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
679         CService addrOnion;
680         if (!mapArgs.count("-tor"))
681             addrOnion = addrProxy;
682         else
683             addrOnion = CService(mapArgs["-tor"], nSocksDefault);
684         if (!addrOnion.IsValid())
685             return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
686         SetProxy(NET_TOR, addrOnion, 5);
687         SetReachable(NET_TOR);
688     }
689
690     // see Step 2: parameter interactions for more information about these
691     if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
692     {
693         fNoListen = !GetBoolArg("-listen", true);
694         fDiscover = GetBoolArg("-discover", true);
695         fNameLookup = GetBoolArg("-dns", true);
696     } else {
697         // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
698         fNoListen = true;
699         fDiscover = fNameLookup = false;
700         SoftSetBoolArg("-irc", false);
701         SoftSetBoolArg("-dnsseed", false);
702     }
703
704     bool fBound = false;
705     if (!fNoListen)
706     {
707         if (mapArgs.count("-bind")) {
708             for(std::string strBind :  mapMultiArgs["-bind"]) {
709                 CService addrBind;
710                 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
711                     return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
712                 fBound |= Bind(addrBind);
713             }
714         } else {
715             struct in_addr inaddr_any;
716             inaddr_any.s_addr = INADDR_ANY;
717 #ifdef USE_IPV6
718             if (!IsLimited(NET_IPV6))
719                 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
720 #endif
721             if (!IsLimited(NET_IPV4))
722                 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
723
724         }
725         if (!fBound)
726             return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
727     }
728
729     // If Tor is reachable then listen on loopback interface,
730     //    to allow allow other users reach you through the hidden service
731     if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
732         std::string strError;
733         struct in_addr inaddr_loopback;
734         inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
735
736 #ifdef USE_IPV6
737         if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
738             return InitError(strError);
739 #endif
740         if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
741             return InitError(strError);
742     }
743
744     if (mapArgs.count("-externalip"))
745     {
746         for(string strAddr :  mapMultiArgs["-externalip"]) {
747             CService addrLocal(strAddr, GetListenPort(), fNameLookup);
748             if (!addrLocal.IsValid())
749                 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
750             AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
751         }
752     }
753
754     if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
755     {
756         if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
757         {
758             InitError(_("Invalid amount for -reservebalance=<amount>"));
759             return false;
760         }
761     }
762
763     if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
764     {
765         if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
766             InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
767     }
768
769     for(string strDest :  mapMultiArgs["-seednode"])
770         AddOneShot(strDest);
771
772     // ********************************************************* Step 7: load blockchain
773
774     if (!bitdb.Open(GetDataDir()))
775     {
776         string msg = strprintf(_("Error initializing database environment %s!"
777                                  " To recover, BACKUP THAT DIRECTORY, then remove"
778                                  " everything from it except for wallet.dat."), strDataDir.c_str());
779         return InitError(msg);
780     }
781
782     if (GetBoolArg("-loadblockindextest"))
783     {
784         CTxDB txdb("r");
785         txdb.LoadBlockIndex();
786         PrintBlockTree();
787         return false;
788     }
789
790
791     printf("Loading block index...\n");
792     bool fLoaded = false;
793     int64_t nStart;
794     while (!fLoaded) {
795         std::string strLoadError;
796         uiInterface.InitMessage(_("Loading block index..."));
797
798         nStart = GetTimeMillis();
799         do {
800             try {
801                 UnloadBlockIndex();
802
803                 if (!LoadBlockIndex()) {
804                     strLoadError = _("Error loading block database");
805                     break;
806                 }
807             } catch(const std::exception&) {
808                 strLoadError = _("Error opening block database");
809                 break;
810             }
811
812             fLoaded = true;
813         } while(false);
814
815         if (!fLoaded) {
816             DropBlockIndex();
817             // TODO: suggest reindex here
818             return InitError(strLoadError);
819         }
820     }
821
822     // as LoadBlockIndex can take several minutes, it's possible the user
823     // requested to kill bitcoin-qt during the last operation. If so, exit.
824     // As the program has not fully started yet, Shutdown() is possibly overkill.
825     if (fRequestShutdown)
826     {
827         printf("Shutdown requested. Exiting.\n");
828         return false;
829     }
830     printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
831
832     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
833     {
834         PrintBlockTree();
835         return false;
836     }
837
838     if (mapArgs.count("-printblock"))
839     {
840         auto strMatch = mapArgs["-printblock"];
841         int nFound = 0;
842         for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
843         {
844             auto hash = (*mi).first;
845             if (strMatch.compare(hash.ToString()) == 0)
846             {
847                 auto pindex = (*mi).second;
848                 CBlock block;
849                 block.ReadFromDisk(pindex);
850                 block.BuildMerkleTree();
851                 block.print();
852                 printf("\n");
853                 nFound++;
854             }
855         }
856         if (nFound == 0)
857             printf("No blocks matching %s were found\n", strMatch.c_str());
858         return false;
859     }
860
861     // ********************************************************* Step 8: load wallet
862
863     if (GetBoolArg("-zapwallettxes", false)) {
864         uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
865
866         pwalletMain = new CWallet(strWalletFileName);
867         DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
868         if (nZapWalletRet != DB_LOAD_OK) {
869             uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
870             return false;
871         }
872         delete pwalletMain;
873         pwalletMain = NULL;
874     }
875
876     uiInterface.InitMessage(_("Loading wallet..."));
877     printf("Loading wallet...\n");
878     nStart = GetTimeMillis();
879     std::ostringstream strErrors;
880     bool fFirstRun = true;
881     pwalletMain = new CWallet(strWalletFileName);
882     DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
883     if (nLoadWalletRet != DB_LOAD_OK)
884     {
885         if (nLoadWalletRet == DB_CORRUPT)
886             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
887         else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
888         {
889             string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
890                          " or address book entries might be missing or incorrect."));
891             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
892         }
893         else if (nLoadWalletRet == DB_TOO_NEW)
894             strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
895         else if (nLoadWalletRet == DB_NEED_REWRITE)
896         {
897             strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
898             printf("%s", strErrors.str().c_str());
899             return InitError(strErrors.str());
900         }
901         else
902             strErrors << _("Error loading wallet.dat") << "\n";
903     }
904
905     if (GetBoolArg("-upgradewallet", fFirstRun))
906     {
907         int nMaxVersion = GetArgInt("-upgradewallet", 0);
908         if (nMaxVersion == 0) // the -upgradewallet without argument case
909         {
910             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
911             nMaxVersion = CLIENT_VERSION;
912             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
913         }
914         else
915             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
916         if (nMaxVersion < pwalletMain->GetVersion())
917             strErrors << _("Cannot downgrade wallet") << "\n";
918         pwalletMain->SetMaxVersion(nMaxVersion);
919     }
920
921     if (fFirstRun)
922     {
923         // Create new keyUser and set as default key
924         RandAddSeedPerfmon();
925
926         CPubKey newDefaultKey;
927         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
928             strErrors << _("Cannot initialize keypool") << "\n";
929         pwalletMain->SetDefaultKey(newDefaultKey);
930         if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
931             strErrors << _("Cannot write default address") << "\n";
932
933         auto keyView = pwalletMain->GenerateNewMalleableKey();
934         CMalleableKey mKey;
935         if (!pwalletMain->GetMalleableKey(keyView, mKey))
936             strErrors << _("Unable to generate new malleable key");
937         if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
938             strErrors << _("Cannot write default address") << "\n";
939     }
940
941     printf("%s", strErrors.str().c_str());
942     printf(" wallet      %15" PRId64 "ms\n", GetTimeMillis() - nStart);
943
944     RegisterWallet(pwalletMain);
945
946     CBlockIndex *pindexRescan = pindexBest;
947     if (GetBoolArg("-rescan"))
948         pindexRescan = pindexGenesisBlock;
949     else
950     {
951         CWalletDB walletdb(strWalletFileName);
952         CBlockLocator locator;
953         if (walletdb.ReadBestBlock(locator))
954             pindexRescan = locator.GetBlockIndex();
955     }
956     if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
957     {
958         uiInterface.InitMessage(_("Rescanning..."));
959         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
960         nStart = GetTimeMillis();
961         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
962         printf(" rescan      %15" PRId64 "ms\n", GetTimeMillis() - nStart);
963     }
964
965     // ********************************************************* Step 9: import blocks
966
967     if (mapArgs.count("-loadblock"))
968     {
969         uiInterface.InitMessage(_("Importing blockchain data file."));
970
971         for(string strFile :  mapMultiArgs["-loadblock"])
972         {
973             FILE *file = fopen(strFile.c_str(), "rb");
974             if (file)
975                 LoadExternalBlockFile(file, uiInterface);
976         }
977         StartShutdown();
978     }
979
980     filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
981     if (filesystem::exists(pathBootstrap)) {
982         uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
983
984         FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
985         if (file) {
986             filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
987             LoadExternalBlockFile(file, uiInterface);
988             RenameOver(pathBootstrap, pathBootstrapOld);
989         }
990     }
991
992     // ********************************************************* Step 10: load peers
993
994     uiInterface.InitMessage(_("Loading addresses..."));
995     printf("Loading addresses...\n");
996     nStart = GetTimeMillis();
997
998     {
999         CAddrDB adb;
1000         if (!adb.Read(addrman))
1001             printf("Invalid or missing peers.dat; recreating\n");
1002     }
1003
1004     printf("Loaded %i addresses from peers.dat  %" PRId64 "ms\n",
1005            addrman.size(), GetTimeMillis() - nStart);
1006
1007     // ********************************************************* Step 11: start node
1008
1009     if (!CheckDiskSpace())
1010         return false;
1011
1012     RandAddSeedPerfmon();
1013
1014     //// debug print
1015     printf("mapBlockIndex.size() = %" PRIszu "\n",   mapBlockIndex.size());
1016     printf("nBestHeight = %d\n",            nBestHeight);
1017     printf("setKeyPool.size() = %" PRIszu "\n",      pwalletMain->setKeyPool.size());
1018     printf("mapWallet.size() = %" PRIszu "\n",       pwalletMain->mapWallet.size());
1019     printf("mapAddressBook.size() = %" PRIszu "\n",  pwalletMain->mapAddressBook.size());
1020
1021     if (!NewThread(StartNode, NULL))
1022         InitError(_("Error: could not start node"));
1023
1024     if (fServer)
1025         NewThread(ThreadRPCServer, NULL);
1026
1027     // ********************************************************* Step 13: IP collection thread
1028     strCollectorCommand = GetArg("-peercollector", "");
1029     if (!fTestNet && strCollectorCommand != "")
1030         NewThread(ThreadIPCollector, NULL);
1031     // ********************************************************* Step 14: finished
1032
1033     uiInterface.InitMessage(_("Done loading"));
1034     printf("Done loading\n");
1035
1036     if (!strErrors.str().empty())
1037         return InitError(strErrors.str());
1038
1039      // Add wallet transactions that aren't already in a block to mapTransactions
1040     pwalletMain->ReacceptWalletTransactions();
1041
1042 #if !defined(QT_GUI)
1043     // Loop until process is exit()ed from shutdown() function,
1044     // called from ThreadRPCServer thread when a "stop" command is received.
1045     for ( ; ; )
1046         Sleep(5000);
1047 #endif
1048
1049     return true;
1050 }