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;
32 //////////////////////////////////////////////////////////////////////////////
37 void ExitTimeout(void* parg)
48 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
49 uiInterface.QueueShutdown();
51 // Without UI, Shutdown() can simply be started in a new thread
52 NewThread(Shutdown, NULL);
56 void Shutdown(void* parg)
58 static CCriticalSection cs_Shutdown;
61 // Make this thread recognisable as the shutdown thread
62 RenameThread("bitcoin-shutoff");
64 bool fFirstThread = false;
66 TRY_LOCK(cs_Shutdown, lockShutdown);
69 fFirstThread = !fTaken;
77 nTransactionsUpdated++;
81 boost::filesystem::remove(GetPidFile());
82 UnregisterWallet(pwalletMain);
84 NewThread(ExitTimeout, NULL);
86 printf("NovaCoin exited\n\n");
89 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
102 void HandleSIGTERM(int)
104 fRequestShutdown = true;
107 void HandleSIGHUP(int)
109 fReopenDebugLog = true;
116 //////////////////////////////////////////////////////////////////////////////
121 bool AppInit(int argc, char* argv[])
129 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
130 ParseParameters(argc, argv);
131 if (!boost::filesystem::is_directory(GetDataDir(false)))
133 fprintf(stderr, "Error: Specified directory does not exist\n");
136 ReadConfigFile(mapArgs, mapMultiArgs);
138 if (mapArgs.count("-?") || mapArgs.count("--help"))
140 // First part of help message is specific to bitcoind / RPC client
141 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
143 " novacoind [options] " + "\n" +
144 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
145 " novacoind [options] help " + _("List commands") + "\n" +
146 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
148 strUsage += "\n" + HelpMessage();
150 fprintf(stdout, "%s", strUsage.c_str());
155 for (int i = 1; i < argc; i++)
156 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
161 int ret = CommandLineRPC(argc, argv);
167 catch (std::exception& e) {
168 PrintException(&e, "AppInit()");
170 PrintException(NULL, "AppInit()");
177 extern void noui_connect();
178 int main(int argc, char* argv[])
182 // Connect bitcoind signal handlers
185 fRet = AppInit(argc, argv);
194 bool static InitError(const std::string &str)
196 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
200 bool static InitWarning(const std::string &str)
202 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
207 bool static Bind(const CService &addr, bool fError = true) {
210 std::string strError;
211 if (!BindListenPort(addr, strError)) {
213 return InitError(strError);
219 // Core-specific options shared between UI and daemon
220 std::string HelpMessage()
222 string strUsage = _("Options:") + "\n" +
223 " -? " + _("This help message") + "\n" +
224 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
225 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
226 " -datadir=<dir> " + _("Specify data directory") + "\n" +
227 " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
228 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
229 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
230 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
231 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
232 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
233 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
234 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
235 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
236 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
237 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
238 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
239 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
240 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
241 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
242 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
243 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
244 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
245 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
246 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
247 " -nosynccheckpoints " + _("Disable sync checkpoints (default: 0)") + "\n" +
248 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
249 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
250 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
251 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
254 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
256 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
259 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
260 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
262 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
264 #if !defined(WIN32) && !defined(QT_GUI)
265 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
267 " -testnet " + _("Use the test network") + "\n" +
268 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
269 " -debugnet " + _("Output extra network debugging information") + "\n" +
270 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
271 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
272 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
274 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
276 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
277 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
278 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
279 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
280 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
281 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
282 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\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 nNodeLifespan = GetArg("-addrlifespan", 7);
356 fTestNet = GetBoolArg("-testnet");
358 SoftSetBoolArg("-irc", true);
361 if (mapArgs.count("-bind")) {
362 // when specifying an explicit binding address, you want to listen on it
363 // even when -connect or -proxy is specified
364 SoftSetBoolArg("-listen", true);
367 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
368 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
369 SoftSetBoolArg("-dnsseed", false);
370 SoftSetBoolArg("-listen", false);
373 if (mapArgs.count("-proxy")) {
374 // to protect privacy, do not listen by default if a proxy server is specified
375 SoftSetBoolArg("-listen", false);
378 if (!GetBoolArg("-listen", true)) {
379 // do not map ports or try to retrieve public IP when not listening (pointless)
380 SoftSetBoolArg("-upnp", false);
381 SoftSetBoolArg("-discover", false);
384 if (mapArgs.count("-externalip")) {
385 // if an explicit public IP is specified, do not try to find others
386 SoftSetBoolArg("-discover", false);
389 if (GetBoolArg("-salvagewallet")) {
390 // Rewrite just private keys: rescan to find transactions
391 SoftSetBoolArg("-rescan", true);
394 // ********************************************************* Step 3: parameter-to-internal-flags
396 fDebug = GetBoolArg("-debug");
398 // -debug implies fDebug*
402 fDebugNet = GetBoolArg("-debugnet");
404 bitdb.SetDetach(GetBoolArg("-detachdb", false));
406 #if !defined(WIN32) && !defined(QT_GUI)
407 fDaemon = GetBoolArg("-daemon");
415 fServer = GetBoolArg("-server");
417 /* force fServer when running without GUI */
421 fPrintToConsole = GetBoolArg("-printtoconsole");
422 fPrintToDebugger = GetBoolArg("-printtodebugger");
423 fLogTimestamps = GetBoolArg("-logtimestamps");
425 if (mapArgs.count("-timeout"))
427 int nNewTimeout = GetArg("-timeout", 5000);
428 if (nNewTimeout > 0 && nNewTimeout < 600000)
429 nConnectTimeout = nNewTimeout;
432 // Continue to put "/P2SH/" in the coinbase to monitor
434 // This can be removed eventually...
435 const char* pszP2SH = "/P2SH/";
436 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
439 if (mapArgs.count("-paytxfee"))
441 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
442 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
443 if (nTransactionFee > 0.25 * COIN)
444 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
447 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
449 std::string strDataDir = GetDataDir().string();
450 std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
452 // strWalletFileName must be a plain filename without a directory
453 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
454 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
456 // Make sure only a single Bitcoin process is using the data directory.
457 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
458 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
459 if (file) fclose(file);
460 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
461 if (!lock.try_lock())
462 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
464 #if !defined(WIN32) && !defined(QT_GUI)
471 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
476 CreatePidFile(GetPidFile(), pid);
480 pid_t sid = setsid();
482 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
486 if (GetBoolArg("-shrinkdebugfile", !fDebug))
488 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
489 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
490 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
492 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
493 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
494 printf("Used data directory %s\n", strDataDir.c_str());
495 std::ostringstream strErrors;
498 fprintf(stdout, "NovaCoin server starting\n");
502 // ********************************************************* Step 5: verify database integrity
504 uiInterface.InitMessage(_("Verifying database integrity..."));
506 if (!bitdb.Open(GetDataDir()))
508 string msg = strprintf(_("Error initializing database environment %s!"
509 " To recover, BACKUP THAT DIRECTORY, then remove"
510 " everything from it except for wallet.dat."), strDataDir.c_str());
511 return InitError(msg);
514 if (GetBoolArg("-salvagewallet"))
516 // Recover readable keypairs:
517 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
521 if (filesystem::exists(GetDataDir() / strWalletFileName))
523 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
524 if (r == CDBEnv::RECOVER_OK)
526 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
527 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
528 " your balance or transactions are incorrect you should"
529 " restore from a backup."), strDataDir.c_str());
530 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
532 if (r == CDBEnv::RECOVER_FAIL)
533 return InitError(_("wallet.dat corrupt, salvage failed"));
536 // ********************************************************* Step 6: network initialization
538 int nSocksVersion = GetArg("-socks", 5);
540 if (nSocksVersion != 4 && nSocksVersion != 5)
541 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
543 if (mapArgs.count("-onlynet")) {
544 std::set<enum Network> nets;
545 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
546 enum Network net = ParseNetwork(snet);
547 if (net == NET_UNROUTABLE)
548 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
551 for (int n = 0; n < NET_MAX; n++) {
552 enum Network net = (enum Network)n;
553 if (!nets.count(net))
557 #if defined(USE_IPV6)
560 SetLimited(NET_IPV6);
566 if (mapArgs.count("-proxy")) {
567 addrProxy = CService(mapArgs["-proxy"], 9050);
568 if (!addrProxy.IsValid())
569 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
571 if (!IsLimited(NET_IPV4))
572 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
573 if (nSocksVersion > 4) {
575 if (!IsLimited(NET_IPV6))
576 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
578 SetNameProxy(addrProxy, nSocksVersion);
583 // -tor can override normal proxy, -notor disables tor entirely
584 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
586 if (!mapArgs.count("-tor"))
587 addrOnion = addrProxy;
589 addrOnion = CService(mapArgs["-tor"], 9050);
590 if (!addrOnion.IsValid())
591 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
592 SetProxy(NET_TOR, addrOnion, 5);
593 SetReachable(NET_TOR);
596 // see Step 2: parameter interactions for more information about these
597 fNoListen = !GetBoolArg("-listen", true);
598 fDiscover = GetBoolArg("-discover", true);
599 fNameLookup = GetBoolArg("-dns", true);
601 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
607 std::string strError;
608 if (mapArgs.count("-bind")) {
609 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
611 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
612 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
613 fBound |= Bind(addrBind);
616 struct in_addr inaddr_any;
617 inaddr_any.s_addr = INADDR_ANY;
619 if (!IsLimited(NET_IPV6))
620 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
622 if (!IsLimited(NET_IPV4))
623 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
626 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
629 if (mapArgs.count("-externalip"))
631 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
632 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
633 if (!addrLocal.IsValid())
634 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
635 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
639 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
641 int64 nReserveBalance = 0;
642 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
644 InitError(_("Invalid amount for -reservebalance=<amount>"));
649 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
651 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
652 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
655 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
658 // ********************************************************* Step 7: load blockchain
660 if (!bitdb.Open(GetDataDir()))
662 string msg = strprintf(_("Error initializing database environment %s!"
663 " To recover, BACKUP THAT DIRECTORY, then remove"
664 " everything from it except for wallet.dat."), strDataDir.c_str());
665 return InitError(msg);
668 if (GetBoolArg("-loadblockindextest"))
671 txdb.LoadBlockIndex();
676 uiInterface.InitMessage(_("Loading block index..."));
677 printf("Loading block index...\n");
678 nStart = GetTimeMillis();
679 if (!LoadBlockIndex())
680 return InitError(_("Error loading blkindex.dat"));
682 // as LoadBlockIndex can take several minutes, it's possible the user
683 // requested to kill bitcoin-qt during the last operation. If so, exit.
684 // As the program has not fully started yet, Shutdown() is possibly overkill.
685 if (fRequestShutdown)
687 printf("Shutdown requested. Exiting.\n");
690 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
692 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
698 if (mapArgs.count("-printblock"))
700 string strMatch = mapArgs["-printblock"];
702 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
704 uint256 hash = (*mi).first;
705 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
707 CBlockIndex* pindex = (*mi).second;
709 block.ReadFromDisk(pindex);
710 block.BuildMerkleTree();
717 printf("No blocks matching %s were found\n", strMatch.c_str());
721 // ********************************************************* Step 8: load wallet
723 uiInterface.InitMessage(_("Loading wallet..."));
724 printf("Loading wallet...\n");
725 nStart = GetTimeMillis();
726 bool fFirstRun = true;
727 pwalletMain = new CWallet(strWalletFileName);
728 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
729 if (nLoadWalletRet != DB_LOAD_OK)
731 if (nLoadWalletRet == DB_CORRUPT)
732 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
733 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
735 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
736 " or address book entries might be missing or incorrect."));
737 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
739 else if (nLoadWalletRet == DB_TOO_NEW)
740 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
741 else if (nLoadWalletRet == DB_NEED_REWRITE)
743 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
744 printf("%s", strErrors.str().c_str());
745 return InitError(strErrors.str());
748 strErrors << _("Error loading wallet.dat") << "\n";
751 if (GetBoolArg("-upgradewallet", fFirstRun))
753 int nMaxVersion = GetArg("-upgradewallet", 0);
754 if (nMaxVersion == 0) // the -upgradewallet without argument case
756 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
757 nMaxVersion = CLIENT_VERSION;
758 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
761 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
762 if (nMaxVersion < pwalletMain->GetVersion())
763 strErrors << _("Cannot downgrade wallet") << "\n";
764 pwalletMain->SetMaxVersion(nMaxVersion);
769 // Create new keyUser and set as default key
770 RandAddSeedPerfmon();
772 CPubKey newDefaultKey;
773 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
774 strErrors << _("Cannot initialize keypool") << "\n";
775 pwalletMain->SetDefaultKey(newDefaultKey);
776 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
777 strErrors << _("Cannot write default address") << "\n";
780 printf("%s", strErrors.str().c_str());
781 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
783 RegisterWallet(pwalletMain);
785 CBlockIndex *pindexRescan = pindexBest;
786 if (GetBoolArg("-rescan"))
787 pindexRescan = pindexGenesisBlock;
790 CWalletDB walletdb(strWalletFileName);
791 CBlockLocator locator;
792 if (walletdb.ReadBestBlock(locator))
793 pindexRescan = locator.GetBlockIndex();
795 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
797 uiInterface.InitMessage(_("Rescanning..."));
798 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
799 nStart = GetTimeMillis();
800 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
801 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
804 // ********************************************************* Step 9: import blocks
806 if (mapArgs.count("-loadblock"))
808 uiInterface.InitMessage(_("Importing blockchain data file."));
810 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
812 FILE *file = fopen(strFile.c_str(), "rb");
814 LoadExternalBlockFile(file);
818 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
819 if (filesystem::exists(pathBootstrap)) {
820 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
822 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
824 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
825 LoadExternalBlockFile(file);
826 RenameOver(pathBootstrap, pathBootstrapOld);
830 // ********************************************************* Step 10: load peers
832 uiInterface.InitMessage(_("Loading addresses..."));
833 printf("Loading addresses...\n");
834 nStart = GetTimeMillis();
838 if (!adb.Read(addrman))
839 printf("Invalid or missing peers.dat; recreating\n");
842 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
843 addrman.size(), GetTimeMillis() - nStart);
845 // ********************************************************* Step 11: start node
847 if (!CheckDiskSpace())
850 RandAddSeedPerfmon();
853 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
854 printf("nBestHeight = %d\n", nBestHeight);
855 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
856 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
857 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
859 if (!NewThread(StartNode, NULL))
860 InitError(_("Error: could not start node"));
863 NewThread(ThreadRPCServer, NULL);
865 // ********************************************************* Step 12: finished
867 uiInterface.InitMessage(_("Done loading"));
868 printf("Done loading\n");
870 if (!strErrors.str().empty())
871 return InitError(strErrors.str());
873 // Add wallet transactions that aren't already in a block to mapTransactions
874 pwalletMain->ReacceptWalletTransactions();
877 // Loop until process is exit()ed from shutdown() function,
878 // called from ThreadRPCServer thread when a "stop" command is received.