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 "checkpoints.h"
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
15 #include <boost/filesystem/convenience.hpp>
16 #include <boost/interprocess/sync/file_lock.hpp>
17 #include <boost/algorithm/string/predicate.hpp>
18 #include <openssl/crypto.h>
25 using namespace boost;
28 CClientUIInterface uiInterface;
29 std::string strWalletFileName;
31 //////////////////////////////////////////////////////////////////////////////
36 void ExitTimeout(void* parg)
47 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
48 uiInterface.QueueShutdown();
50 // Without UI, Shutdown() can simply be started in a new thread
51 NewThread(Shutdown, NULL);
55 void Shutdown(void* parg)
57 static CCriticalSection cs_Shutdown;
60 // Make this thread recognisable as the shutdown thread
61 RenameThread("bitcoin-shutoff");
63 bool fFirstThread = false;
65 TRY_LOCK(cs_Shutdown, lockShutdown);
68 fFirstThread = !fTaken;
76 nTransactionsUpdated++;
80 boost::filesystem::remove(GetPidFile());
81 UnregisterWallet(pwalletMain);
83 NewThread(ExitTimeout, NULL);
85 printf("NovaCoin exited\n\n");
88 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
101 void HandleSIGTERM(int)
103 fRequestShutdown = true;
106 void HandleSIGHUP(int)
108 fReopenDebugLog = true;
115 //////////////////////////////////////////////////////////////////////////////
120 bool AppInit(int argc, char* argv[])
128 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
129 ParseParameters(argc, argv);
130 if (!boost::filesystem::is_directory(GetDataDir(false)))
132 fprintf(stderr, "Error: Specified directory does not exist\n");
135 ReadConfigFile(mapArgs, mapMultiArgs);
137 if (mapArgs.count("-?") || mapArgs.count("--help"))
139 // First part of help message is specific to bitcoind / RPC client
140 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
142 " novacoind [options] " + "\n" +
143 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
144 " novacoind [options] help " + _("List commands") + "\n" +
145 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
147 strUsage += "\n" + HelpMessage();
149 fprintf(stdout, "%s", strUsage.c_str());
154 for (int i = 1; i < argc; i++)
155 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
160 int ret = CommandLineRPC(argc, argv);
166 catch (std::exception& e) {
167 PrintException(&e, "AppInit()");
169 PrintException(NULL, "AppInit()");
176 extern void noui_connect();
177 int main(int argc, char* argv[])
181 // Connect bitcoind signal handlers
184 fRet = AppInit(argc, argv);
193 bool static InitError(const std::string &str)
195 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
199 bool static InitWarning(const std::string &str)
201 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
206 bool static Bind(const CService &addr, bool fError = true) {
209 std::string strError;
210 if (!BindListenPort(addr, strError)) {
212 return InitError(strError);
218 // Core-specific options shared between UI and daemon
219 std::string HelpMessage()
221 string strUsage = _("Options:") + "\n" +
222 " -? " + _("This help message") + "\n" +
223 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
224 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
225 " -gen " + _("Generate coins") + "\n" +
226 " -gen=0 " + _("Don't generate coins") + "\n" +
227 " -datadir=<dir> " + _("Specify data directory") + "\n" +
228 " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
229 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
230 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
231 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
232 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
233 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
234 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
235 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
236 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
237 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
238 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
239 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
240 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
241 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
242 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
243 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
244 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
245 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
246 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
247 " -dnsseed " + _("Find peers using DNS lookup (default: 0)") + "\n" +
248 " -nosynccheckpoints " + _("Disable sync checkpoints (default: 0)") + "\n" +
249 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
250 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
251 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
252 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
255 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
257 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
260 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
261 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
263 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
265 #if !defined(WIN32) && !defined(QT_GUI)
266 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
268 " -testnet " + _("Use the test network") + "\n" +
269 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
270 " -debugnet " + _("Output extra network debugging information") + "\n" +
271 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
272 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
273 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
275 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
277 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
278 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
279 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
280 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
281 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
282 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
283 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
284 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
285 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
286 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
287 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
288 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
289 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
291 "\n" + _("Block creation options:") + "\n" +
292 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
293 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
294 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
296 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
297 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
298 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
299 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
300 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
305 /** Initialize bitcoin.
306 * @pre Parameters should be parsed and config file should be read.
310 // ********************************************************* Step 1: setup
312 // Turn off Microsoft heap dump noise
313 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
314 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
317 // Disable confusing "helpful" text message on abort, Ctrl-C
318 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
321 // Enable Data Execution Prevention (DEP)
322 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
323 // A failure is non-critical and needs no further attention!
324 #ifndef PROCESS_DEP_ENABLE
325 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
326 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
327 #define PROCESS_DEP_ENABLE 0x00000001
329 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
330 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
331 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
336 // Clean shutdown on SIGTERM
338 sa.sa_handler = HandleSIGTERM;
339 sigemptyset(&sa.sa_mask);
341 sigaction(SIGTERM, &sa, NULL);
342 sigaction(SIGINT, &sa, NULL);
344 // Reopen debug.log on SIGHUP
345 struct sigaction sa_hup;
346 sa_hup.sa_handler = HandleSIGHUP;
347 sigemptyset(&sa_hup.sa_mask);
349 sigaction(SIGHUP, &sa_hup, NULL);
352 // ********************************************************* Step 2: parameter interactions
354 fTestNet = GetBoolArg("-testnet");
356 SoftSetBoolArg("-irc", true);
359 if (mapArgs.count("-bind")) {
360 // when specifying an explicit binding address, you want to listen on it
361 // even when -connect or -proxy is specified
362 SoftSetBoolArg("-listen", true);
365 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
366 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
367 SoftSetBoolArg("-dnsseed", false);
368 SoftSetBoolArg("-listen", false);
371 if (mapArgs.count("-proxy")) {
372 // to protect privacy, do not listen by default if a proxy server is specified
373 SoftSetBoolArg("-listen", false);
376 if (!GetBoolArg("-listen", true)) {
377 // do not map ports or try to retrieve public IP when not listening (pointless)
378 SoftSetBoolArg("-upnp", false);
379 SoftSetBoolArg("-discover", false);
382 if (mapArgs.count("-externalip")) {
383 // if an explicit public IP is specified, do not try to find others
384 SoftSetBoolArg("-discover", false);
387 if (GetBoolArg("-salvagewallet")) {
388 // Rewrite just private keys: rescan to find transactions
389 SoftSetBoolArg("-rescan", true);
392 // ********************************************************* Step 3: parameter-to-internal-flags
394 fDebug = GetBoolArg("-debug");
396 // -debug implies fDebug*
400 fDebugNet = GetBoolArg("-debugnet");
402 bitdb.SetDetach(GetBoolArg("-detachdb", false));
404 #if !defined(WIN32) && !defined(QT_GUI)
405 fDaemon = GetBoolArg("-daemon");
413 fServer = GetBoolArg("-server");
415 /* force fServer when running without GUI */
419 fPrintToConsole = GetBoolArg("-printtoconsole");
420 fPrintToDebugger = GetBoolArg("-printtodebugger");
421 fLogTimestamps = GetBoolArg("-logtimestamps");
423 if (mapArgs.count("-timeout"))
425 int nNewTimeout = GetArg("-timeout", 5000);
426 if (nNewTimeout > 0 && nNewTimeout < 600000)
427 nConnectTimeout = nNewTimeout;
430 // Continue to put "/P2SH/" in the coinbase to monitor
432 // This can be removed eventually...
433 const char* pszP2SH = "/P2SH/";
434 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
437 if (mapArgs.count("-paytxfee"))
439 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
440 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
441 if (nTransactionFee > 0.25 * COIN)
442 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
445 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
447 std::string strDataDir = GetDataDir().string();
448 std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
450 // strWalletFileName must be a plain filename without a directory
451 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
452 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
454 // Make sure only a single Bitcoin process is using the data directory.
455 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
456 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
457 if (file) fclose(file);
458 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
459 if (!lock.try_lock())
460 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
462 #if !defined(WIN32) && !defined(QT_GUI)
469 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
474 CreatePidFile(GetPidFile(), pid);
478 pid_t sid = setsid();
480 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
484 if (GetBoolArg("-shrinkdebugfile", !fDebug))
486 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
487 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
488 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
490 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
491 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
492 printf("Used data directory %s\n", strDataDir.c_str());
493 std::ostringstream strErrors;
496 fprintf(stdout, "NovaCoin server starting\n");
500 // ********************************************************* Step 5: verify database integrity
502 uiInterface.InitMessage(_("Verifying database integrity..."));
504 if (!bitdb.Open(GetDataDir()))
506 string msg = strprintf(_("Error initializing database environment %s!"
507 " To recover, BACKUP THAT DIRECTORY, then remove"
508 " everything from it except for wallet.dat."), strDataDir.c_str());
509 return InitError(msg);
512 if (GetBoolArg("-salvagewallet"))
514 // Recover readable keypairs:
515 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
519 if (filesystem::exists(GetDataDir() / strWalletFileName))
521 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
522 if (r == CDBEnv::RECOVER_OK)
524 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
525 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
526 " your balance or transactions are incorrect you should"
527 " restore from a backup."), strDataDir.c_str());
528 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
530 if (r == CDBEnv::RECOVER_FAIL)
531 return InitError(_("wallet.dat corrupt, salvage failed"));
534 // ********************************************************* Step 6: network initialization
536 int nSocksVersion = GetArg("-socks", 5);
538 if (nSocksVersion != 4 && nSocksVersion != 5)
539 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
541 if (mapArgs.count("-onlynet")) {
542 std::set<enum Network> nets;
543 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
544 enum Network net = ParseNetwork(snet);
545 if (net == NET_UNROUTABLE)
546 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
549 for (int n = 0; n < NET_MAX; n++) {
550 enum Network net = (enum Network)n;
551 if (!nets.count(net))
555 #if defined(USE_IPV6)
558 SetLimited(NET_IPV6);
564 if (mapArgs.count("-proxy")) {
565 addrProxy = CService(mapArgs["-proxy"], 9050);
566 if (!addrProxy.IsValid())
567 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
569 if (!IsLimited(NET_IPV4))
570 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
571 if (nSocksVersion > 4) {
573 if (!IsLimited(NET_IPV6))
574 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
576 SetNameProxy(addrProxy, nSocksVersion);
581 // -tor can override normal proxy, -notor disables tor entirely
582 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
584 if (!mapArgs.count("-tor"))
585 addrOnion = addrProxy;
587 addrOnion = CService(mapArgs["-tor"], 9050);
588 if (!addrOnion.IsValid())
589 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
590 SetProxy(NET_TOR, addrOnion, 5);
591 SetReachable(NET_TOR);
594 // see Step 2: parameter interactions for more information about these
595 fNoListen = !GetBoolArg("-listen", true);
596 fDiscover = GetBoolArg("-discover", true);
597 fNameLookup = GetBoolArg("-dns", true);
599 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
605 std::string strError;
606 if (mapArgs.count("-bind")) {
607 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
609 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
610 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
611 fBound |= Bind(addrBind);
614 struct in_addr inaddr_any;
615 inaddr_any.s_addr = INADDR_ANY;
617 if (!IsLimited(NET_IPV6))
618 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
620 if (!IsLimited(NET_IPV4))
621 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
624 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
627 if (mapArgs.count("-externalip"))
629 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
630 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
631 if (!addrLocal.IsValid())
632 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
633 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
637 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
639 int64 nReserveBalance = 0;
640 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
642 InitError(_("Invalid amount for -reservebalance=<amount>"));
647 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
649 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
650 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
653 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
656 // ********************************************************* Step 7: load blockchain
658 if (!bitdb.Open(GetDataDir()))
660 string msg = strprintf(_("Error initializing database environment %s!"
661 " To recover, BACKUP THAT DIRECTORY, then remove"
662 " everything from it except for wallet.dat."), strDataDir.c_str());
663 return InitError(msg);
666 if (GetBoolArg("-loadblockindextest"))
669 txdb.LoadBlockIndex();
674 uiInterface.InitMessage(_("Loading block index..."));
675 printf("Loading block index...\n");
676 nStart = GetTimeMillis();
677 if (!LoadBlockIndex())
678 return InitError(_("Error loading blkindex.dat"));
680 // as LoadBlockIndex can take several minutes, it's possible the user
681 // requested to kill bitcoin-qt during the last operation. If so, exit.
682 // As the program has not fully started yet, Shutdown() is possibly overkill.
683 if (fRequestShutdown)
685 printf("Shutdown requested. Exiting.\n");
688 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
690 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
696 if (mapArgs.count("-printblock"))
698 string strMatch = mapArgs["-printblock"];
700 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
702 uint256 hash = (*mi).first;
703 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
705 CBlockIndex* pindex = (*mi).second;
707 block.ReadFromDisk(pindex);
708 block.BuildMerkleTree();
715 printf("No blocks matching %s were found\n", strMatch.c_str());
719 // ********************************************************* Step 8: load wallet
721 uiInterface.InitMessage(_("Loading wallet..."));
722 printf("Loading wallet...\n");
723 nStart = GetTimeMillis();
724 bool fFirstRun = true;
725 pwalletMain = new CWallet(strWalletFileName);
726 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
727 if (nLoadWalletRet != DB_LOAD_OK)
729 if (nLoadWalletRet == DB_CORRUPT)
730 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
731 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
733 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
734 " or address book entries might be missing or incorrect."));
735 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
737 else if (nLoadWalletRet == DB_TOO_NEW)
738 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
739 else if (nLoadWalletRet == DB_NEED_REWRITE)
741 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
742 printf("%s", strErrors.str().c_str());
743 return InitError(strErrors.str());
746 strErrors << _("Error loading wallet.dat") << "\n";
749 if (GetBoolArg("-upgradewallet", fFirstRun))
751 int nMaxVersion = GetArg("-upgradewallet", 0);
752 if (nMaxVersion == 0) // the -upgradewallet without argument case
754 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
755 nMaxVersion = CLIENT_VERSION;
756 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
759 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
760 if (nMaxVersion < pwalletMain->GetVersion())
761 strErrors << _("Cannot downgrade wallet") << "\n";
762 pwalletMain->SetMaxVersion(nMaxVersion);
767 // Create new keyUser and set as default key
768 RandAddSeedPerfmon();
770 CPubKey newDefaultKey;
771 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
772 strErrors << _("Cannot initialize keypool") << "\n";
773 pwalletMain->SetDefaultKey(newDefaultKey);
774 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
775 strErrors << _("Cannot write default address") << "\n";
778 printf("%s", strErrors.str().c_str());
779 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
781 RegisterWallet(pwalletMain);
783 CBlockIndex *pindexRescan = pindexBest;
784 if (GetBoolArg("-rescan"))
785 pindexRescan = pindexGenesisBlock;
788 CWalletDB walletdb(strWalletFileName);
789 CBlockLocator locator;
790 if (walletdb.ReadBestBlock(locator))
791 pindexRescan = locator.GetBlockIndex();
793 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
795 uiInterface.InitMessage(_("Rescanning..."));
796 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
797 nStart = GetTimeMillis();
798 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
799 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
802 // ********************************************************* Step 9: import blocks
804 if (mapArgs.count("-loadblock"))
806 uiInterface.InitMessage(_("Importing blockchain data file."));
808 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
810 FILE *file = fopen(strFile.c_str(), "rb");
812 LoadExternalBlockFile(file);
816 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
817 if (filesystem::exists(pathBootstrap)) {
818 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
820 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
822 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
823 LoadExternalBlockFile(file);
824 RenameOver(pathBootstrap, pathBootstrapOld);
828 // ********************************************************* Step 10: load peers
830 uiInterface.InitMessage(_("Loading addresses..."));
831 printf("Loading addresses...\n");
832 nStart = GetTimeMillis();
836 if (!adb.Read(addrman))
837 printf("Invalid or missing peers.dat; recreating\n");
840 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
841 addrman.size(), GetTimeMillis() - nStart);
843 // ********************************************************* Step 11: start node
845 if (!CheckDiskSpace())
848 RandAddSeedPerfmon();
851 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
852 printf("nBestHeight = %d\n", nBestHeight);
853 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
854 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
855 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
857 if (!NewThread(StartNode, NULL))
858 InitError(_("Error: could not start node"));
861 NewThread(ThreadRPCServer, NULL);
863 // ********************************************************* Step 12: finished
865 uiInterface.InitMessage(_("Done loading"));
866 printf("Done loading\n");
868 if (!strErrors.str().empty())
869 return InitError(strErrors.str());
871 // Add wallet transactions that aren't already in a block to mapTransactions
872 pwalletMain->ReacceptWalletTransactions();
875 // Loop until process is exit()ed from shutdown() function,
876 // called from ThreadRPCServer thread when a "stop" command is received.