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