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"
13 #include "ipcollector.h"
14 #include "interface.h"
15 #include "checkpoints.h"
17 #include <boost/filesystem.hpp>
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>
33 CClientUIInterface uiInterface;
34 std::string strWalletFileName;
36 unsigned int nNodeLifespan;
39 enum Checkpoints::CPMode CheckpointsMode;
41 // Ping and address broadcast intervals
42 extern int64_t nPingInterval;
43 extern int64_t nReserveBalance;
45 //////////////////////////////////////////////////////////////////////////////
50 void ExitTimeout(void* parg)
61 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
62 uiInterface.QueueShutdown();
64 // Without UI, Shutdown() can simply be started in a new thread
65 NewThread(Shutdown, NULL);
69 void Shutdown(void* parg)
71 static CCriticalSection cs_Shutdown;
74 // Make this thread recognisable as the shutdown thread
75 RenameThread("novacoin-shutoff");
77 bool fFirstThread = false;
79 TRY_LOCK(cs_Shutdown, lockShutdown);
82 fFirstThread = !fTaken;
90 fRequestShutdown = true;
91 nTransactionsUpdated++;
97 boost::filesystem::remove(GetPidFile());
98 UnregisterWallet(pwalletMain);
100 NewThread(ExitTimeout, NULL);
102 printf("NovaCoin exited\n\n");
105 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
118 void HandleSIGTERM(int)
120 fRequestShutdown = true;
123 void HandleSIGHUP(int)
125 fReopenDebugLog = true;
132 //////////////////////////////////////////////////////////////////////////////
137 bool AppInit(int argc, char* argv[])
145 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
146 ParseParameters(argc, argv);
147 if (!boost::filesystem::is_directory(GetDataDir(false)))
149 fprintf(stderr, "Error: Specified directory does not exist\n");
152 ReadConfigFile(mapArgs, mapMultiArgs);
154 if (mapArgs.count("-?") || mapArgs.count("--help"))
156 // First part of help message is specific to bitcoind / RPC client
157 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
159 " novacoind [options] " + "\n" +
160 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
161 " novacoind [options] help " + _("List commands") + "\n" +
162 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
164 strUsage += "\n" + HelpMessage();
166 fprintf(stdout, "%s", strUsage.c_str());
171 for (int i = 1; i < argc; i++)
172 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
177 int ret = CommandLineRPC(argc, argv);
183 catch (std::exception& e) {
184 PrintException(&e, "AppInit()");
186 PrintException(NULL, "AppInit()");
193 extern void noui_connect();
194 int main(int argc, char* argv[])
197 // Connect bitcoind signal handlers
200 bool 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=<file> " + _("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 " -torname=<host.onion> " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
250 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
251 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
252 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
253 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
254 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
255 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
256 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
257 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
258 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
259 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
260 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
261 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
262 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
263 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
264 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
265 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
266 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
267 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
268 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
270 #ifdef DB_LOG_IN_MEMORY
271 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\n" +
274 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
275 " -mininput=<amt> " + (_("When creating transactions, ignore inputs with value less than this (default: ") + FormatMoney(MIN_TXOUT_AMOUNT) + ")") + "\n" +
277 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
279 #if !defined(WIN32) && !defined(QT_GUI)
280 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
282 " -testnet " + _("Use the test network") + "\n" +
283 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
284 " -debugnet " + _("Output extra network debugging information") + "\n" +
285 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
286 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
287 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
289 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
291 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
292 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
293 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
294 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
295 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
296 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
297 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
298 " -peercollector=<cmd> " + _("Execute command to collect peer addresses") + "\n" +
299 " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
300 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
301 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
302 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
303 " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n" +
304 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
305 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
306 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
307 " -par=N " + _("Set the number of script verification threads (1-16, 0=auto, default: 0)") + "\n" +
308 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
310 "\n" + _("Block creation options:") + "\n" +
311 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
312 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
313 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n";
318 /** Initialize bitcoin.
319 * @pre Parameters should be parsed and config file should be read.
323 // ********************************************************* Step 1: setup
325 // Turn off Microsoft heap dump noise
326 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
327 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
330 // Disable confusing "helpful" text message on abort, Ctrl-C
331 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
334 // Enable Data Execution Prevention (DEP)
335 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
336 // A failure is non-critical and needs no further attention!
337 #ifndef PROCESS_DEP_ENABLE
338 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
339 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
340 #define PROCESS_DEP_ENABLE 0x00000001
342 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
343 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
344 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
346 // Initialize Windows Sockets
348 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
351 return InitError(strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret));
357 // Clean shutdown on SIGTERM
359 sa.sa_handler = HandleSIGTERM;
360 sigemptyset(&sa.sa_mask);
362 sigaction(SIGTERM, &sa, NULL);
363 sigaction(SIGINT, &sa, NULL);
365 // Reopen debug.log on SIGHUP
366 struct sigaction sa_hup;
367 sa_hup.sa_handler = HandleSIGHUP;
368 sigemptyset(&sa_hup.sa_mask);
370 sigaction(SIGHUP, &sa_hup, NULL);
373 // ********************************************************* Step 2: parameter interactions
375 nNodeLifespan = GetArgUInt("-addrlifespan", 7);
376 fUseFastIndex = GetBoolArg("-fastindex", true);
377 fUseMemoryLog = GetBoolArg("-memorylog", true);
379 // Ping and address broadcast intervals
380 nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
382 CheckpointsMode = Checkpoints::STRICT;
383 std::string strCpMode = GetArg("-cppolicy", "strict");
385 if(strCpMode == "strict") {
386 CheckpointsMode = Checkpoints::STRICT;
389 if(strCpMode == "advisory") {
390 CheckpointsMode = Checkpoints::ADVISORY;
393 if(strCpMode == "permissive") {
394 CheckpointsMode = Checkpoints::PERMISSIVE;
397 fTestNet = GetBoolArg("-testnet");
399 SoftSetBoolArg("-irc", true);
402 if (mapArgs.count("-bind")) {
403 // when specifying an explicit binding address, you want to listen on it
404 // even when -connect or -proxy is specified
405 SoftSetBoolArg("-listen", true);
408 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
409 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
410 SoftSetBoolArg("-dnsseed", false);
411 SoftSetBoolArg("-listen", false);
414 if (mapArgs.count("-proxy")) {
415 // to protect privacy, do not listen by default if a proxy server is specified
416 SoftSetBoolArg("-listen", false);
419 if (!GetBoolArg("-listen", true)) {
420 // do not map ports or try to retrieve public IP when not listening (pointless)
421 SoftSetBoolArg("-discover", false);
424 if (mapArgs.count("-externalip")) {
425 // if an explicit public IP is specified, do not try to find others
426 SoftSetBoolArg("-discover", false);
429 if (GetBoolArg("-salvagewallet")) {
430 // Rewrite just private keys: rescan to find transactions
431 SoftSetBoolArg("-rescan", true);
434 if (GetBoolArg("-zapwallettxes", false)) {
435 // -zapwallettx implies a rescan
436 if (SoftSetBoolArg("-rescan", true))
437 printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
440 // ********************************************************* Step 3: parameter-to-internal-flags
442 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
443 nScriptCheckThreads = GetArgInt("-par", 0);
444 if (nScriptCheckThreads == 0)
445 nScriptCheckThreads = boost::thread::hardware_concurrency();
446 if (nScriptCheckThreads <= 1)
447 nScriptCheckThreads = 0;
448 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
449 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
451 fDebug = GetBoolArg("-debug");
453 // -debug implies fDebug*
457 fDebugNet = GetBoolArg("-debugnet");
459 bitdb.SetDetach(GetBoolArg("-detachdb", false));
461 #if !defined(WIN32) && !defined(QT_GUI)
462 fDaemon = GetBoolArg("-daemon");
470 fServer = GetBoolArg("-server");
472 /* force fServer when running without GUI */
476 fPrintToConsole = GetBoolArg("-printtoconsole");
477 fPrintToDebugger = GetBoolArg("-printtodebugger");
478 fLogTimestamps = GetBoolArg("-logtimestamps");
480 if (mapArgs.count("-timeout"))
482 int nNewTimeout = GetArgInt("-timeout", 5000);
483 if (nNewTimeout > 0 && nNewTimeout < 600000)
484 nConnectTimeout = nNewTimeout;
487 // Put client version data into coinbase flags.
488 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
490 if (mapArgs.count("-paytxfee"))
492 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
493 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
494 if (nTransactionFee > 0.25 * COIN)
495 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
498 fConfChange = GetBoolArg("-confchange", false);
500 if (mapArgs.count("-mininput"))
502 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
503 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
506 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
508 std::string strDataDir = GetDataDir().string();
509 strWalletFileName = GetArg("-wallet", "wallet.dat");
511 // strWalletFileName must be a plain filename without a directory
512 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
513 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
515 // Make sure only a single Bitcoin process is using the data directory.
516 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
517 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
518 if (file) fclose(file);
519 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
520 if (!lock.try_lock())
521 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
523 #if !defined(WIN32) && !defined(QT_GUI)
530 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
535 CreatePidFile(GetPidFile(), pid);
539 pid_t sid = setsid();
541 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
545 if (GetBoolArg("-shrinkdebugfile", !fDebug))
547 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
548 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
549 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
551 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
552 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
553 printf("Used data directory %s\n", strDataDir.c_str());
554 std::ostringstream strErrors;
557 fprintf(stdout, "NovaCoin server starting\n");
559 if (nScriptCheckThreads) {
560 printf("Using %u threads for script verification\n", nScriptCheckThreads);
561 for (int i=0; i<nScriptCheckThreads-1; i++)
562 NewThread(ThreadScriptCheck, NULL);
567 // ********************************************************* Step 5: verify database integrity
569 uiInterface.InitMessage(_("Verifying database integrity..."));
571 if (!bitdb.Open(GetDataDir()))
573 string msg = strprintf(_("Error initializing database environment %s!"
574 " To recover, BACKUP THAT DIRECTORY, then remove"
575 " everything from it except for wallet.dat."), strDataDir.c_str());
576 return InitError(msg);
579 if (GetBoolArg("-salvagewallet"))
581 // Recover readable keypairs:
582 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
586 if (boost::filesystem::exists(GetDataDir() / strWalletFileName))
588 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
589 if (r == CDBEnv::RECOVER_OK)
591 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
592 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
593 " your balance or transactions are incorrect you should"
594 " restore from a backup."), strDataDir.c_str());
595 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
597 if (r == CDBEnv::RECOVER_FAIL)
598 return InitError(_("wallet.dat corrupt, salvage failed"));
601 // ********************************************************* Step 6: network initialization
603 int nSocksVersion = GetArgInt("-socks", 5);
605 if (nSocksVersion != 4 && nSocksVersion != 5)
606 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
608 if (mapArgs.count("-onlynet")) {
609 std::set<enum Network> nets;
610 for (std::string snet : mapMultiArgs["-onlynet"]) {
611 enum Network net = ParseNetwork(snet);
612 if (net == NET_UNROUTABLE)
613 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
616 for (int n = 0; n < NET_MAX; n++) {
617 enum Network net = (enum Network)n;
618 if (!nets.count(net))
622 #if defined(USE_IPV6)
625 SetLimited(NET_IPV6);
631 if (mapArgs.count("-proxy")) {
632 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
633 if (!addrProxy.IsValid())
634 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
636 if (!IsLimited(NET_IPV4))
637 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
638 if (nSocksVersion > 4) {
640 if (!IsLimited(NET_IPV6))
641 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
643 SetNameProxy(addrProxy, nSocksVersion);
648 // -tor can override normal proxy, -notor disables tor entirely
649 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
651 if (!mapArgs.count("-tor"))
652 addrOnion = addrProxy;
654 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
655 if (!addrOnion.IsValid())
656 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
657 SetProxy(NET_TOR, addrOnion, 5);
658 SetReachable(NET_TOR);
661 // see Step 2: parameter interactions for more information about these
662 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
664 fNoListen = !GetBoolArg("-listen", true);
665 fDiscover = GetBoolArg("-discover", true);
666 fNameLookup = GetBoolArg("-dns", true);
668 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
670 fDiscover = fNameLookup = false;
671 SoftSetBoolArg("-irc", false);
672 SoftSetBoolArg("-dnsseed", false);
678 std::string strError;
679 if (mapArgs.count("-bind")) {
680 for(std::string strBind : mapMultiArgs["-bind"]) {
682 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
683 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
684 fBound |= Bind(addrBind);
687 struct in_addr inaddr_any;
688 inaddr_any.s_addr = INADDR_ANY;
690 if (!IsLimited(NET_IPV6))
691 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
693 if (!IsLimited(NET_IPV4))
694 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
698 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
701 // If Tor is reachable then listen on loopback interface,
702 // to allow allow other users reach you through the hidden service
703 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
704 std::string strError;
705 struct in_addr inaddr_loopback;
706 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
709 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
710 return InitError(strError);
712 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
713 return InitError(strError);
716 if (mapArgs.count("-externalip"))
718 for (string strAddr : mapMultiArgs["-externalip"]) {
719 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
720 if (!addrLocal.IsValid())
721 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
722 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
726 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
728 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
730 InitError(_("Invalid amount for -reservebalance=<amount>"));
735 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
737 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
738 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
741 for (string strDest : mapMultiArgs["-seednode"])
744 // ********************************************************* Step 7: load blockchain
746 if (!bitdb.Open(GetDataDir()))
748 string msg = strprintf(_("Error initializing database environment %s!"
749 " To recover, BACKUP THAT DIRECTORY, then remove"
750 " everything from it except for wallet.dat."), strDataDir.c_str());
751 return InitError(msg);
754 if (GetBoolArg("-loadblockindextest"))
757 txdb.LoadBlockIndex();
763 printf("Loading block index...\n");
764 bool fLoaded = false;
766 std::string strLoadError;
767 uiInterface.InitMessage(_("Loading block index..."));
769 nStart = GetTimeMillis();
774 if (!LoadBlockIndex()) {
775 strLoadError = _("Error loading block database");
778 } catch(const std::exception&) {
779 strLoadError = _("Error opening block database");
787 // TODO: suggest reindex here
788 return InitError(strLoadError);
792 // as LoadBlockIndex can take several minutes, it's possible the user
793 // requested to kill bitcoin-qt during the last operation. If so, exit.
794 // As the program has not fully started yet, Shutdown() is possibly overkill.
795 if (fRequestShutdown)
797 printf("Shutdown requested. Exiting.\n");
800 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
802 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
808 if (mapArgs.count("-printblock"))
810 string strMatch = mapArgs["-printblock"];
812 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
814 uint256 hash = (*mi).first;
815 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
817 CBlockIndex* pindex = (*mi).second;
819 block.ReadFromDisk(pindex);
820 block.BuildMerkleTree();
827 printf("No blocks matching %s were found\n", strMatch.c_str());
831 // ********************************************************* Step 8: load wallet
833 if (GetBoolArg("-zapwallettxes", false)) {
834 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
836 pwalletMain = new CWallet(strWalletFileName);
837 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
838 if (nZapWalletRet != DB_LOAD_OK) {
839 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
846 uiInterface.InitMessage(_("Loading wallet..."));
847 printf("Loading wallet...\n");
848 nStart = GetTimeMillis();
849 bool fFirstRun = true;
850 pwalletMain = new CWallet(strWalletFileName);
851 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
852 if (nLoadWalletRet != DB_LOAD_OK)
854 if (nLoadWalletRet == DB_CORRUPT)
855 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
856 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
858 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
859 " or address book entries might be missing or incorrect."));
860 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
862 else if (nLoadWalletRet == DB_TOO_NEW)
863 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
864 else if (nLoadWalletRet == DB_NEED_REWRITE)
866 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
867 printf("%s", strErrors.str().c_str());
868 return InitError(strErrors.str());
871 strErrors << _("Error loading wallet.dat") << "\n";
874 if (GetBoolArg("-upgradewallet", fFirstRun))
876 int nMaxVersion = GetArgInt("-upgradewallet", 0);
877 if (nMaxVersion == 0) // the -upgradewallet without argument case
879 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
880 nMaxVersion = CLIENT_VERSION;
881 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
884 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
885 if (nMaxVersion < pwalletMain->GetVersion())
886 strErrors << _("Cannot downgrade wallet") << "\n";
887 pwalletMain->SetMaxVersion(nMaxVersion);
892 // Create new keyUser and set as default key
893 RandAddSeedPerfmon();
895 CPubKey newDefaultKey;
896 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
897 strErrors << _("Cannot initialize keypool") << "\n";
898 pwalletMain->SetDefaultKey(newDefaultKey);
899 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
900 strErrors << _("Cannot write default address") << "\n";
902 CMalleableKeyView keyView = pwalletMain->GenerateNewMalleableKey();
904 if (!pwalletMain->GetMalleableKey(keyView, mKey))
905 strErrors << _("Unable to generate new malleable key");
906 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
907 strErrors << _("Cannot write default address") << "\n";
910 printf("%s", strErrors.str().c_str());
911 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
913 RegisterWallet(pwalletMain);
915 CBlockIndex *pindexRescan = pindexBest;
916 if (GetBoolArg("-rescan"))
917 pindexRescan = pindexGenesisBlock;
920 CWalletDB walletdb(strWalletFileName);
921 CBlockLocator locator;
922 if (walletdb.ReadBestBlock(locator))
923 pindexRescan = locator.GetBlockIndex();
925 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
927 uiInterface.InitMessage(_("Rescanning..."));
928 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
929 nStart = GetTimeMillis();
930 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
931 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
934 // ********************************************************* Step 9: import blocks
936 if (mapArgs.count("-loadblock"))
938 uiInterface.InitMessage(_("Importing blockchain data file."));
940 for (string strFile : mapMultiArgs["-loadblock"])
942 FILE *file = fopen(strFile.c_str(), "rb");
944 LoadExternalBlockFile(file);
949 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
950 if (boost::filesystem::exists(pathBootstrap)) {
951 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
953 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
955 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
956 LoadExternalBlockFile(file);
957 RenameOver(pathBootstrap, pathBootstrapOld);
961 // ********************************************************* Step 10: load peers
963 uiInterface.InitMessage(_("Loading addresses..."));
964 printf("Loading addresses...\n");
965 nStart = GetTimeMillis();
969 if (!adb.Read(addrman))
970 printf("Invalid or missing peers.dat; recreating\n");
973 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
974 addrman.size(), GetTimeMillis() - nStart);
976 // ********************************************************* Step 11: start node
978 if (!CheckDiskSpace())
981 RandAddSeedPerfmon();
984 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
985 printf("nBestHeight = %d\n", nBestHeight);
986 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
987 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
988 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
990 if (!NewThread(StartNode, NULL))
991 InitError(_("Error: could not start node"));
996 // ********************************************************* Step 13: IP collection thread
997 strCollectorCommand = GetArg("-peercollector", "");
998 if (!fTestNet && strCollectorCommand != "")
999 NewThread(ThreadIPCollector, NULL);
1000 // ********************************************************* Step 14: finished
1002 uiInterface.InitMessage(_("Done loading"));
1003 printf("Done loading\n");
1005 if (!strErrors.str().empty())
1006 return InitError(strErrors.str());
1008 // Add wallet transactions that aren't already in a block to mapTransactions
1009 pwalletMain->ReacceptWalletTransactions();
1011 #if !defined(QT_GUI)
1012 // Loop until process is exit()ed from shutdown() function,
1013 // called from ThreadRPCServer thread when a "stop" command is received.