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