Remove socks4 support
[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 #if defined(USE_IPV6)
646 #if ! USE_IPV6
647     else
648         SetLimited(NET_IPV6);
649 #endif
650 #endif
651
652     CService addrProxy;
653     bool fProxy = false;
654     if (mapArgs.count("-proxy")) {
655         addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
656         if (!addrProxy.IsValid())
657             return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
658
659         if (!IsLimited(NET_IPV4))
660             SetProxy(NET_IPV4, addrProxy);
661 #ifdef USE_IPV6
662             if (!IsLimited(NET_IPV6))
663                 SetProxy(NET_IPV6, addrProxy);
664 #endif
665             SetNameProxy(addrProxy);
666         fProxy = true;
667     }
668
669     // -tor can override normal proxy, -notor disables tor entirely
670     if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
671         CService addrOnion;
672         if (!mapArgs.count("-tor"))
673             addrOnion = addrProxy;
674         else
675             addrOnion = CService(mapArgs["-tor"], nSocksDefault);
676         if (!addrOnion.IsValid())
677             return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
678         SetProxy(NET_TOR, addrOnion);
679         SetReachable(NET_TOR);
680     }
681
682     // see Step 2: parameter interactions for more information about these
683     if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
684     {
685         fNoListen = !GetBoolArg("-listen", true);
686         fDiscover = GetBoolArg("-discover", true);
687         fNameLookup = GetBoolArg("-dns", true);
688     } else {
689         // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
690         fNoListen = true;
691         fDiscover = fNameLookup = false;
692         SoftSetBoolArg("-irc", false);
693         SoftSetBoolArg("-dnsseed", false);
694     }
695
696     bool fBound = false;
697     if (!fNoListen)
698     {
699         if (mapArgs.count("-bind")) {
700             for(std::string strBind :  mapMultiArgs["-bind"]) {
701                 CService addrBind;
702                 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
703                     return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
704                 fBound |= Bind(addrBind);
705             }
706         } else {
707             struct in_addr inaddr_any;
708             inaddr_any.s_addr = INADDR_ANY;
709 #ifdef USE_IPV6
710             if (!IsLimited(NET_IPV6))
711                 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
712 #endif
713             if (!IsLimited(NET_IPV4))
714                 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
715
716         }
717         if (!fBound)
718             return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
719     }
720
721     // If Tor is reachable then listen on loopback interface,
722     //    to allow allow other users reach you through the hidden service
723     if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
724         std::string strError;
725         struct in_addr inaddr_loopback;
726         inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
727
728 #ifdef USE_IPV6
729         if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
730             return InitError(strError);
731 #endif
732         if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
733             return InitError(strError);
734     }
735
736     if (mapArgs.count("-externalip"))
737     {
738         for(string strAddr :  mapMultiArgs["-externalip"]) {
739             CService addrLocal(strAddr, GetListenPort(), fNameLookup);
740             if (!addrLocal.IsValid())
741                 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
742             AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
743         }
744     }
745
746     if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
747     {
748         if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
749         {
750             InitError(_("Invalid amount for -reservebalance=<amount>"));
751             return false;
752         }
753     }
754
755     if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
756     {
757         if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
758             InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
759     }
760
761     for(string strDest :  mapMultiArgs["-seednode"])
762         AddOneShot(strDest);
763
764     // ********************************************************* Step 7: load blockchain
765
766     if (!bitdb.Open(GetDataDir()))
767     {
768         string msg = strprintf(_("Error initializing database environment %s!"
769                                  " To recover, BACKUP THAT DIRECTORY, then remove"
770                                  " everything from it except for wallet.dat."), strDataDir.c_str());
771         return InitError(msg);
772     }
773
774     if (GetBoolArg("-loadblockindextest"))
775     {
776         CTxDB txdb("r");
777         txdb.LoadBlockIndex();
778         PrintBlockTree();
779         return false;
780     }
781
782
783     printf("Loading block index...\n");
784     bool fLoaded = false;
785     int64_t nStart;
786     while (!fLoaded) {
787         std::string strLoadError;
788         uiInterface.InitMessage(_("Loading block index..."));
789
790         nStart = GetTimeMillis();
791         do {
792             try {
793                 UnloadBlockIndex();
794
795                 if (!LoadBlockIndex()) {
796                     strLoadError = _("Error loading block database");
797                     break;
798                 }
799             } catch(const std::exception&) {
800                 strLoadError = _("Error opening block database");
801                 break;
802             }
803
804             fLoaded = true;
805         } while(false);
806
807         if (!fLoaded) {
808             DropBlockIndex();
809             // TODO: suggest reindex here
810             return InitError(strLoadError);
811         }
812     }
813
814     // as LoadBlockIndex can take several minutes, it's possible the user
815     // requested to kill bitcoin-qt during the last operation. If so, exit.
816     // As the program has not fully started yet, Shutdown() is possibly overkill.
817     if (fRequestShutdown)
818     {
819         printf("Shutdown requested. Exiting.\n");
820         return false;
821     }
822     printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
823
824     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
825     {
826         PrintBlockTree();
827         return false;
828     }
829
830     if (mapArgs.count("-printblock"))
831     {
832         auto strMatch = mapArgs["-printblock"];
833         int nFound = 0;
834         for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
835         {
836             auto hash = (*mi).first;
837             if (strMatch.compare(hash.ToString()) == 0)
838             {
839                 auto pindex = (*mi).second;
840                 CBlock block;
841                 block.ReadFromDisk(pindex);
842                 block.BuildMerkleTree();
843                 block.print();
844                 printf("\n");
845                 nFound++;
846             }
847         }
848         if (nFound == 0)
849             printf("No blocks matching %s were found\n", strMatch.c_str());
850         return false;
851     }
852
853     // ********************************************************* Step 8: load wallet
854
855     if (GetBoolArg("-zapwallettxes", false)) {
856         uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
857
858         pwalletMain = new CWallet(strWalletFileName);
859         DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
860         if (nZapWalletRet != DB_LOAD_OK) {
861             uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
862             return false;
863         }
864         delete pwalletMain;
865         pwalletMain = NULL;
866     }
867
868     uiInterface.InitMessage(_("Loading wallet..."));
869     printf("Loading wallet...\n");
870     nStart = GetTimeMillis();
871     std::ostringstream strErrors;
872     bool fFirstRun = true;
873     pwalletMain = new CWallet(strWalletFileName);
874     DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
875     if (nLoadWalletRet != DB_LOAD_OK)
876     {
877         if (nLoadWalletRet == DB_CORRUPT)
878             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
879         else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
880         {
881             string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
882                          " or address book entries might be missing or incorrect."));
883             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
884         }
885         else if (nLoadWalletRet == DB_TOO_NEW)
886             strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
887         else if (nLoadWalletRet == DB_NEED_REWRITE)
888         {
889             strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
890             printf("%s", strErrors.str().c_str());
891             return InitError(strErrors.str());
892         }
893         else
894             strErrors << _("Error loading wallet.dat") << "\n";
895     }
896
897     if (GetBoolArg("-upgradewallet", fFirstRun))
898     {
899         int nMaxVersion = GetArgInt("-upgradewallet", 0);
900         if (nMaxVersion == 0) // the -upgradewallet without argument case
901         {
902             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
903             nMaxVersion = CLIENT_VERSION;
904             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
905         }
906         else
907             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
908         if (nMaxVersion < pwalletMain->GetVersion())
909             strErrors << _("Cannot downgrade wallet") << "\n";
910         pwalletMain->SetMaxVersion(nMaxVersion);
911     }
912
913     if (fFirstRun)
914     {
915         // Create new keyUser and set as default key
916         RandAddSeedPerfmon();
917
918         CPubKey newDefaultKey;
919         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
920             strErrors << _("Cannot initialize keypool") << "\n";
921         pwalletMain->SetDefaultKey(newDefaultKey);
922         if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
923             strErrors << _("Cannot write default address") << "\n";
924
925         auto keyView = pwalletMain->GenerateNewMalleableKey();
926         CMalleableKey mKey;
927         if (!pwalletMain->GetMalleableKey(keyView, mKey))
928             strErrors << _("Unable to generate new malleable key");
929         if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
930             strErrors << _("Cannot write default address") << "\n";
931     }
932
933     printf("%s", strErrors.str().c_str());
934     printf(" wallet      %15" PRId64 "ms\n", GetTimeMillis() - nStart);
935
936     RegisterWallet(pwalletMain);
937
938     CBlockIndex *pindexRescan = pindexBest;
939     if (GetBoolArg("-rescan"))
940         pindexRescan = pindexGenesisBlock;
941     else
942     {
943         CWalletDB walletdb(strWalletFileName);
944         CBlockLocator locator;
945         if (walletdb.ReadBestBlock(locator))
946             pindexRescan = locator.GetBlockIndex();
947     }
948     if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
949     {
950         uiInterface.InitMessage(_("Rescanning..."));
951         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
952         nStart = GetTimeMillis();
953         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
954         printf(" rescan      %15" PRId64 "ms\n", GetTimeMillis() - nStart);
955     }
956
957     // ********************************************************* Step 9: import blocks
958
959     if (mapArgs.count("-loadblock"))
960     {
961         uiInterface.InitMessage(_("Importing blockchain data file."));
962
963         for(string strFile :  mapMultiArgs["-loadblock"])
964         {
965             FILE *file = fopen(strFile.c_str(), "rb");
966             if (file)
967                 LoadExternalBlockFile(file, uiInterface);
968         }
969         StartShutdown();
970     }
971
972     filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
973     if (filesystem::exists(pathBootstrap)) {
974         uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
975
976         FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
977         if (file) {
978             filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
979             LoadExternalBlockFile(file, uiInterface);
980             RenameOver(pathBootstrap, pathBootstrapOld);
981         }
982     }
983
984     // ********************************************************* Step 10: load peers
985
986     uiInterface.InitMessage(_("Loading addresses..."));
987     printf("Loading addresses...\n");
988     nStart = GetTimeMillis();
989
990     {
991         CAddrDB adb;
992         if (!adb.Read(addrman))
993             printf("Invalid or missing peers.dat; recreating\n");
994     }
995
996     printf("Loaded %i addresses from peers.dat  %" PRId64 "ms\n",
997            addrman.size(), GetTimeMillis() - nStart);
998
999     // ********************************************************* Step 11: start node
1000
1001     if (!CheckDiskSpace())
1002         return false;
1003
1004     RandAddSeedPerfmon();
1005
1006     //// debug print
1007     printf("mapBlockIndex.size() = %" PRIszu "\n",   mapBlockIndex.size());
1008     printf("nBestHeight = %d\n",            nBestHeight);
1009     printf("setKeyPool.size() = %" PRIszu "\n",      pwalletMain->setKeyPool.size());
1010     printf("mapWallet.size() = %" PRIszu "\n",       pwalletMain->mapWallet.size());
1011     printf("mapAddressBook.size() = %" PRIszu "\n",  pwalletMain->mapAddressBook.size());
1012
1013     if (!NewThread(StartNode, NULL))
1014         InitError(_("Error: could not start node"));
1015
1016     if (fServer)
1017         NewThread(ThreadRPCServer, NULL);
1018
1019     // ********************************************************* Step 13: IP collection thread
1020     strCollectorCommand = GetArg("-peercollector", "");
1021     if (!fTestNet && strCollectorCommand != "")
1022         NewThread(ThreadIPCollector, NULL);
1023     // ********************************************************* Step 14: finished
1024
1025     uiInterface.InitMessage(_("Done loading"));
1026     printf("Done loading\n");
1027
1028     if (!strErrors.str().empty())
1029         return InitError(strErrors.str());
1030
1031      // Add wallet transactions that aren't already in a block to mapTransactions
1032     pwalletMain->ReacceptWalletTransactions();
1033
1034 #if !defined(QT_GUI)
1035     // Loop until process is exit()ed from shutdown() function,
1036     // called from ThreadRPCServer thread when a "stop" command is received.
1037     for ( ; ; )
1038         Sleep(5000);
1039 #endif
1040
1041     return true;
1042 }