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 "ipcollector.h"
12 #include "ui_interface.h"
13 #include "checkpoints.h"
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 nReserveBalance;
42 //////////////////////////////////////////////////////////////////////////////
47 void ExitTimeout(void* parg)
58 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
59 uiInterface.QueueShutdown();
61 // Without UI, Shutdown() can simply be started in a new thread
62 NewThread(Shutdown, NULL);
66 void Shutdown(void* parg)
68 static CCriticalSection cs_Shutdown;
71 // Make this thread recognisable as the shutdown thread
72 RenameThread("novacoin-shutoff");
74 bool fFirstThread = false;
76 TRY_LOCK(cs_Shutdown, lockShutdown);
79 fFirstThread = !fTaken;
83 volatile static bool fExit;
87 fRequestShutdown = true;
88 nTransactionsUpdated++;
93 boost::filesystem::remove(GetPidFile());
94 UnregisterWallet(pwalletMain);
96 NewThread(ExitTimeout, NULL);
98 printf("NovaCoin exited\n\n");
101 // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
114 void HandleSIGTERM(int)
116 fRequestShutdown = true;
119 void HandleSIGHUP(int)
121 fReopenDebugLog = true;
128 //////////////////////////////////////////////////////////////////////////////
133 bool AppInit(int argc, char* argv[])
141 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
142 ParseParameters(argc, argv);
143 if (!boost::filesystem::is_directory(GetDataDir(false)))
145 fprintf(stderr, "Error: Specified directory does not exist\n");
148 ReadConfigFile(mapArgs, mapMultiArgs);
150 if (mapArgs.count("-?") || mapArgs.count("--help"))
152 // First part of help message is specific to bitcoind / RPC client
153 std::string strUsage = _("NovaCoin version") + " " + FormatFullVersion() + "\n\n" +
155 " novacoind [options] " + "\n" +
156 " novacoind [options] <command> [params] " + _("Send command to -server or novacoind") + "\n" +
157 " novacoind [options] help " + _("List commands") + "\n" +
158 " novacoind [options] help <command> " + _("Get help for a command") + "\n";
160 strUsage += "\n" + HelpMessage();
162 fprintf(stdout, "%s", strUsage.c_str());
167 for (int i = 1; i < argc; i++)
168 if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "novacoin:"))
173 int ret = CommandLineRPC(argc, argv);
179 catch (std::exception& e) {
180 PrintException(&e, "AppInit()");
182 PrintException(NULL, "AppInit()");
189 extern void noui_connect();
190 int main(int argc, char* argv[])
193 // Connect bitcoind signal handlers
196 bool fRet = AppInit(argc, argv);
205 bool static InitError(const std::string &str)
207 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
211 bool static InitWarning(const std::string &str)
213 uiInterface.ThreadSafeMessageBox(str, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
218 bool static Bind(const CService &addr, bool fError = true) {
221 std::string strError;
222 if (!BindListenPort(addr, strError)) {
224 return InitError(strError);
230 // Core-specific options shared between UI and daemon
231 std::string HelpMessage()
233 string strUsage = _("Options:") + "\n" +
234 " -? " + _("This help message") + "\n" +
235 " -conf=<file> " + _("Specify configuration file (default: novacoin.conf)") + "\n" +
236 " -pid=<file> " + _("Specify pid file (default: novacoind.pid)") + "\n" +
237 " -datadir=<dir> " + _("Specify data directory") + "\n" +
238 " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n" +
239 " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
240 " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
241 " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
242 " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
243 " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
244 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
245 " -torname=<host.onion> " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
246 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
247 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
248 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
249 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
250 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
251 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
252 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
253 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
254 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
255 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
256 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
257 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
258 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
259 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
260 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
261 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
262 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
263 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
264 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
266 #ifdef DB_LOG_IN_MEMORY
267 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\n" +
270 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
271 " -mininput=<amt> " + ((string)("When creating transactions, ignore inputs with value less than this (default: ") + FormatMoney(MIN_TXOUT_AMOUNT) + ")") + "\n" +
273 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
275 #if !defined(WIN32) && !defined(QT_GUI)
276 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
278 " -testnet " + _("Use the test network") + "\n" +
279 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
280 " -debugnet " + _("Output extra network debugging information") + "\n" +
281 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
282 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
283 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
285 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
287 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
288 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
289 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
290 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
291 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
292 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
293 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
294 " -peercollector=<cmd> " + _("Execute command to collect peer addresses") + "\n" +
295 " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
296 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
297 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
298 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
299 " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n" +
300 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
301 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 192, 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 bool DropBlockIndex()
325 filesystem::path directory = GetDataDir() / "txleveldb";
326 filesystem::remove_all(directory); // remove directory
328 filesystem::path indexFile = GetDataDir() / "blkindex.dat";
329 filesystem::remove(indexFile); // remove index file
332 unsigned int nFile = 1;
335 filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
336 // Break if no such file
337 if( !filesystem::exists( strBlockFile ) )
339 filesystem::remove(strBlockFile);
344 catch(const std::exception&)
346 // TODO: report error here
351 // Initialize bitcoin.
352 // @pre Parameters should be parsed and config file should be read.
355 // ********************************************************* Step 1: setup
357 // Turn off Microsoft heap dump noise
358 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
359 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
362 // Disable confusing "helpful" text message on abort, Ctrl-C
363 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
366 // Enable Data Execution Prevention (DEP)
367 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
368 // A failure is non-critical and needs no further attention!
369 #ifndef PROCESS_DEP_ENABLE
370 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
371 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
372 #define PROCESS_DEP_ENABLE 0x00000001
374 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
375 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
376 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
378 // Initialize Windows Sockets
380 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
383 return InitError(strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret));
389 // Clean shutdown on SIGTERM
391 sa.sa_handler = HandleSIGTERM;
392 sigemptyset(&sa.sa_mask);
394 sigaction(SIGTERM, &sa, NULL);
395 sigaction(SIGINT, &sa, NULL);
397 // Reopen debug.log on SIGHUP
398 struct sigaction sa_hup;
399 sa_hup.sa_handler = HandleSIGHUP;
400 sigemptyset(&sa_hup.sa_mask);
402 sigaction(SIGHUP, &sa_hup, NULL);
405 // ********************************************************* Step 2: parameter interactions
407 nNodeLifespan = GetArgUInt("-addrlifespan", 7);
408 fUseFastIndex = GetBoolArg("-fastindex", true);
409 fUseMemoryLog = GetBoolArg("-memorylog", true);
411 // Ping and address broadcast intervals
412 nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
414 CheckpointsMode = Checkpoints::CP_STRICT;
415 auto strCpMode = GetArg("-cppolicy", "strict");
417 if(strCpMode == "strict") {
418 CheckpointsMode = Checkpoints::CP_STRICT;
421 if(strCpMode == "advisory") {
422 CheckpointsMode = Checkpoints::CP_ADVISORY;
425 if(strCpMode == "permissive") {
426 CheckpointsMode = Checkpoints::CP_PERMISSIVE;
429 fTestNet = GetBoolArg("-testnet");
431 SoftSetBoolArg("-irc", true);
434 if (mapArgs.count("-bind")) {
435 // when specifying an explicit binding address, you want to listen on it
436 // even when -connect or -proxy is specified
437 SoftSetBoolArg("-listen", true);
440 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
441 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
442 SoftSetBoolArg("-dnsseed", false);
443 SoftSetBoolArg("-listen", false);
446 if (mapArgs.count("-proxy")) {
447 // to protect privacy, do not listen by default if a proxy server is specified
448 SoftSetBoolArg("-listen", false);
451 if (!GetBoolArg("-listen", true)) {
452 // do not map ports or try to retrieve public IP when not listening (pointless)
453 SoftSetBoolArg("-discover", false);
456 if (mapArgs.count("-externalip")) {
457 // if an explicit public IP is specified, do not try to find others
458 SoftSetBoolArg("-discover", false);
461 if (GetBoolArg("-salvagewallet")) {
462 // Rewrite just private keys: rescan to find transactions
463 SoftSetBoolArg("-rescan", true);
466 if (GetBoolArg("-zapwallettxes", false)) {
467 // -zapwallettx implies a rescan
468 if (SoftSetBoolArg("-rescan", true))
469 printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
472 // ********************************************************* Step 3: parameter-to-internal-flags
474 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
475 nScriptCheckThreads = GetArgInt("-par", 0);
476 if (nScriptCheckThreads == 0)
477 nScriptCheckThreads = boost::thread::hardware_concurrency();
478 if (nScriptCheckThreads <= 1)
479 nScriptCheckThreads = 0;
480 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
481 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
483 fDebug = GetBoolArg("-debug");
485 // -debug implies fDebug*
489 fDebugNet = GetBoolArg("-debugnet");
491 bitdb.SetDetach(GetBoolArg("-detachdb", false));
493 #if !defined(WIN32) && !defined(QT_GUI)
494 fDaemon = GetBoolArg("-daemon");
502 fServer = GetBoolArg("-server");
504 /* force fServer when running without GUI */
508 fPrintToConsole = GetBoolArg("-printtoconsole");
509 fPrintToDebugger = GetBoolArg("-printtodebugger");
510 fLogTimestamps = GetBoolArg("-logtimestamps");
512 if (mapArgs.count("-timeout"))
514 int nNewTimeout = GetArgInt("-timeout", 5000);
515 if (nNewTimeout > 0 && nNewTimeout < 600000)
516 nConnectTimeout = nNewTimeout;
519 // Put client version data into coinbase flags.
520 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
522 if (mapArgs.count("-paytxfee"))
524 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
525 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
526 if (nTransactionFee > 0.25 * COIN)
527 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
530 fConfChange = GetBoolArg("-confchange", false);
532 if (mapArgs.count("-mininput"))
534 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
535 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
538 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
540 auto strDataDir = GetDataDir().string();
541 strWalletFileName = GetArg("-wallet", "wallet.dat");
543 // strWalletFileName must be a plain filename without a directory
544 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
545 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
547 // Make sure only a single Bitcoin process is using the data directory.
548 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
549 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
550 if (file) fclose(file);
551 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
552 if (!lock.try_lock())
553 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
555 #if !defined(WIN32) && !defined(QT_GUI)
562 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
567 CreatePidFile(GetPidFile(), pid);
571 pid_t sid = setsid();
573 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
577 if (GetBoolArg("-shrinkdebugfile", !fDebug))
579 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
580 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
581 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
583 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
584 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
585 printf("Used data directory %s\n", strDataDir.c_str());
588 fprintf(stdout, "NovaCoin server starting\n");
590 if (nScriptCheckThreads) {
591 printf("Using %u threads for script verification\n", nScriptCheckThreads);
592 for (int i=0; i<nScriptCheckThreads-1; i++)
593 NewThread(ThreadScriptCheck, NULL);
596 // ********************************************************* Step 5: verify database integrity
598 uiInterface.InitMessage(_("Verifying database integrity..."));
600 if (!bitdb.Open(GetDataDir()))
602 string msg = strprintf(_("Error initializing database environment %s!"
603 " To recover, BACKUP THAT DIRECTORY, then remove"
604 " everything from it except for wallet.dat."), strDataDir.c_str());
605 return InitError(msg);
608 if (GetBoolArg("-salvagewallet"))
610 // Recover readable keypairs:
611 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
615 if (filesystem::exists(GetDataDir() / strWalletFileName))
617 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
618 if (r == CDBEnv::RECOVER_OK)
620 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
621 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
622 " your balance or transactions are incorrect you should"
623 " restore from a backup."), strDataDir.c_str());
624 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
626 if (r == CDBEnv::RECOVER_FAIL)
627 return InitError(_("wallet.dat corrupt, salvage failed"));
630 // ********************************************************* Step 6: network initialization
632 int nSocksVersion = GetArgInt("-socks", 5);
634 if (nSocksVersion != 4 && nSocksVersion != 5)
635 return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
637 if (mapArgs.count("-onlynet")) {
638 std::set<enum Network> nets;
639 for(std::string snet : mapMultiArgs["-onlynet"]) {
640 enum Network net = ParseNetwork(snet);
641 if (net == NET_UNROUTABLE)
642 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
645 for (int n = 0; n < NET_MAX; n++) {
646 enum Network net = (enum Network)n;
647 if (!nets.count(net))
651 #if defined(USE_IPV6)
654 SetLimited(NET_IPV6);
660 if (mapArgs.count("-proxy")) {
661 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
662 if (!addrProxy.IsValid())
663 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
665 if (!IsLimited(NET_IPV4))
666 SetProxy(NET_IPV4, addrProxy, nSocksVersion);
667 if (nSocksVersion > 4) {
669 if (!IsLimited(NET_IPV6))
670 SetProxy(NET_IPV6, addrProxy, nSocksVersion);
672 SetNameProxy(addrProxy, nSocksVersion);
677 // -tor can override normal proxy, -notor disables tor entirely
678 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
680 if (!mapArgs.count("-tor"))
681 addrOnion = addrProxy;
683 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
684 if (!addrOnion.IsValid())
685 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
686 SetProxy(NET_TOR, addrOnion, 5);
687 SetReachable(NET_TOR);
690 // see Step 2: parameter interactions for more information about these
691 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
693 fNoListen = !GetBoolArg("-listen", true);
694 fDiscover = GetBoolArg("-discover", true);
695 fNameLookup = GetBoolArg("-dns", true);
697 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
699 fDiscover = fNameLookup = false;
700 SoftSetBoolArg("-irc", false);
701 SoftSetBoolArg("-dnsseed", false);
707 if (mapArgs.count("-bind")) {
708 for(std::string strBind : mapMultiArgs["-bind"]) {
710 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
711 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
712 fBound |= Bind(addrBind);
715 struct in_addr inaddr_any;
716 inaddr_any.s_addr = INADDR_ANY;
718 if (!IsLimited(NET_IPV6))
719 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
721 if (!IsLimited(NET_IPV4))
722 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
726 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
729 // If Tor is reachable then listen on loopback interface,
730 // to allow allow other users reach you through the hidden service
731 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
732 std::string strError;
733 struct in_addr inaddr_loopback;
734 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
737 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
738 return InitError(strError);
740 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
741 return InitError(strError);
744 if (mapArgs.count("-externalip"))
746 for(string strAddr : mapMultiArgs["-externalip"]) {
747 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
748 if (!addrLocal.IsValid())
749 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
750 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
754 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
756 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
758 InitError(_("Invalid amount for -reservebalance=<amount>"));
763 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
765 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
766 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
769 for(string strDest : mapMultiArgs["-seednode"])
772 // ********************************************************* Step 7: load blockchain
774 if (!bitdb.Open(GetDataDir()))
776 string msg = strprintf(_("Error initializing database environment %s!"
777 " To recover, BACKUP THAT DIRECTORY, then remove"
778 " everything from it except for wallet.dat."), strDataDir.c_str());
779 return InitError(msg);
782 if (GetBoolArg("-loadblockindextest"))
785 txdb.LoadBlockIndex();
791 printf("Loading block index...\n");
792 bool fLoaded = false;
795 std::string strLoadError;
796 uiInterface.InitMessage(_("Loading block index..."));
798 nStart = GetTimeMillis();
803 if (!LoadBlockIndex()) {
804 strLoadError = _("Error loading block database");
807 } catch(const std::exception&) {
808 strLoadError = _("Error opening block database");
817 // TODO: suggest reindex here
818 return InitError(strLoadError);
822 // as LoadBlockIndex can take several minutes, it's possible the user
823 // requested to kill bitcoin-qt during the last operation. If so, exit.
824 // As the program has not fully started yet, Shutdown() is possibly overkill.
825 if (fRequestShutdown)
827 printf("Shutdown requested. Exiting.\n");
830 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
832 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
838 if (mapArgs.count("-printblock"))
840 auto strMatch = mapArgs["-printblock"];
842 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
844 auto hash = (*mi).first;
845 if (strMatch.compare(hash.ToString()) == 0)
847 auto pindex = (*mi).second;
849 block.ReadFromDisk(pindex);
850 block.BuildMerkleTree();
857 printf("No blocks matching %s were found\n", strMatch.c_str());
861 // ********************************************************* Step 8: load wallet
863 if (GetBoolArg("-zapwallettxes", false)) {
864 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
866 pwalletMain = new CWallet(strWalletFileName);
867 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
868 if (nZapWalletRet != DB_LOAD_OK) {
869 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
876 uiInterface.InitMessage(_("Loading wallet..."));
877 printf("Loading wallet...\n");
878 nStart = GetTimeMillis();
879 std::ostringstream strErrors;
880 bool fFirstRun = true;
881 pwalletMain = new CWallet(strWalletFileName);
882 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
883 if (nLoadWalletRet != DB_LOAD_OK)
885 if (nLoadWalletRet == DB_CORRUPT)
886 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
887 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
889 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
890 " or address book entries might be missing or incorrect."));
891 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
893 else if (nLoadWalletRet == DB_TOO_NEW)
894 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
895 else if (nLoadWalletRet == DB_NEED_REWRITE)
897 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
898 printf("%s", strErrors.str().c_str());
899 return InitError(strErrors.str());
902 strErrors << _("Error loading wallet.dat") << "\n";
905 if (GetBoolArg("-upgradewallet", fFirstRun))
907 int nMaxVersion = GetArgInt("-upgradewallet", 0);
908 if (nMaxVersion == 0) // the -upgradewallet without argument case
910 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
911 nMaxVersion = CLIENT_VERSION;
912 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
915 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
916 if (nMaxVersion < pwalletMain->GetVersion())
917 strErrors << _("Cannot downgrade wallet") << "\n";
918 pwalletMain->SetMaxVersion(nMaxVersion);
923 // Create new keyUser and set as default key
924 RandAddSeedPerfmon();
926 CPubKey newDefaultKey;
927 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
928 strErrors << _("Cannot initialize keypool") << "\n";
929 pwalletMain->SetDefaultKey(newDefaultKey);
930 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
931 strErrors << _("Cannot write default address") << "\n";
933 auto keyView = pwalletMain->GenerateNewMalleableKey();
935 if (!pwalletMain->GetMalleableKey(keyView, mKey))
936 strErrors << _("Unable to generate new malleable key");
937 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
938 strErrors << _("Cannot write default address") << "\n";
941 printf("%s", strErrors.str().c_str());
942 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
944 RegisterWallet(pwalletMain);
946 CBlockIndex *pindexRescan = pindexBest;
947 if (GetBoolArg("-rescan"))
948 pindexRescan = pindexGenesisBlock;
951 CWalletDB walletdb(strWalletFileName);
952 CBlockLocator locator;
953 if (walletdb.ReadBestBlock(locator))
954 pindexRescan = locator.GetBlockIndex();
956 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
958 uiInterface.InitMessage(_("Rescanning..."));
959 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
960 nStart = GetTimeMillis();
961 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
962 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
965 // ********************************************************* Step 9: import blocks
967 if (mapArgs.count("-loadblock"))
969 uiInterface.InitMessage(_("Importing blockchain data file."));
971 for(string strFile : mapMultiArgs["-loadblock"])
973 FILE *file = fopen(strFile.c_str(), "rb");
975 LoadExternalBlockFile(file, uiInterface);
980 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
981 if (filesystem::exists(pathBootstrap)) {
982 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
984 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
986 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
987 LoadExternalBlockFile(file, uiInterface);
988 RenameOver(pathBootstrap, pathBootstrapOld);
992 // ********************************************************* Step 10: load peers
994 uiInterface.InitMessage(_("Loading addresses..."));
995 printf("Loading addresses...\n");
996 nStart = GetTimeMillis();
1000 if (!adb.Read(addrman))
1001 printf("Invalid or missing peers.dat; recreating\n");
1004 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
1005 addrman.size(), GetTimeMillis() - nStart);
1007 // ********************************************************* Step 11: start node
1009 if (!CheckDiskSpace())
1012 RandAddSeedPerfmon();
1015 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
1016 printf("nBestHeight = %d\n", nBestHeight);
1017 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
1018 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
1019 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
1021 if (!NewThread(StartNode, NULL))
1022 InitError(_("Error: could not start node"));
1025 NewThread(ThreadRPCServer, NULL);
1027 // ********************************************************* Step 13: IP collection thread
1028 strCollectorCommand = GetArg("-peercollector", "");
1029 if (!fTestNet && strCollectorCommand != "")
1030 NewThread(ThreadIPCollector, NULL);
1031 // ********************************************************* Step 14: finished
1033 uiInterface.InitMessage(_("Done loading"));
1034 printf("Done loading\n");
1036 if (!strErrors.str().empty())
1037 return InitError(strErrors.str());
1039 // Add wallet transactions that aren't already in a block to mapTransactions
1040 pwalletMain->ReacceptWalletTransactions();
1042 #if !defined(QT_GUI)
1043 // Loop until process is exit()ed from shutdown() function,
1044 // called from ThreadRPCServer thread when a "stop" command is received.