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.
8 #include "bitcoinrpc.h"
12 #include "ui_interface.h"
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/filesystem/convenience.hpp>
17 #include <boost/interprocess/sync/file_lock.hpp>
18 #include <boost/algorithm/string/predicate.hpp>
19 #include <openssl/crypto.h>
26 using namespace boost;
29 CClientUIInterface uiInterface;
31 // Used to pass flags to the Bind() function
34 BF_EXPLICIT = (1U << 0),
35 BF_REPORT_ERROR = (1U << 1)
38 //////////////////////////////////////////////////////////////////////////////
44 // Thread management and startup/shutdown:
46 // The network-processing threads are all part of a thread group
47 // created by AppInit() or the Qt main() function.
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).
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.
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().
63 // Shutdown for Qt is very similar, only it uses a QTimer to detect
64 // fRequestShutdown getting set, and then does the normal Qt
68 volatile bool fRequestShutdown = false;
72 fRequestShutdown = true;
74 bool ShutdownRequested()
76 return fRequestShutdown;
79 static CCoinsViewDB *pcoinsdbview;
83 static CCriticalSection cs_Shutdown;
84 TRY_LOCK(cs_Shutdown, lockShutdown);
85 if (!lockShutdown) return;
87 RenameThread("bitcoin-shutoff");
88 nTransactionsUpdated++;
98 delete pcoinsTip; pcoinsTip = NULL;
99 delete pcoinsdbview; pcoinsdbview = NULL;
100 delete pblocktree; pblocktree = NULL;
103 boost::filesystem::remove(GetPidFile());
104 UnregisterWallet(pwalletMain);
109 // Signal handlers are very limited in what they are allowed to do, so:
111 void DetectShutdownThread(boost::thread_group* threadGroup)
113 // Tell the main threads to shutdown.
114 while (!fRequestShutdown)
117 if (fRequestShutdown)
118 threadGroup->interrupt_all();
122 void HandleSIGTERM(int)
124 fRequestShutdown = true;
127 void HandleSIGHUP(int)
129 fReopenDebugLog = true;
136 //////////////////////////////////////////////////////////////////////////////
141 bool AppInit(int argc, char* argv[])
143 boost::thread_group threadGroup;
144 boost::thread* detectShutdownThread = NULL;
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)))
156 fprintf(stderr, "Error: Specified directory does not exist\n");
159 ReadConfigFile(mapArgs, mapMultiArgs);
161 if (mapArgs.count("-?") || mapArgs.count("--help"))
163 // First part of help message is specific to bitcoind / RPC client
164 std::string strUsage = _("Bitcoin version") + " " + FormatFullVersion() + "\n\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";
171 strUsage += "\n" + HelpMessage();
173 fprintf(stdout, "%s", strUsage.c_str());
178 for (int i = 1; i < argc; i++)
179 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
184 int ret = CommandLineRPC(argc, argv);
188 fDaemon = GetBoolArg("-daemon");
195 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
198 if (pid > 0) // Parent process, pid is child process id
200 CreatePidFile(GetPidFile(), pid);
203 // Child process falls through to rest of initialization
205 pid_t sid = setsid();
207 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
211 detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
212 fRet = AppInit2(threadGroup);
214 catch (std::exception& e) {
215 PrintExceptionContinue(&e, "AppInit()");
217 PrintExceptionContinue(NULL, "AppInit()");
220 if (detectShutdownThread)
221 detectShutdownThread->interrupt();
222 threadGroup.interrupt_all();
225 if (detectShutdownThread)
227 detectShutdownThread->join();
228 delete detectShutdownThread;
229 detectShutdownThread = NULL;
236 extern void noui_connect();
237 int main(int argc, char* argv[])
241 // Connect bitcoind signal handlers
244 fRet = AppInit(argc, argv);
249 return (fRet ? 0 : 1);
253 bool static InitError(const std::string &str)
255 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
259 bool static InitWarning(const std::string &str)
261 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
265 bool static Bind(const CService &addr, unsigned int flags) {
266 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
268 std::string strError;
269 if (!BindListenPort(addr, strError)) {
270 if (flags & BF_REPORT_ERROR)
271 return InitError(strError);
277 // Core-specific options shared between UI and daemon
278 std::string HelpMessage()
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" +
311 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
313 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
316 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
318 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
320 #if !defined(WIN32) && !defined(QT_GUI)
321 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
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" +
330 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
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" +
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" +
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";
369 assert(fImporting == false);
374 assert(fImporting == true);
379 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
381 RenameThread("bitcoin-loadblk");
388 CDiskBlockPos pos(nFile, 0);
389 FILE *file = OpenBlockFile(pos, true);
392 printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
393 LoadExternalBlockFile(file, &pos);
396 pblocktree->WriteReindexing(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):
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");
409 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
410 printf("Importing bootstrap.dat...\n");
411 LoadExternalBlockFile(file);
412 RenameOver(pathBootstrap, pathBootstrapOld);
417 BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
418 FILE *file = fopen(path.string().c_str(), "rb");
421 printf("Importing %s...\n", path.string().c_str());
422 LoadExternalBlockFile(file);
427 /** Initialize bitcoin.
428 * @pre Parameters should be parsed and config file should be read.
430 bool AppInit2(boost::thread_group& threadGroup)
432 // ********************************************************* Step 1: setup
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));
439 // Disable confusing "helpful" text message on abort, Ctrl-C
440 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
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
451 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
452 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
453 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
458 // Clean shutdown on SIGTERM
460 sa.sa_handler = HandleSIGTERM;
461 sigemptyset(&sa.sa_mask);
463 sigaction(SIGTERM, &sa, NULL);
464 sigaction(SIGINT, &sa, NULL);
466 // Reopen debug.log on SIGHUP
467 struct sigaction sa_hup;
468 sa_hup.sa_handler = HandleSIGHUP;
469 sigemptyset(&sa_hup.sa_mask);
471 sigaction(SIGHUP, &sa_hup, NULL);
474 // ********************************************************* Step 2: parameter interactions
476 fTestNet = GetBoolArg("-testnet");
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);
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);
490 if (mapArgs.count("-proxy")) {
491 // to protect privacy, do not listen by default if a proxy server is specified
492 SoftSetBoolArg("-listen", false);
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);
501 if (mapArgs.count("-externalip")) {
502 // if an explicit public IP is specified, do not try to find others
503 SoftSetBoolArg("-discover", false);
506 if (GetBoolArg("-salvagewallet")) {
507 // Rewrite just private keys: rescan to find transactions
508 SoftSetBoolArg("-rescan", true);
511 // ********************************************************* Step 3: parameter-to-internal-flags
513 fDebug = GetBoolArg("-debug");
514 fBenchmark = GetBoolArg("-benchmark");
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;
525 // -debug implies fDebug*
529 fDebugNet = GetBoolArg("-debugnet");
534 fServer = GetBoolArg("-server");
536 /* force fServer when running without GUI */
540 fPrintToConsole = GetBoolArg("-printtoconsole");
541 fPrintToDebugger = GetBoolArg("-printtodebugger");
542 fLogTimestamps = GetBoolArg("-logtimestamps");
544 if (mapArgs.count("-timeout"))
546 int nNewTimeout = GetArg("-timeout", 5000);
547 if (nNewTimeout > 0 && nNewTimeout < 600000)
548 nConnectTimeout = nNewTimeout;
551 // Continue to put "/P2SH/" in the coinbase to monitor
553 // This can be removed eventually...
554 const char* pszP2SH = "/P2SH/";
555 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
558 if (mapArgs.count("-paytxfee"))
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."));
566 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
568 std::string strDataDir = GetDataDir().string();
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()));
578 if (GetBoolArg("-shrinkdebugfile", !fDebug))
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));
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;
590 fprintf(stdout, "Bitcoin server starting\n");
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);
600 // ********************************************************* Step 5: verify wallet database integrity
602 uiInterface.InitMessage(_("Verifying wallet..."));
604 if (!bitdb.Open(GetDataDir()))
606 string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
607 return InitError(msg);
610 if (GetBoolArg("-salvagewallet"))
612 // Recover readable keypairs:
613 if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
617 if (filesystem::exists(GetDataDir() / "wallet.dat"))
619 CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
620 if (r == CDBEnv::RECOVER_OK)
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());
628 if (r == CDBEnv::RECOVER_FAIL)
629 return InitError(_("wallet.dat corrupt, salvage failed"));
632 // ********************************************************* Step 6: network initialization
634 int nSocksVersion = GetArg("-socks", 5);
635 if (nSocksVersion != 4 && nSocksVersion != 5)
636 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
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()));
646 for (int n = 0; n < NET_MAX; n++) {
647 enum Network net = (enum Network)n;
648 if (!nets.count(net))
652 #if defined(USE_IPV6)
655 SetLimited(NET_IPV6);
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()));
666 if (!IsLimited(NET_IPV4))
667 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
668 if (nSocksVersion > 4) {
670 if (!IsLimited(NET_IPV6))
671 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
673 SetNameProxy(addrProxy, nSocksVersion);
678 // -tor can override normal proxy, -notor disables tor entirely
679 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
681 if (!mapArgs.count("-tor"))
682 addrOnion = addrProxy;
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);
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);
698 if (mapArgs.count("-bind")) {
699 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
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));
707 struct in_addr inaddr_any;
708 inaddr_any.s_addr = INADDR_ANY;
710 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
712 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
715 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
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);
727 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
730 // ********************************************************* Step 7: load block chain
732 fReindex = GetBoolArg("-reindex");
734 // Todo: Check if needed, because in step 5 we do the same
735 if (!bitdb.Open(GetDataDir()))
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);
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))
747 filesystem::create_directories(blocksDir);
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);
754 filesystem::create_hard_link(source, dest);
755 printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
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());
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
782 bool fLoaded = false;
784 bool fReset = fReindex;
785 std::string strLoadError;
787 uiInterface.InitMessage(_("Loading block index..."));
789 nStart = GetTimeMillis();
797 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
798 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
799 pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
802 pblocktree->WriteReindexing(true);
804 if (!LoadBlockIndex()) {
805 strLoadError = _("Error loading block database");
809 // Initialize the block index (no-op if non-empty database was already loaded)
810 if (!InitBlockIndex()) {
811 strLoadError = _("Error initializing block database");
815 uiInterface.InitMessage(_("Verifying blocks..."));
817 strLoadError = _("Corrupted block database detected");
820 } catch(std::exception &e) {
821 strLoadError = _("Error opening block database");
829 // first suggest a reindex
831 bool fRet = uiInterface.ThreadSafeMessageBox(
832 strLoadError + ".\n" + _("Do you want to rebuild the block database now?"),
833 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
836 fRequestShutdown = false;
841 return InitError(strLoadError);
846 if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false))
847 return InitError(_("You need to rebuild the databases using -reindex to change -txindex"));
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)
854 printf("Shutdown requested. Exiting.\n");
857 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
859 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
865 if (mapArgs.count("-printblock"))
867 string strMatch = mapArgs["-printblock"];
869 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
871 uint256 hash = (*mi).first;
872 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
874 CBlockIndex* pindex = (*mi).second;
876 block.ReadFromDisk(pindex);
877 block.BuildMerkleTree();
884 printf("No blocks matching %s were found\n", strMatch.c_str());
888 // ********************************************************* Step 8: load wallet
890 uiInterface.InitMessage(_("Loading wallet..."));
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)
898 if (nLoadWalletRet == DB_CORRUPT)
899 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
900 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
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."));
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)
910 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
911 printf("%s", strErrors.str().c_str());
912 return InitError(strErrors.str());
915 strErrors << _("Error loading wallet.dat") << "\n";
918 if (GetBoolArg("-upgradewallet", fFirstRun))
920 int nMaxVersion = GetArg("-upgradewallet", 0);
921 if (nMaxVersion == 0) // the -upgradewallet without argument case
923 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
924 nMaxVersion = CLIENT_VERSION;
925 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
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);
936 // Create new keyUser and set as default key
937 RandAddSeedPerfmon();
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";
947 printf("%s", strErrors.str().c_str());
948 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
950 RegisterWallet(pwalletMain);
952 CBlockIndex *pindexRescan = pindexBest;
953 if (GetBoolArg("-rescan"))
954 pindexRescan = pindexGenesisBlock;
957 CWalletDB walletdb("wallet.dat");
958 CBlockLocator locator;
959 if (walletdb.ReadBestBlock(locator))
960 pindexRescan = locator.GetBlockIndex();
962 if (pindexBest && pindexBest != pindexRescan)
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);
971 // ********************************************************* Step 9: import blocks
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";
978 std::vector<boost::filesystem::path> vImportFiles;
979 if (mapArgs.count("-loadblock"))
981 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
982 vImportFiles.push_back(strFile);
984 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
986 // ********************************************************* Step 10: load peers
988 uiInterface.InitMessage(_("Loading addresses..."));
990 nStart = GetTimeMillis();
994 if (!adb.Read(addrman))
995 printf("Invalid or missing peers.dat; recreating\n");
998 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
999 addrman.size(), GetTimeMillis() - nStart);
1001 // ********************************************************* Step 11: start node
1003 if (!CheckDiskSpace())
1006 RandAddSeedPerfmon();
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());
1015 StartNode(threadGroup);
1020 // Generate coins in the background
1021 GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
1023 // ********************************************************* Step 12: finished
1025 uiInterface.InitMessage(_("Done loading"));
1027 if (!strErrors.str().empty())
1028 return InitError(strErrors.str());
1030 // Add wallet transactions that aren't already in a block to mapTransactions
1031 pwalletMain->ReacceptWalletTransactions();
1033 // Run a thread to flush wallet periodically
1034 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1036 return !fRequestShutdown;