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;
30 //////////////////////////////////////////////////////////////////////////////
35 void ExitTimeout(void* parg)
46 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
47 uiInterface.QueueShutdown();
49 // Without UI, Shutdown() can simply be started in a new thread
50 NewThread(Shutdown, NULL);
54 void Shutdown(void* parg)
56 static CCriticalSection cs_Shutdown;
59 // Make this thread recognisable as the shutdown thread
60 RenameThread("bitcoin-shutoff");
62 bool fFirstThread = false;
64 TRY_LOCK(cs_Shutdown, lockShutdown);
67 fFirstThread = !fTaken;
75 nTransactionsUpdated++;
79 boost::filesystem::remove(GetPidFile());
80 UnregisterWallet(pwalletMain);
82 NewThread(ExitTimeout, NULL);
84 printf("NovaCoin exited\n\n");
87 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
100 void HandleSIGTERM(int)
102 fRequestShutdown = true;
105 void HandleSIGHUP(int)
107 fReopenDebugLog = true;
114 //////////////////////////////////////////////////////////////////////////////
119 bool AppInit(int argc, char* argv[])
127 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
128 ParseParameters(argc, argv);
129 if (!boost::filesystem::is_directory(GetDataDir(false)))
131 fprintf(stderr, "Error: Specified directory does not exist\n");
134 ReadConfigFile(mapArgs, mapMultiArgs);
136 if (mapArgs.count("-?") || mapArgs.count("--help"))
138 // First part of help message is specific to bitcoind / RPC client
139 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
141 " novacoind [options] " + "\n" +
142 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
143 " novacoind [options] help " + _("List commands") + "\n" +
144 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
146 strUsage += "\n" + HelpMessage();
148 fprintf(stdout, "%s", strUsage.c_str());
153 for (int i = 1; i < argc; i++)
154 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
159 int ret = CommandLineRPC(argc, argv);
165 catch (std::exception& e) {
166 PrintException(&e, "AppInit()");
168 PrintException(NULL, "AppInit()");
175 extern void noui_connect();
176 int main(int argc, char* argv[])
180 // Connect bitcoind signal handlers
183 fRet = AppInit(argc, argv);
192 bool static InitError(const std::string &str)
194 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
198 bool static InitWarning(const std::string &str)
200 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
205 bool static Bind(const CService &addr, bool fError = true) {
208 std::string strError;
209 if (!BindListenPort(addr, strError)) {
211 return InitError(strError);
217 // Core-specific options shared between UI and daemon
218 std::string HelpMessage()
220 string strUsage = _("Options:") + "\n" +
221 " -? " + _("This help message") + "\n" +
222 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
223 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
224 " -gen " + _("Generate coins") + "\n" +
225 " -gen=0 " + _("Don't generate coins") + "\n" +
226 " -datadir=<dir> " + _("Specify data directory") + "\n" +
227 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
228 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
229 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
230 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
231 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
232 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
233 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
234 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
235 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
236 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
237 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
238 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
239 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
240 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
241 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
242 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
243 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
244 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
245 " -dnsseed " + _("Find peers using DNS lookup (default: 0)") + "\n" +
246 " -nosynccheckpoints " + _("Disable sync checkpoints (default: 0)") + "\n" +
247 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
248 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
249 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
250 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
253 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
255 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
258 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
259 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
261 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
263 #if !defined(WIN32) && !defined(QT_GUI)
264 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
266 " -testnet " + _("Use the test network") + "\n" +
267 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
268 " -debugnet " + _("Output extra network debugging information") + "\n" +
269 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
270 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
271 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
273 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
275 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
276 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
277 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
278 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
279 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
280 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
281 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
282 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
283 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
284 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
285 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
286 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
287 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
289 "\n" + _("Block creation options:") + "\n" +
290 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
291 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
292 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
294 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
295 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
296 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
297 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
298 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
303 /** Initialize bitcoin.
304 * @pre Parameters should be parsed and config file should be read.
308 // ********************************************************* Step 1: setup
310 // Turn off Microsoft heap dump noise
311 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
312 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
315 // Disable confusing "helpful" text message on abort, Ctrl-C
316 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
319 // Enable Data Execution Prevention (DEP)
320 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
321 // A failure is non-critical and needs no further attention!
322 #ifndef PROCESS_DEP_ENABLE
323 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
324 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
325 #define PROCESS_DEP_ENABLE 0x00000001
327 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
328 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
329 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
334 // Clean shutdown on SIGTERM
336 sa.sa_handler = HandleSIGTERM;
337 sigemptyset(&sa.sa_mask);
339 sigaction(SIGTERM, &sa, NULL);
340 sigaction(SIGINT, &sa, NULL);
342 // Reopen debug.log on SIGHUP
343 struct sigaction sa_hup;
344 sa_hup.sa_handler = HandleSIGHUP;
345 sigemptyset(&sa_hup.sa_mask);
347 sigaction(SIGHUP, &sa_hup, NULL);
350 // ********************************************************* Step 2: parameter interactions
352 fTestNet = GetBoolArg("-testnet");
354 SoftSetBoolArg("-irc", true);
357 if (mapArgs.count("-bind")) {
358 // when specifying an explicit binding address, you want to listen on it
359 // even when -connect or -proxy is specified
360 SoftSetBoolArg("-listen", true);
363 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
364 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
365 SoftSetBoolArg("-dnsseed", false);
366 SoftSetBoolArg("-listen", false);
369 if (mapArgs.count("-proxy")) {
370 // to protect privacy, do not listen by default if a proxy server is specified
371 SoftSetBoolArg("-listen", false);
374 if (!GetBoolArg("-listen", true)) {
375 // do not map ports or try to retrieve public IP when not listening (pointless)
376 SoftSetBoolArg("-upnp", false);
377 SoftSetBoolArg("-discover", false);
380 if (mapArgs.count("-externalip")) {
381 // if an explicit public IP is specified, do not try to find others
382 SoftSetBoolArg("-discover", false);
385 if (GetBoolArg("-salvagewallet")) {
386 // Rewrite just private keys: rescan to find transactions
387 SoftSetBoolArg("-rescan", true);
390 // ********************************************************* Step 3: parameter-to-internal-flags
392 fDebug = GetBoolArg("-debug");
394 // -debug implies fDebug*
398 fDebugNet = GetBoolArg("-debugnet");
400 bitdb.SetDetach(GetBoolArg("-detachdb", false));
402 #if !defined(WIN32) && !defined(QT_GUI)
403 fDaemon = GetBoolArg("-daemon");
411 fServer = GetBoolArg("-server");
413 /* force fServer when running without GUI */
417 fPrintToConsole = GetBoolArg("-printtoconsole");
418 fPrintToDebugger = GetBoolArg("-printtodebugger");
419 fLogTimestamps = GetBoolArg("-logtimestamps");
421 if (mapArgs.count("-timeout"))
423 int nNewTimeout = GetArg("-timeout", 5000);
424 if (nNewTimeout > 0 && nNewTimeout < 600000)
425 nConnectTimeout = nNewTimeout;
428 // Continue to put "/P2SH/" in the coinbase to monitor
430 // This can be removed eventually...
431 const char* pszP2SH = "/P2SH/";
432 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
435 if (mapArgs.count("-paytxfee"))
437 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
438 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
439 if (nTransactionFee > 0.25 * COIN)
440 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
443 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
445 std::string strDataDir = GetDataDir().string();
447 // Make sure only a single Bitcoin process is using the data directory.
448 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
449 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
450 if (file) fclose(file);
451 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
452 if (!lock.try_lock())
453 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
455 #if !defined(WIN32) && !defined(QT_GUI)
462 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
467 CreatePidFile(GetPidFile(), pid);
471 pid_t sid = setsid();
473 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
477 if (GetBoolArg("-shrinkdebugfile", !fDebug))
479 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
480 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
481 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
483 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
484 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
485 printf("Used data directory %s\n", strDataDir.c_str());
486 std::ostringstream strErrors;
489 fprintf(stdout, "NovaCoin server starting\n");
493 // ********************************************************* Step 5: verify database integrity
495 uiInterface.InitMessage(_("Verifying database integrity..."));
497 if (!bitdb.Open(GetDataDir()))
499 string msg = strprintf(_("Error initializing database environment %s!"
500 " To recover, BACKUP THAT DIRECTORY, then remove"
501 " everything from it except for wallet.dat."), strDataDir.c_str());
502 return InitError(msg);
505 if (GetBoolArg("-salvagewallet"))
507 // Recover readable keypairs:
508 if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
512 if (filesystem::exists(GetDataDir() / "wallet.dat"))
514 CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
515 if (r == CDBEnv::RECOVER_OK)
517 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
518 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
519 " your balance or transactions are incorrect you should"
520 " restore from a backup."), strDataDir.c_str());
521 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
523 if (r == CDBEnv::RECOVER_FAIL)
524 return InitError(_("wallet.dat corrupt, salvage failed"));
527 // ********************************************************* Step 6: network initialization
529 int nSocksVersion = GetArg("-socks", 5);
531 if (nSocksVersion != 4 && nSocksVersion != 5)
532 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
534 if (mapArgs.count("-onlynet")) {
535 std::set<enum Network> nets;
536 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
537 enum Network net = ParseNetwork(snet);
538 if (net == NET_UNROUTABLE)
539 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
542 for (int n = 0; n < NET_MAX; n++) {
543 enum Network net = (enum Network)n;
544 if (!nets.count(net))
548 #if defined(USE_IPV6)
551 SetLimited(NET_IPV6);
557 if (mapArgs.count("-proxy")) {
558 addrProxy = CService(mapArgs["-proxy"], 9050);
559 if (!addrProxy.IsValid())
560 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
562 if (!IsLimited(NET_IPV4))
563 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
564 if (nSocksVersion > 4) {
566 if (!IsLimited(NET_IPV6))
567 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
569 SetNameProxy(addrProxy, nSocksVersion);
574 // -tor can override normal proxy, -notor disables tor entirely
575 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
577 if (!mapArgs.count("-tor"))
578 addrOnion = addrProxy;
580 addrOnion = CService(mapArgs["-tor"], 9050);
581 if (!addrOnion.IsValid())
582 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
583 SetProxy(NET_TOR, addrOnion, 5);
584 SetReachable(NET_TOR);
587 // see Step 2: parameter interactions for more information about these
588 fNoListen = !GetBoolArg("-listen", true);
589 fDiscover = GetBoolArg("-discover", true);
590 fNameLookup = GetBoolArg("-dns", true);
592 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
598 std::string strError;
599 if (mapArgs.count("-bind")) {
600 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
602 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
603 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
604 fBound |= Bind(addrBind);
607 struct in_addr inaddr_any;
608 inaddr_any.s_addr = INADDR_ANY;
610 if (!IsLimited(NET_IPV6))
611 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
613 if (!IsLimited(NET_IPV4))
614 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
617 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
620 if (mapArgs.count("-externalip"))
622 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
623 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
624 if (!addrLocal.IsValid())
625 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
626 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
630 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
632 int64 nReserveBalance = 0;
633 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
635 InitError(_("Invalid amount for -reservebalance=<amount>"));
640 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
642 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
643 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
646 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
649 // ********************************************************* Step 7: load blockchain
651 if (!bitdb.Open(GetDataDir()))
653 string msg = strprintf(_("Error initializing database environment %s!"
654 " To recover, BACKUP THAT DIRECTORY, then remove"
655 " everything from it except for wallet.dat."), strDataDir.c_str());
656 return InitError(msg);
659 if (GetBoolArg("-loadblockindextest"))
662 txdb.LoadBlockIndex();
667 uiInterface.InitMessage(_("Loading block index..."));
668 printf("Loading block index...\n");
669 nStart = GetTimeMillis();
670 if (!LoadBlockIndex())
671 return InitError(_("Error loading blkindex.dat"));
673 // as LoadBlockIndex can take several minutes, it's possible the user
674 // requested to kill bitcoin-qt during the last operation. If so, exit.
675 // As the program has not fully started yet, Shutdown() is possibly overkill.
676 if (fRequestShutdown)
678 printf("Shutdown requested. Exiting.\n");
681 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
683 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
689 if (mapArgs.count("-printblock"))
691 string strMatch = mapArgs["-printblock"];
693 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
695 uint256 hash = (*mi).first;
696 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
698 CBlockIndex* pindex = (*mi).second;
700 block.ReadFromDisk(pindex);
701 block.BuildMerkleTree();
708 printf("No blocks matching %s were found\n", strMatch.c_str());
712 // ********************************************************* Step 8: load wallet
714 uiInterface.InitMessage(_("Loading wallet..."));
715 printf("Loading wallet...\n");
716 nStart = GetTimeMillis();
717 bool fFirstRun = true;
718 pwalletMain = new CWallet("wallet.dat");
719 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
720 if (nLoadWalletRet != DB_LOAD_OK)
722 if (nLoadWalletRet == DB_CORRUPT)
723 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
724 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
726 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
727 " or address book entries might be missing or incorrect."));
728 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
730 else if (nLoadWalletRet == DB_TOO_NEW)
731 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
732 else if (nLoadWalletRet == DB_NEED_REWRITE)
734 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
735 printf("%s", strErrors.str().c_str());
736 return InitError(strErrors.str());
739 strErrors << _("Error loading wallet.dat") << "\n";
742 if (GetBoolArg("-upgradewallet", fFirstRun))
744 int nMaxVersion = GetArg("-upgradewallet", 0);
745 if (nMaxVersion == 0) // the -upgradewallet without argument case
747 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
748 nMaxVersion = CLIENT_VERSION;
749 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
752 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
753 if (nMaxVersion < pwalletMain->GetVersion())
754 strErrors << _("Cannot downgrade wallet") << "\n";
755 pwalletMain->SetMaxVersion(nMaxVersion);
760 // Create new keyUser and set as default key
761 RandAddSeedPerfmon();
763 CPubKey newDefaultKey;
764 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
765 strErrors << _("Cannot initialize keypool") << "\n";
766 pwalletMain->SetDefaultKey(newDefaultKey);
767 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
768 strErrors << _("Cannot write default address") << "\n";
771 printf("%s", strErrors.str().c_str());
772 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
774 RegisterWallet(pwalletMain);
776 CBlockIndex *pindexRescan = pindexBest;
777 if (GetBoolArg("-rescan"))
778 pindexRescan = pindexGenesisBlock;
781 CWalletDB walletdb("wallet.dat");
782 CBlockLocator locator;
783 if (walletdb.ReadBestBlock(locator))
784 pindexRescan = locator.GetBlockIndex();
786 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
788 uiInterface.InitMessage(_("Rescanning..."));
789 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
790 nStart = GetTimeMillis();
791 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
792 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
795 // ********************************************************* Step 9: import blocks
797 if (mapArgs.count("-loadblock"))
799 uiInterface.InitMessage(_("Importing blockchain data file."));
801 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
803 FILE *file = fopen(strFile.c_str(), "rb");
805 LoadExternalBlockFile(file);
809 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
810 if (filesystem::exists(pathBootstrap)) {
811 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
813 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
815 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
816 LoadExternalBlockFile(file);
817 RenameOver(pathBootstrap, pathBootstrapOld);
821 // ********************************************************* Step 10: load peers
823 uiInterface.InitMessage(_("Loading addresses..."));
824 printf("Loading addresses...\n");
825 nStart = GetTimeMillis();
829 if (!adb.Read(addrman))
830 printf("Invalid or missing peers.dat; recreating\n");
833 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
834 addrman.size(), GetTimeMillis() - nStart);
836 // ********************************************************* Step 11: start node
838 if (!CheckDiskSpace())
841 RandAddSeedPerfmon();
844 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
845 printf("nBestHeight = %d\n", nBestHeight);
846 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
847 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
848 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
850 if (!NewThread(StartNode, NULL))
851 InitError(_("Error: could not start node"));
854 NewThread(ThreadRPCServer, NULL);
856 // ********************************************************* Step 12: finished
858 uiInterface.InitMessage(_("Done loading"));
859 printf("Done loading\n");
861 if (!strErrors.str().empty())
862 return InitError(strErrors.str());
864 // Add wallet transactions that aren't already in a block to mapTransactions
865 pwalletMain->ReacceptWalletTransactions();
868 // Loop until process is exit()ed from shutdown() function,
869 // called from ThreadRPCServer thread when a "stop" command is received.