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.
7 #include "bitcoinrpc.h"
11 #include "ui_interface.h"
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
14 #include <boost/filesystem/convenience.hpp>
15 #include <boost/interprocess/sync/file_lock.hpp>
16 #include <boost/algorithm/string/predicate.hpp>
17 #include <openssl/crypto.h>
24 using namespace boost;
27 CClientUIInterface uiInterface;
29 //////////////////////////////////////////////////////////////////////////////
34 void ExitTimeout(void* parg)
45 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
46 uiInterface.QueueShutdown();
48 // Without UI, Shutdown() can simply be started in a new thread
49 NewThread(Shutdown, NULL);
53 void Shutdown(void* parg)
55 static CCriticalSection cs_Shutdown;
58 // Make this thread recognisable as the shutdown thread
59 RenameThread("bitcoin-shutoff");
61 bool fFirstThread = false;
63 TRY_LOCK(cs_Shutdown, lockShutdown);
66 fFirstThread = !fTaken;
74 nTransactionsUpdated++;
78 boost::filesystem::remove(GetPidFile());
79 UnregisterWallet(pwalletMain);
81 NewThread(ExitTimeout, NULL);
83 printf("Bitcoin exited\n\n");
86 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
99 void HandleSIGTERM(int)
101 fRequestShutdown = true;
104 void HandleSIGHUP(int)
106 fReopenDebugLog = true;
113 //////////////////////////////////////////////////////////////////////////////
118 bool AppInit(int argc, char* argv[])
126 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
127 ParseParameters(argc, argv);
128 if (!boost::filesystem::is_directory(GetDataDir(false)))
130 fprintf(stderr, "Error: Specified directory does not exist\n");
133 ReadConfigFile(mapArgs, mapMultiArgs);
135 if (mapArgs.count("-?") || mapArgs.count("--help"))
137 // First part of help message is specific to bitcoind / RPC client
138 std::string strUsage = _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
140 " bitcoind [options] " + "\n" +
141 " bitcoind [options] <command> [params] " + _("Send command to -server or bitcoind") + "\n" +
142 " bitcoind [options] help " + _("List commands") + "\n" +
143 " bitcoind [options] help <command> " + _("Get help for a command") + "\n";
145 strUsage += "\n" + HelpMessage();
147 fprintf(stdout, "%s", strUsage.c_str());
152 for (int i = 1; i < argc; i++)
153 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
158 int ret = CommandLineRPC(argc, argv);
164 catch (std::exception& e) {
165 PrintException(&e, "AppInit()");
167 PrintException(NULL, "AppInit()");
174 extern void noui_connect();
175 int main(int argc, char* argv[])
179 // Connect bitcoind signal handlers
182 fRet = AppInit(argc, argv);
191 bool static InitError(const std::string &str)
193 uiInterface.ThreadSafeMessageBox(str, _("Bitcoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
197 bool static InitWarning(const std::string &str)
199 uiInterface.ThreadSafeMessageBox(str, _("Bitcoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
204 bool static Bind(const CService &addr, bool fError = true) {
207 std::string strError;
208 if (!BindListenPort(addr, strError)) {
210 return InitError(strError);
216 // Core-specific options shared between UI and daemon
217 std::string HelpMessage()
219 string strUsage = _("Options:") + "\n" +
220 " -? " + _("This help message") + "\n" +
221 " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
222 " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
223 " -gen " + _("Generate coins") + "\n" +
224 " -gen=0 " + _("Don't generate coins") + "\n" +
225 " -datadir=<dir> " + _("Specify data directory") + "\n" +
226 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
227 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
228 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
229 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
230 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
231 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
232 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
233 " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
234 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
235 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
236 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
237 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
238 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
239 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
240 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
241 " -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" +
242 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
243 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
244 " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
245 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
246 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
247 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
248 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
251 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
253 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
256 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
257 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
259 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
261 #if !defined(WIN32) && !defined(QT_GUI)
262 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
264 " -testnet " + _("Use the test network") + "\n" +
265 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
266 " -debugnet " + _("Output extra network debugging information") + "\n" +
267 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
268 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
269 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
271 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
273 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
274 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
275 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n" +
276 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
277 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
278 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
279 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
280 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
281 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
282 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
283 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
284 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
285 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
287 "\n" + _("Block creation options:") + "\n" +
288 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
289 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
290 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
292 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
293 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
294 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
295 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
296 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
301 /** Initialize bitcoin.
302 * @pre Parameters should be parsed and config file should be read.
306 // ********************************************************* Step 1: setup
308 // Turn off Microsoft heap dump noise
309 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
310 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
313 // Disable confusing "helpful" text message on abort, Ctrl-C
314 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
317 // Enable Data Execution Prevention (DEP)
318 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
319 // A failure is non-critical and needs no further attention!
320 #ifndef PROCESS_DEP_ENABLE
321 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
322 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
323 #define PROCESS_DEP_ENABLE 0x00000001
325 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
326 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
327 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
332 // Clean shutdown on SIGTERM
334 sa.sa_handler = HandleSIGTERM;
335 sigemptyset(&sa.sa_mask);
337 sigaction(SIGTERM, &sa, NULL);
338 sigaction(SIGINT, &sa, NULL);
340 // Reopen debug.log on SIGHUP
341 struct sigaction sa_hup;
342 sa_hup.sa_handler = HandleSIGHUP;
343 sigemptyset(&sa_hup.sa_mask);
345 sigaction(SIGHUP, &sa_hup, NULL);
348 // ********************************************************* Step 2: parameter interactions
350 fTestNet = GetBoolArg("-testnet");
352 SoftSetBoolArg("-irc", true);
355 if (mapArgs.count("-bind")) {
356 // when specifying an explicit binding address, you want to listen on it
357 // even when -connect or -proxy is specified
358 SoftSetBoolArg("-listen", true);
361 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
362 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
363 SoftSetBoolArg("-dnsseed", false);
364 SoftSetBoolArg("-listen", false);
367 if (mapArgs.count("-proxy")) {
368 // to protect privacy, do not listen by default if a proxy server is specified
369 SoftSetBoolArg("-listen", false);
372 if (!GetBoolArg("-listen", true)) {
373 // do not map ports or try to retrieve public IP when not listening (pointless)
374 SoftSetBoolArg("-upnp", false);
375 SoftSetBoolArg("-discover", false);
378 if (mapArgs.count("-externalip")) {
379 // if an explicit public IP is specified, do not try to find others
380 SoftSetBoolArg("-discover", false);
383 if (GetBoolArg("-salvagewallet")) {
384 // Rewrite just private keys: rescan to find transactions
385 SoftSetBoolArg("-rescan", true);
388 // ********************************************************* Step 3: parameter-to-internal-flags
390 fDebug = GetBoolArg("-debug");
392 // -debug implies fDebug*
396 fDebugNet = GetBoolArg("-debugnet");
398 bitdb.SetDetach(GetBoolArg("-detachdb", false));
400 #if !defined(WIN32) && !defined(QT_GUI)
401 fDaemon = GetBoolArg("-daemon");
409 fServer = GetBoolArg("-server");
411 /* force fServer when running without GUI */
415 fPrintToConsole = GetBoolArg("-printtoconsole");
416 fPrintToDebugger = GetBoolArg("-printtodebugger");
417 fLogTimestamps = GetBoolArg("-logtimestamps");
419 if (mapArgs.count("-timeout"))
421 int nNewTimeout = GetArg("-timeout", 5000);
422 if (nNewTimeout > 0 && nNewTimeout < 600000)
423 nConnectTimeout = nNewTimeout;
426 // Continue to put "/P2SH/" in the coinbase to monitor
428 // This can be removed eventually...
429 const char* pszP2SH = "/P2SH/";
430 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
433 if (mapArgs.count("-paytxfee"))
435 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
436 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
437 if (nTransactionFee > 0.25 * COIN)
438 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
441 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
443 const char* pszDataDir = GetDataDir().string().c_str();
445 // Make sure only a single Bitcoin process is using the data directory.
446 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
447 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
448 if (file) fclose(file);
449 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
450 if (!lock.try_lock())
451 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), pszDataDir));
453 #if !defined(WIN32) && !defined(QT_GUI)
460 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
465 CreatePidFile(GetPidFile(), pid);
469 pid_t sid = setsid();
471 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
475 if (GetBoolArg("-shrinkdebugfile", !fDebug))
477 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
478 printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
479 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
481 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
482 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
483 printf("Used data directory %s\n", pszDataDir);
484 std::ostringstream strErrors;
487 fprintf(stdout, "Bitcoin server starting\n");
491 // ********************************************************* Step 5: verify database integrity
493 uiInterface.InitMessage(_("Verifying database integrity..."));
495 if (!bitdb.Open(GetDataDir()))
497 string msg = strprintf(_("Error initializing database environment %s!"
498 " To recover, BACKUP THAT DIRECTORY, then remove"
499 " everything from it except for wallet.dat."), pszDataDir);
500 return InitError(msg);
503 if (GetBoolArg("-salvagewallet"))
505 // Recover readable keypairs:
506 if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
510 CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
511 if (r == CDBEnv::RECOVER_OK)
513 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
514 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
515 " your balance or transactions are incorrect you should"
516 " restore from a backup."), pszDataDir);
517 uiInterface.ThreadSafeMessageBox(msg, _("Bitcoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
519 if (r == CDBEnv::RECOVER_FAIL)
520 return InitError(_("wallet.dat corrupt, salvage failed"));
522 // ********************************************************* Step 6: network initialization
524 int nSocksVersion = GetArg("-socks", 5);
526 if (nSocksVersion != 4 && nSocksVersion != 5)
527 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
529 if (mapArgs.count("-onlynet")) {
530 std::set<enum Network> nets;
531 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
532 enum Network net = ParseNetwork(snet);
533 if (net == NET_UNROUTABLE)
534 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
537 for (int n = 0; n < NET_MAX; n++) {
538 enum Network net = (enum Network)n;
539 if (!nets.count(net))
543 #if defined(USE_IPV6)
546 SetLimited(NET_IPV6);
552 if (mapArgs.count("-proxy")) {
553 addrProxy = CService(mapArgs["-proxy"], 9050);
554 if (!addrProxy.IsValid())
555 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
557 if (!IsLimited(NET_IPV4))
558 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
559 if (nSocksVersion > 4) {
561 if (!IsLimited(NET_IPV6))
562 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
564 SetNameProxy(addrProxy, nSocksVersion);
569 // -tor can override normal proxy, -notor disables tor entirely
570 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
572 if (!mapArgs.count("-tor"))
573 addrOnion = addrProxy;
575 addrOnion = CService(mapArgs["-tor"], 9050);
576 if (!addrOnion.IsValid())
577 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
578 SetProxy(NET_TOR, addrOnion, 5);
579 SetReachable(NET_TOR);
582 // see Step 2: parameter interactions for more information about these
583 fNoListen = !GetBoolArg("-listen", true);
584 fDiscover = GetBoolArg("-discover", true);
585 fNameLookup = GetBoolArg("-dns", true);
587 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
593 std::string strError;
594 if (mapArgs.count("-bind")) {
595 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
597 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
598 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
599 fBound |= Bind(addrBind);
602 struct in_addr inaddr_any;
603 inaddr_any.s_addr = INADDR_ANY;
605 if (!IsLimited(NET_IPV6))
606 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
608 if (!IsLimited(NET_IPV4))
609 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
612 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
615 if (mapArgs.count("-externalip"))
617 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
618 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
619 if (!addrLocal.IsValid())
620 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
621 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
625 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
628 // ********************************************************* Step 7: load blockchain
630 if (GetBoolArg("-loadblockindextest"))
633 txdb.LoadBlockIndex();
638 uiInterface.InitMessage(_("Loading block index..."));
639 printf("Loading block index...\n");
640 nStart = GetTimeMillis();
641 if (!LoadBlockIndex())
642 return InitError(_("Error loading blkindex.dat"));
644 // as LoadBlockIndex can take several minutes, it's possible the user
645 // requested to kill bitcoin-qt during the last operation. If so, exit.
646 // As the program has not fully started yet, Shutdown() is possibly overkill.
647 if (fRequestShutdown)
649 printf("Shutdown requested. Exiting.\n");
652 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
654 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
660 if (mapArgs.count("-printblock"))
662 string strMatch = mapArgs["-printblock"];
664 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
666 uint256 hash = (*mi).first;
667 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
669 CBlockIndex* pindex = (*mi).second;
671 block.ReadFromDisk(pindex);
672 block.BuildMerkleTree();
679 printf("No blocks matching %s were found\n", strMatch.c_str());
683 // ********************************************************* Step 8: load wallet
685 uiInterface.InitMessage(_("Loading wallet..."));
686 printf("Loading wallet...\n");
687 nStart = GetTimeMillis();
688 bool fFirstRun = true;
689 pwalletMain = new CWallet("wallet.dat");
690 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
691 if (nLoadWalletRet != DB_LOAD_OK)
693 if (nLoadWalletRet == DB_CORRUPT)
694 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
695 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
697 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
698 " or address book entries might be missing or incorrect."));
699 uiInterface.ThreadSafeMessageBox(msg, _("Bitcoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
701 else if (nLoadWalletRet == DB_TOO_NEW)
702 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
703 else if (nLoadWalletRet == DB_NEED_REWRITE)
705 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
706 printf("%s", strErrors.str().c_str());
707 return InitError(strErrors.str());
710 strErrors << _("Error loading wallet.dat") << "\n";
713 if (GetBoolArg("-upgradewallet", fFirstRun))
715 int nMaxVersion = GetArg("-upgradewallet", 0);
716 if (nMaxVersion == 0) // the -upgradewallet without argument case
718 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
719 nMaxVersion = CLIENT_VERSION;
720 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
723 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
724 if (nMaxVersion < pwalletMain->GetVersion())
725 strErrors << _("Cannot downgrade wallet") << "\n";
726 pwalletMain->SetMaxVersion(nMaxVersion);
731 // Create new keyUser and set as default key
732 RandAddSeedPerfmon();
734 CPubKey newDefaultKey;
735 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
736 strErrors << _("Cannot initialize keypool") << "\n";
737 pwalletMain->SetDefaultKey(newDefaultKey);
738 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
739 strErrors << _("Cannot write default address") << "\n";
742 printf("%s", strErrors.str().c_str());
743 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
745 RegisterWallet(pwalletMain);
747 CBlockIndex *pindexRescan = pindexBest;
748 if (GetBoolArg("-rescan"))
749 pindexRescan = pindexGenesisBlock;
752 CWalletDB walletdb("wallet.dat");
753 CBlockLocator locator;
754 if (walletdb.ReadBestBlock(locator))
755 pindexRescan = locator.GetBlockIndex();
757 if (pindexBest != pindexRescan)
759 uiInterface.InitMessage(_("Rescanning..."));
760 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
761 nStart = GetTimeMillis();
762 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
763 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
766 // ********************************************************* Step 9: import blocks
768 if (mapArgs.count("-loadblock"))
770 uiInterface.InitMessage(_("Importing blockchain data file."));
772 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
774 FILE *file = fopen(strFile.c_str(), "rb");
776 LoadExternalBlockFile(file);
780 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
781 if (filesystem::exists(pathBootstrap)) {
782 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
784 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
786 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
787 LoadExternalBlockFile(file);
788 RenameOver(pathBootstrap, pathBootstrapOld);
792 // ********************************************************* Step 10: load peers
794 uiInterface.InitMessage(_("Loading addresses..."));
795 printf("Loading addresses...\n");
796 nStart = GetTimeMillis();
800 if (!adb.Read(addrman))
801 printf("Invalid or missing peers.dat; recreating\n");
804 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
805 addrman.size(), GetTimeMillis() - nStart);
807 // ********************************************************* Step 11: start node
809 if (!CheckDiskSpace())
812 RandAddSeedPerfmon();
815 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
816 printf("nBestHeight = %d\n", nBestHeight);
817 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
818 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
819 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
821 if (!NewThread(StartNode, NULL))
822 InitError(_("Error: could not start node"));
825 NewThread(ThreadRPCServer, NULL);
827 // ********************************************************* Step 12: finished
829 uiInterface.InitMessage(_("Done loading"));
830 printf("Done loading\n");
832 if (!strErrors.str().empty())
833 return InitError(strErrors.str());
835 // Add wallet transactions that aren't already in a block to mapTransactions
836 pwalletMain->ReacceptWalletTransactions();
839 // Loop until process is exit()ed from shutdown() function,
840 // called from ThreadRPCServer thread when a "stop" command is received.