1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "bitcoinrpc.h"
11 #include "ui_interface.h"
12 #include "checkpoints.h"
13 #include <boost/format.hpp>
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/filesystem/convenience.hpp>
17 #include <boost/interprocess/sync/file_lock.hpp>
18 #include <boost/algorithm/string/predicate.hpp>
19 #include <openssl/crypto.h>
27 using namespace boost;
30 CClientUIInterface uiInterface;
31 std::string strWalletFileName;
33 unsigned int nNodeLifespan;
36 enum Checkpoints::CPMode CheckpointsMode;
38 // Ping and address broadcast intervals
39 extern int64_t nPingInterval;
40 extern int64_t nBroadcastInterval;
41 extern int64_t nReserveBalance;
43 //////////////////////////////////////////////////////////////////////////////
48 void ExitTimeout(void* parg)
59 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
60 uiInterface.QueueShutdown();
62 // Without UI, Shutdown() can simply be started in a new thread
63 NewThread(Shutdown, NULL);
67 void Shutdown(void* parg)
69 static CCriticalSection cs_Shutdown;
72 // Make this thread recognisable as the shutdown thread
73 RenameThread("novacoin-shutoff");
75 bool fFirstThread = false;
77 TRY_LOCK(cs_Shutdown, lockShutdown);
80 fFirstThread = !fTaken;
88 fRequestShutdown = true;
89 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 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" +
265 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
267 #ifdef DB_LOG_IN_MEMORY
268 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\n" +
271 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
272 " -mininput=<amt> " + str(boost::format(_("When creating transactions, ignore inputs with value less than this (default: %s)")) % FormatMoney(MIN_TXOUT_AMOUNT)) + "\n" +
274 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
276 #if !defined(WIN32) && !defined(QT_GUI)
277 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
279 " -testnet " + _("Use the test network") + "\n" +
280 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
281 " -debugnet " + _("Output extra network debugging information") + "\n" +
282 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
283 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
284 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
286 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
288 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
289 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
290 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
291 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
292 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
293 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
294 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\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" +
311 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
312 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
313 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
314 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
315 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
320 /** Initialize bitcoin.
321 * @pre Parameters should be parsed and config file should be read.
325 // ********************************************************* Step 1: setup
327 // Turn off Microsoft heap dump noise
328 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
329 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
332 // Disable confusing "helpful" text message on abort, Ctrl-C
333 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
336 // Enable Data Execution Prevention (DEP)
337 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
338 // A failure is non-critical and needs no further attention!
339 #ifndef PROCESS_DEP_ENABLE
340 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
341 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
342 #define PROCESS_DEP_ENABLE 0x00000001
344 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
345 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
346 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
351 // Clean shutdown on SIGTERM
353 sa.sa_handler = HandleSIGTERM;
354 sigemptyset(&sa.sa_mask);
356 sigaction(SIGTERM, &sa, NULL);
357 sigaction(SIGINT, &sa, NULL);
359 // Reopen debug.log on SIGHUP
360 struct sigaction sa_hup;
361 sa_hup.sa_handler = HandleSIGHUP;
362 sigemptyset(&sa_hup.sa_mask);
364 sigaction(SIGHUP, &sa_hup, NULL);
367 // ********************************************************* Step 2: parameter interactions
369 nNodeLifespan = (unsigned int)(GetArg("-addrlifespan", 7));
370 fUseFastIndex = GetBoolArg("-fastindex", true);
371 fUseMemoryLog = GetBoolArg("-memorylog", true);
373 // Ping and address broadcast intervals
374 nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
375 nBroadcastInterval = max<int64_t>(6 * nOneHour, GetArg("-addrsetlifetime", nOneDay));
377 CheckpointsMode = Checkpoints::STRICT;
378 std::string strCpMode = GetArg("-cppolicy", "strict");
380 if(strCpMode == "strict") {
381 CheckpointsMode = Checkpoints::STRICT;
384 if(strCpMode == "advisory") {
385 CheckpointsMode = Checkpoints::ADVISORY;
388 if(strCpMode == "permissive") {
389 CheckpointsMode = Checkpoints::PERMISSIVE;
392 fTestNet = GetBoolArg("-testnet");
394 SoftSetBoolArg("-irc", true);
397 if (mapArgs.count("-bind")) {
398 // when specifying an explicit binding address, you want to listen on it
399 // even when -connect or -proxy is specified
400 SoftSetBoolArg("-listen", true);
403 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
404 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
405 SoftSetBoolArg("-dnsseed", false);
406 SoftSetBoolArg("-listen", false);
409 if (mapArgs.count("-proxy")) {
410 // to protect privacy, do not listen by default if a proxy server is specified
411 SoftSetBoolArg("-listen", false);
414 if (!GetBoolArg("-listen", true)) {
415 // do not map ports or try to retrieve public IP when not listening (pointless)
416 SoftSetBoolArg("-discover", false);
419 if (mapArgs.count("-externalip")) {
420 // if an explicit public IP is specified, do not try to find others
421 SoftSetBoolArg("-discover", false);
424 if (GetBoolArg("-salvagewallet")) {
425 // Rewrite just private keys: rescan to find transactions
426 SoftSetBoolArg("-rescan", true);
429 if (GetBoolArg("-zapwallettxes", false)) {
430 // -zapwallettx implies a rescan
431 if (SoftSetBoolArg("-rescan", true))
432 printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
435 // ********************************************************* Step 3: parameter-to-internal-flags
437 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
438 nScriptCheckThreads = GetArgInt("-par", 0);
439 if (nScriptCheckThreads == 0)
440 nScriptCheckThreads = boost::thread::hardware_concurrency();
441 if (nScriptCheckThreads <= 1)
442 nScriptCheckThreads = 0;
443 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
444 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
446 fDebug = GetBoolArg("-debug");
448 // -debug implies fDebug*
452 fDebugNet = GetBoolArg("-debugnet");
454 bitdb.SetDetach(GetBoolArg("-detachdb", false));
456 #if !defined(WIN32) && !defined(QT_GUI)
457 fDaemon = GetBoolArg("-daemon");
465 fServer = GetBoolArg("-server");
467 /* force fServer when running without GUI */
471 fPrintToConsole = GetBoolArg("-printtoconsole");
472 fPrintToDebugger = GetBoolArg("-printtodebugger");
473 fLogTimestamps = GetBoolArg("-logtimestamps");
475 if (mapArgs.count("-timeout"))
477 int nNewTimeout = GetArgInt("-timeout", 5000);
478 if (nNewTimeout > 0 && nNewTimeout < 600000)
479 nConnectTimeout = nNewTimeout;
482 // Put client version data into coinbase flags.
483 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
485 if (mapArgs.count("-paytxfee"))
487 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
488 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
489 if (nTransactionFee > 0.25 * COIN)
490 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
493 fConfChange = GetBoolArg("-confchange", false);
495 if (mapArgs.count("-mininput"))
497 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
498 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
501 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
503 std::string strDataDir = GetDataDir().string();
504 strWalletFileName = GetArg("-wallet", "wallet.dat");
506 // strWalletFileName must be a plain filename without a directory
507 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
508 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
510 // Make sure only a single Bitcoin process is using the data directory.
511 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
512 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
513 if (file) fclose(file);
514 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
515 if (!lock.try_lock())
516 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
518 #if !defined(WIN32) && !defined(QT_GUI)
525 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
530 CreatePidFile(GetPidFile(), pid);
534 pid_t sid = setsid();
536 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
540 if (GetBoolArg("-shrinkdebugfile", !fDebug))
542 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
543 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
544 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
546 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
547 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
548 printf("Used data directory %s\n", strDataDir.c_str());
549 std::ostringstream strErrors;
552 fprintf(stdout, "NovaCoin server starting\n");
554 if (nScriptCheckThreads) {
555 printf("Using %u threads for script verification\n", nScriptCheckThreads);
556 for (int i=0; i<nScriptCheckThreads-1; i++)
557 NewThread(ThreadScriptCheck, NULL);
562 // ********************************************************* Step 5: verify database integrity
564 uiInterface.InitMessage(_("Verifying database integrity..."));
566 if (!bitdb.Open(GetDataDir()))
568 string msg = strprintf(_("Error initializing database environment %s!"
569 " To recover, BACKUP THAT DIRECTORY, then remove"
570 " everything from it except for wallet.dat."), strDataDir.c_str());
571 return InitError(msg);
574 if (GetBoolArg("-salvagewallet"))
576 // Recover readable keypairs:
577 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
581 if (filesystem::exists(GetDataDir() / strWalletFileName))
583 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
584 if (r == CDBEnv::RECOVER_OK)
586 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
587 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
588 " your balance or transactions are incorrect you should"
589 " restore from a backup."), strDataDir.c_str());
590 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
592 if (r == CDBEnv::RECOVER_FAIL)
593 return InitError(_("wallet.dat corrupt, salvage failed"));
596 // ********************************************************* Step 6: network initialization
598 int nSocksVersion = GetArgInt("-socks", 5);
600 if (nSocksVersion != 4 && nSocksVersion != 5)
601 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
603 if (mapArgs.count("-onlynet")) {
604 std::set<enum Network> nets;
605 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
606 enum Network net = ParseNetwork(snet);
607 if (net == NET_UNROUTABLE)
608 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
611 for (int n = 0; n < NET_MAX; n++) {
612 enum Network net = (enum Network)n;
613 if (!nets.count(net))
617 #if defined(USE_IPV6)
620 SetLimited(NET_IPV6);
626 if (mapArgs.count("-proxy")) {
627 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
628 if (!addrProxy.IsValid())
629 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
631 if (!IsLimited(NET_IPV4))
632 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
633 if (nSocksVersion > 4) {
635 if (!IsLimited(NET_IPV6))
636 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
638 SetNameProxy(addrProxy, nSocksVersion);
643 // -tor can override normal proxy, -notor disables tor entirely
644 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
646 if (!mapArgs.count("-tor"))
647 addrOnion = addrProxy;
649 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
650 if (!addrOnion.IsValid())
651 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
652 SetProxy(NET_TOR, addrOnion, 5);
653 SetReachable(NET_TOR);
656 // see Step 2: parameter interactions for more information about these
657 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
659 fNoListen = !GetBoolArg("-listen", true);
660 fDiscover = GetBoolArg("-discover", true);
661 fNameLookup = GetBoolArg("-dns", true);
663 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
665 fDiscover = fNameLookup = false;
666 SoftSetBoolArg("-irc", false);
667 SoftSetBoolArg("-dnsseed", false);
673 std::string strError;
674 if (mapArgs.count("-bind")) {
675 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
677 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
678 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
679 fBound |= Bind(addrBind);
682 struct in_addr inaddr_any;
683 inaddr_any.s_addr = INADDR_ANY;
685 if (!IsLimited(NET_IPV6))
686 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
688 if (!IsLimited(NET_IPV4))
689 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
693 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
696 // If Tor is reachable then listen on loopback interface,
697 // to allow allow other users reach you through the hidden service
698 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
699 std::string strError;
700 struct in_addr inaddr_loopback;
701 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
704 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
705 return InitError(strError);
707 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
708 return InitError(strError);
711 if (mapArgs.count("-externalip"))
713 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
714 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
715 if (!addrLocal.IsValid())
716 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
717 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
721 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
723 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
725 InitError(_("Invalid amount for -reservebalance=<amount>"));
730 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
732 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
733 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
736 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
739 // ********************************************************* Step 7: load blockchain
741 if (!bitdb.Open(GetDataDir()))
743 string msg = strprintf(_("Error initializing database environment %s!"
744 " To recover, BACKUP THAT DIRECTORY, then remove"
745 " everything from it except for wallet.dat."), strDataDir.c_str());
746 return InitError(msg);
749 if (GetBoolArg("-loadblockindextest"))
752 txdb.LoadBlockIndex();
758 printf("Loading block index...\n");
759 bool fLoaded = false;
761 std::string strLoadError;
762 uiInterface.InitMessage(_("Loading block index..."));
764 nStart = GetTimeMillis();
769 if (!LoadBlockIndex()) {
770 strLoadError = _("Error loading block database");
773 } catch(std::exception &e) {
775 strLoadError = _("Error opening block database");
783 // TODO: suggest reindex here
784 return InitError(strLoadError);
788 // as LoadBlockIndex can take several minutes, it's possible the user
789 // requested to kill bitcoin-qt during the last operation. If so, exit.
790 // As the program has not fully started yet, Shutdown() is possibly overkill.
791 if (fRequestShutdown)
793 printf("Shutdown requested. Exiting.\n");
796 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
798 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
804 if (mapArgs.count("-printblock"))
806 string strMatch = mapArgs["-printblock"];
808 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
810 uint256 hash = (*mi).first;
811 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
813 CBlockIndex* pindex = (*mi).second;
815 block.ReadFromDisk(pindex);
816 block.BuildMerkleTree();
823 printf("No blocks matching %s were found\n", strMatch.c_str());
827 // ********************************************************* Step 8: load wallet
829 if (GetBoolArg("-zapwallettxes", false)) {
830 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
832 pwalletMain = new CWallet(strWalletFileName);
833 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
834 if (nZapWalletRet != DB_LOAD_OK) {
835 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
842 uiInterface.InitMessage(_("Loading wallet..."));
843 printf("Loading wallet...\n");
844 nStart = GetTimeMillis();
845 bool fFirstRun = true;
846 pwalletMain = new CWallet(strWalletFileName);
847 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
848 if (nLoadWalletRet != DB_LOAD_OK)
850 if (nLoadWalletRet == DB_CORRUPT)
851 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
852 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
854 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
855 " or address book entries might be missing or incorrect."));
856 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
858 else if (nLoadWalletRet == DB_TOO_NEW)
859 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
860 else if (nLoadWalletRet == DB_NEED_REWRITE)
862 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
863 printf("%s", strErrors.str().c_str());
864 return InitError(strErrors.str());
867 strErrors << _("Error loading wallet.dat") << "\n";
870 if (GetBoolArg("-upgradewallet", fFirstRun))
872 int nMaxVersion = GetArgInt("-upgradewallet", 0);
873 if (nMaxVersion == 0) // the -upgradewallet without argument case
875 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
876 nMaxVersion = CLIENT_VERSION;
877 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
880 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
881 if (nMaxVersion < pwalletMain->GetVersion())
882 strErrors << _("Cannot downgrade wallet") << "\n";
883 pwalletMain->SetMaxVersion(nMaxVersion);
888 // Create new keyUser and set as default key
889 RandAddSeedPerfmon();
891 CPubKey newDefaultKey;
892 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
893 strErrors << _("Cannot initialize keypool") << "\n";
894 pwalletMain->SetDefaultKey(newDefaultKey);
895 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
896 strErrors << _("Cannot write default address") << "\n";
899 printf("%s", strErrors.str().c_str());
900 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
902 RegisterWallet(pwalletMain);
904 CBlockIndex *pindexRescan = pindexBest;
905 if (GetBoolArg("-rescan"))
906 pindexRescan = pindexGenesisBlock;
909 CWalletDB walletdb(strWalletFileName);
910 CBlockLocator locator;
911 if (walletdb.ReadBestBlock(locator))
912 pindexRescan = locator.GetBlockIndex();
914 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
916 uiInterface.InitMessage(_("Rescanning..."));
917 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
918 nStart = GetTimeMillis();
919 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
920 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
923 // ********************************************************* Step 9: import blocks
925 if (mapArgs.count("-loadblock"))
927 uiInterface.InitMessage(_("Importing blockchain data file."));
929 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
931 FILE *file = fopen(strFile.c_str(), "rb");
933 LoadExternalBlockFile(file);
938 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
939 if (filesystem::exists(pathBootstrap)) {
940 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
942 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
944 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
945 LoadExternalBlockFile(file);
946 RenameOver(pathBootstrap, pathBootstrapOld);
950 // ********************************************************* Step 10: load peers
952 uiInterface.InitMessage(_("Loading addresses..."));
953 printf("Loading addresses...\n");
954 nStart = GetTimeMillis();
958 if (!adb.Read(addrman))
959 printf("Invalid or missing peers.dat; recreating\n");
962 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
963 addrman.size(), GetTimeMillis() - nStart);
965 // ********************************************************* Step 11: start node
967 if (!CheckDiskSpace())
970 RandAddSeedPerfmon();
973 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
974 printf("nBestHeight = %d\n", nBestHeight);
975 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
976 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
977 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
979 if (!NewThread(StartNode, NULL))
980 InitError(_("Error: could not start node"));
983 NewThread(ThreadRPCServer, NULL);
985 // ********************************************************* Step 12: finished
987 uiInterface.InitMessage(_("Done loading"));
988 printf("Done loading\n");
990 if (!strErrors.str().empty())
991 return InitError(strErrors.str());
993 // Add wallet transactions that aren't already in a block to mapTransactions
994 pwalletMain->ReacceptWalletTransactions();
997 // Loop until process is exit()ed from shutdown() function,
998 // called from ThreadRPCServer thread when a "stop" command is received.