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 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
247 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
248 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
249 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
252 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
254 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
257 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
258 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
260 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
262 #if !defined(WIN32) && !defined(QT_GUI)
263 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
265 " -testnet " + _("Use the test network") + "\n" +
266 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
267 " -debugnet " + _("Output extra network debugging information") + "\n" +
268 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
269 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
270 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
272 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
274 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
275 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
276 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
277 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
278 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
279 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
280 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
281 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
282 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
283 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
284 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
285 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
286 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
288 "\n" + _("Block creation options:") + "\n" +
289 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
290 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
291 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
293 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
294 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
295 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
296 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
297 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
302 /** Initialize bitcoin.
303 * @pre Parameters should be parsed and config file should be read.
307 // ********************************************************* Step 1: setup
309 // Turn off Microsoft heap dump noise
310 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
311 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
314 // Disable confusing "helpful" text message on abort, Ctrl-C
315 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
318 // Enable Data Execution Prevention (DEP)
319 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
320 // A failure is non-critical and needs no further attention!
321 #ifndef PROCESS_DEP_ENABLE
322 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
323 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
324 #define PROCESS_DEP_ENABLE 0x00000001
326 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
327 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
328 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
333 // Clean shutdown on SIGTERM
335 sa.sa_handler = HandleSIGTERM;
336 sigemptyset(&sa.sa_mask);
338 sigaction(SIGTERM, &sa, NULL);
339 sigaction(SIGINT, &sa, NULL);
341 // Reopen debug.log on SIGHUP
342 struct sigaction sa_hup;
343 sa_hup.sa_handler = HandleSIGHUP;
344 sigemptyset(&sa_hup.sa_mask);
346 sigaction(SIGHUP, &sa_hup, NULL);
349 // ********************************************************* Step 2: parameter interactions
351 fTestNet = GetBoolArg("-testnet");
353 SoftSetBoolArg("-irc", true);
356 if (mapArgs.count("-bind")) {
357 // when specifying an explicit binding address, you want to listen on it
358 // even when -connect or -proxy is specified
359 SoftSetBoolArg("-listen", true);
362 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
363 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
364 SoftSetBoolArg("-dnsseed", false);
365 SoftSetBoolArg("-listen", false);
368 if (mapArgs.count("-proxy")) {
369 // to protect privacy, do not listen by default if a proxy server is specified
370 SoftSetBoolArg("-listen", false);
373 if (!GetBoolArg("-listen", true)) {
374 // do not map ports or try to retrieve public IP when not listening (pointless)
375 SoftSetBoolArg("-upnp", false);
376 SoftSetBoolArg("-discover", false);
379 if (mapArgs.count("-externalip")) {
380 // if an explicit public IP is specified, do not try to find others
381 SoftSetBoolArg("-discover", false);
384 if (GetBoolArg("-salvagewallet")) {
385 // Rewrite just private keys: rescan to find transactions
386 SoftSetBoolArg("-rescan", true);
389 // ********************************************************* Step 3: parameter-to-internal-flags
391 fDebug = GetBoolArg("-debug");
393 // -debug implies fDebug*
397 fDebugNet = GetBoolArg("-debugnet");
399 bitdb.SetDetach(GetBoolArg("-detachdb", false));
401 #if !defined(WIN32) && !defined(QT_GUI)
402 fDaemon = GetBoolArg("-daemon");
410 fServer = GetBoolArg("-server");
412 /* force fServer when running without GUI */
416 fPrintToConsole = GetBoolArg("-printtoconsole");
417 fPrintToDebugger = GetBoolArg("-printtodebugger");
418 fLogTimestamps = GetBoolArg("-logtimestamps");
420 if (mapArgs.count("-timeout"))
422 int nNewTimeout = GetArg("-timeout", 5000);
423 if (nNewTimeout > 0 && nNewTimeout < 600000)
424 nConnectTimeout = nNewTimeout;
427 // Continue to put "/P2SH/" in the coinbase to monitor
429 // This can be removed eventually...
430 const char* pszP2SH = "/P2SH/";
431 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
434 if (mapArgs.count("-paytxfee"))
436 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
437 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
438 if (nTransactionFee > 0.25 * COIN)
439 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
442 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
444 std::string strDataDir = GetDataDir().string();
446 // Make sure only a single Bitcoin process is using the data directory.
447 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
448 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
449 if (file) fclose(file);
450 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
451 if (!lock.try_lock())
452 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
454 #if !defined(WIN32) && !defined(QT_GUI)
461 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
466 CreatePidFile(GetPidFile(), pid);
470 pid_t sid = setsid();
472 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
476 if (GetBoolArg("-shrinkdebugfile", !fDebug))
478 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
479 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
480 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
482 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
483 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
484 printf("Used data directory %s\n", strDataDir.c_str());
485 std::ostringstream strErrors;
488 fprintf(stdout, "NovaCoin server starting\n");
492 // ********************************************************* Step 5: verify database integrity
494 uiInterface.InitMessage(_("Verifying database integrity..."));
496 if (!bitdb.Open(GetDataDir()))
498 string msg = strprintf(_("Error initializing database environment %s!"
499 " To recover, BACKUP THAT DIRECTORY, then remove"
500 " everything from it except for wallet.dat."), strDataDir.c_str());
501 return InitError(msg);
504 if (GetBoolArg("-salvagewallet"))
506 // Recover readable keypairs:
507 if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
511 if (filesystem::exists(GetDataDir() / "wallet.dat"))
513 CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
514 if (r == CDBEnv::RECOVER_OK)
516 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
517 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
518 " your balance or transactions are incorrect you should"
519 " restore from a backup."), strDataDir.c_str());
520 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
522 if (r == CDBEnv::RECOVER_FAIL)
523 return InitError(_("wallet.dat corrupt, salvage failed"));
526 // ********************************************************* Step 6: network initialization
528 int nSocksVersion = GetArg("-socks", 5);
530 if (nSocksVersion != 4 && nSocksVersion != 5)
531 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
533 if (mapArgs.count("-onlynet")) {
534 std::set<enum Network> nets;
535 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
536 enum Network net = ParseNetwork(snet);
537 if (net == NET_UNROUTABLE)
538 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
541 for (int n = 0; n < NET_MAX; n++) {
542 enum Network net = (enum Network)n;
543 if (!nets.count(net))
547 #if defined(USE_IPV6)
550 SetLimited(NET_IPV6);
556 if (mapArgs.count("-proxy")) {
557 addrProxy = CService(mapArgs["-proxy"], 9050);
558 if (!addrProxy.IsValid())
559 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
561 if (!IsLimited(NET_IPV4))
562 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
563 if (nSocksVersion > 4) {
565 if (!IsLimited(NET_IPV6))
566 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
568 SetNameProxy(addrProxy, nSocksVersion);
573 // -tor can override normal proxy, -notor disables tor entirely
574 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
576 if (!mapArgs.count("-tor"))
577 addrOnion = addrProxy;
579 addrOnion = CService(mapArgs["-tor"], 9050);
580 if (!addrOnion.IsValid())
581 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
582 SetProxy(NET_TOR, addrOnion, 5);
583 SetReachable(NET_TOR);
586 // see Step 2: parameter interactions for more information about these
587 fNoListen = !GetBoolArg("-listen", true);
588 fDiscover = GetBoolArg("-discover", true);
589 fNameLookup = GetBoolArg("-dns", true);
591 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
597 std::string strError;
598 if (mapArgs.count("-bind")) {
599 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
601 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
602 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
603 fBound |= Bind(addrBind);
606 struct in_addr inaddr_any;
607 inaddr_any.s_addr = INADDR_ANY;
609 if (!IsLimited(NET_IPV6))
610 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
612 if (!IsLimited(NET_IPV4))
613 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
616 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
619 if (mapArgs.count("-externalip"))
621 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
622 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
623 if (!addrLocal.IsValid())
624 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
625 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
629 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
631 int64 nReserveBalance = 0;
632 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
634 InitError(_("Invalid amount for -reservebalance=<amount>"));
639 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
641 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
642 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
645 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
648 // ********************************************************* Step 7: load blockchain
650 if (!bitdb.Open(GetDataDir()))
652 string msg = strprintf(_("Error initializing database environment %s!"
653 " To recover, BACKUP THAT DIRECTORY, then remove"
654 " everything from it except for wallet.dat."), strDataDir.c_str());
655 return InitError(msg);
658 if (GetBoolArg("-loadblockindextest"))
661 txdb.LoadBlockIndex();
666 uiInterface.InitMessage(_("Loading block index..."));
667 printf("Loading block index...\n");
668 nStart = GetTimeMillis();
669 if (!LoadBlockIndex())
670 return InitError(_("Error loading blkindex.dat"));
672 // as LoadBlockIndex can take several minutes, it's possible the user
673 // requested to kill bitcoin-qt during the last operation. If so, exit.
674 // As the program has not fully started yet, Shutdown() is possibly overkill.
675 if (fRequestShutdown)
677 printf("Shutdown requested. Exiting.\n");
680 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
682 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
688 if (mapArgs.count("-printblock"))
690 string strMatch = mapArgs["-printblock"];
692 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
694 uint256 hash = (*mi).first;
695 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
697 CBlockIndex* pindex = (*mi).second;
699 block.ReadFromDisk(pindex);
700 block.BuildMerkleTree();
707 printf("No blocks matching %s were found\n", strMatch.c_str());
711 // ********************************************************* Step 8: load wallet
713 uiInterface.InitMessage(_("Loading wallet..."));
714 printf("Loading wallet...\n");
715 nStart = GetTimeMillis();
716 bool fFirstRun = true;
717 pwalletMain = new CWallet("wallet.dat");
718 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
719 if (nLoadWalletRet != DB_LOAD_OK)
721 if (nLoadWalletRet == DB_CORRUPT)
722 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
723 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
725 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
726 " or address book entries might be missing or incorrect."));
727 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
729 else if (nLoadWalletRet == DB_TOO_NEW)
730 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
731 else if (nLoadWalletRet == DB_NEED_REWRITE)
733 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
734 printf("%s", strErrors.str().c_str());
735 return InitError(strErrors.str());
738 strErrors << _("Error loading wallet.dat") << "\n";
741 if (GetBoolArg("-upgradewallet", fFirstRun))
743 int nMaxVersion = GetArg("-upgradewallet", 0);
744 if (nMaxVersion == 0) // the -upgradewallet without argument case
746 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
747 nMaxVersion = CLIENT_VERSION;
748 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
751 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
752 if (nMaxVersion < pwalletMain->GetVersion())
753 strErrors << _("Cannot downgrade wallet") << "\n";
754 pwalletMain->SetMaxVersion(nMaxVersion);
759 // Create new keyUser and set as default key
760 RandAddSeedPerfmon();
762 CPubKey newDefaultKey;
763 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
764 strErrors << _("Cannot initialize keypool") << "\n";
765 pwalletMain->SetDefaultKey(newDefaultKey);
766 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
767 strErrors << _("Cannot write default address") << "\n";
770 printf("%s", strErrors.str().c_str());
771 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
773 RegisterWallet(pwalletMain);
775 CBlockIndex *pindexRescan = pindexBest;
776 if (GetBoolArg("-rescan"))
777 pindexRescan = pindexGenesisBlock;
780 CWalletDB walletdb("wallet.dat");
781 CBlockLocator locator;
782 if (walletdb.ReadBestBlock(locator))
783 pindexRescan = locator.GetBlockIndex();
785 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
787 uiInterface.InitMessage(_("Rescanning..."));
788 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
789 nStart = GetTimeMillis();
790 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
791 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
794 // ********************************************************* Step 9: import blocks
796 if (mapArgs.count("-loadblock"))
798 uiInterface.InitMessage(_("Importing blockchain data file."));
800 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
802 FILE *file = fopen(strFile.c_str(), "rb");
804 LoadExternalBlockFile(file);
808 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
809 if (filesystem::exists(pathBootstrap)) {
810 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
812 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
814 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
815 LoadExternalBlockFile(file);
816 RenameOver(pathBootstrap, pathBootstrapOld);
820 // ********************************************************* Step 10: load peers
822 uiInterface.InitMessage(_("Loading addresses..."));
823 printf("Loading addresses...\n");
824 nStart = GetTimeMillis();
828 if (!adb.Read(addrman))
829 printf("Invalid or missing peers.dat; recreating\n");
832 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
833 addrman.size(), GetTimeMillis() - nStart);
835 // ********************************************************* Step 11: start node
837 if (!CheckDiskSpace())
840 RandAddSeedPerfmon();
843 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
844 printf("nBestHeight = %d\n", nBestHeight);
845 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
846 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
847 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
849 if (!NewThread(StartNode, NULL))
850 InitError(_("Error: could not start node"));
853 NewThread(ThreadRPCServer, NULL);
855 // ********************************************************* Step 12: finished
857 uiInterface.InitMessage(_("Done loading"));
858 printf("Done loading\n");
860 if (!strErrors.str().empty())
861 return InitError(strErrors.str());
863 // Add wallet transactions that aren't already in a block to mapTransactions
864 pwalletMain->ReacceptWalletTransactions();
867 // Loop until process is exit()ed from shutdown() function,
868 // called from ThreadRPCServer thread when a "stop" command is received.