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