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