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