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;
30 unsigned int nNodeLifespan;
31 unsigned int nDerivationMethodIndex;
33 //////////////////////////////////////////////////////////////////////////////
38 void ExitTimeout(void* parg)
49 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
50 uiInterface.QueueShutdown();
52 // Without UI, Shutdown() can simply be started in a new thread
53 NewThread(Shutdown, NULL);
57 void Shutdown(void* parg)
59 static CCriticalSection cs_Shutdown;
62 // Make this thread recognisable as the shutdown thread
63 RenameThread("bitcoin-shutoff");
65 bool fFirstThread = false;
67 TRY_LOCK(cs_Shutdown, lockShutdown);
70 fFirstThread = !fTaken;
78 nTransactionsUpdated++;
82 boost::filesystem::remove(GetPidFile());
83 UnregisterWallet(pwalletMain);
85 NewThread(ExitTimeout, NULL);
87 printf("NovaCoin exited\n\n");
90 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
103 void HandleSIGTERM(int)
105 fRequestShutdown = true;
108 void HandleSIGHUP(int)
110 fReopenDebugLog = true;
117 //////////////////////////////////////////////////////////////////////////////
122 bool AppInit(int argc, char* argv[])
130 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
131 ParseParameters(argc, argv);
132 if (!boost::filesystem::is_directory(GetDataDir(false)))
134 fprintf(stderr, "Error: Specified directory does not exist\n");
137 ReadConfigFile(mapArgs, mapMultiArgs);
139 if (mapArgs.count("-?") || mapArgs.count("--help"))
141 // First part of help message is specific to bitcoind / RPC client
142 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
144 " novacoind [options] " + "\n" +
145 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
146 " novacoind [options] help " + _("List commands") + "\n" +
147 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
149 strUsage += "\n" + HelpMessage();
151 fprintf(stdout, "%s", strUsage.c_str());
156 for (int i = 1; i < argc; i++)
157 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
162 int ret = CommandLineRPC(argc, argv);
168 catch (std::exception& e) {
169 PrintException(&e, "AppInit()");
171 PrintException(NULL, "AppInit()");
178 extern void noui_connect();
179 int main(int argc, char* argv[])
183 // Connect bitcoind signal handlers
186 fRet = AppInit(argc, argv);
195 bool static InitError(const std::string &str)
197 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
201 bool static InitWarning(const std::string &str)
203 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
208 bool static Bind(const CService &addr, bool fError = true) {
211 std::string strError;
212 if (!BindListenPort(addr, strError)) {
214 return InitError(strError);
220 // Core-specific options shared between UI and daemon
221 std::string HelpMessage()
223 string strUsage = _("Options:") + "\n" +
224 " -? " + _("This help message") + "\n" +
225 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
226 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\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: 1)") + "\n" +
248 " -nosynccheckpoints " + _("Disable sync checkpoints (default: 0)") + "\n" +
249 " -stakepooledkeys " + _("Use pooled pubkeys for the last coinstake output (default: 0)") + "\n" +
250 " -derivationmethod " + _("Which key derivation method to use by default (default: sha512)") + "\n" +
251 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
252 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
253 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
254 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
257 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
259 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
262 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
263 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
265 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
267 #if !defined(WIN32) && !defined(QT_GUI)
268 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
270 " -testnet " + _("Use the test network") + "\n" +
271 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
272 " -debugnet " + _("Output extra network debugging information") + "\n" +
273 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
274 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
275 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
277 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
279 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
280 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
281 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
282 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
283 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
284 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
285 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
286 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
287 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
288 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
289 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
290 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
291 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
292 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
294 "\n" + _("Block creation options:") + "\n" +
295 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
296 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
297 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
299 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
300 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
301 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
302 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
303 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
308 /** Initialize bitcoin.
309 * @pre Parameters should be parsed and config file should be read.
313 // ********************************************************* Step 1: setup
315 // Turn off Microsoft heap dump noise
316 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
317 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
320 // Disable confusing "helpful" text message on abort, Ctrl-C
321 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
324 // Enable Data Execution Prevention (DEP)
325 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
326 // A failure is non-critical and needs no further attention!
327 #ifndef PROCESS_DEP_ENABLE
328 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
329 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
330 #define PROCESS_DEP_ENABLE 0x00000001
332 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
333 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
334 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
339 // Clean shutdown on SIGTERM
341 sa.sa_handler = HandleSIGTERM;
342 sigemptyset(&sa.sa_mask);
344 sigaction(SIGTERM, &sa, NULL);
345 sigaction(SIGINT, &sa, NULL);
347 // Reopen debug.log on SIGHUP
348 struct sigaction sa_hup;
349 sa_hup.sa_handler = HandleSIGHUP;
350 sigemptyset(&sa_hup.sa_mask);
352 sigaction(SIGHUP, &sa_hup, NULL);
355 // ********************************************************* Step 2: parameter interactions
357 nNodeLifespan = GetArg("-addrlifespan", 7);
358 fStakeUsePooledKeys = GetBoolArg("-stakepooledkeys", false);
360 if(GetArg("-derivationmethod", "sha512") == "scrypt+sha512")
361 nDerivationMethodIndex = 1;
363 fTestNet = GetBoolArg("-testnet");
365 SoftSetBoolArg("-irc", true);
368 if (mapArgs.count("-bind")) {
369 // when specifying an explicit binding address, you want to listen on it
370 // even when -connect or -proxy is specified
371 SoftSetBoolArg("-listen", true);
374 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
375 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
376 SoftSetBoolArg("-dnsseed", false);
377 SoftSetBoolArg("-listen", false);
380 if (mapArgs.count("-proxy")) {
381 // to protect privacy, do not listen by default if a proxy server is specified
382 SoftSetBoolArg("-listen", false);
385 if (!GetBoolArg("-listen", true)) {
386 // do not map ports or try to retrieve public IP when not listening (pointless)
387 SoftSetBoolArg("-upnp", false);
388 SoftSetBoolArg("-discover", false);
391 if (mapArgs.count("-externalip")) {
392 // if an explicit public IP is specified, do not try to find others
393 SoftSetBoolArg("-discover", false);
396 if (GetBoolArg("-salvagewallet")) {
397 // Rewrite just private keys: rescan to find transactions
398 SoftSetBoolArg("-rescan", true);
401 // ********************************************************* Step 3: parameter-to-internal-flags
403 fDebug = GetBoolArg("-debug");
405 // -debug implies fDebug*
409 fDebugNet = GetBoolArg("-debugnet");
411 bitdb.SetDetach(GetBoolArg("-detachdb", false));
413 #if !defined(WIN32) && !defined(QT_GUI)
414 fDaemon = GetBoolArg("-daemon");
422 fServer = GetBoolArg("-server");
424 /* force fServer when running without GUI */
428 fPrintToConsole = GetBoolArg("-printtoconsole");
429 fPrintToDebugger = GetBoolArg("-printtodebugger");
430 fLogTimestamps = GetBoolArg("-logtimestamps");
432 if (mapArgs.count("-timeout"))
434 int nNewTimeout = GetArg("-timeout", 5000);
435 if (nNewTimeout > 0 && nNewTimeout < 600000)
436 nConnectTimeout = nNewTimeout;
439 // Continue to put "/P2SH/" in the coinbase to monitor
441 // This can be removed eventually...
442 const char* pszP2SH = "/P2SH/";
443 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
446 if (mapArgs.count("-paytxfee"))
448 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
449 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
450 if (nTransactionFee > 0.25 * COIN)
451 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
454 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
456 std::string strDataDir = GetDataDir().string();
457 std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
459 // strWalletFileName must be a plain filename without a directory
460 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
461 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
463 // Make sure only a single Bitcoin process is using the data directory.
464 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
465 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
466 if (file) fclose(file);
467 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
468 if (!lock.try_lock())
469 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
471 #if !defined(WIN32) && !defined(QT_GUI)
478 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
483 CreatePidFile(GetPidFile(), pid);
487 pid_t sid = setsid();
489 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
493 if (GetBoolArg("-shrinkdebugfile", !fDebug))
495 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
496 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
497 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
499 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
500 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
501 printf("Used data directory %s\n", strDataDir.c_str());
502 std::ostringstream strErrors;
505 fprintf(stdout, "NovaCoin server starting\n");
509 // ********************************************************* Step 5: verify database integrity
511 uiInterface.InitMessage(_("Verifying database integrity..."));
513 if (!bitdb.Open(GetDataDir()))
515 string msg = strprintf(_("Error initializing database environment %s!"
516 " To recover, BACKUP THAT DIRECTORY, then remove"
517 " everything from it except for wallet.dat."), strDataDir.c_str());
518 return InitError(msg);
521 if (GetBoolArg("-salvagewallet"))
523 // Recover readable keypairs:
524 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
528 if (filesystem::exists(GetDataDir() / strWalletFileName))
530 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
531 if (r == CDBEnv::RECOVER_OK)
533 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
534 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
535 " your balance or transactions are incorrect you should"
536 " restore from a backup."), strDataDir.c_str());
537 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
539 if (r == CDBEnv::RECOVER_FAIL)
540 return InitError(_("wallet.dat corrupt, salvage failed"));
543 // ********************************************************* Step 6: network initialization
545 int nSocksVersion = GetArg("-socks", 5);
547 if (nSocksVersion != 4 && nSocksVersion != 5)
548 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
550 if (mapArgs.count("-onlynet")) {
551 std::set<enum Network> nets;
552 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
553 enum Network net = ParseNetwork(snet);
554 if (net == NET_UNROUTABLE)
555 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
558 for (int n = 0; n < NET_MAX; n++) {
559 enum Network net = (enum Network)n;
560 if (!nets.count(net))
564 #if defined(USE_IPV6)
567 SetLimited(NET_IPV6);
573 if (mapArgs.count("-proxy")) {
574 addrProxy = CService(mapArgs["-proxy"], 9050);
575 if (!addrProxy.IsValid())
576 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
578 if (!IsLimited(NET_IPV4))
579 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
580 if (nSocksVersion > 4) {
582 if (!IsLimited(NET_IPV6))
583 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
585 SetNameProxy(addrProxy, nSocksVersion);
590 // -tor can override normal proxy, -notor disables tor entirely
591 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
593 if (!mapArgs.count("-tor"))
594 addrOnion = addrProxy;
596 addrOnion = CService(mapArgs["-tor"], 9050);
597 if (!addrOnion.IsValid())
598 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
599 SetProxy(NET_TOR, addrOnion, 5);
600 SetReachable(NET_TOR);
603 // see Step 2: parameter interactions for more information about these
604 fNoListen = !GetBoolArg("-listen", true);
605 fDiscover = GetBoolArg("-discover", true);
606 fNameLookup = GetBoolArg("-dns", true);
608 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
614 std::string strError;
615 if (mapArgs.count("-bind")) {
616 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
618 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
619 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
620 fBound |= Bind(addrBind);
623 struct in_addr inaddr_any;
624 inaddr_any.s_addr = INADDR_ANY;
626 if (!IsLimited(NET_IPV6))
627 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
629 if (!IsLimited(NET_IPV4))
630 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
633 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
636 if (mapArgs.count("-externalip"))
638 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
639 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
640 if (!addrLocal.IsValid())
641 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
642 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
646 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
648 int64 nReserveBalance = 0;
649 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
651 InitError(_("Invalid amount for -reservebalance=<amount>"));
656 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
658 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
659 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
662 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
665 // ********************************************************* Step 7: load blockchain
667 if (!bitdb.Open(GetDataDir()))
669 string msg = strprintf(_("Error initializing database environment %s!"
670 " To recover, BACKUP THAT DIRECTORY, then remove"
671 " everything from it except for wallet.dat."), strDataDir.c_str());
672 return InitError(msg);
675 if (GetBoolArg("-loadblockindextest"))
678 txdb.LoadBlockIndex();
683 uiInterface.InitMessage(_("Loading block index..."));
684 printf("Loading block index...\n");
685 nStart = GetTimeMillis();
686 if (!LoadBlockIndex())
687 return InitError(_("Error loading blkindex.dat"));
689 // as LoadBlockIndex can take several minutes, it's possible the user
690 // requested to kill bitcoin-qt during the last operation. If so, exit.
691 // As the program has not fully started yet, Shutdown() is possibly overkill.
692 if (fRequestShutdown)
694 printf("Shutdown requested. Exiting.\n");
697 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
699 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
705 if (mapArgs.count("-printblock"))
707 string strMatch = mapArgs["-printblock"];
709 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
711 uint256 hash = (*mi).first;
712 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
714 CBlockIndex* pindex = (*mi).second;
716 block.ReadFromDisk(pindex);
717 block.BuildMerkleTree();
724 printf("No blocks matching %s were found\n", strMatch.c_str());
728 // ********************************************************* Step 8: load wallet
730 uiInterface.InitMessage(_("Loading wallet..."));
731 printf("Loading wallet...\n");
732 nStart = GetTimeMillis();
733 bool fFirstRun = true;
734 pwalletMain = new CWallet(strWalletFileName);
735 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
736 if (nLoadWalletRet != DB_LOAD_OK)
738 if (nLoadWalletRet == DB_CORRUPT)
739 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
740 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
742 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
743 " or address book entries might be missing or incorrect."));
744 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
746 else if (nLoadWalletRet == DB_TOO_NEW)
747 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
748 else if (nLoadWalletRet == DB_NEED_REWRITE)
750 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
751 printf("%s", strErrors.str().c_str());
752 return InitError(strErrors.str());
755 strErrors << _("Error loading wallet.dat") << "\n";
758 if (GetBoolArg("-upgradewallet", fFirstRun))
760 int nMaxVersion = GetArg("-upgradewallet", 0);
761 if (nMaxVersion == 0) // the -upgradewallet without argument case
763 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
764 nMaxVersion = CLIENT_VERSION;
765 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
768 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
769 if (nMaxVersion < pwalletMain->GetVersion())
770 strErrors << _("Cannot downgrade wallet") << "\n";
771 pwalletMain->SetMaxVersion(nMaxVersion);
776 // Create new keyUser and set as default key
777 RandAddSeedPerfmon();
779 CPubKey newDefaultKey;
780 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
781 strErrors << _("Cannot initialize keypool") << "\n";
782 pwalletMain->SetDefaultKey(newDefaultKey);
783 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
784 strErrors << _("Cannot write default address") << "\n";
787 printf("%s", strErrors.str().c_str());
788 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
790 RegisterWallet(pwalletMain);
792 CBlockIndex *pindexRescan = pindexBest;
793 if (GetBoolArg("-rescan"))
794 pindexRescan = pindexGenesisBlock;
797 CWalletDB walletdb(strWalletFileName);
798 CBlockLocator locator;
799 if (walletdb.ReadBestBlock(locator))
800 pindexRescan = locator.GetBlockIndex();
802 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
804 uiInterface.InitMessage(_("Rescanning..."));
805 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
806 nStart = GetTimeMillis();
807 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
808 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
811 // ********************************************************* Step 9: import blocks
813 if (mapArgs.count("-loadblock"))
815 uiInterface.InitMessage(_("Importing blockchain data file."));
817 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
819 FILE *file = fopen(strFile.c_str(), "rb");
821 LoadExternalBlockFile(file);
825 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
826 if (filesystem::exists(pathBootstrap)) {
827 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
829 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
831 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
832 LoadExternalBlockFile(file);
833 RenameOver(pathBootstrap, pathBootstrapOld);
837 // ********************************************************* Step 10: load peers
839 uiInterface.InitMessage(_("Loading addresses..."));
840 printf("Loading addresses...\n");
841 nStart = GetTimeMillis();
845 if (!adb.Read(addrman))
846 printf("Invalid or missing peers.dat; recreating\n");
849 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
850 addrman.size(), GetTimeMillis() - nStart);
852 // ********************************************************* Step 11: start node
854 if (!CheckDiskSpace())
857 RandAddSeedPerfmon();
860 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
861 printf("nBestHeight = %d\n", nBestHeight);
862 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
863 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
864 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
866 if (!NewThread(StartNode, NULL))
867 InitError(_("Error: could not start node"));
870 NewThread(ThreadRPCServer, NULL);
872 // ********************************************************* Step 12: finished
874 uiInterface.InitMessage(_("Done loading"));
875 printf("Done loading\n");
877 if (!strErrors.str().empty())
878 return InitError(strErrors.str());
880 // Add wallet transactions that aren't already in a block to mapTransactions
881 pwalletMain->ReacceptWalletTransactions();
884 // Loop until process is exit()ed from shutdown() function,
885 // called from ThreadRPCServer thread when a "stop" command is received.