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