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" +
337 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
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" +
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" +
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";
371 assert(fImporting == false);
376 assert(fImporting == true);
381 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
383 RenameThread("bitcoin-loadblk");
390 CDiskBlockPos pos(nFile, 0);
391 FILE *file = OpenBlockFile(pos, true);
394 printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
395 LoadExternalBlockFile(file, &pos);
398 pblocktree->WriteReindexing(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):
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");
411 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
412 printf("Importing bootstrap.dat...\n");
413 LoadExternalBlockFile(file);
414 RenameOver(pathBootstrap, pathBootstrapOld);
419 BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
420 FILE *file = fopen(path.string().c_str(), "rb");
423 printf("Importing %s...\n", path.string().c_str());
424 LoadExternalBlockFile(file);
429 /** Initialize bitcoin.
430 * @pre Parameters should be parsed and config file should be read.
432 bool AppInit2(boost::thread_group& threadGroup)
434 // ********************************************************* Step 1: setup
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));
441 // Disable confusing "helpful" text message on abort, Ctrl-C
442 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
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
453 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
454 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
455 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
460 // Clean shutdown on SIGTERM
462 sa.sa_handler = HandleSIGTERM;
463 sigemptyset(&sa.sa_mask);
465 sigaction(SIGTERM, &sa, NULL);
466 sigaction(SIGINT, &sa, NULL);
468 // Reopen debug.log on SIGHUP
469 struct sigaction sa_hup;
470 sa_hup.sa_handler = HandleSIGHUP;
471 sigemptyset(&sa_hup.sa_mask);
473 sigaction(SIGHUP, &sa_hup, NULL);
476 // ********************************************************* Step 2: parameter interactions
478 fTestNet = GetBoolArg("-testnet");
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);
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);
492 if (mapArgs.count("-proxy")) {
493 // to protect privacy, do not listen by default if a proxy server is specified
494 SoftSetBoolArg("-listen", false);
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);
503 if (mapArgs.count("-externalip")) {
504 // if an explicit public IP is specified, do not try to find others
505 SoftSetBoolArg("-discover", false);
508 if (GetBoolArg("-salvagewallet")) {
509 // Rewrite just private keys: rescan to find transactions
510 SoftSetBoolArg("-rescan", true);
513 // ********************************************************* Step 3: parameter-to-internal-flags
515 fDebug = GetBoolArg("-debug");
516 fBenchmark = GetBoolArg("-benchmark");
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;
527 // -debug implies fDebug*
531 fDebugNet = GetBoolArg("-debugnet");
536 fServer = GetBoolArg("-server");
538 /* force fServer when running without GUI */
542 fPrintToConsole = GetBoolArg("-printtoconsole");
543 fPrintToDebugger = GetBoolArg("-printtodebugger");
544 fLogTimestamps = GetBoolArg("-logtimestamps");
546 if (mapArgs.count("-timeout"))
548 int nNewTimeout = GetArg("-timeout", 5000);
549 if (nNewTimeout > 0 && nNewTimeout < 600000)
550 nConnectTimeout = nNewTimeout;
553 // Continue to put "/P2SH/" in the coinbase to monitor
555 // This can be removed eventually...
556 const char* pszP2SH = "/P2SH/";
557 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
560 if (mapArgs.count("-paytxfee"))
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."));
568 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
570 std::string strDataDir = GetDataDir().string();
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()));
580 if (GetBoolArg("-shrinkdebugfile", !fDebug))
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));
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;
592 fprintf(stdout, "Bitcoin server starting\n");
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);
602 // ********************************************************* Step 5: verify wallet database integrity
604 uiInterface.InitMessage(_("Verifying wallet..."));
606 if (!bitdb.Open(GetDataDir()))
608 string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
609 return InitError(msg);
612 if (GetBoolArg("-salvagewallet"))
614 // Recover readable keypairs:
615 if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
619 if (filesystem::exists(GetDataDir() / "wallet.dat"))
621 CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
622 if (r == CDBEnv::RECOVER_OK)
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());
630 if (r == CDBEnv::RECOVER_FAIL)
631 return InitError(_("wallet.dat corrupt, salvage failed"));
634 // ********************************************************* Step 6: network initialization
636 int nSocksVersion = GetArg("-socks", 5);
637 if (nSocksVersion != 4 && nSocksVersion != 5)
638 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
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()));
648 for (int n = 0; n < NET_MAX; n++) {
649 enum Network net = (enum Network)n;
650 if (!nets.count(net))
654 #if defined(USE_IPV6)
657 SetLimited(NET_IPV6);
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()));
668 if (!IsLimited(NET_IPV4))
669 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
670 if (nSocksVersion > 4) {
672 if (!IsLimited(NET_IPV6))
673 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
675 SetNameProxy(addrProxy, nSocksVersion);
680 // -tor can override normal proxy, -notor disables tor entirely
681 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
683 if (!mapArgs.count("-tor"))
684 addrOnion = addrProxy;
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);
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);
700 if (mapArgs.count("-bind")) {
701 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
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));
709 struct in_addr inaddr_any;
710 inaddr_any.s_addr = INADDR_ANY;
712 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
714 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
717 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
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);
729 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
732 // ********************************************************* Step 7: load block chain
734 fReindex = GetBoolArg("-reindex");
736 // Todo: Check if needed, because in step 5 we do the same
737 if (!bitdb.Open(GetDataDir()))
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);
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))
749 filesystem::create_directories(blocksDir);
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);
756 filesystem::create_hard_link(source, dest);
757 printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
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());
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
784 bool fLoaded = false;
786 bool fReset = fReindex;
787 std::string strLoadError;
789 uiInterface.InitMessage(_("Loading block index..."));
791 nStart = GetTimeMillis();
799 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
800 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
801 pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
804 pblocktree->WriteReindexing(true);
806 if (!LoadBlockIndex()) {
807 strLoadError = _("Error loading block database");
811 // Initialize the block index (no-op if non-empty database was already loaded)
812 if (!InitBlockIndex()) {
813 strLoadError = _("Error initializing block database");
817 uiInterface.InitMessage(_("Verifying blocks..."));
819 strLoadError = _("Corrupted block database detected");
822 } catch(std::exception &e) {
823 strLoadError = _("Error opening block database");
831 // first suggest a reindex
833 bool fRet = uiInterface.ThreadSafeMessageBox(
834 strLoadError + ".\n" + _("Do you want to rebuild the block database now?"),
835 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
838 fRequestShutdown = false;
843 return InitError(strLoadError);
848 if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false))
849 return InitError(_("You need to rebuild the databases using -reindex to change -txindex"));
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)
856 printf("Shutdown requested. Exiting.\n");
859 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
861 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
867 if (mapArgs.count("-printblock"))
869 string strMatch = mapArgs["-printblock"];
871 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
873 uint256 hash = (*mi).first;
874 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
876 CBlockIndex* pindex = (*mi).second;
878 block.ReadFromDisk(pindex);
879 block.BuildMerkleTree();
886 printf("No blocks matching %s were found\n", strMatch.c_str());
890 // ********************************************************* Step 8: load wallet
892 uiInterface.InitMessage(_("Loading wallet..."));
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)
900 if (nLoadWalletRet == DB_CORRUPT)
901 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
902 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
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."));
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)
912 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
913 printf("%s", strErrors.str().c_str());
914 return InitError(strErrors.str());
917 strErrors << _("Error loading wallet.dat") << "\n";
920 if (GetBoolArg("-upgradewallet", fFirstRun))
922 int nMaxVersion = GetArg("-upgradewallet", 0);
923 if (nMaxVersion == 0) // the -upgradewallet without argument case
925 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
926 nMaxVersion = CLIENT_VERSION;
927 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
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);
938 // Create new keyUser and set as default key
939 RandAddSeedPerfmon();
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";
949 printf("%s", strErrors.str().c_str());
950 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
952 RegisterWallet(pwalletMain);
954 CBlockIndex *pindexRescan = pindexBest;
955 if (GetBoolArg("-rescan"))
956 pindexRescan = pindexGenesisBlock;
959 CWalletDB walletdb("wallet.dat");
960 CBlockLocator locator;
961 if (walletdb.ReadBestBlock(locator))
962 pindexRescan = locator.GetBlockIndex();
964 if (pindexBest && pindexBest != pindexRescan)
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);
973 // ********************************************************* Step 9: import blocks
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";
980 std::vector<boost::filesystem::path> vImportFiles;
981 if (mapArgs.count("-loadblock"))
983 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
984 vImportFiles.push_back(strFile);
986 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
988 // ********************************************************* Step 10: load peers
990 uiInterface.InitMessage(_("Loading addresses..."));
992 nStart = GetTimeMillis();
996 if (!adb.Read(addrman))
997 printf("Invalid or missing peers.dat; recreating\n");
1000 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
1001 addrman.size(), GetTimeMillis() - nStart);
1003 // ********************************************************* Step 11: start node
1005 if (!CheckDiskSpace())
1008 RandAddSeedPerfmon();
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());
1017 StartNode(threadGroup);
1022 // Generate coins in the background
1023 GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
1025 // ********************************************************* Step 12: finished
1027 uiInterface.InitMessage(_("Done loading"));
1029 if (!strErrors.str().empty())
1030 return InitError(strErrors.str());
1032 // Add wallet transactions that aren't already in a block to mapTransactions
1033 pwalletMain->ReacceptWalletTransactions();
1035 // Run a thread to flush wallet periodically
1036 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1038 return !fRequestShutdown;