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