update to 0.4.1
[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         "  -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         "  -upgradewallet         " + _("Upgrade wallet to latest format") + "\n" +
282         "  -keypool=<n>           " + _("Set key pool size to <n> (default: 100)") + "\n" +
283         "  -rescan                " + _("Rescan the block chain for missing wallet transactions") + "\n" +
284         "  -salvagewallet         " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
285         "  -checkblocks=<n>       " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
286         "  -checklevel=<n>        " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
287         "  -loadblock=<file>      " + _("Imports blocks from external blk000?.dat file") + "\n" +
288
289         "\n" + _("Block creation options:") + "\n" +
290         "  -blockminsize=<n>      "   + _("Set minimum block size in bytes (default: 0)") + "\n" +
291         "  -blockmaxsize=<n>      "   + _("Set maximum block size in bytes (default: 250000)") + "\n" +
292         "  -blockprioritysize=<n> "   + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
293
294         "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
295         "  -rpcssl                                  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
296         "  -rpcsslcertificatechainfile=<file.cert>  " + _("Server certificate file (default: server.cert)") + "\n" +
297         "  -rpcsslprivatekeyfile=<file.pem>         " + _("Server private key (default: server.pem)") + "\n" +
298         "  -rpcsslciphers=<ciphers>                 " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
299
300     return strUsage;
301 }
302
303 /** Initialize bitcoin.
304  *  @pre Parameters should be parsed and config file should be read.
305  */
306 bool AppInit2()
307 {
308     // ********************************************************* Step 1: setup
309 #ifdef _MSC_VER
310     // Turn off Microsoft heap dump noise
311     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
312     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
313 #endif
314 #if _MSC_VER >= 1400
315     // Disable confusing "helpful" text message on abort, Ctrl-C
316     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
317 #endif
318 #ifdef WIN32
319     // Enable Data Execution Prevention (DEP)
320     // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
321     // A failure is non-critical and needs no further attention!
322 #ifndef PROCESS_DEP_ENABLE
323 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
324 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
325 #define PROCESS_DEP_ENABLE 0x00000001
326 #endif
327     typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
328     PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
329     if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
330 #endif
331 #ifndef WIN32
332     umask(077);
333
334     // Clean shutdown on SIGTERM
335     struct sigaction sa;
336     sa.sa_handler = HandleSIGTERM;
337     sigemptyset(&sa.sa_mask);
338     sa.sa_flags = 0;
339     sigaction(SIGTERM, &sa, NULL);
340     sigaction(SIGINT, &sa, NULL);
341
342     // Reopen debug.log on SIGHUP
343     struct sigaction sa_hup;
344     sa_hup.sa_handler = HandleSIGHUP;
345     sigemptyset(&sa_hup.sa_mask);
346     sa_hup.sa_flags = 0;
347     sigaction(SIGHUP, &sa_hup, NULL);
348 #endif
349
350     // ********************************************************* Step 2: parameter interactions
351
352     fTestNet = GetBoolArg("-testnet");
353     if (fTestNet) {
354         SoftSetBoolArg("-irc", true);
355     }
356
357     if (mapArgs.count("-bind")) {
358         // when specifying an explicit binding address, you want to listen on it
359         // even when -connect or -proxy is specified
360         SoftSetBoolArg("-listen", true);
361     }
362
363     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
364         // when only connecting to trusted nodes, do not seed via DNS, or listen by default
365         SoftSetBoolArg("-dnsseed", false);
366         SoftSetBoolArg("-listen", false);
367     }
368
369     if (mapArgs.count("-proxy")) {
370         // to protect privacy, do not listen by default if a proxy server is specified
371         SoftSetBoolArg("-listen", false);
372     }
373
374     if (!GetBoolArg("-listen", true)) {
375         // do not map ports or try to retrieve public IP when not listening (pointless)
376         SoftSetBoolArg("-upnp", false);
377         SoftSetBoolArg("-discover", false);
378     }
379
380     if (mapArgs.count("-externalip")) {
381         // if an explicit public IP is specified, do not try to find others
382         SoftSetBoolArg("-discover", false);
383     }
384
385     if (GetBoolArg("-salvagewallet")) {
386         // Rewrite just private keys: rescan to find transactions
387         SoftSetBoolArg("-rescan", true);
388     }
389
390     // ********************************************************* Step 3: parameter-to-internal-flags
391
392     fDebug = GetBoolArg("-debug");
393
394     // -debug implies fDebug*
395     if (fDebug)
396         fDebugNet = true;
397     else
398         fDebugNet = GetBoolArg("-debugnet");
399
400     bitdb.SetDetach(GetBoolArg("-detachdb", false));
401
402 #if !defined(WIN32) && !defined(QT_GUI)
403     fDaemon = GetBoolArg("-daemon");
404 #else
405     fDaemon = false;
406 #endif
407
408     if (fDaemon)
409         fServer = true;
410     else
411         fServer = GetBoolArg("-server");
412
413     /* force fServer when running without GUI */
414 #if !defined(QT_GUI)
415     fServer = true;
416 #endif
417     fPrintToConsole = GetBoolArg("-printtoconsole");
418     fPrintToDebugger = GetBoolArg("-printtodebugger");
419     fLogTimestamps = GetBoolArg("-logtimestamps");
420
421     if (mapArgs.count("-timeout"))
422     {
423         int nNewTimeout = GetArg("-timeout", 5000);
424         if (nNewTimeout > 0 && nNewTimeout < 600000)
425             nConnectTimeout = nNewTimeout;
426     }
427
428     // Continue to put "/P2SH/" in the coinbase to monitor
429     // BIP16 support.
430     // This can be removed eventually...
431     const char* pszP2SH = "/P2SH/";
432     COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
433
434
435     if (mapArgs.count("-paytxfee"))
436     {
437         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
438             return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
439         if (nTransactionFee > 0.25 * COIN)
440             InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
441     }
442
443     // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
444
445     std::string strDataDir = GetDataDir().string();
446
447     // Make sure only a single Bitcoin process is using the data directory.
448     boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
449     FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
450     if (file) fclose(file);
451     static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
452     if (!lock.try_lock())
453         return InitError(strprintf(_("Cannot obtain a lock on data directory %s.  NovaCoin is probably already running."), strDataDir.c_str()));
454
455 #if !defined(WIN32) && !defined(QT_GUI)
456     if (fDaemon)
457     {
458         // Daemonize
459         pid_t pid = fork();
460         if (pid < 0)
461         {
462             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
463             return false;
464         }
465         if (pid > 0)
466         {
467             CreatePidFile(GetPidFile(), pid);
468             return true;
469         }
470
471         pid_t sid = setsid();
472         if (sid < 0)
473             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
474     }
475 #endif
476
477     if (GetBoolArg("-shrinkdebugfile", !fDebug))
478         ShrinkDebugFile();
479     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
480     printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
481     printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
482     if (!fLogTimestamps)
483         printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
484     printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
485     printf("Used data directory %s\n", strDataDir.c_str());
486     std::ostringstream strErrors;
487
488     if (fDaemon)
489         fprintf(stdout, "NovaCoin server starting\n");
490
491     int64 nStart;
492
493     // ********************************************************* Step 5: verify database integrity
494
495     uiInterface.InitMessage(_("Verifying database integrity..."));
496
497     if (!bitdb.Open(GetDataDir()))
498     {
499         string msg = strprintf(_("Error initializing database environment %s!"
500                                  " To recover, BACKUP THAT DIRECTORY, then remove"
501                                  " everything from it except for wallet.dat."), strDataDir.c_str());
502         return InitError(msg);
503     }
504
505     if (GetBoolArg("-salvagewallet"))
506     {
507         // Recover readable keypairs:
508         if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
509             return false;
510     }
511
512     if (filesystem::exists(GetDataDir() / "wallet.dat"))
513     {
514         CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
515         if (r == CDBEnv::RECOVER_OK)
516         {
517             string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
518                                      " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
519                                      " your balance or transactions are incorrect you should"
520                                      " restore from a backup."), strDataDir.c_str());
521             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
522         }
523         if (r == CDBEnv::RECOVER_FAIL)
524             return InitError(_("wallet.dat corrupt, salvage failed"));
525     }
526
527     // ********************************************************* Step 6: network initialization
528
529     int nSocksVersion = GetArg("-socks", 5);
530
531     if (nSocksVersion != 4 && nSocksVersion != 5)
532         return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
533
534     if (mapArgs.count("-onlynet")) {
535         std::set<enum Network> nets;
536         BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
537             enum Network net = ParseNetwork(snet);
538             if (net == NET_UNROUTABLE)
539                 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
540             nets.insert(net);
541         }
542         for (int n = 0; n < NET_MAX; n++) {
543             enum Network net = (enum Network)n;
544             if (!nets.count(net))
545                 SetLimited(net);
546         }
547     }
548 #if defined(USE_IPV6)
549 #if ! USE_IPV6
550     else
551         SetLimited(NET_IPV6);
552 #endif
553 #endif
554
555     CService addrProxy;
556     bool fProxy = false;
557     if (mapArgs.count("-proxy")) {
558         addrProxy = CService(mapArgs["-proxy"], 9050);
559         if (!addrProxy.IsValid())
560             return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
561
562         if (!IsLimited(NET_IPV4))
563             SetProxy(NET_IPV4, addrProxy, nSocksVersion);
564         if (nSocksVersion > 4) {
565 #ifdef USE_IPV6
566             if (!IsLimited(NET_IPV6))
567                 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
568 #endif
569             SetNameProxy(addrProxy, nSocksVersion);
570         }
571         fProxy = true;
572     }
573
574     // -tor can override normal proxy, -notor disables tor entirely
575     if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
576         CService addrOnion;
577         if (!mapArgs.count("-tor"))
578             addrOnion = addrProxy;
579         else
580             addrOnion = CService(mapArgs["-tor"], 9050);
581         if (!addrOnion.IsValid())
582             return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
583         SetProxy(NET_TOR, addrOnion, 5);
584         SetReachable(NET_TOR);
585     }
586
587     // see Step 2: parameter interactions for more information about these
588     fNoListen = !GetBoolArg("-listen", true);
589     fDiscover = GetBoolArg("-discover", true);
590     fNameLookup = GetBoolArg("-dns", true);
591 #ifdef USE_UPNP
592     fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
593 #endif
594
595     bool fBound = false;
596     if (!fNoListen)
597     {
598         std::string strError;
599         if (mapArgs.count("-bind")) {
600             BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
601                 CService addrBind;
602                 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
603                     return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
604                 fBound |= Bind(addrBind);
605             }
606         } else {
607             struct in_addr inaddr_any;
608             inaddr_any.s_addr = INADDR_ANY;
609 #ifdef USE_IPV6
610             if (!IsLimited(NET_IPV6))
611                 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
612 #endif
613             if (!IsLimited(NET_IPV4))
614                 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
615         }
616         if (!fBound)
617             return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
618     }
619
620     if (mapArgs.count("-externalip"))
621     {
622         BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
623             CService addrLocal(strAddr, GetListenPort(), fNameLookup);
624             if (!addrLocal.IsValid())
625                 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
626             AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
627         }
628     }
629
630     if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
631     {
632         int64 nReserveBalance = 0;
633         if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
634         {
635             InitError(_("Invalid amount for -reservebalance=<amount>"));
636             return false;
637         }
638     }
639
640     if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
641     {
642         if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
643             InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
644     }
645
646     BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
647         AddOneShot(strDest);
648
649     // ********************************************************* Step 7: load blockchain
650
651     if (!bitdb.Open(GetDataDir()))
652     {
653         string msg = strprintf(_("Error initializing database environment %s!"
654                                  " To recover, BACKUP THAT DIRECTORY, then remove"
655                                  " everything from it except for wallet.dat."), strDataDir.c_str());
656         return InitError(msg);
657     }
658
659     if (GetBoolArg("-loadblockindextest"))
660     {
661         CTxDB txdb("r");
662         txdb.LoadBlockIndex();
663         PrintBlockTree();
664         return false;
665     }
666
667     uiInterface.InitMessage(_("Loading block index..."));
668     printf("Loading block index...\n");
669     nStart = GetTimeMillis();
670     if (!LoadBlockIndex())
671         return InitError(_("Error loading blkindex.dat"));
672
673     // as LoadBlockIndex can take several minutes, it's possible the user
674     // requested to kill bitcoin-qt during the last operation. If so, exit.
675     // As the program has not fully started yet, Shutdown() is possibly overkill.
676     if (fRequestShutdown)
677     {
678         printf("Shutdown requested. Exiting.\n");
679         return false;
680     }
681     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
682
683     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
684     {
685         PrintBlockTree();
686         return false;
687     }
688
689     if (mapArgs.count("-printblock"))
690     {
691         string strMatch = mapArgs["-printblock"];
692         int nFound = 0;
693         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
694         {
695             uint256 hash = (*mi).first;
696             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
697             {
698                 CBlockIndex* pindex = (*mi).second;
699                 CBlock block;
700                 block.ReadFromDisk(pindex);
701                 block.BuildMerkleTree();
702                 block.print();
703                 printf("\n");
704                 nFound++;
705             }
706         }
707         if (nFound == 0)
708             printf("No blocks matching %s were found\n", strMatch.c_str());
709         return false;
710     }
711
712     // ********************************************************* Step 8: load wallet
713
714     uiInterface.InitMessage(_("Loading wallet..."));
715     printf("Loading wallet...\n");
716     nStart = GetTimeMillis();
717     bool fFirstRun = true;
718     pwalletMain = new CWallet("wallet.dat");
719     DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
720     if (nLoadWalletRet != DB_LOAD_OK)
721     {
722         if (nLoadWalletRet == DB_CORRUPT)
723             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
724         else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
725         {
726             string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
727                          " or address book entries might be missing or incorrect."));
728             uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
729         }
730         else if (nLoadWalletRet == DB_TOO_NEW)
731             strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
732         else if (nLoadWalletRet == DB_NEED_REWRITE)
733         {
734             strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
735             printf("%s", strErrors.str().c_str());
736             return InitError(strErrors.str());
737         }
738         else
739             strErrors << _("Error loading wallet.dat") << "\n";
740     }
741
742     if (GetBoolArg("-upgradewallet", fFirstRun))
743     {
744         int nMaxVersion = GetArg("-upgradewallet", 0);
745         if (nMaxVersion == 0) // the -upgradewallet without argument case
746         {
747             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
748             nMaxVersion = CLIENT_VERSION;
749             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
750         }
751         else
752             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
753         if (nMaxVersion < pwalletMain->GetVersion())
754             strErrors << _("Cannot downgrade wallet") << "\n";
755         pwalletMain->SetMaxVersion(nMaxVersion);
756     }
757
758     if (fFirstRun)
759     {
760         // Create new keyUser and set as default key
761         RandAddSeedPerfmon();
762
763         CPubKey newDefaultKey;
764         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
765             strErrors << _("Cannot initialize keypool") << "\n";
766         pwalletMain->SetDefaultKey(newDefaultKey);
767         if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
768             strErrors << _("Cannot write default address") << "\n";
769     }
770
771     printf("%s", strErrors.str().c_str());
772     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
773
774     RegisterWallet(pwalletMain);
775
776     CBlockIndex *pindexRescan = pindexBest;
777     if (GetBoolArg("-rescan"))
778         pindexRescan = pindexGenesisBlock;
779     else
780     {
781         CWalletDB walletdb("wallet.dat");
782         CBlockLocator locator;
783         if (walletdb.ReadBestBlock(locator))
784             pindexRescan = locator.GetBlockIndex();
785     }
786     if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
787     {
788         uiInterface.InitMessage(_("Rescanning..."));
789         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
790         nStart = GetTimeMillis();
791         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
792         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
793     }
794
795     // ********************************************************* Step 9: import blocks
796
797     if (mapArgs.count("-loadblock"))
798     {
799         uiInterface.InitMessage(_("Importing blockchain data file."));
800
801         BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
802         {
803             FILE *file = fopen(strFile.c_str(), "rb");
804             if (file)
805                 LoadExternalBlockFile(file);
806         }
807     }
808
809     filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
810     if (filesystem::exists(pathBootstrap)) {
811         uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
812
813         FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
814         if (file) {
815             filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
816             LoadExternalBlockFile(file);
817             RenameOver(pathBootstrap, pathBootstrapOld);
818         }
819     }
820
821     // ********************************************************* Step 10: load peers
822
823     uiInterface.InitMessage(_("Loading addresses..."));
824     printf("Loading addresses...\n");
825     nStart = GetTimeMillis();
826
827     {
828         CAddrDB adb;
829         if (!adb.Read(addrman))
830             printf("Invalid or missing peers.dat; recreating\n");
831     }
832
833     printf("Loaded %i addresses from peers.dat  %"PRI64d"ms\n",
834            addrman.size(), GetTimeMillis() - nStart);
835
836     // ********************************************************* Step 11: start node
837
838     if (!CheckDiskSpace())
839         return false;
840
841     RandAddSeedPerfmon();
842
843     //// debug print
844     printf("mapBlockIndex.size() = %"PRIszu"\n",   mapBlockIndex.size());
845     printf("nBestHeight = %d\n",            nBestHeight);
846     printf("setKeyPool.size() = %"PRIszu"\n",      pwalletMain->setKeyPool.size());
847     printf("mapWallet.size() = %"PRIszu"\n",       pwalletMain->mapWallet.size());
848     printf("mapAddressBook.size() = %"PRIszu"\n",  pwalletMain->mapAddressBook.size());
849
850     if (!NewThread(StartNode, NULL))
851         InitError(_("Error: could not start node"));
852
853     if (fServer)
854         NewThread(ThreadRPCServer, NULL);
855
856     // ********************************************************* Step 12: finished
857
858     uiInterface.InitMessage(_("Done loading"));
859     printf("Done loading\n");
860
861     if (!strErrors.str().empty())
862         return InitError(strErrors.str());
863
864      // Add wallet transactions that aren't already in a block to mapTransactions
865     pwalletMain->ReacceptWalletTransactions();
866
867 #if !defined(QT_GUI)
868     // Loop until process is exit()ed from shutdown() function,
869     // called from ThreadRPCServer thread when a "stop" command is received.
870     while (1)
871         Sleep(5000);
872 #endif
873
874     return true;
875 }