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