]> Git Repo - VerusCoin.git/blob - src/init.cpp
Merge pull request #2418 from sipa/uintwork
[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 #ifndef QT_GUI
337         "  -rpcconnect=<ip>       " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
338 #endif
339         "  -rpcthreads=<n>        " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
340         "  -blocknotify=<cmd>     " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
341         "  -walletnotify=<cmd>    " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
342         "  -alertnotify=<cmd>     " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
343         "  -upgradewallet         " + _("Upgrade wallet to latest format") + "\n" +
344         "  -keypool=<n>           " + _("Set key pool size to <n> (default: 100)") + "\n" +
345         "  -rescan                " + _("Rescan the block chain for missing wallet transactions") + "\n" +
346         "  -salvagewallet         " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
347         "  -checkblocks=<n>       " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
348         "  -checklevel=<n>        " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
349         "  -txindex               " + _("Maintain a full transaction index (default: 0)") + "\n" +
350         "  -loadblock=<file>      " + _("Imports blocks from external blk000??.dat file") + "\n" +
351         "  -reindex               " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
352         "  -par=<n>               " + _("Set the number of script verification threads (1-16, 0=auto, default: 0)") + "\n" +
353
354         "\n" + _("Block creation options:") + "\n" +
355         "  -blockminsize=<n>      "   + _("Set minimum block size in bytes (default: 0)") + "\n" +
356         "  -blockmaxsize=<n>      "   + _("Set maximum block size in bytes (default: 250000)") + "\n" +
357         "  -blockprioritysize=<n> "   + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
358
359         "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
360         "  -rpcssl                                  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
361         "  -rpcsslcertificatechainfile=<file.cert>  " + _("Server certificate file (default: server.cert)") + "\n" +
362         "  -rpcsslprivatekeyfile=<file.pem>         " + _("Server private key (default: server.pem)") + "\n" +
363         "  -rpcsslciphers=<ciphers>                 " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
364
365     return strUsage;
366 }
367
368 struct CImportingNow
369 {
370     CImportingNow() {
371         assert(fImporting == false);
372         fImporting = true;
373     }
374
375     ~CImportingNow() {
376         assert(fImporting == true);
377         fImporting = false;
378     }
379 };
380
381 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
382 {
383     RenameThread("bitcoin-loadblk");
384
385     // -reindex
386     if (fReindex) {
387         CImportingNow imp;
388         int nFile = 0;
389         while (true) {
390             CDiskBlockPos pos(nFile, 0);
391             FILE *file = OpenBlockFile(pos, true);
392             if (!file)
393                 break;
394             printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
395             LoadExternalBlockFile(file, &pos);
396             nFile++;
397         }
398         pblocktree->WriteReindexing(false);
399         fReindex = false;
400         printf("Reindexing finished\n");
401         // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
402         InitBlockIndex();
403     }
404
405     // hardcoded $DATADIR/bootstrap.dat
406     filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
407     if (filesystem::exists(pathBootstrap)) {
408         FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
409         if (file) {
410             CImportingNow imp;
411             filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
412             printf("Importing bootstrap.dat...\n");
413             LoadExternalBlockFile(file);
414             RenameOver(pathBootstrap, pathBootstrapOld);
415         }
416     }
417
418     // -loadblock=
419     BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
420         FILE *file = fopen(path.string().c_str(), "rb");
421         if (file) {
422             CImportingNow imp;
423             printf("Importing %s...\n", path.string().c_str());
424             LoadExternalBlockFile(file);
425         }
426     }
427 }
428
429 /** Initialize bitcoin.
430  *  @pre Parameters should be parsed and config file should be read.
431  */
432 bool AppInit2(boost::thread_group& threadGroup)
433 {
434     // ********************************************************* Step 1: setup
435 #ifdef _MSC_VER
436     // Turn off Microsoft heap dump noise
437     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
438     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
439 #endif
440 #if _MSC_VER >= 1400
441     // Disable confusing "helpful" text message on abort, Ctrl-C
442     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
443 #endif
444 #ifdef WIN32
445     // Enable Data Execution Prevention (DEP)
446     // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
447     // A failure is non-critical and needs no further attention!
448 #ifndef PROCESS_DEP_ENABLE
449 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
450 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
451 #define PROCESS_DEP_ENABLE 0x00000001
452 #endif
453     typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
454     PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
455     if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
456 #endif
457 #ifndef WIN32
458     umask(077);
459
460     // Clean shutdown on SIGTERM
461     struct sigaction sa;
462     sa.sa_handler = HandleSIGTERM;
463     sigemptyset(&sa.sa_mask);
464     sa.sa_flags = 0;
465     sigaction(SIGTERM, &sa, NULL);
466     sigaction(SIGINT, &sa, NULL);
467
468     // Reopen debug.log on SIGHUP
469     struct sigaction sa_hup;
470     sa_hup.sa_handler = HandleSIGHUP;
471     sigemptyset(&sa_hup.sa_mask);
472     sa_hup.sa_flags = 0;
473     sigaction(SIGHUP, &sa_hup, NULL);
474 #endif
475
476     // ********************************************************* Step 2: parameter interactions
477
478     fTestNet = GetBoolArg("-testnet");
479
480     if (mapArgs.count("-bind")) {
481         // when specifying an explicit binding address, you want to listen on it
482         // even when -connect or -proxy is specified
483         SoftSetBoolArg("-listen", true);
484     }
485
486     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
487         // when only connecting to trusted nodes, do not seed via DNS, or listen by default
488         SoftSetBoolArg("-dnsseed", false);
489         SoftSetBoolArg("-listen", false);
490     }
491
492     if (mapArgs.count("-proxy")) {
493         // to protect privacy, do not listen by default if a proxy server is specified
494         SoftSetBoolArg("-listen", false);
495     }
496
497     if (!GetBoolArg("-listen", true)) {
498         // do not map ports or try to retrieve public IP when not listening (pointless)
499         SoftSetBoolArg("-upnp", false);
500         SoftSetBoolArg("-discover", false);
501     }
502
503     if (mapArgs.count("-externalip")) {
504         // if an explicit public IP is specified, do not try to find others
505         SoftSetBoolArg("-discover", false);
506     }
507
508     if (GetBoolArg("-salvagewallet")) {
509         // Rewrite just private keys: rescan to find transactions
510         SoftSetBoolArg("-rescan", true);
511     }
512
513     // ********************************************************* Step 3: parameter-to-internal-flags
514
515     fDebug = GetBoolArg("-debug");
516     fBenchmark = GetBoolArg("-benchmark");
517
518     // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
519     nScriptCheckThreads = GetArg("-par", 0);
520     if (nScriptCheckThreads == 0)
521         nScriptCheckThreads = boost::thread::hardware_concurrency();
522     if (nScriptCheckThreads <= 1)
523         nScriptCheckThreads = 0;
524     else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
525         nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
526
527     // -debug implies fDebug*
528     if (fDebug)
529         fDebugNet = true;
530     else
531         fDebugNet = GetBoolArg("-debugnet");
532
533     if (fDaemon)
534         fServer = true;
535     else
536         fServer = GetBoolArg("-server");
537
538     /* force fServer when running without GUI */
539 #if !defined(QT_GUI)
540     fServer = true;
541 #endif
542     fPrintToConsole = GetBoolArg("-printtoconsole");
543     fPrintToDebugger = GetBoolArg("-printtodebugger");
544     fLogTimestamps = GetBoolArg("-logtimestamps");
545
546     if (mapArgs.count("-timeout"))
547     {
548         int nNewTimeout = GetArg("-timeout", 5000);
549         if (nNewTimeout > 0 && nNewTimeout < 600000)
550             nConnectTimeout = nNewTimeout;
551     }
552
553     // Continue to put "/P2SH/" in the coinbase to monitor
554     // BIP16 support.
555     // This can be removed eventually...
556     const char* pszP2SH = "/P2SH/";
557     COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
558
559
560     if (mapArgs.count("-paytxfee"))
561     {
562         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
563             return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
564         if (nTransactionFee > 0.25 * COIN)
565             InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
566     }
567
568     // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
569
570     std::string strDataDir = GetDataDir().string();
571
572     // Make sure only a single Bitcoin process is using the data directory.
573     boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
574     FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
575     if (file) fclose(file);
576     static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
577     if (!lock.try_lock())
578         return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), strDataDir.c_str()));
579
580     if (GetBoolArg("-shrinkdebugfile", !fDebug))
581         ShrinkDebugFile();
582     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
583     printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
584     printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
585     if (!fLogTimestamps)
586         printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
587     printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
588     printf("Used data directory %s\n", strDataDir.c_str());
589     std::ostringstream strErrors;
590
591     if (fDaemon)
592         fprintf(stdout, "Bitcoin server starting\n");
593
594     if (nScriptCheckThreads) {
595         printf("Using %u threads for script verification\n", nScriptCheckThreads);
596         for (int i=0; i<nScriptCheckThreads-1; i++)
597             threadGroup.create_thread(&ThreadScriptCheck);
598     }
599
600     int64 nStart;
601
602     // ********************************************************* Step 5: verify wallet database integrity
603
604     uiInterface.InitMessage(_("Verifying wallet..."));
605
606     if (!bitdb.Open(GetDataDir()))
607     {
608         string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
609         return InitError(msg);
610     }
611
612     if (GetBoolArg("-salvagewallet"))
613     {
614         // Recover readable keypairs:
615         if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
616             return false;
617     }
618
619     if (filesystem::exists(GetDataDir() / "wallet.dat"))
620     {
621         CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
622         if (r == CDBEnv::RECOVER_OK)
623         {
624             string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
625                                      " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
626                                      " your balance or transactions are incorrect you should"
627                                      " restore from a backup."), strDataDir.c_str());
628             InitWarning(msg);
629         }
630         if (r == CDBEnv::RECOVER_FAIL)
631             return InitError(_("wallet.dat corrupt, salvage failed"));
632     }
633
634     // ********************************************************* Step 6: network initialization
635
636     int nSocksVersion = GetArg("-socks", 5);
637     if (nSocksVersion != 4 && nSocksVersion != 5)
638         return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
639
640     if (mapArgs.count("-onlynet")) {
641         std::set<enum Network> nets;
642         BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
643             enum Network net = ParseNetwork(snet);
644             if (net == NET_UNROUTABLE)
645                 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
646             nets.insert(net);
647         }
648         for (int n = 0; n < NET_MAX; n++) {
649             enum Network net = (enum Network)n;
650             if (!nets.count(net))
651                 SetLimited(net);
652         }
653     }
654 #if defined(USE_IPV6)
655 #if ! USE_IPV6
656     else
657         SetLimited(NET_IPV6);
658 #endif
659 #endif
660
661     CService addrProxy;
662     bool fProxy = false;
663     if (mapArgs.count("-proxy")) {
664         addrProxy = CService(mapArgs["-proxy"], 9050);
665         if (!addrProxy.IsValid())
666             return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
667
668         if (!IsLimited(NET_IPV4))
669             SetProxy(NET_IPV4, addrProxy, nSocksVersion);
670         if (nSocksVersion > 4) {
671 #ifdef USE_IPV6
672             if (!IsLimited(NET_IPV6))
673                 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
674 #endif
675             SetNameProxy(addrProxy, nSocksVersion);
676         }
677         fProxy = true;
678     }
679
680     // -tor can override normal proxy, -notor disables tor entirely
681     if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
682         CService addrOnion;
683         if (!mapArgs.count("-tor"))
684             addrOnion = addrProxy;
685         else
686             addrOnion = CService(mapArgs["-tor"], 9050);
687         if (!addrOnion.IsValid())
688             return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
689         SetProxy(NET_TOR, addrOnion, 5);
690         SetReachable(NET_TOR);
691     }
692
693     // see Step 2: parameter interactions for more information about these
694     fNoListen = !GetBoolArg("-listen", true);
695     fDiscover = GetBoolArg("-discover", true);
696     fNameLookup = GetBoolArg("-dns", true);
697
698     bool fBound = false;
699     if (!fNoListen) {
700         if (mapArgs.count("-bind")) {
701             BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
702                 CService addrBind;
703                 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
704                     return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
705                 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
706             }
707         }
708         else {
709             struct in_addr inaddr_any;
710             inaddr_any.s_addr = INADDR_ANY;
711 #ifdef USE_IPV6
712             fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
713 #endif
714             fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
715         }
716         if (!fBound)
717             return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
718     }
719
720     if (mapArgs.count("-externalip")) {
721         BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
722             CService addrLocal(strAddr, GetListenPort(), fNameLookup);
723             if (!addrLocal.IsValid())
724                 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
725             AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
726         }
727     }
728
729     BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
730         AddOneShot(strDest);
731
732     // ********************************************************* Step 7: load block chain
733
734     fReindex = GetBoolArg("-reindex");
735
736     // Todo: Check if needed, because in step 5 we do the same
737     if (!bitdb.Open(GetDataDir()))
738     {
739         string msg = strprintf(_("Error initializing database environment %s!"
740                                  " To recover, BACKUP THAT DIRECTORY, then remove"
741                                  " everything from it except for wallet.dat."), strDataDir.c_str());
742         return InitError(msg);
743     }
744
745     // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
746     filesystem::path blocksDir = GetDataDir() / "blocks";
747     if (!filesystem::exists(blocksDir))
748     {
749         filesystem::create_directories(blocksDir);
750         bool linked = false;
751         for (unsigned int i = 1; i < 10000; i++) {
752             filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
753             if (!filesystem::exists(source)) break;
754             filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
755             try {
756                 filesystem::create_hard_link(source, dest);
757                 printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
758                 linked = true;
759             } catch (filesystem::filesystem_error & e) {
760                 // Note: hardlink creation failing is not a disaster, it just means
761                 // blocks will get re-downloaded from peers.
762                 printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
763                 break;
764             }
765         }
766         if (linked)
767         {
768             fReindex = true;
769         }
770     }
771
772     // cache size calculations
773     size_t nTotalCache = GetArg("-dbcache", 25) << 20;
774     if (nTotalCache < (1 << 22))
775         nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
776     size_t nBlockTreeDBCache = nTotalCache / 8;
777     if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
778         nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
779     nTotalCache -= nBlockTreeDBCache;
780     size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
781     nTotalCache -= nCoinDBCache;
782     nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
783
784     bool fLoaded = false;
785     while (!fLoaded) {
786         bool fReset = fReindex;
787         std::string strLoadError;
788
789         uiInterface.InitMessage(_("Loading block index..."));
790
791         nStart = GetTimeMillis();
792         do {
793             try {
794                 UnloadBlockIndex();
795                 delete pcoinsTip;
796                 delete pcoinsdbview;
797                 delete pblocktree;
798
799                 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
800                 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
801                 pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
802
803                 if (fReindex)
804                     pblocktree->WriteReindexing(true);
805
806                 if (!LoadBlockIndex()) {
807                     strLoadError = _("Error loading block database");
808                     break;
809                 }
810
811                 // Initialize the block index (no-op if non-empty database was already loaded)
812                 if (!InitBlockIndex()) {
813                     strLoadError = _("Error initializing block database");
814                     break;
815                 }
816
817                 uiInterface.InitMessage(_("Verifying blocks..."));
818                 if (!VerifyDB()) {
819                     strLoadError = _("Corrupted block database detected");
820                     break;
821                 }
822             } catch(std::exception &e) {
823                 strLoadError = _("Error opening block database");
824                 break;
825             }
826
827             fLoaded = true;
828         } while(false);
829
830         if (!fLoaded) {
831             // first suggest a reindex
832             if (!fReset) {
833                 bool fRet = uiInterface.ThreadSafeMessageBox(
834                     strLoadError + ".\n" + _("Do you want to rebuild the block database now?"),
835                     "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
836                 if (fRet) {
837                     fReindex = true;
838                     fRequestShutdown = false;
839                 } else {
840                     return false;
841                 }
842             } else {
843                 return InitError(strLoadError);
844             }
845         }
846     }
847
848     if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false))
849         return InitError(_("You need to rebuild the databases using -reindex to change -txindex"));
850
851     // as LoadBlockIndex can take several minutes, it's possible the user
852     // requested to kill bitcoin-qt during the last operation. If so, exit.
853     // As the program has not fully started yet, Shutdown() is possibly overkill.
854     if (fRequestShutdown)
855     {
856         printf("Shutdown requested. Exiting.\n");
857         return false;
858     }
859     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
860
861     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
862     {
863         PrintBlockTree();
864         return false;
865     }
866
867     if (mapArgs.count("-printblock"))
868     {
869         string strMatch = mapArgs["-printblock"];
870         int nFound = 0;
871         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
872         {
873             uint256 hash = (*mi).first;
874             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
875             {
876                 CBlockIndex* pindex = (*mi).second;
877                 CBlock block;
878                 block.ReadFromDisk(pindex);
879                 block.BuildMerkleTree();
880                 block.print();
881                 printf("\n");
882                 nFound++;
883             }
884         }
885         if (nFound == 0)
886             printf("No blocks matching %s were found\n", strMatch.c_str());
887         return false;
888     }
889
890     // ********************************************************* Step 8: load wallet
891
892     uiInterface.InitMessage(_("Loading wallet..."));
893
894     nStart = GetTimeMillis();
895     bool fFirstRun = true;
896     pwalletMain = new CWallet("wallet.dat");
897     DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
898     if (nLoadWalletRet != DB_LOAD_OK)
899     {
900         if (nLoadWalletRet == DB_CORRUPT)
901             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
902         else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
903         {
904             string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
905                          " or address book entries might be missing or incorrect."));
906             InitWarning(msg);
907         }
908         else if (nLoadWalletRet == DB_TOO_NEW)
909             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
910         else if (nLoadWalletRet == DB_NEED_REWRITE)
911         {
912             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
913             printf("%s", strErrors.str().c_str());
914             return InitError(strErrors.str());
915         }
916         else
917             strErrors << _("Error loading wallet.dat") << "\n";
918     }
919
920     if (GetBoolArg("-upgradewallet", fFirstRun))
921     {
922         int nMaxVersion = GetArg("-upgradewallet", 0);
923         if (nMaxVersion == 0) // the -upgradewallet without argument case
924         {
925             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
926             nMaxVersion = CLIENT_VERSION;
927             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
928         }
929         else
930             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
931         if (nMaxVersion < pwalletMain->GetVersion())
932             strErrors << _("Cannot downgrade wallet") << "\n";
933         pwalletMain->SetMaxVersion(nMaxVersion);
934     }
935
936     if (fFirstRun)
937     {
938         // Create new keyUser and set as default key
939         RandAddSeedPerfmon();
940
941         CPubKey newDefaultKey;
942         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
943             strErrors << _("Cannot initialize keypool") << "\n";
944         pwalletMain->SetDefaultKey(newDefaultKey);
945         if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
946             strErrors << _("Cannot write default address") << "\n";
947     }
948
949     printf("%s", strErrors.str().c_str());
950     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
951
952     RegisterWallet(pwalletMain);
953
954     CBlockIndex *pindexRescan = pindexBest;
955     if (GetBoolArg("-rescan"))
956         pindexRescan = pindexGenesisBlock;
957     else
958     {
959         CWalletDB walletdb("wallet.dat");
960         CBlockLocator locator;
961         if (walletdb.ReadBestBlock(locator))
962             pindexRescan = locator.GetBlockIndex();
963     }
964     if (pindexBest && pindexBest != pindexRescan)
965     {
966         uiInterface.InitMessage(_("Rescanning..."));
967         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
968         nStart = GetTimeMillis();
969         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
970         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
971     }
972
973     // ********************************************************* Step 9: import blocks
974
975     // scan for better chains in the block chain database, that are not yet connected in the active best chain
976     CValidationState state;
977     if (!ConnectBestBlock(state))
978         strErrors << "Failed to connect best block";
979
980     std::vector<boost::filesystem::path> vImportFiles;
981     if (mapArgs.count("-loadblock"))
982     {
983         BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
984             vImportFiles.push_back(strFile);
985     }
986     threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
987
988     // ********************************************************* Step 10: load peers
989
990     uiInterface.InitMessage(_("Loading addresses..."));
991
992     nStart = GetTimeMillis();
993
994     {
995         CAddrDB adb;
996         if (!adb.Read(addrman))
997             printf("Invalid or missing peers.dat; recreating\n");
998     }
999
1000     printf("Loaded %i addresses from peers.dat  %"PRI64d"ms\n",
1001            addrman.size(), GetTimeMillis() - nStart);
1002
1003     // ********************************************************* Step 11: start node
1004
1005     if (!CheckDiskSpace())
1006         return false;
1007
1008     RandAddSeedPerfmon();
1009
1010     //// debug print
1011     printf("mapBlockIndex.size() = %"PRIszu"\n",   mapBlockIndex.size());
1012     printf("nBestHeight = %d\n",                   nBestHeight);
1013     printf("setKeyPool.size() = %"PRIszu"\n",      pwalletMain->setKeyPool.size());
1014     printf("mapWallet.size() = %"PRIszu"\n",       pwalletMain->mapWallet.size());
1015     printf("mapAddressBook.size() = %"PRIszu"\n",  pwalletMain->mapAddressBook.size());
1016
1017     StartNode(threadGroup);
1018
1019     if (fServer)
1020         StartRPCThreads();
1021
1022     // Generate coins in the background
1023     GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
1024
1025     // ********************************************************* Step 12: finished
1026
1027     uiInterface.InitMessage(_("Done loading"));
1028
1029     if (!strErrors.str().empty())
1030         return InitError(strErrors.str());
1031
1032      // Add wallet transactions that aren't already in a block to mapTransactions
1033     pwalletMain->ReacceptWalletTransactions();
1034
1035     // Run a thread to flush wallet periodically
1036     threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1037
1038     return !fRequestShutdown;
1039 }
This page took 0.085022 seconds and 4 git commands to generate.