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