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 static CCoinsViewDB *pcoinsdbview;
65 void Shutdown(void* parg)
67 static CCriticalSection cs_Shutdown;
70 // Make this thread recognisable as the shutdown thread
71 RenameThread("bitcoin-shutoff");
73 bool fFirstThread = false;
75 TRY_LOCK(cs_Shutdown, lockShutdown);
78 fFirstThread = !fTaken;
86 nTransactionsUpdated++;
96 boost::filesystem::remove(GetPidFile());
97 UnregisterWallet(pwalletMain);
99 NewThread(ExitTimeout, NULL);
101 printf("NovaCoin exited\n\n");
104 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
117 void HandleSIGTERM(int)
119 fRequestShutdown = true;
122 void HandleSIGHUP(int)
124 fReopenDebugLog = true;
131 //////////////////////////////////////////////////////////////////////////////
136 bool AppInit(int argc, char* argv[])
144 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
145 ParseParameters(argc, argv);
146 if (!boost::filesystem::is_directory(GetDataDir(false)))
148 fprintf(stderr, "Error: Specified directory does not exist\n");
151 ReadConfigFile(mapArgs, mapMultiArgs);
153 if (mapArgs.count("-?") || mapArgs.count("--help"))
155 // First part of help message is specific to bitcoind / RPC client
156 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
158 " novacoind [options] " + "\n" +
159 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
160 " novacoind [options] help " + _("List commands") + "\n" +
161 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
163 strUsage += "\n" + HelpMessage();
165 fprintf(stdout, "%s", strUsage.c_str());
170 for (int i = 1; i < argc; i++)
171 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
176 int ret = CommandLineRPC(argc, argv);
182 catch (std::exception& e) {
183 PrintException(&e, "AppInit()");
185 PrintException(NULL, "AppInit()");
192 extern void noui_connect();
193 int main(int argc, char* argv[])
197 // Connect bitcoind signal handlers
200 fRet = AppInit(argc, argv);
209 bool static InitError(const std::string &str)
211 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
215 bool static InitWarning(const std::string &str)
217 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
222 bool static Bind(const CService &addr, bool fError = true) {
225 std::string strError;
226 if (!BindListenPort(addr, strError)) {
228 return InitError(strError);
234 // Core-specific options shared between UI and daemon
235 std::string HelpMessage()
237 string strUsage = _("Options:") + "\n" +
238 " -? " + _("This help message") + "\n" +
239 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
240 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
241 " -datadir=<dir> " + _("Specify data directory") + "\n" +
242 " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
243 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
244 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
245 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
246 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
247 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
248 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
249 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
250 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
251 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
252 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
253 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
254 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
255 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
256 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
257 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
258 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
259 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
260 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
261 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
262 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
263 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
264 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
265 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
266 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
269 " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
271 " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
274 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
275 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
276 " -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
278 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
280 #if !defined(WIN32) && !defined(QT_GUI)
281 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
283 " -testnet " + _("Use the test network") + "\n" +
284 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
285 " -debugnet " + _("Output extra network debugging information") + "\n" +
286 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
287 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
288 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
290 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
292 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
293 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
294 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
295 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
296 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
297 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
298 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
299 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
300 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
301 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
302 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
303 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
304 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
305 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
307 "\n" + _("Block creation options:") + "\n" +
308 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
309 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
310 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
312 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
313 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
314 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
315 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
316 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
321 /** Initialize bitcoin.
322 * @pre Parameters should be parsed and config file should be read.
326 // ********************************************************* Step 1: setup
328 // Turn off Microsoft heap dump noise
329 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
330 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
333 // Disable confusing "helpful" text message on abort, Ctrl-C
334 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
337 // Enable Data Execution Prevention (DEP)
338 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
339 // A failure is non-critical and needs no further attention!
340 #ifndef PROCESS_DEP_ENABLE
341 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
342 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
343 #define PROCESS_DEP_ENABLE 0x00000001
345 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
346 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
347 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
352 // Clean shutdown on SIGTERM
354 sa.sa_handler = HandleSIGTERM;
355 sigemptyset(&sa.sa_mask);
357 sigaction(SIGTERM, &sa, NULL);
358 sigaction(SIGINT, &sa, NULL);
360 // Reopen debug.log on SIGHUP
361 struct sigaction sa_hup;
362 sa_hup.sa_handler = HandleSIGHUP;
363 sigemptyset(&sa_hup.sa_mask);
365 sigaction(SIGHUP, &sa_hup, NULL);
368 // ********************************************************* Step 2: parameter interactions
370 nNodeLifespan = GetArg("-addrlifespan", 7);
371 fUseFastIndex = GetBoolArg("-fastindex", true);
372 nMinerSleep = GetArg("-minersleep", 500);
374 CheckpointsMode = Checkpoints::STRICT;
375 std::string strCpMode = GetArg("-cppolicy", "strict");
377 if(strCpMode == "strict")
378 CheckpointsMode = Checkpoints::STRICT;
380 if(strCpMode == "advisory")
381 CheckpointsMode = Checkpoints::ADVISORY;
383 if(strCpMode == "permissive")
384 CheckpointsMode = Checkpoints::PERMISSIVE;
386 nDerivationMethodIndex = 0;
388 fTestNet = GetBoolArg("-testnet");
390 SoftSetBoolArg("-irc", true);
393 if (mapArgs.count("-bind")) {
394 // when specifying an explicit binding address, you want to listen on it
395 // even when -connect or -proxy is specified
396 SoftSetBoolArg("-listen", true);
399 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
400 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
401 SoftSetBoolArg("-dnsseed", false);
402 SoftSetBoolArg("-listen", false);
405 if (mapArgs.count("-proxy")) {
406 // to protect privacy, do not listen by default if a proxy server is specified
407 SoftSetBoolArg("-listen", false);
410 if (!GetBoolArg("-listen", true)) {
411 // do not map ports or try to retrieve public IP when not listening (pointless)
412 SoftSetBoolArg("-upnp", false);
413 SoftSetBoolArg("-discover", false);
416 if (mapArgs.count("-externalip")) {
417 // if an explicit public IP is specified, do not try to find others
418 SoftSetBoolArg("-discover", false);
421 if (GetBoolArg("-salvagewallet")) {
422 // Rewrite just private keys: rescan to find transactions
423 SoftSetBoolArg("-rescan", true);
426 // ********************************************************* Step 3: parameter-to-internal-flags
428 fDebug = GetBoolArg("-debug");
430 // -debug implies fDebug*
434 fDebugNet = GetBoolArg("-debugnet");
436 bitdb.SetDetach(GetBoolArg("-detachdb", false));
438 #if !defined(WIN32) && !defined(QT_GUI)
439 fDaemon = GetBoolArg("-daemon");
447 fServer = GetBoolArg("-server");
449 /* force fServer when running without GUI */
453 fPrintToConsole = GetBoolArg("-printtoconsole");
454 fPrintToDebugger = GetBoolArg("-printtodebugger");
455 fLogTimestamps = GetBoolArg("-logtimestamps");
457 if (mapArgs.count("-timeout"))
459 int nNewTimeout = GetArg("-timeout", 5000);
460 if (nNewTimeout > 0 && nNewTimeout < 600000)
461 nConnectTimeout = nNewTimeout;
464 // Continue to put "/P2SH/" in the coinbase to monitor
466 // This can be removed eventually...
467 const char* pszP2SH = "/P2SH/";
468 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
471 if (mapArgs.count("-paytxfee"))
473 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
474 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
475 if (nTransactionFee > 0.25 * COIN)
476 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
479 if (mapArgs.count("-mininput"))
481 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
482 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
485 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
487 std::string strDataDir = GetDataDir().string();
488 std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
490 // strWalletFileName must be a plain filename without a directory
491 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
492 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
494 // Make sure only a single Bitcoin process is using the data directory.
495 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
496 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
497 if (file) fclose(file);
498 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
499 if (!lock.try_lock())
500 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
502 #if !defined(WIN32) && !defined(QT_GUI)
509 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
514 CreatePidFile(GetPidFile(), pid);
518 pid_t sid = setsid();
520 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
524 if (GetBoolArg("-shrinkdebugfile", !fDebug))
526 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
527 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
528 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
530 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
531 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
532 printf("Used data directory %s\n", strDataDir.c_str());
533 std::ostringstream strErrors;
536 fprintf(stdout, "NovaCoin server starting\n");
540 // ********************************************************* Step 5: verify database integrity
542 uiInterface.InitMessage(_("Verifying database integrity..."));
544 if (!bitdb.Open(GetDataDir()))
546 string msg = strprintf(_("Error initializing database environment %s!"
547 " To recover, BACKUP THAT DIRECTORY, then remove"
548 " everything from it except for wallet.dat."), strDataDir.c_str());
549 return InitError(msg);
552 if (GetBoolArg("-salvagewallet"))
554 // Recover readable keypairs:
555 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
559 if (filesystem::exists(GetDataDir() / strWalletFileName))
561 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
562 if (r == CDBEnv::RECOVER_OK)
564 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
565 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
566 " your balance or transactions are incorrect you should"
567 " restore from a backup."), strDataDir.c_str());
568 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
570 if (r == CDBEnv::RECOVER_FAIL)
571 return InitError(_("wallet.dat corrupt, salvage failed"));
574 // ********************************************************* Step 6: network initialization
576 int nSocksVersion = GetArg("-socks", 5);
578 if (nSocksVersion != 4 && nSocksVersion != 5)
579 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
581 if (mapArgs.count("-onlynet")) {
582 std::set<enum Network> nets;
583 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
584 enum Network net = ParseNetwork(snet);
585 if (net == NET_UNROUTABLE)
586 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
589 for (int n = 0; n < NET_MAX; n++) {
590 enum Network net = (enum Network)n;
591 if (!nets.count(net))
595 #if defined(USE_IPV6)
598 SetLimited(NET_IPV6);
604 if (mapArgs.count("-proxy")) {
605 addrProxy = CService(mapArgs["-proxy"], 9050);
606 if (!addrProxy.IsValid())
607 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
609 if (!IsLimited(NET_IPV4))
610 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
611 if (nSocksVersion > 4) {
613 if (!IsLimited(NET_IPV6))
614 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
616 SetNameProxy(addrProxy, nSocksVersion);
621 // -tor can override normal proxy, -notor disables tor entirely
622 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
624 if (!mapArgs.count("-tor"))
625 addrOnion = addrProxy;
627 addrOnion = CService(mapArgs["-tor"], 9050);
628 if (!addrOnion.IsValid())
629 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
630 SetProxy(NET_TOR, addrOnion, 5);
631 SetReachable(NET_TOR);
634 // see Step 2: parameter interactions for more information about these
635 fNoListen = !GetBoolArg("-listen", true);
636 fDiscover = GetBoolArg("-discover", true);
637 fNameLookup = GetBoolArg("-dns", true);
639 fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
645 std::string strError;
646 if (mapArgs.count("-bind")) {
647 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
649 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
650 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
651 fBound |= Bind(addrBind);
654 struct in_addr inaddr_any;
655 inaddr_any.s_addr = INADDR_ANY;
657 if (!IsLimited(NET_IPV6))
658 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
660 if (!IsLimited(NET_IPV4))
661 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
664 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
667 if (mapArgs.count("-externalip"))
669 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
670 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
671 if (!addrLocal.IsValid())
672 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
673 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
677 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
679 int64 nReserveBalance = 0;
680 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
682 InitError(_("Invalid amount for -reservebalance=<amount>"));
687 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
689 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
690 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
693 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
696 // ********************************************************* Step 7: load blockchain
698 if (!bitdb.Open(GetDataDir()))
700 string msg = strprintf(_("Error initializing database environment %s!"
701 " To recover, BACKUP THAT DIRECTORY, then remove"
702 " everything from it except for wallet.dat."), strDataDir.c_str());
703 return InitError(msg);
706 uiInterface.InitMessage(_("Loading block index..."));
707 printf("Loading block index...\n");
708 nStart = GetTimeMillis();
709 pcoinsdbview = new CCoinsViewDB();
710 pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
712 if (!LoadBlockIndex())
713 return InitError(_("Error loading blkindex.dat"));
715 // as LoadBlockIndex can take several minutes, it's possible the user
716 // requested to kill bitcoin-qt during the last operation. If so, exit.
717 // As the program has not fully started yet, Shutdown() is possibly overkill.
718 if (fRequestShutdown)
720 printf("Shutdown requested. Exiting.\n");
723 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
725 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
731 if (mapArgs.count("-printblock"))
733 string strMatch = mapArgs["-printblock"];
735 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
737 uint256 hash = (*mi).first;
738 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
740 CBlockIndex* pindex = (*mi).second;
742 block.ReadFromDisk(pindex);
743 block.BuildMerkleTree();
750 printf("No blocks matching %s were found\n", strMatch.c_str());
754 // ********************************************************* Testing Zerocoin
757 if (GetBoolArg("-zerotest", false))
759 printf("\n=== ZeroCoin tests start ===\n");
761 printf("=== ZeroCoin tests end ===\n\n");
764 // ********************************************************* Step 8: load wallet
766 uiInterface.InitMessage(_("Loading wallet..."));
767 printf("Loading wallet...\n");
768 nStart = GetTimeMillis();
769 bool fFirstRun = true;
770 pwalletMain = new CWallet(strWalletFileName);
771 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
772 if (nLoadWalletRet != DB_LOAD_OK)
774 if (nLoadWalletRet == DB_CORRUPT)
775 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
776 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
778 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
779 " or address book entries might be missing or incorrect."));
780 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
782 else if (nLoadWalletRet == DB_TOO_NEW)
783 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
784 else if (nLoadWalletRet == DB_NEED_REWRITE)
786 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
787 printf("%s", strErrors.str().c_str());
788 return InitError(strErrors.str());
791 strErrors << _("Error loading wallet.dat") << "\n";
794 if (GetBoolArg("-upgradewallet", fFirstRun))
796 int nMaxVersion = GetArg("-upgradewallet", 0);
797 if (nMaxVersion == 0) // the -upgradewallet without argument case
799 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
800 nMaxVersion = CLIENT_VERSION;
801 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
804 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
805 if (nMaxVersion < pwalletMain->GetVersion())
806 strErrors << _("Cannot downgrade wallet") << "\n";
807 pwalletMain->SetMaxVersion(nMaxVersion);
812 // Create new keyUser and set as default key
813 RandAddSeedPerfmon();
815 CPubKey newDefaultKey;
816 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
817 strErrors << _("Cannot initialize keypool") << "\n";
818 pwalletMain->SetDefaultKey(newDefaultKey);
819 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
820 strErrors << _("Cannot write default address") << "\n";
823 printf("%s", strErrors.str().c_str());
824 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
826 RegisterWallet(pwalletMain);
828 CBlockIndex *pindexRescan = pindexBest;
829 if (GetBoolArg("-rescan"))
830 pindexRescan = pindexGenesisBlock;
833 CWalletDB walletdb(strWalletFileName);
834 CBlockLocator locator;
835 if (walletdb.ReadBestBlock(locator))
836 pindexRescan = locator.GetBlockIndex();
838 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
840 uiInterface.InitMessage(_("Rescanning..."));
841 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
842 nStart = GetTimeMillis();
843 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
844 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
847 // ********************************************************* Step 9: import blocks
849 // scan for better chains in the block chain database, that are not yet connected in the active best chain
850 uiInterface.InitMessage(_("Importing blocks from block database..."));
851 if (!ConnectBestBlock())
852 strErrors << "Failed to connect best block";
854 if (mapArgs.count("-loadblock"))
856 uiInterface.InitMessage(_("Importing blockchain data file."));
858 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
860 FILE *file = fopen(strFile.c_str(), "rb");
862 LoadExternalBlockFile(file);
867 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
868 if (filesystem::exists(pathBootstrap)) {
869 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
871 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
873 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
874 LoadExternalBlockFile(file);
875 RenameOver(pathBootstrap, pathBootstrapOld);
879 // ********************************************************* Step 10: load peers
881 uiInterface.InitMessage(_("Loading addresses..."));
882 printf("Loading addresses...\n");
883 nStart = GetTimeMillis();
887 if (!adb.Read(addrman))
888 printf("Invalid or missing peers.dat; recreating\n");
891 printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
892 addrman.size(), GetTimeMillis() - nStart);
894 // ********************************************************* Step 11: start node
896 if (!CheckDiskSpace())
899 RandAddSeedPerfmon();
902 printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
903 printf("nBestHeight = %d\n", nBestHeight);
904 printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
905 printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
906 printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
908 if (!NewThread(StartNode, NULL))
909 InitError(_("Error: could not start node"));
912 NewThread(ThreadRPCServer, NULL);
914 // ********************************************************* Step 12: finished
916 uiInterface.InitMessage(_("Done loading"));
917 printf("Done loading\n");
919 if (!strErrors.str().empty())
920 return InitError(strErrors.str());
922 // Add wallet transactions that aren't already in a block to mapTransactions
923 pwalletMain->ReacceptWalletTransactions();
926 // Loop until process is exit()ed from shutdown() function,
927 // called from ThreadRPCServer thread when a "stop" command is received.