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.
8 #include "txdb-leveldb.h"
10 #include "bitcoinrpc.h"
14 #include "ipcollector.h"
15 #include "interface.h"
16 #include "checkpoints.h"
18 #include <boost/filesystem.hpp>
19 #include <boost/filesystem/fstream.hpp>
20 #include <boost/filesystem/convenience.hpp>
21 #include <boost/interprocess/sync/file_lock.hpp>
22 #include <boost/algorithm/string/predicate.hpp>
23 #include <openssl/crypto.h>
34 CClientUIInterface uiInterface;
35 std::string strWalletFileName;
37 unsigned int nNodeLifespan;
40 enum Checkpoints::CPMode CheckpointsMode;
42 // Ping and address broadcast intervals
43 extern int64_t nPingInterval;
44 extern int64_t nReserveBalance;
46 //////////////////////////////////////////////////////////////////////////////
51 void ExitTimeout(void* parg)
62 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
63 uiInterface.QueueShutdown();
65 // Without UI, Shutdown() can simply be started in a new thread
66 NewThread(Shutdown, NULL);
70 void Shutdown(void* parg)
72 static CCriticalSection cs_Shutdown;
75 // Make this thread recognisable as the shutdown thread
76 RenameThread("novacoin-shutoff");
78 bool fFirstThread = false;
80 TRY_LOCK(cs_Shutdown, lockShutdown);
83 fFirstThread = !fTaken;
91 fRequestShutdown = true;
92 nTransactionsUpdated++;
98 boost::filesystem::remove(GetPidFile());
99 UnregisterWallet(pwalletMain);
101 NewThread(ExitTimeout, NULL);
103 printf("NovaCoin exited\n\n");
106 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
119 void HandleSIGTERM(int)
121 fRequestShutdown = true;
124 void HandleSIGHUP(int)
126 fReopenDebugLog = true;
133 //////////////////////////////////////////////////////////////////////////////
138 bool AppInit(int argc, char* argv[])
146 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
147 ParseParameters(argc, argv);
148 if (!boost::filesystem::is_directory(GetDataDir(false)))
150 fprintf(stderr, "Error: Specified directory does not exist\n");
153 ReadConfigFile(mapArgs, mapMultiArgs);
155 if (mapArgs.count("-?") || mapArgs.count("--help"))
157 // First part of help message is specific to bitcoind / RPC client
158 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
160 " novacoind [options] " + "\n" +
161 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
162 " novacoind [options] help " + _("List commands") + "\n" +
163 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
165 strUsage += "\n" + HelpMessage();
167 fprintf(stdout, "%s", strUsage.c_str());
172 for (int i = 1; i < argc; i++)
173 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
178 int ret = CommandLineRPC(argc, argv);
184 catch (std::exception& e) {
185 PrintException(&e, "AppInit()");
187 PrintException(NULL, "AppInit()");
194 extern void noui_connect();
195 int main(int argc, char* argv[])
198 // Connect bitcoind signal handlers
201 bool fRet = AppInit(argc, argv);
210 bool static InitError(const std::string &str)
212 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
216 bool static InitWarning(const std::string &str)
218 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
223 bool static Bind(const CService &addr, bool fError = true) {
226 std::string strError;
227 if (!BindListenPort(addr, strError)) {
229 return InitError(strError);
235 // Core-specific options shared between UI and daemon
236 std::string HelpMessage()
238 string strUsage = _("Options:") + "\n" +
239 " -? " + _("This help message") + "\n" +
240 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
241 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
242 " -datadir=<dir> " + _("Specify data directory") + "\n" +
243 " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n" +
244 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
245 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
246 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
247 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
248 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
249 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
250 " -torname=<host.onion> " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
251 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
252 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
253 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
254 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
255 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
256 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
257 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
258 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
259 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
260 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
261 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
262 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
263 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
264 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
265 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
266 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
267 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
268 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
269 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
271 #ifdef DB_LOG_IN_MEMORY
272 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\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: ") + FormatMoney(MIN_TXOUT_AMOUNT) + ")") + "\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 " -peercollector=<cmd> " + _("Execute command to collect peer addresses") + "\n" +
300 " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
301 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
302 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
303 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
304 " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n" +
305 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
306 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
307 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
308 " -par=N " + _("Set the number of script verification threads (1-16, 0=auto, default: 0)") + "\n" +
309 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
311 "\n" + _("Block creation options:") + "\n" +
312 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
313 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
314 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n";
319 /** Initialize bitcoin.
320 * @pre Parameters should be parsed and config file should be read.
324 // ********************************************************* Step 1: setup
326 // Turn off Microsoft heap dump noise
327 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
328 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
331 // Disable confusing "helpful" text message on abort, Ctrl-C
332 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
335 // Enable Data Execution Prevention (DEP)
336 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
337 // A failure is non-critical and needs no further attention!
338 #ifndef PROCESS_DEP_ENABLE
339 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
340 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
341 #define PROCESS_DEP_ENABLE 0x00000001
343 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
344 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
345 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
347 // Initialize Windows Sockets
349 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
352 return InitError(strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret));
358 // Clean shutdown on SIGTERM
360 sa.sa_handler = HandleSIGTERM;
361 sigemptyset(&sa.sa_mask);
363 sigaction(SIGTERM, &sa, NULL);
364 sigaction(SIGINT, &sa, NULL);
366 // Reopen debug.log on SIGHUP
367 struct sigaction sa_hup;
368 sa_hup.sa_handler = HandleSIGHUP;
369 sigemptyset(&sa_hup.sa_mask);
371 sigaction(SIGHUP, &sa_hup, NULL);
374 // ********************************************************* Step 2: parameter interactions
376 nNodeLifespan = GetArgUInt("-addrlifespan", 7);
377 fUseFastIndex = GetBoolArg("-fastindex", true);
378 fUseMemoryLog = GetBoolArg("-memorylog", true);
380 // Ping and address broadcast intervals
381 nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
383 CheckpointsMode = Checkpoints::STRICT;
384 std::string strCpMode = GetArg("-cppolicy", "strict");
386 if(strCpMode == "strict") {
387 CheckpointsMode = Checkpoints::STRICT;
390 if(strCpMode == "advisory") {
391 CheckpointsMode = Checkpoints::ADVISORY;
394 if(strCpMode == "permissive") {
395 CheckpointsMode = Checkpoints::PERMISSIVE;
398 fTestNet = GetBoolArg("-testnet");
400 SoftSetBoolArg("-irc", true);
403 if (mapArgs.count("-bind")) {
404 // when specifying an explicit binding address, you want to listen on it
405 // even when -connect or -proxy is specified
406 SoftSetBoolArg("-listen", true);
409 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
410 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
411 SoftSetBoolArg("-dnsseed", false);
412 SoftSetBoolArg("-listen", false);
415 if (mapArgs.count("-proxy")) {
416 // to protect privacy, do not listen by default if a proxy server is specified
417 SoftSetBoolArg("-listen", false);
420 if (!GetBoolArg("-listen", true)) {
421 // do not map ports or try to retrieve public IP when not listening (pointless)
422 SoftSetBoolArg("-discover", false);
425 if (mapArgs.count("-externalip")) {
426 // if an explicit public IP is specified, do not try to find others
427 SoftSetBoolArg("-discover", false);
430 if (GetBoolArg("-salvagewallet")) {
431 // Rewrite just private keys: rescan to find transactions
432 SoftSetBoolArg("-rescan", true);
435 if (GetBoolArg("-zapwallettxes", false)) {
436 // -zapwallettx implies a rescan
437 if (SoftSetBoolArg("-rescan", true))
438 printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
441 // ********************************************************* Step 3: parameter-to-internal-flags
443 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
444 nScriptCheckThreads = GetArgInt("-par", 0);
445 if (nScriptCheckThreads == 0)
446 nScriptCheckThreads = boost::thread::hardware_concurrency();
447 if (nScriptCheckThreads <= 1)
448 nScriptCheckThreads = 0;
449 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
450 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
452 fDebug = GetBoolArg("-debug");
454 // -debug implies fDebug*
458 fDebugNet = GetBoolArg("-debugnet");
460 bitdb.SetDetach(GetBoolArg("-detachdb", false));
462 #if !defined(WIN32) && !defined(QT_GUI)
463 fDaemon = GetBoolArg("-daemon");
471 fServer = GetBoolArg("-server");
473 /* force fServer when running without GUI */
477 fPrintToConsole = GetBoolArg("-printtoconsole");
478 fPrintToDebugger = GetBoolArg("-printtodebugger");
479 fLogTimestamps = GetBoolArg("-logtimestamps");
481 if (mapArgs.count("-timeout"))
483 int nNewTimeout = GetArgInt("-timeout", 5000);
484 if (nNewTimeout > 0 && nNewTimeout < 600000)
485 nConnectTimeout = nNewTimeout;
488 // Put client version data into coinbase flags.
489 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
491 if (mapArgs.count("-paytxfee"))
493 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
494 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
495 if (nTransactionFee > 0.25 * COIN)
496 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
499 fConfChange = GetBoolArg("-confchange", false);
501 if (mapArgs.count("-mininput"))
503 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
504 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
507 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
509 std::string strDataDir = GetDataDir().string();
510 strWalletFileName = GetArg("-wallet", "wallet.dat");
512 // strWalletFileName must be a plain filename without a directory
513 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
514 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
516 // Make sure only a single Bitcoin process is using the data directory.
517 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
518 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
519 if (file) fclose(file);
520 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
521 if (!lock.try_lock())
522 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
524 #if !defined(WIN32) && !defined(QT_GUI)
531 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
536 CreatePidFile(GetPidFile(), pid);
540 pid_t sid = setsid();
542 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
546 if (GetBoolArg("-shrinkdebugfile", !fDebug))
548 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
549 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
550 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
552 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
553 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
554 printf("Used data directory %s\n", strDataDir.c_str());
555 std::ostringstream strErrors;
558 fprintf(stdout, "NovaCoin server starting\n");
560 if (nScriptCheckThreads) {
561 printf("Using %u threads for script verification\n", nScriptCheckThreads);
562 for (int i=0; i<nScriptCheckThreads-1; i++)
563 NewThread(ThreadScriptCheck, NULL);
568 // ********************************************************* Step 5: verify database integrity
570 uiInterface.InitMessage(_("Verifying database integrity..."));
572 if (!bitdb.Open(GetDataDir()))
574 string msg = strprintf(_("Error initializing database environment %s!"
575 " To recover, BACKUP THAT DIRECTORY, then remove"
576 " everything from it except for wallet.dat."), strDataDir.c_str());
577 return InitError(msg);
580 if (GetBoolArg("-salvagewallet"))
582 // Recover readable keypairs:
583 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
587 if (boost::filesystem::exists(GetDataDir() / strWalletFileName))
589 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
590 if (r == CDBEnv::RECOVER_OK)
592 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
593 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
594 " your balance or transactions are incorrect you should"
595 " restore from a backup."), strDataDir.c_str());
596 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
598 if (r == CDBEnv::RECOVER_FAIL)
599 return InitError(_("wallet.dat corrupt, salvage failed"));
602 // ********************************************************* Step 6: network initialization
604 int nSocksVersion = GetArgInt("-socks", 5);
606 if (nSocksVersion != 4 && nSocksVersion != 5)
607 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
609 if (mapArgs.count("-onlynet")) {
610 std::set<enum Network> nets;
611 for (std::string snet : mapMultiArgs["-onlynet"]) {
612 enum Network net = ParseNetwork(snet);
613 if (net == NET_UNROUTABLE)
614 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
617 for (int n = 0; n < NET_MAX; n++) {
618 enum Network net = (enum Network)n;
619 if (!nets.count(net))
623 #if defined(USE_IPV6)
626 SetLimited(NET_IPV6);
632 if (mapArgs.count("-proxy")) {
633 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
634 if (!addrProxy.IsValid())
635 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
637 if (!IsLimited(NET_IPV4))
638 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
639 if (nSocksVersion > 4) {
641 if (!IsLimited(NET_IPV6))
642 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
644 SetNameProxy(addrProxy, nSocksVersion);
649 // -tor can override normal proxy, -notor disables tor entirely
650 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
652 if (!mapArgs.count("-tor"))
653 addrOnion = addrProxy;
655 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
656 if (!addrOnion.IsValid())
657 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
658 SetProxy(NET_TOR, addrOnion, 5);
659 SetReachable(NET_TOR);
662 // see Step 2: parameter interactions for more information about these
663 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
665 fNoListen = !GetBoolArg("-listen", true);
666 fDiscover = GetBoolArg("-discover", true);
667 fNameLookup = GetBoolArg("-dns", true);
669 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
671 fDiscover = fNameLookup = false;
672 SoftSetBoolArg("-irc", false);
673 SoftSetBoolArg("-dnsseed", false);
679 std::string strError;
680 if (mapArgs.count("-bind")) {
681 for(std::string strBind : mapMultiArgs["-bind"]) {
683 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
684 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
685 fBound |= Bind(addrBind);
688 struct in_addr inaddr_any;
689 inaddr_any.s_addr = INADDR_ANY;
691 if (!IsLimited(NET_IPV6))
692 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
694 if (!IsLimited(NET_IPV4))
695 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
699 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
702 // If Tor is reachable then listen on loopback interface,
703 // to allow allow other users reach you through the hidden service
704 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
705 std::string strError;
706 struct in_addr inaddr_loopback;
707 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
710 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
711 return InitError(strError);
713 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
714 return InitError(strError);
717 if (mapArgs.count("-externalip"))
719 for (string strAddr : mapMultiArgs["-externalip"]) {
720 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
721 if (!addrLocal.IsValid())
722 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
723 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
727 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
729 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
731 InitError(_("Invalid amount for -reservebalance=<amount>"));
736 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
738 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
739 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
742 for (string strDest : mapMultiArgs["-seednode"])
745 // ********************************************************* Step 7: load blockchain
747 if (!bitdb.Open(GetDataDir()))
749 string msg = strprintf(_("Error initializing database environment %s!"
750 " To recover, BACKUP THAT DIRECTORY, then remove"
751 " everything from it except for wallet.dat."), strDataDir.c_str());
752 return InitError(msg);
755 if (GetBoolArg("-loadblockindextest"))
758 txdb.LoadBlockIndex();
764 printf("Loading block index...\n");
765 bool fLoaded = false;
767 std::string strLoadError;
768 uiInterface.InitMessage(_("Loading block index..."));
770 nStart = GetTimeMillis();
775 if (!LoadBlockIndex()) {
776 strLoadError = _("Error loading block database");
779 } catch(const std::exception&) {
780 strLoadError = _("Error opening block database");
788 // TODO: suggest reindex here
789 return InitError(strLoadError);
793 // as LoadBlockIndex can take several minutes, it's possible the user
794 // requested to kill bitcoin-qt during the last operation. If so, exit.
795 // As the program has not fully started yet, Shutdown() is possibly overkill.
796 if (fRequestShutdown)
798 printf("Shutdown requested. Exiting.\n");
801 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
803 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
809 if (mapArgs.count("-printblock"))
811 string strMatch = mapArgs["-printblock"];
813 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
815 uint256 hash = (*mi).first;
816 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
818 CBlockIndex* pindex = (*mi).second;
820 block.ReadFromDisk(pindex);
821 block.BuildMerkleTree();
828 printf("No blocks matching %s were found\n", strMatch.c_str());
832 // ********************************************************* Step 8: load wallet
834 if (GetBoolArg("-zapwallettxes", false)) {
835 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
837 pwalletMain = new CWallet(strWalletFileName);
838 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
839 if (nZapWalletRet != DB_LOAD_OK) {
840 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
847 uiInterface.InitMessage(_("Loading wallet..."));
848 printf("Loading wallet...\n");
849 nStart = GetTimeMillis();
850 bool fFirstRun = true;
851 pwalletMain = new CWallet(strWalletFileName);
852 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
853 if (nLoadWalletRet != DB_LOAD_OK)
855 if (nLoadWalletRet == DB_CORRUPT)
856 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
857 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
859 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
860 " or address book entries might be missing or incorrect."));
861 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
863 else if (nLoadWalletRet == DB_TOO_NEW)
864 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
865 else if (nLoadWalletRet == DB_NEED_REWRITE)
867 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
868 printf("%s", strErrors.str().c_str());
869 return InitError(strErrors.str());
872 strErrors << _("Error loading wallet.dat") << "\n";
875 if (GetBoolArg("-upgradewallet", fFirstRun))
877 int nMaxVersion = GetArgInt("-upgradewallet", 0);
878 if (nMaxVersion == 0) // the -upgradewallet without argument case
880 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
881 nMaxVersion = CLIENT_VERSION;
882 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
885 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
886 if (nMaxVersion < pwalletMain->GetVersion())
887 strErrors << _("Cannot downgrade wallet") << "\n";
888 pwalletMain->SetMaxVersion(nMaxVersion);
893 // Create new keyUser and set as default key
894 RandAddSeedPerfmon();
896 CPubKey newDefaultKey;
897 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
898 strErrors << _("Cannot initialize keypool") << "\n";
899 pwalletMain->SetDefaultKey(newDefaultKey);
900 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
901 strErrors << _("Cannot write default address") << "\n";
903 CMalleableKeyView keyView = pwalletMain->GenerateNewMalleableKey();
905 if (!pwalletMain->GetMalleableKey(keyView, mKey))
906 strErrors << _("Unable to generate new malleable key");
907 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
908 strErrors << _("Cannot write default address") << "\n";
911 printf("%s", strErrors.str().c_str());
912 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
914 RegisterWallet(pwalletMain);
916 CBlockIndex *pindexRescan = pindexBest;
917 if (GetBoolArg("-rescan"))
918 pindexRescan = pindexGenesisBlock;
921 CWalletDB walletdb(strWalletFileName);
922 CBlockLocator locator;
923 if (walletdb.ReadBestBlock(locator))
924 pindexRescan = locator.GetBlockIndex();
926 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
928 uiInterface.InitMessage(_("Rescanning..."));
929 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
930 nStart = GetTimeMillis();
931 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
932 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
935 // ********************************************************* Step 9: import blocks
937 if (mapArgs.count("-loadblock"))
939 uiInterface.InitMessage(_("Importing blockchain data file."));
941 for (string strFile : mapMultiArgs["-loadblock"])
943 FILE *file = fopen(strFile.c_str(), "rb");
945 LoadExternalBlockFile(file);
950 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
951 if (boost::filesystem::exists(pathBootstrap)) {
952 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
954 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
956 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
957 LoadExternalBlockFile(file);
958 RenameOver(pathBootstrap, pathBootstrapOld);
962 // ********************************************************* Step 10: load peers
964 uiInterface.InitMessage(_("Loading addresses..."));
965 printf("Loading addresses...\n");
966 nStart = GetTimeMillis();
970 if (!adb.Read(addrman))
971 printf("Invalid or missing peers.dat; recreating\n");
974 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
975 addrman.size(), GetTimeMillis() - nStart);
977 // ********************************************************* Step 11: start node
979 if (!CheckDiskSpace())
982 RandAddSeedPerfmon();
985 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
986 printf("nBestHeight = %d\n", nBestHeight);
987 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
988 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
989 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
991 if (!NewThread(StartNode, NULL))
992 InitError(_("Error: could not start node"));
997 // ********************************************************* Step 13: IP collection thread
998 strCollectorCommand = GetArg("-peercollector", "");
999 if (!fTestNet && strCollectorCommand != "")
1000 NewThread(ThreadIPCollector, NULL);
1001 // ********************************************************* Step 14: finished
1003 uiInterface.InitMessage(_("Done loading"));
1004 printf("Done loading\n");
1006 if (!strErrors.str().empty())
1007 return InitError(strErrors.str());
1009 // Add wallet transactions that aren't already in a block to mapTransactions
1010 pwalletMain->ReacceptWalletTransactions();
1012 #if !defined(QT_GUI)
1013 // Loop until process is exit()ed from shutdown() function,
1014 // called from ThreadRPCServer thread when a "stop" command is received.