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/fstream.hpp>
19 #include <boost/filesystem/convenience.hpp>
20 #include <boost/interprocess/sync/file_lock.hpp>
21 #include <boost/algorithm/string/predicate.hpp>
22 #include <openssl/crypto.h>
30 CClientUIInterface uiInterface;
31 std::string strWalletFileName;
33 unsigned int nNodeLifespan;
36 enum Checkpoints::CPMode CheckpointsMode;
38 // Ping and address broadcast intervals
39 extern int64_t nPingInterval;
40 extern int64_t nReserveBalance;
42 //////////////////////////////////////////////////////////////////////////////
47 void ExitTimeout(void* parg)
58 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
59 uiInterface.QueueShutdown();
61 // Without UI, Shutdown() can simply be started in a new thread
62 NewThread(Shutdown, NULL);
66 void Shutdown(void* parg)
68 static CCriticalSection cs_Shutdown;
71 // Make this thread recognisable as the shutdown thread
72 RenameThread("novacoin-shutoff");
74 bool fFirstThread = false;
76 TRY_LOCK(cs_Shutdown, lockShutdown);
79 fFirstThread = !fTaken;
87 fRequestShutdown = true;
88 nTransactionsUpdated++;
94 boost::filesystem::remove(GetPidFile());
95 UnregisterWallet(pwalletMain);
97 NewThread(ExitTimeout, NULL);
99 printf("NovaCoin exited\n\n");
102 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
115 void HandleSIGTERM(int)
117 fRequestShutdown = true;
120 void HandleSIGHUP(int)
122 fReopenDebugLog = true;
129 //////////////////////////////////////////////////////////////////////////////
134 bool AppInit(int argc, char* argv[])
142 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
143 ParseParameters(argc, argv);
144 if (!boost::filesystem::is_directory(GetDataDir(false)))
146 fprintf(stderr, "Error: Specified directory does not exist\n");
149 ReadConfigFile(mapArgs, mapMultiArgs);
151 if (mapArgs.count("-?") || mapArgs.count("--help"))
153 // First part of help message is specific to bitcoind / RPC client
154 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
156 " novacoind [options] " + "\n" +
157 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
158 " novacoind [options] help " + _("List commands") + "\n" +
159 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
161 strUsage += "\n" + HelpMessage();
163 fprintf(stdout, "%s", strUsage.c_str());
168 for (int i = 1; i < argc; i++)
169 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
174 int ret = CommandLineRPC(argc, argv);
180 catch (std::exception& e) {
181 PrintException(&e, "AppInit()");
183 PrintException(NULL, "AppInit()");
190 extern void noui_connect();
191 int main(int argc, char* argv[])
194 // Connect bitcoind signal handlers
197 bool fRet = AppInit(argc, argv);
206 bool static InitError(const std::string &str)
208 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
212 bool static InitWarning(const std::string &str)
214 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
219 bool static Bind(const CService &addr, bool fError = true) {
222 std::string strError;
223 if (!BindListenPort(addr, strError)) {
225 return InitError(strError);
231 // Core-specific options shared between UI and daemon
232 std::string HelpMessage()
234 std::string strUsage = _("Options:") + "\n" +
235 " -? " + _("This help message") + "\n" +
236 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
237 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
238 " -datadir=<dir> " + _("Specify data directory") + "\n" +
239 " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n" +
240 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
241 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
242 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
243 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
244 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
245 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
246 " -torname=<host.onion> " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
247 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
248 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
249 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
250 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
251 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
252 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
253 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
254 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
255 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
256 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
257 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
258 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
259 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
260 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
261 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
262 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
263 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
264 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
266 #ifdef DB_LOG_IN_MEMORY
267 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\n" +
270 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
271 " -mininput=<amt> " + (_("When creating transactions, ignore inputs with value less than this (default: ") + FormatMoney(MIN_TXOUT_AMOUNT) + ")") + "\n" +
273 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
275 #if !defined(WIN32) && !defined(QT_GUI)
276 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
278 " -testnet " + _("Use the test network") + "\n" +
279 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
280 " -debugnet " + _("Output extra network debugging information") + "\n" +
281 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
282 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
283 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
285 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
287 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
288 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
289 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
290 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
291 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
292 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
293 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
294 " -peercollector=<cmd> " + _("Execute command to collect peer addresses") + "\n" +
295 " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
296 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
297 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
298 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
299 " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n" +
300 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
301 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
302 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
303 " -par=N " + _("Set the number of script verification threads (1-16, 0=auto, default: 0)") + "\n" +
304 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
306 "\n" + _("Block creation options:") + "\n" +
307 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
308 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
309 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\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);
342 // Initialize Windows Sockets
344 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
347 return InitError(strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret));
353 // Clean shutdown on SIGTERM
355 sa.sa_handler = HandleSIGTERM;
356 sigemptyset(&sa.sa_mask);
358 sigaction(SIGTERM, &sa, NULL);
359 sigaction(SIGINT, &sa, NULL);
361 // Reopen debug.log on SIGHUP
362 struct sigaction sa_hup;
363 sa_hup.sa_handler = HandleSIGHUP;
364 sigemptyset(&sa_hup.sa_mask);
366 sigaction(SIGHUP, &sa_hup, NULL);
369 // ********************************************************* Step 2: parameter interactions
371 nNodeLifespan = GetArgUInt("-addrlifespan", 7);
372 fUseFastIndex = GetBoolArg("-fastindex", true);
373 fUseMemoryLog = GetBoolArg("-memorylog", true);
375 // Ping and address broadcast intervals
376 nPingInterval = std::max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
378 CheckpointsMode = Checkpoints::STRICT;
379 std::string strCpMode = GetArg("-cppolicy", "strict");
381 if(strCpMode == "strict") {
382 CheckpointsMode = Checkpoints::STRICT;
385 if(strCpMode == "advisory") {
386 CheckpointsMode = Checkpoints::ADVISORY;
389 if(strCpMode == "permissive") {
390 CheckpointsMode = Checkpoints::PERMISSIVE;
393 fTestNet = GetBoolArg("-testnet");
395 SoftSetBoolArg("-irc", true);
398 if (mapArgs.count("-bind")) {
399 // when specifying an explicit binding address, you want to listen on it
400 // even when -connect or -proxy is specified
401 SoftSetBoolArg("-listen", true);
404 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
405 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
406 SoftSetBoolArg("-dnsseed", false);
407 SoftSetBoolArg("-listen", false);
410 if (mapArgs.count("-proxy")) {
411 // to protect privacy, do not listen by default if a proxy server is specified
412 SoftSetBoolArg("-listen", false);
415 if (!GetBoolArg("-listen", true)) {
416 // do not map ports or try to retrieve public IP when not listening (pointless)
417 SoftSetBoolArg("-discover", false);
420 if (mapArgs.count("-externalip")) {
421 // if an explicit public IP is specified, do not try to find others
422 SoftSetBoolArg("-discover", false);
425 if (GetBoolArg("-salvagewallet")) {
426 // Rewrite just private keys: rescan to find transactions
427 SoftSetBoolArg("-rescan", true);
430 if (GetBoolArg("-zapwallettxes", false)) {
431 // -zapwallettx implies a rescan
432 if (SoftSetBoolArg("-rescan", true))
433 printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
436 // ********************************************************* Step 3: parameter-to-internal-flags
438 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
439 nScriptCheckThreads = GetArgInt("-par", 0);
440 if (nScriptCheckThreads == 0)
441 nScriptCheckThreads = boost::thread::hardware_concurrency();
442 if (nScriptCheckThreads <= 1)
443 nScriptCheckThreads = 0;
444 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
445 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
447 fDebug = GetBoolArg("-debug");
449 // -debug implies fDebug*
453 fDebugNet = GetBoolArg("-debugnet");
455 #if !defined(WIN32) && !defined(QT_GUI)
456 fDaemon = GetBoolArg("-daemon");
464 fServer = GetBoolArg("-server");
466 /* force fServer when running without GUI */
470 fPrintToConsole = GetBoolArg("-printtoconsole");
471 fPrintToDebugger = GetBoolArg("-printtodebugger");
472 fLogTimestamps = GetBoolArg("-logtimestamps");
474 if (mapArgs.count("-timeout"))
476 int nNewTimeout = GetArgInt("-timeout", 5000);
477 if (nNewTimeout > 0 && nNewTimeout < 600000)
478 nConnectTimeout = nNewTimeout;
481 // Put client version data into coinbase flags.
482 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
484 if (mapArgs.count("-paytxfee"))
486 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
487 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
488 if (nTransactionFee > 0.25 * COIN)
489 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
492 fConfChange = GetBoolArg("-confchange", false);
494 if (mapArgs.count("-mininput"))
496 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
497 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
500 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
502 std::string strDataDir = GetDataDir().string();
503 strWalletFileName = GetArg("-wallet", "wallet.dat");
505 // strWalletFileName must be a plain filename without a directory
506 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
507 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
509 // Make sure only a single Bitcoin process is using the data directory.
510 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
511 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
512 if (file) fclose(file);
513 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
514 if (!lock.try_lock())
515 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
517 #if !defined(WIN32) && !defined(QT_GUI)
524 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
529 CreatePidFile(GetPidFile(), pid);
533 pid_t sid = setsid();
535 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
539 if (GetBoolArg("-shrinkdebugfile", !fDebug))
541 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
542 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
543 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
545 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
546 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
547 printf("Used data directory %s\n", strDataDir.c_str());
548 std::ostringstream strErrors;
551 fprintf(stdout, "NovaCoin server starting\n");
553 if (nScriptCheckThreads) {
554 printf("Using %u threads for script verification\n", nScriptCheckThreads);
555 for (int i=0; i<nScriptCheckThreads-1; i++)
556 NewThread(ThreadScriptCheck, NULL);
561 // ********************************************************* Step 5: verify database integrity
563 uiInterface.InitMessage(_("Verifying database integrity..."));
565 if (!bitdb.Open(GetDataDir()))
567 std::string msg = strprintf(_("Error initializing database environment %s!"
568 " To recover, BACKUP THAT DIRECTORY, then remove"
569 " everything from it except for wallet.dat."), strDataDir.c_str());
570 return InitError(msg);
573 if (GetBoolArg("-salvagewallet"))
575 // Recover readable keypairs:
576 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
580 if (boost::filesystem::exists(GetDataDir() / strWalletFileName))
582 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
583 if (r == CDBEnv::RECOVER_OK)
585 std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
586 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
587 " your balance or transactions are incorrect you should"
588 " restore from a backup."), strDataDir.c_str());
589 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
591 if (r == CDBEnv::RECOVER_FAIL)
592 return InitError(_("wallet.dat corrupt, salvage failed"));
595 // ********************************************************* Step 6: network initialization
597 int nSocksVersion = GetArgInt("-socks", 5);
599 if (nSocksVersion != 4 && nSocksVersion != 5)
600 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
602 if (mapArgs.count("-onlynet")) {
603 std::set<enum Network> nets;
604 for (std::string snet : mapMultiArgs["-onlynet"]) {
605 enum Network net = ParseNetwork(snet);
606 if (net == NET_UNROUTABLE)
607 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
610 for (int n = 0; n < NET_MAX; n++) {
611 enum Network net = (enum Network)n;
612 if (!nets.count(net))
616 #if defined(USE_IPV6)
619 SetLimited(NET_IPV6);
625 if (mapArgs.count("-proxy")) {
626 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
627 if (!addrProxy.IsValid())
628 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
630 if (!IsLimited(NET_IPV4))
631 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
632 if (nSocksVersion > 4) {
634 if (!IsLimited(NET_IPV6))
635 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
637 SetNameProxy(addrProxy, nSocksVersion);
642 // -tor can override normal proxy, -notor disables tor entirely
643 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
645 if (!mapArgs.count("-tor"))
646 addrOnion = addrProxy;
648 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
649 if (!addrOnion.IsValid())
650 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
651 SetProxy(NET_TOR, addrOnion, 5);
652 SetReachable(NET_TOR);
655 // see Step 2: parameter interactions for more information about these
656 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
658 fNoListen = !GetBoolArg("-listen", true);
659 fDiscover = GetBoolArg("-discover", true);
660 fNameLookup = GetBoolArg("-dns", true);
662 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
664 fDiscover = fNameLookup = false;
665 SoftSetBoolArg("-irc", false);
666 SoftSetBoolArg("-dnsseed", false);
672 std::string strError;
673 if (mapArgs.count("-bind")) {
674 for(std::string strBind : mapMultiArgs["-bind"]) {
676 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
677 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
678 fBound |= Bind(addrBind);
681 struct in_addr inaddr_any;
682 inaddr_any.s_addr = INADDR_ANY;
684 if (!IsLimited(NET_IPV6))
685 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
687 if (!IsLimited(NET_IPV4))
688 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
692 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
695 // If Tor is reachable then listen on loopback interface,
696 // to allow allow other users reach you through the hidden service
697 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
698 std::string strError;
699 struct in_addr inaddr_loopback;
700 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
703 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
704 return InitError(strError);
706 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
707 return InitError(strError);
710 if (mapArgs.count("-externalip"))
712 for (std::string strAddr : mapMultiArgs["-externalip"]) {
713 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
714 if (!addrLocal.IsValid())
715 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
716 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
720 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
722 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
724 InitError(_("Invalid amount for -reservebalance=<amount>"));
729 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
731 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
732 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
735 for (std::string strDest : mapMultiArgs["-seednode"])
738 // ********************************************************* Step 7: load blockchain
740 if (!bitdb.Open(GetDataDir()))
742 std::string msg = strprintf(_("Error initializing database environment %s!"
743 " To recover, BACKUP THAT DIRECTORY, then remove"
744 " everything from it except for wallet.dat."), strDataDir.c_str());
745 return InitError(msg);
748 if (GetBoolArg("-loadblockindextest"))
751 txdb.LoadBlockIndex();
757 printf("Loading block index...\n");
758 bool fLoaded = false;
760 std::string strLoadError;
761 uiInterface.InitMessage(_("Loading block index..."));
763 nStart = GetTimeMillis();
768 if (!LoadBlockIndex()) {
769 strLoadError = _("Error loading block database");
772 } catch(const std::exception&) {
773 strLoadError = _("Error opening block database");
781 // TODO: suggest reindex here
782 return InitError(strLoadError);
786 // as LoadBlockIndex can take several minutes, it's possible the user
787 // requested to kill bitcoin-qt during the last operation. If so, exit.
788 // As the program has not fully started yet, Shutdown() is possibly overkill.
789 if (fRequestShutdown)
791 printf("Shutdown requested. Exiting.\n");
794 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
796 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
802 if (mapArgs.count("-printblock"))
804 std::string strMatch = mapArgs["-printblock"];
806 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
808 uint256 hash = (*mi).first;
809 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
811 CBlockIndex* pindex = (*mi).second;
813 block.ReadFromDisk(pindex);
814 block.BuildMerkleTree();
821 printf("No blocks matching %s were found\n", strMatch.c_str());
825 // ********************************************************* Step 8: load wallet
827 if (GetBoolArg("-zapwallettxes", false)) {
828 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
830 pwalletMain = new CWallet(strWalletFileName);
831 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
832 if (nZapWalletRet != DB_LOAD_OK) {
833 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
840 uiInterface.InitMessage(_("Loading wallet..."));
841 printf("Loading wallet...\n");
842 nStart = GetTimeMillis();
843 bool fFirstRun = true;
844 pwalletMain = new CWallet(strWalletFileName);
845 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
846 if (nLoadWalletRet != DB_LOAD_OK)
848 if (nLoadWalletRet == DB_CORRUPT)
849 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
850 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
852 std::string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
853 " or address book entries might be missing or incorrect."));
854 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
856 else if (nLoadWalletRet == DB_TOO_NEW)
857 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
858 else if (nLoadWalletRet == DB_NEED_REWRITE)
860 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
861 printf("%s", strErrors.str().c_str());
862 return InitError(strErrors.str());
865 strErrors << _("Error loading wallet.dat") << "\n";
868 if (GetBoolArg("-upgradewallet", fFirstRun))
870 int nMaxVersion = GetArgInt("-upgradewallet", 0);
871 if (nMaxVersion == 0) // the -upgradewallet without argument case
873 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
874 nMaxVersion = CLIENT_VERSION;
875 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
878 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
879 if (nMaxVersion < pwalletMain->GetVersion())
880 strErrors << _("Cannot downgrade wallet") << "\n";
881 pwalletMain->SetMaxVersion(nMaxVersion);
886 // Create new keyUser and set as default key
887 RandAddSeedPerfmon();
889 CPubKey newDefaultKey;
890 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
891 strErrors << _("Cannot initialize keypool") << "\n";
892 pwalletMain->SetDefaultKey(newDefaultKey);
893 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
894 strErrors << _("Cannot write default address") << "\n";
896 CMalleableKeyView keyView = pwalletMain->GenerateNewMalleableKey();
898 if (!pwalletMain->GetMalleableKey(keyView, mKey))
899 strErrors << _("Unable to generate new malleable key");
900 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
901 strErrors << _("Cannot write default address") << "\n";
904 printf("%s", strErrors.str().c_str());
905 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
907 RegisterWallet(pwalletMain);
909 CBlockIndex *pindexRescan = pindexBest;
910 if (GetBoolArg("-rescan"))
911 pindexRescan = pindexGenesisBlock;
914 CWalletDB walletdb(strWalletFileName);
915 CBlockLocator locator;
916 if (walletdb.ReadBestBlock(locator))
917 pindexRescan = locator.GetBlockIndex();
919 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
921 uiInterface.InitMessage(_("Rescanning..."));
922 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
923 nStart = GetTimeMillis();
924 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
925 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
928 // ********************************************************* Step 9: import blocks
930 if (mapArgs.count("-loadblock"))
932 uiInterface.InitMessage(_("Importing blockchain data file."));
934 for (std::string strFile : mapMultiArgs["-loadblock"])
936 FILE *file = fopen(strFile.c_str(), "rb");
938 LoadExternalBlockFile(file);
943 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
944 if (boost::filesystem::exists(pathBootstrap)) {
945 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
947 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
949 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
950 LoadExternalBlockFile(file);
951 RenameOver(pathBootstrap, pathBootstrapOld);
955 // ********************************************************* Step 10: load peers
957 uiInterface.InitMessage(_("Loading addresses..."));
958 printf("Loading addresses...\n");
959 nStart = GetTimeMillis();
962 CAddrDB::SetMessageStart(pchMessageStart);
964 if (!adb.Read(addrman))
965 printf("Invalid or missing peers.dat; recreating\n");
968 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
969 addrman.size(), GetTimeMillis() - nStart);
971 // ********************************************************* Step 11: start node
973 if (!CheckDiskSpace())
976 RandAddSeedPerfmon();
979 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
980 printf("nBestHeight = %d\n", nBestHeight);
981 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
982 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
983 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
985 if (!NewThread(StartNode, NULL))
986 InitError(_("Error: could not start node"));
991 // ********************************************************* Step 13: IP collection thread
992 strCollectorCommand = GetArg("-peercollector", "");
993 if (!fTestNet && strCollectorCommand != "")
994 NewThread(ThreadIPCollector, NULL);
995 // ********************************************************* Step 14: finished
997 uiInterface.InitMessage(_("Done loading"));
998 printf("Done loading\n");
1000 if (!strErrors.str().empty())
1001 return InitError(strErrors.str());
1003 // Add wallet transactions that aren't already in a block to mapTransactions
1004 pwalletMain->ReacceptWalletTransactions();
1006 #if !defined(QT_GUI)
1007 // Loop until process is exit()ed from shutdown() function,
1008 // called from ThreadRPCServer thread when a "stop" command is received.