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