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[])
195 // Connect bitcoind signal handlers
198 fRet = AppInit(argc, argv);
207 bool static InitError(const std::string &str)
209 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
213 bool static InitWarning(const std::string &str)
215 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
220 bool static Bind(const CService &addr, bool fError = true) {
223 std::string strError;
224 if (!BindListenPort(addr, strError)) {
226 return InitError(strError);
232 // Core-specific options shared between UI and daemon
233 std::string HelpMessage()
235 string strUsage = _("Options:") + "\n" +
236 " -? " + _("This help message") + "\n" +
237 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
238 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
239 " -datadir=<dir> " + _("Specify data directory") + "\n" +
240 " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n" +
241 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
242 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
243 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
244 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
245 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
246 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
247 " -torname=<host.onion> " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
248 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
249 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
250 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
251 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
252 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
253 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
254 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
255 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
256 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
257 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
258 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
259 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
260 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
261 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
262 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
263 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
264 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
265 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
266 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
268 #ifdef DB_LOG_IN_MEMORY
269 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\n" +
272 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
273 " -mininput=<amt> " + str(boost::format(_("When creating transactions, ignore inputs with value less than this (default: %s)")) % FormatMoney(MIN_TXOUT_AMOUNT)) + "\n" +
275 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
277 #if !defined(WIN32) && !defined(QT_GUI)
278 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
280 " -testnet " + _("Use the test network") + "\n" +
281 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
282 " -debugnet " + _("Output extra network debugging information") + "\n" +
283 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
284 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
285 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
287 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
289 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
290 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
291 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
292 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
293 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
294 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
295 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
296 " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
297 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
298 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
299 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
300 " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n" +
301 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
302 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
303 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
304 " -par=N " + _("Set the number of script verification threads (1-16, 0=auto, default: 0)") + "\n" +
305 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
307 "\n" + _("Block creation options:") + "\n" +
308 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
309 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
310 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
312 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
313 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
314 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
315 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
316 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
321 /** Initialize bitcoin.
322 * @pre Parameters should be parsed and config file should be read.
326 // ********************************************************* Step 1: setup
328 // Turn off Microsoft heap dump noise
329 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
330 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
333 // Disable confusing "helpful" text message on abort, Ctrl-C
334 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
337 // Enable Data Execution Prevention (DEP)
338 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
339 // A failure is non-critical and needs no further attention!
340 #ifndef PROCESS_DEP_ENABLE
341 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
342 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
343 #define PROCESS_DEP_ENABLE 0x00000001
345 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
346 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
347 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
352 // Clean shutdown on SIGTERM
354 sa.sa_handler = HandleSIGTERM;
355 sigemptyset(&sa.sa_mask);
357 sigaction(SIGTERM, &sa, NULL);
358 sigaction(SIGINT, &sa, NULL);
360 // Reopen debug.log on SIGHUP
361 struct sigaction sa_hup;
362 sa_hup.sa_handler = HandleSIGHUP;
363 sigemptyset(&sa_hup.sa_mask);
365 sigaction(SIGHUP, &sa_hup, NULL);
368 // ********************************************************* Step 2: parameter interactions
370 nNodeLifespan = (unsigned int)(GetArg("-addrlifespan", 7));
371 fUseFastIndex = GetBoolArg("-fastindex", true);
372 fUseMemoryLog = GetBoolArg("-memorylog", true);
374 // Ping and address broadcast intervals
375 nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
376 nBroadcastInterval = max<int64_t>(6 * nOneHour, GetArg("-addrsetlifetime", nOneDay));
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 bitdb.SetDetach(GetBoolArg("-detachdb", false));
457 #if !defined(WIN32) && !defined(QT_GUI)
458 fDaemon = GetBoolArg("-daemon");
466 fServer = GetBoolArg("-server");
468 /* force fServer when running without GUI */
472 fPrintToConsole = GetBoolArg("-printtoconsole");
473 fPrintToDebugger = GetBoolArg("-printtodebugger");
474 fLogTimestamps = GetBoolArg("-logtimestamps");
476 if (mapArgs.count("-timeout"))
478 int nNewTimeout = GetArgInt("-timeout", 5000);
479 if (nNewTimeout > 0 && nNewTimeout < 600000)
480 nConnectTimeout = nNewTimeout;
483 // Put client version data into coinbase flags.
484 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
486 if (mapArgs.count("-paytxfee"))
488 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
489 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
490 if (nTransactionFee > 0.25 * COIN)
491 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
494 fConfChange = GetBoolArg("-confchange", false);
496 if (mapArgs.count("-mininput"))
498 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
499 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
502 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
504 std::string strDataDir = GetDataDir().string();
505 strWalletFileName = GetArg("-wallet", "wallet.dat");
507 // strWalletFileName must be a plain filename without a directory
508 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
509 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
511 // Make sure only a single Bitcoin process is using the data directory.
512 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
513 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
514 if (file) fclose(file);
515 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
516 if (!lock.try_lock())
517 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
519 #if !defined(WIN32) && !defined(QT_GUI)
526 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
531 CreatePidFile(GetPidFile(), pid);
535 pid_t sid = setsid();
537 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
541 if (GetBoolArg("-shrinkdebugfile", !fDebug))
543 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
544 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
545 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
547 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
548 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
549 printf("Used data directory %s\n", strDataDir.c_str());
550 std::ostringstream strErrors;
553 fprintf(stdout, "NovaCoin server starting\n");
555 if (nScriptCheckThreads) {
556 printf("Using %u threads for script verification\n", nScriptCheckThreads);
557 for (int i=0; i<nScriptCheckThreads-1; i++)
558 NewThread(ThreadScriptCheck, NULL);
563 // ********************************************************* Step 5: verify database integrity
565 uiInterface.InitMessage(_("Verifying database integrity..."));
567 if (!bitdb.Open(GetDataDir()))
569 string msg = strprintf(_("Error initializing database environment %s!"
570 " To recover, BACKUP THAT DIRECTORY, then remove"
571 " everything from it except for wallet.dat."), strDataDir.c_str());
572 return InitError(msg);
575 if (GetBoolArg("-salvagewallet"))
577 // Recover readable keypairs:
578 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
582 if (filesystem::exists(GetDataDir() / strWalletFileName))
584 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
585 if (r == CDBEnv::RECOVER_OK)
587 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
588 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
589 " your balance or transactions are incorrect you should"
590 " restore from a backup."), strDataDir.c_str());
591 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
593 if (r == CDBEnv::RECOVER_FAIL)
594 return InitError(_("wallet.dat corrupt, salvage failed"));
597 // ********************************************************* Step 6: network initialization
599 int nSocksVersion = GetArgInt("-socks", 5);
601 if (nSocksVersion != 4 && nSocksVersion != 5)
602 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
604 if (mapArgs.count("-onlynet")) {
605 std::set<enum Network> nets;
606 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
607 enum Network net = ParseNetwork(snet);
608 if (net == NET_UNROUTABLE)
609 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
612 for (int n = 0; n < NET_MAX; n++) {
613 enum Network net = (enum Network)n;
614 if (!nets.count(net))
618 #if defined(USE_IPV6)
621 SetLimited(NET_IPV6);
627 if (mapArgs.count("-proxy")) {
628 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
629 if (!addrProxy.IsValid())
630 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
632 if (!IsLimited(NET_IPV4))
633 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
634 if (nSocksVersion > 4) {
636 if (!IsLimited(NET_IPV6))
637 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
639 SetNameProxy(addrProxy, nSocksVersion);
644 // -tor can override normal proxy, -notor disables tor entirely
645 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
647 if (!mapArgs.count("-tor"))
648 addrOnion = addrProxy;
650 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
651 if (!addrOnion.IsValid())
652 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
653 SetProxy(NET_TOR, addrOnion, 5);
654 SetReachable(NET_TOR);
657 // see Step 2: parameter interactions for more information about these
658 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
660 fNoListen = !GetBoolArg("-listen", true);
661 fDiscover = GetBoolArg("-discover", true);
662 fNameLookup = GetBoolArg("-dns", true);
664 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
666 fDiscover = fNameLookup = false;
667 SoftSetBoolArg("-irc", false);
668 SoftSetBoolArg("-dnsseed", false);
674 std::string strError;
675 if (mapArgs.count("-bind")) {
676 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
678 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
679 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
680 fBound |= Bind(addrBind);
683 struct in_addr inaddr_any;
684 inaddr_any.s_addr = INADDR_ANY;
686 if (!IsLimited(NET_IPV6))
687 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
689 if (!IsLimited(NET_IPV4))
690 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
694 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
697 // If Tor is reachable then listen on loopback interface,
698 // to allow allow other users reach you through the hidden service
699 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
700 std::string strError;
701 struct in_addr inaddr_loopback;
702 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
705 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
706 return InitError(strError);
708 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
709 return InitError(strError);
712 if (mapArgs.count("-externalip"))
714 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
715 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
716 if (!addrLocal.IsValid())
717 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
718 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
722 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
724 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
726 InitError(_("Invalid amount for -reservebalance=<amount>"));
731 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
733 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
734 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
737 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
740 // ********************************************************* Step 7: load blockchain
742 if (!bitdb.Open(GetDataDir()))
744 string msg = strprintf(_("Error initializing database environment %s!"
745 " To recover, BACKUP THAT DIRECTORY, then remove"
746 " everything from it except for wallet.dat."), strDataDir.c_str());
747 return InitError(msg);
750 if (GetBoolArg("-loadblockindextest"))
753 txdb.LoadBlockIndex();
759 printf("Loading block index...\n");
760 bool fLoaded = false;
762 std::string strLoadError;
763 uiInterface.InitMessage(_("Loading block index..."));
765 nStart = GetTimeMillis();
770 if (!LoadBlockIndex()) {
771 strLoadError = _("Error loading block database");
774 } catch(std::exception &e) {
776 strLoadError = _("Error opening block database");
784 // TODO: suggest reindex here
785 return InitError(strLoadError);
789 // as LoadBlockIndex can take several minutes, it's possible the user
790 // requested to kill bitcoin-qt during the last operation. If so, exit.
791 // As the program has not fully started yet, Shutdown() is possibly overkill.
792 if (fRequestShutdown)
794 printf("Shutdown requested. Exiting.\n");
797 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
799 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
805 if (mapArgs.count("-printblock"))
807 string strMatch = mapArgs["-printblock"];
809 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
811 uint256 hash = (*mi).first;
812 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
814 CBlockIndex* pindex = (*mi).second;
816 block.ReadFromDisk(pindex);
817 block.BuildMerkleTree();
824 printf("No blocks matching %s were found\n", strMatch.c_str());
828 // ********************************************************* Step 8: load wallet
830 if (GetBoolArg("-zapwallettxes", false)) {
831 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
833 pwalletMain = new CWallet(strWalletFileName);
834 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
835 if (nZapWalletRet != DB_LOAD_OK) {
836 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
843 uiInterface.InitMessage(_("Loading wallet..."));
844 printf("Loading wallet...\n");
845 nStart = GetTimeMillis();
846 bool fFirstRun = true;
847 pwalletMain = new CWallet(strWalletFileName);
848 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
849 if (nLoadWalletRet != DB_LOAD_OK)
851 if (nLoadWalletRet == DB_CORRUPT)
852 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
853 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
855 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
856 " or address book entries might be missing or incorrect."));
857 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
859 else if (nLoadWalletRet == DB_TOO_NEW)
860 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
861 else if (nLoadWalletRet == DB_NEED_REWRITE)
863 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
864 printf("%s", strErrors.str().c_str());
865 return InitError(strErrors.str());
868 strErrors << _("Error loading wallet.dat") << "\n";
871 if (GetBoolArg("-upgradewallet", fFirstRun))
873 int nMaxVersion = GetArgInt("-upgradewallet", 0);
874 if (nMaxVersion == 0) // the -upgradewallet without argument case
876 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
877 nMaxVersion = CLIENT_VERSION;
878 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
881 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
882 if (nMaxVersion < pwalletMain->GetVersion())
883 strErrors << _("Cannot downgrade wallet") << "\n";
884 pwalletMain->SetMaxVersion(nMaxVersion);
889 // Create new keyUser and set as default key
890 RandAddSeedPerfmon();
892 CPubKey newDefaultKey;
893 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
894 strErrors << _("Cannot initialize keypool") << "\n";
895 pwalletMain->SetDefaultKey(newDefaultKey);
896 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
897 strErrors << _("Cannot write default address") << "\n";
900 printf("%s", strErrors.str().c_str());
901 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
903 RegisterWallet(pwalletMain);
905 CBlockIndex *pindexRescan = pindexBest;
906 if (GetBoolArg("-rescan"))
907 pindexRescan = pindexGenesisBlock;
910 CWalletDB walletdb(strWalletFileName);
911 CBlockLocator locator;
912 if (walletdb.ReadBestBlock(locator))
913 pindexRescan = locator.GetBlockIndex();
915 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
917 uiInterface.InitMessage(_("Rescanning..."));
918 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
919 nStart = GetTimeMillis();
920 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
921 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
924 // ********************************************************* Step 9: import blocks
926 if (mapArgs.count("-loadblock"))
928 uiInterface.InitMessage(_("Importing blockchain data file."));
930 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
932 FILE *file = fopen(strFile.c_str(), "rb");
934 LoadExternalBlockFile(file);
939 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
940 if (filesystem::exists(pathBootstrap)) {
941 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
943 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
945 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
946 LoadExternalBlockFile(file);
947 RenameOver(pathBootstrap, pathBootstrapOld);
951 // ********************************************************* Step 10: load peers
953 uiInterface.InitMessage(_("Loading addresses..."));
954 printf("Loading addresses...\n");
955 nStart = GetTimeMillis();
959 if (!adb.Read(addrman))
960 printf("Invalid or missing peers.dat; recreating\n");
963 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
964 addrman.size(), GetTimeMillis() - nStart);
966 // ********************************************************* Step 11: start node
968 if (!CheckDiskSpace())
971 RandAddSeedPerfmon();
974 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
975 printf("nBestHeight = %d\n", nBestHeight);
976 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
977 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
978 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
980 if (!NewThread(StartNode, NULL))
981 InitError(_("Error: could not start node"));
984 NewThread(ThreadRPCServer, NULL);
986 // ********************************************************* Step 12: finished
988 uiInterface.InitMessage(_("Done loading"));
989 printf("Done loading\n");
991 if (!strErrors.str().empty())
992 return InitError(strErrors.str());
994 // Add wallet transactions that aren't already in a block to mapTransactions
995 pwalletMain->ReacceptWalletTransactions();
998 // Loop until process is exit()ed from shutdown() function,
999 // called from ThreadRPCServer thread when a "stop" command is received.