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