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