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 "zerocoin/ZeroTest.h"
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/filesystem/convenience.hpp>
17 #include <boost/interprocess/sync/file_lock.hpp>
18 #include <boost/algorithm/string/predicate.hpp>
19 #include <openssl/crypto.h>
27 using namespace boost;
30 CClientUIInterface uiInterface;
31 std::string strWalletFileName;
32 unsigned int nNodeLifespan;
33 unsigned int nDerivationMethodIndex;
34 unsigned int nMinerSleep;
36 bool fUseFastStakeMiner;
37 enum Checkpoints::CPMode CheckpointsMode;
39 //////////////////////////////////////////////////////////////////////////////
44 void ExitTimeout(void* parg)
55 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
56 uiInterface.QueueShutdown();
58 // Without UI, Shutdown() can simply be started in a new thread
59 NewThread(Shutdown, NULL);
63 void Shutdown(void* parg)
65 static CCriticalSection cs_Shutdown;
68 // Make this thread recognisable as the shutdown thread
69 RenameThread("bitcoin-shutoff");
71 bool fFirstThread = false;
73 TRY_LOCK(cs_Shutdown, lockShutdown);
76 fFirstThread = !fTaken;
84 nTransactionsUpdated++;
89 boost::filesystem::remove(GetPidFile());
90 UnregisterWallet(pwalletMain);
92 NewThread(ExitTimeout, NULL);
94 printf("NovaCoin exited\n\n");
97 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
110 void HandleSIGTERM(int)
112 fRequestShutdown = true;
115 void HandleSIGHUP(int)
117 fReopenDebugLog = true;
124 //////////////////////////////////////////////////////////////////////////////
129 bool AppInit(int argc, char* argv[])
137 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
138 ParseParameters(argc, argv);
139 if (!boost::filesystem::is_directory(GetDataDir(false)))
141 fprintf(stderr, "Error: Specified directory does not exist\n");
144 ReadConfigFile(mapArgs, mapMultiArgs);
146 if (mapArgs.count("-?") || mapArgs.count("--help"))
148 // First part of help message is specific to bitcoind / RPC client
149 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
151 " novacoind [options] " + "\n" +
152 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
153 " novacoind [options] help " + _("List commands") + "\n" +
154 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
156 strUsage += "\n" + HelpMessage();
158 fprintf(stdout, "%s", strUsage.c_str());
163 for (int i = 1; i < argc; i++)
164 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
169 int ret = CommandLineRPC(argc, argv);
175 catch (std::exception& e) {
176 PrintException(&e, "AppInit()");
178 PrintException(NULL, "AppInit()");
185 extern void noui_connect();
186 int main(int argc, char* argv[])
190 // Connect bitcoind signal handlers
193 fRet = AppInit(argc, argv);
202 bool static InitError(const std::string &str)
204 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
208 bool static InitWarning(const std::string &str)
210 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
215 bool static Bind(const CService &addr, bool fError = true) {
218 std::string strError;
219 if (!BindListenPort(addr, strError)) {
221 return InitError(strError);
227 // Core-specific options shared between UI and daemon
228 std::string HelpMessage()
230 string strUsage = _("Options:") + "\n" +
231 " -? " + _("This help message") + "\n" +
232 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
233 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
234 " -datadir=<dir> " + _("Specify data directory") + "\n" +
235 " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
236 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
237 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
238 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
239 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
240 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
241 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
242 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
243 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
244 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
245 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
246 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
247 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
248 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
249 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
250 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
251 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
252 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
253 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
254 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
255 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
256 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
257 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
258 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
259 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
262 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
264 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
267 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
268 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
269 " -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
271 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
273 #if !defined(WIN32) && !defined(QT_GUI)
274 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
276 " -testnet " + _("Use the test network") + "\n" +
277 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
278 " -debugnet " + _("Output extra network debugging information") + "\n" +
279 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
280 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
281 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
283 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
285 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
286 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
287 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
288 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
289 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
290 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
291 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
292 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
293 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
294 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
295 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
296 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
297 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
298 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
300 "\n" + _("Block creation options:") + "\n" +
301 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
302 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
303 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
305 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
306 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
307 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
308 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
309 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
314 /** Initialize bitcoin.
315 * @pre Parameters should be parsed and config file should be read.
319 // ********************************************************* Step 1: setup
321 // Turn off Microsoft heap dump noise
322 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
323 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
326 // Disable confusing "helpful" text message on abort, Ctrl-C
327 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
330 // Enable Data Execution Prevention (DEP)
331 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
332 // A failure is non-critical and needs no further attention!
333 #ifndef PROCESS_DEP_ENABLE
334 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
335 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
336 #define PROCESS_DEP_ENABLE 0x00000001
338 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
339 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
340 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
345 // Clean shutdown on SIGTERM
347 sa.sa_handler = HandleSIGTERM;
348 sigemptyset(&sa.sa_mask);
350 sigaction(SIGTERM, &sa, NULL);
351 sigaction(SIGINT, &sa, NULL);
353 // Reopen debug.log on SIGHUP
354 struct sigaction sa_hup;
355 sa_hup.sa_handler = HandleSIGHUP;
356 sigemptyset(&sa_hup.sa_mask);
358 sigaction(SIGHUP, &sa_hup, NULL);
361 // ********************************************************* Step 2: parameter interactions
363 nNodeLifespan = GetArg("-addrlifespan", 7);
364 fUseFastIndex = GetBoolArg("-fastindex", true);
365 nMinerSleep = GetArg("-minersleep", 500);
367 CheckpointsMode = Checkpoints::STRICT;
368 std::string strCpMode = GetArg("-cppolicy", "strict");
370 if(strCpMode == "strict")
371 CheckpointsMode = Checkpoints::STRICT;
373 if(strCpMode == "advisory")
374 CheckpointsMode = Checkpoints::ADVISORY;
376 if(strCpMode == "permissive")
377 CheckpointsMode = Checkpoints::PERMISSIVE;
379 nDerivationMethodIndex = 0;
381 fTestNet = GetBoolArg("-testnet");
383 SoftSetBoolArg("-irc", true);
386 if (mapArgs.count("-bind")) {
387 // when specifying an explicit binding address, you want to listen on it
388 // even when -connect or -proxy is specified
389 SoftSetBoolArg("-listen", true);
392 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
393 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
394 SoftSetBoolArg("-dnsseed", false);
395 SoftSetBoolArg("-listen", false);
398 if (mapArgs.count("-proxy")) {
399 // to protect privacy, do not listen by default if a proxy server is specified
400 SoftSetBoolArg("-listen", false);
403 if (!GetBoolArg("-listen", true)) {
404 // do not map ports or try to retrieve public IP when not listening (pointless)
405 SoftSetBoolArg("-upnp", false);
406 SoftSetBoolArg("-discover", false);
409 if (mapArgs.count("-externalip")) {
410 // if an explicit public IP is specified, do not try to find others
411 SoftSetBoolArg("-discover", false);
414 if (GetBoolArg("-salvagewallet")) {
415 // Rewrite just private keys: rescan to find transactions
416 SoftSetBoolArg("-rescan", true);
419 // ********************************************************* Step 3: parameter-to-internal-flags
421 fDebug = GetBoolArg("-debug");
423 // -debug implies fDebug*
427 fDebugNet = GetBoolArg("-debugnet");
429 bitdb.SetDetach(GetBoolArg("-detachdb", false));
431 #if !defined(WIN32) && !defined(QT_GUI)
432 fDaemon = GetBoolArg("-daemon");
440 fServer = GetBoolArg("-server");
442 /* force fServer when running without GUI */
446 fPrintToConsole = GetBoolArg("-printtoconsole");
447 fPrintToDebugger = GetBoolArg("-printtodebugger");
448 fLogTimestamps = GetBoolArg("-logtimestamps");
450 if (mapArgs.count("-timeout"))
452 int nNewTimeout = GetArg("-timeout", 5000);
453 if (nNewTimeout > 0 && nNewTimeout < 600000)
454 nConnectTimeout = nNewTimeout;
457 // Continue to put "/P2SH/" in the coinbase to monitor
459 // This can be removed eventually...
460 const char* pszP2SH = "/P2SH/";
461 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
464 if (mapArgs.count("-paytxfee"))
466 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
467 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
468 if (nTransactionFee > 0.25 * COIN)
469 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
472 if (mapArgs.count("-mininput"))
474 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
475 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
478 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
480 std::string strDataDir = GetDataDir().string();
481 std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
483 // strWalletFileName must be a plain filename without a directory
484 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
485 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
487 // Make sure only a single Bitcoin process is using the data directory.
488 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
489 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
490 if (file) fclose(file);
491 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
492 if (!lock.try_lock())
493 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
495 #if !defined(WIN32) && !defined(QT_GUI)
502 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
507 CreatePidFile(GetPidFile(), pid);
511 pid_t sid = setsid();
513 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
517 if (GetBoolArg("-shrinkdebugfile", !fDebug))
519 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
520 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
521 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
523 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
524 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
525 printf("Used data directory %s\n", strDataDir.c_str());
526 std::ostringstream strErrors;
529 fprintf(stdout, "NovaCoin server starting\n");
533 // ********************************************************* Step 5: verify database integrity
535 uiInterface.InitMessage(_("Verifying database integrity..."));
537 if (!bitdb.Open(GetDataDir()))
539 string msg = strprintf(_("Error initializing database environment %s!"
540 " To recover, BACKUP THAT DIRECTORY, then remove"
541 " everything from it except for wallet.dat."), strDataDir.c_str());
542 return InitError(msg);
545 if (GetBoolArg("-salvagewallet"))
547 // Recover readable keypairs:
548 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
552 if (filesystem::exists(GetDataDir() / strWalletFileName))
554 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
555 if (r == CDBEnv::RECOVER_OK)
557 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
558 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
559 " your balance or transactions are incorrect you should"
560 " restore from a backup."), strDataDir.c_str());
561 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
563 if (r == CDBEnv::RECOVER_FAIL)
564 return InitError(_("wallet.dat corrupt, salvage failed"));
567 // ********************************************************* Step 6: network initialization
569 int nSocksVersion = GetArg("-socks", 5);
571 if (nSocksVersion != 4 && nSocksVersion != 5)
572 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
574 if (mapArgs.count("-onlynet")) {
575 std::set<enum Network> nets;
576 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
577 enum Network net = ParseNetwork(snet);
578 if (net == NET_UNROUTABLE)
579 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
582 for (int n = 0; n < NET_MAX; n++) {
583 enum Network net = (enum Network)n;
584 if (!nets.count(net))
588 #if defined(USE_IPV6)
591 SetLimited(NET_IPV6);
597 if (mapArgs.count("-proxy")) {
598 addrProxy = CService(mapArgs["-proxy"], 9050);
599 if (!addrProxy.IsValid())
600 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
602 if (!IsLimited(NET_IPV4))
603 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
604 if (nSocksVersion > 4) {
606 if (!IsLimited(NET_IPV6))
607 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
609 SetNameProxy(addrProxy, nSocksVersion);
614 // -tor can override normal proxy, -notor disables tor entirely
615 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
617 if (!mapArgs.count("-tor"))
618 addrOnion = addrProxy;
620 addrOnion = CService(mapArgs["-tor"], 9050);
621 if (!addrOnion.IsValid())
622 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
623 SetProxy(NET_TOR, addrOnion, 5);
624 SetReachable(NET_TOR);
627 // see Step 2: parameter interactions for more information about these
628 fNoListen = !GetBoolArg("-listen", true);
629 fDiscover = GetBoolArg("-discover", true);
630 fNameLookup = GetBoolArg("-dns", true);
632 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
638 std::string strError;
639 if (mapArgs.count("-bind")) {
640 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
642 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
643 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
644 fBound |= Bind(addrBind);
647 struct in_addr inaddr_any;
648 inaddr_any.s_addr = INADDR_ANY;
650 if (!IsLimited(NET_IPV6))
651 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
653 if (!IsLimited(NET_IPV4))
654 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
657 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
660 if (mapArgs.count("-externalip"))
662 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
663 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
664 if (!addrLocal.IsValid())
665 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
666 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
670 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
672 int64 nReserveBalance = 0;
673 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
675 InitError(_("Invalid amount for -reservebalance=<amount>"));
680 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
682 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
683 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
686 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
689 // ********************************************************* Step 7: load blockchain
691 if (!bitdb.Open(GetDataDir()))
693 string msg = strprintf(_("Error initializing database environment %s!"
694 " To recover, BACKUP THAT DIRECTORY, then remove"
695 " everything from it except for wallet.dat."), strDataDir.c_str());
696 return InitError(msg);
699 if (GetBoolArg("-loadblockindextest"))
702 txdb.LoadBlockIndex();
707 uiInterface.InitMessage(_("Loading block index..."));
708 printf("Loading block index...\n");
709 nStart = GetTimeMillis();
710 if (!LoadBlockIndex())
711 return InitError(_("Error loading blkindex.dat"));
714 // as LoadBlockIndex can take several minutes, it's possible the user
715 // requested to kill bitcoin-qt during the last operation. If so, exit.
716 // As the program has not fully started yet, Shutdown() is possibly overkill.
717 if (fRequestShutdown)
719 printf("Shutdown requested. Exiting.\n");
722 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
724 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
730 if (mapArgs.count("-printblock"))
732 string strMatch = mapArgs["-printblock"];
734 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
736 uint256 hash = (*mi).first;
737 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
739 CBlockIndex* pindex = (*mi).second;
741 block.ReadFromDisk(pindex);
742 block.BuildMerkleTree();
749 printf("No blocks matching %s were found\n", strMatch.c_str());
753 // ********************************************************* Testing Zerocoin
756 if (GetBoolArg("-zerotest", false))
758 printf("\n=== ZeroCoin tests start ===\n");
760 printf("=== ZeroCoin tests end ===\n\n");
763 // ********************************************************* Step 8: load wallet
765 uiInterface.InitMessage(_("Loading wallet..."));
766 printf("Loading wallet...\n");
767 nStart = GetTimeMillis();
768 bool fFirstRun = true;
769 pwalletMain = new CWallet(strWalletFileName);
770 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
771 if (nLoadWalletRet != DB_LOAD_OK)
773 if (nLoadWalletRet == DB_CORRUPT)
774 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
775 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
777 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
778 " or address book entries might be missing or incorrect."));
779 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
781 else if (nLoadWalletRet == DB_TOO_NEW)
782 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
783 else if (nLoadWalletRet == DB_NEED_REWRITE)
785 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
786 printf("%s", strErrors.str().c_str());
787 return InitError(strErrors.str());
790 strErrors << _("Error loading wallet.dat") << "\n";
793 if (GetBoolArg("-upgradewallet", fFirstRun))
795 int nMaxVersion = GetArg("-upgradewallet", 0);
796 if (nMaxVersion == 0) // the -upgradewallet without argument case
798 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
799 nMaxVersion = CLIENT_VERSION;
800 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
803 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
804 if (nMaxVersion < pwalletMain->GetVersion())
805 strErrors << _("Cannot downgrade wallet") << "\n";
806 pwalletMain->SetMaxVersion(nMaxVersion);
811 // Create new keyUser and set as default key
812 RandAddSeedPerfmon();
814 CPubKey newDefaultKey;
815 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
816 strErrors << _("Cannot initialize keypool") << "\n";
817 pwalletMain->SetDefaultKey(newDefaultKey);
818 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
819 strErrors << _("Cannot write default address") << "\n";
822 printf("%s", strErrors.str().c_str());
823 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
825 RegisterWallet(pwalletMain);
827 CBlockIndex *pindexRescan = pindexBest;
828 if (GetBoolArg("-rescan"))
829 pindexRescan = pindexGenesisBlock;
832 CWalletDB walletdb(strWalletFileName);
833 CBlockLocator locator;
834 if (walletdb.ReadBestBlock(locator))
835 pindexRescan = locator.GetBlockIndex();
837 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
839 uiInterface.InitMessage(_("Rescanning..."));
840 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
841 nStart = GetTimeMillis();
842 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
843 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
846 // ********************************************************* Step 9: import blocks
848 if (mapArgs.count("-loadblock"))
850 uiInterface.InitMessage(_("Importing blockchain data file."));
852 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
854 FILE *file = fopen(strFile.c_str(), "rb");
856 LoadExternalBlockFile(file);
861 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
862 if (filesystem::exists(pathBootstrap)) {
863 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
865 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
867 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
868 LoadExternalBlockFile(file);
869 RenameOver(pathBootstrap, pathBootstrapOld);
873 // ********************************************************* Step 10: load peers
875 uiInterface.InitMessage(_("Loading addresses..."));
876 printf("Loading addresses...\n");
877 nStart = GetTimeMillis();
881 if (!adb.Read(addrman))
882 printf("Invalid or missing peers.dat; recreating\n");
885 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
886 addrman.size(), GetTimeMillis() - nStart);
888 // ********************************************************* Step 11: start node
890 if (!CheckDiskSpace())
893 RandAddSeedPerfmon();
896 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
897 printf("nBestHeight = %d\n", nBestHeight);
898 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
899 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
900 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
902 if (!NewThread(StartNode, NULL))
903 InitError(_("Error: could not start node"));
906 NewThread(ThreadRPCServer, NULL);
908 // ********************************************************* Step 12: finished
910 uiInterface.InitMessage(_("Done loading"));
911 printf("Done loading\n");
913 if (!strErrors.str().empty())
914 return InitError(strErrors.str());
916 // Add wallet transactions that aren't already in a block to mapTransactions
917 pwalletMain->ReacceptWalletTransactions();
920 // Loop until process is exit()ed from shutdown() function,
921 // called from ThreadRPCServer thread when a "stop" command is received.