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