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 socks5 proxy") + "\n" +
243 " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
244 " -torname=<host.onion> " + _("Send the specified hidden service name when connecting to Tor nodes (default: none)") + "\n"
245 " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
246 " -port=<port> " + _("Listen for connections on <port> (default: 7777 or testnet: 17777)") + "\n" +
247 " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
248 " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
249 " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
250 " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
251 " -externalip=<ip> " + _("Specify your own public address") + "\n" +
252 " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Onion)") + "\n" +
253 " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
254 " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
255 " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
256 " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
257 " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
258 " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
259 " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
260 " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
261 " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
262 " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
263 " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
265 #ifdef DB_LOG_IN_MEMORY
266 " -memorylog " + _("Use in-memory logging for block index database (default: 1)") + "\n" +
269 " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
270 " -mininput=<amt> " + ((string)("When creating transactions, ignore inputs with value less than this (default: ") + FormatMoney(MIN_TXOUT_AMOUNT) + ")") + "\n" +
272 " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
274 #if !defined(WIN32) && !defined(QT_GUI)
275 " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
277 " -testnet " + _("Use the test network") + "\n" +
278 " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
279 " -debugnet " + _("Output extra network debugging information") + "\n" +
280 " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
281 " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
282 " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
284 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
286 " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
287 " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
288 " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)") + "\n" +
289 " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
290 " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
291 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
292 " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
293 " -peercollector=<cmd> " + _("Execute command to collect peer addresses") + "\n" +
294 " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
295 " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
296 " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
297 " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
298 " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n" +
299 " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
300 " -checkblocks=<n> " + _("How many blocks to check at startup (default: 192, 0 = all)") + "\n" +
301 " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
302 " -par=N " + _("Set the number of script verification threads (1-16, 0=auto, default: 0)") + "\n" +
303 " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
305 "\n" + _("Block creation options:") + "\n" +
306 " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
307 " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
308 " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
310 "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
311 " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
312 " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
313 " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
314 " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
319 bool DropBlockIndex()
324 filesystem::path directory = GetDataDir() / "txleveldb";
325 filesystem::remove_all(directory); // remove directory
327 filesystem::path indexFile = GetDataDir() / "blkindex.dat";
328 filesystem::remove(indexFile); // remove index file
331 unsigned int nFile = 1;
334 filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
335 // Break if no such file
336 if( !filesystem::exists( strBlockFile ) )
338 filesystem::remove(strBlockFile);
343 catch(const std::exception&)
345 // TODO: report error here
350 // Initialize bitcoin.
351 // @pre Parameters should be parsed and config file should be read.
354 // ********************************************************* Step 1: setup
356 // Turn off Microsoft heap dump noise
357 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
358 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
361 // Disable confusing "helpful" text message on abort, Ctrl-C
362 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
365 // Enable Data Execution Prevention (DEP)
366 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
367 // A failure is non-critical and needs no further attention!
368 #ifndef PROCESS_DEP_ENABLE
369 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
370 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
371 #define PROCESS_DEP_ENABLE 0x00000001
373 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
374 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
375 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
377 // Initialize Windows Sockets
379 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
382 return InitError(strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret));
388 // Clean shutdown on SIGTERM
390 sa.sa_handler = HandleSIGTERM;
391 sigemptyset(&sa.sa_mask);
393 sigaction(SIGTERM, &sa, NULL);
394 sigaction(SIGINT, &sa, NULL);
396 // Reopen debug.log on SIGHUP
397 struct sigaction sa_hup;
398 sa_hup.sa_handler = HandleSIGHUP;
399 sigemptyset(&sa_hup.sa_mask);
401 sigaction(SIGHUP, &sa_hup, NULL);
404 // ********************************************************* Step 2: parameter interactions
406 nNodeLifespan = GetArgUInt("-addrlifespan", 7);
407 fUseFastIndex = GetBoolArg("-fastindex", true);
408 fUseMemoryLog = GetBoolArg("-memorylog", true);
410 // Ping and address broadcast intervals
411 nPingInterval = max<int64_t>(10 * 60, GetArg("-keepalive", 30 * 60));
413 CheckpointsMode = Checkpoints::CP_STRICT;
414 auto strCpMode = GetArg("-cppolicy", "strict");
416 if(strCpMode == "strict") {
417 CheckpointsMode = Checkpoints::CP_STRICT;
420 if(strCpMode == "advisory") {
421 CheckpointsMode = Checkpoints::CP_ADVISORY;
424 if(strCpMode == "permissive") {
425 CheckpointsMode = Checkpoints::CP_PERMISSIVE;
428 fTestNet = GetBoolArg("-testnet");
430 SoftSetBoolArg("-irc", true);
433 if (mapArgs.count("-bind")) {
434 // when specifying an explicit binding address, you want to listen on it
435 // even when -connect or -proxy is specified
436 SoftSetBoolArg("-listen", true);
439 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
440 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
441 SoftSetBoolArg("-dnsseed", false);
442 SoftSetBoolArg("-listen", false);
445 if (mapArgs.count("-proxy")) {
446 // to protect privacy, do not listen by default if a proxy server is specified
447 SoftSetBoolArg("-listen", false);
450 if (!GetBoolArg("-listen", true)) {
451 // do not map ports or try to retrieve public IP when not listening (pointless)
452 SoftSetBoolArg("-discover", false);
455 if (mapArgs.count("-externalip")) {
456 // if an explicit public IP is specified, do not try to find others
457 SoftSetBoolArg("-discover", false);
460 if (GetBoolArg("-salvagewallet")) {
461 // Rewrite just private keys: rescan to find transactions
462 SoftSetBoolArg("-rescan", true);
465 if (GetBoolArg("-zapwallettxes", false)) {
466 // -zapwallettx implies a rescan
467 if (SoftSetBoolArg("-rescan", true))
468 printf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
471 // ********************************************************* Step 3: parameter-to-internal-flags
473 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
474 nScriptCheckThreads = GetArgInt("-par", 0);
475 if (nScriptCheckThreads == 0)
476 nScriptCheckThreads = boost::thread::hardware_concurrency();
477 if (nScriptCheckThreads <= 1)
478 nScriptCheckThreads = 0;
479 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
480 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
482 fDebug = GetBoolArg("-debug");
484 // -debug implies fDebug*
488 fDebugNet = GetBoolArg("-debugnet");
490 bitdb.SetDetach(GetBoolArg("-detachdb", false));
492 #if !defined(WIN32) && !defined(QT_GUI)
493 fDaemon = GetBoolArg("-daemon");
501 fServer = GetBoolArg("-server");
503 /* force fServer when running without GUI */
507 fPrintToConsole = GetBoolArg("-printtoconsole");
508 fPrintToDebugger = GetBoolArg("-printtodebugger");
509 fLogTimestamps = GetBoolArg("-logtimestamps");
511 if (mapArgs.count("-timeout"))
513 int nNewTimeout = GetArgInt("-timeout", 5000);
514 if (nNewTimeout > 0 && nNewTimeout < 600000)
515 nConnectTimeout = nNewTimeout;
518 // Put client version data into coinbase flags.
519 COINBASE_FLAGS << PROTOCOL_VERSION << DISPLAY_VERSION_MAJOR << DISPLAY_VERSION_MINOR << DISPLAY_VERSION_REVISION;
521 if (mapArgs.count("-paytxfee"))
523 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
524 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
525 if (nTransactionFee > 0.25 * COIN)
526 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
529 fConfChange = GetBoolArg("-confchange", false);
531 if (mapArgs.count("-mininput"))
533 if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
534 return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
537 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
539 auto strDataDir = GetDataDir().string();
540 strWalletFileName = GetArg("-wallet", "wallet.dat");
542 // strWalletFileName must be a plain filename without a directory
543 if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
544 return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
546 // Make sure only a single Bitcoin process is using the data directory.
547 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
548 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
549 if (file) fclose(file);
550 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
551 if (!lock.try_lock())
552 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. NovaCoin is probably already running."), strDataDir.c_str()));
554 #if !defined(WIN32) && !defined(QT_GUI)
561 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
566 CreatePidFile(GetPidFile(), pid);
570 pid_t sid = setsid();
572 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
576 if (GetBoolArg("-shrinkdebugfile", !fDebug))
578 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
579 printf("NovaCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
580 printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
582 printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
583 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
584 printf("Used data directory %s\n", strDataDir.c_str());
587 fprintf(stdout, "NovaCoin server starting\n");
589 if (nScriptCheckThreads) {
590 printf("Using %u threads for script verification\n", nScriptCheckThreads);
591 for (int i=0; i<nScriptCheckThreads-1; i++)
592 NewThread(ThreadScriptCheck, NULL);
595 // ********************************************************* Step 5: verify database integrity
597 uiInterface.InitMessage(_("Verifying database integrity..."));
599 if (!bitdb.Open(GetDataDir()))
601 string msg = strprintf(_("Error initializing database environment %s!"
602 " To recover, BACKUP THAT DIRECTORY, then remove"
603 " everything from it except for wallet.dat."), strDataDir.c_str());
604 return InitError(msg);
607 if (GetBoolArg("-salvagewallet"))
609 // Recover readable keypairs:
610 if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
614 if (filesystem::exists(GetDataDir() / strWalletFileName))
616 CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
617 if (r == CDBEnv::RECOVER_OK)
619 string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
620 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
621 " your balance or transactions are incorrect you should"
622 " restore from a backup."), strDataDir.c_str());
623 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
625 if (r == CDBEnv::RECOVER_FAIL)
626 return InitError(_("wallet.dat corrupt, salvage failed"));
629 // ********************************************************* Step 6: network initialization
631 if (mapArgs.count("-onlynet")) {
632 std::set<enum Network> nets;
633 for(std::string snet : mapMultiArgs["-onlynet"]) {
634 enum Network net = ParseNetwork(snet);
635 if (net == NET_UNROUTABLE)
636 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
639 for (int n = 0; n < NET_MAX; n++) {
640 enum Network net = (enum Network)n;
641 if (!nets.count(net))
645 #if defined(USE_IPV6)
648 SetLimited(NET_IPV6);
654 if (mapArgs.count("-proxy")) {
655 addrProxy = CService(mapArgs["-proxy"], nSocksDefault);
656 if (!addrProxy.IsValid())
657 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
659 if (!IsLimited(NET_IPV4))
660 SetProxy(NET_IPV4, addrProxy);
662 if (!IsLimited(NET_IPV6))
663 SetProxy(NET_IPV6, addrProxy);
665 SetNameProxy(addrProxy);
669 // -tor can override normal proxy, -notor disables tor entirely
670 if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
672 if (!mapArgs.count("-tor"))
673 addrOnion = addrProxy;
675 addrOnion = CService(mapArgs["-tor"], nSocksDefault);
676 if (!addrOnion.IsValid())
677 return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
678 SetProxy(NET_TOR, addrOnion);
679 SetReachable(NET_TOR);
682 // see Step 2: parameter interactions for more information about these
683 if (!IsLimited(NET_IPV4) || !IsLimited(NET_IPV6))
685 fNoListen = !GetBoolArg("-listen", true);
686 fDiscover = GetBoolArg("-discover", true);
687 fNameLookup = GetBoolArg("-dns", true);
689 // Don't listen, discover addresses or search for nodes if IPv4 and IPv6 networking is disabled.
691 fDiscover = fNameLookup = false;
692 SoftSetBoolArg("-irc", false);
693 SoftSetBoolArg("-dnsseed", false);
699 if (mapArgs.count("-bind")) {
700 for(std::string strBind : mapMultiArgs["-bind"]) {
702 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
703 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
704 fBound |= Bind(addrBind);
707 struct in_addr inaddr_any;
708 inaddr_any.s_addr = INADDR_ANY;
710 if (!IsLimited(NET_IPV6))
711 fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
713 if (!IsLimited(NET_IPV4))
714 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
718 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
721 // If Tor is reachable then listen on loopback interface,
722 // to allow allow other users reach you through the hidden service
723 if (!IsLimited(NET_TOR) && mapArgs.count("-torname")) {
724 std::string strError;
725 struct in_addr inaddr_loopback;
726 inaddr_loopback.s_addr = htonl(INADDR_LOOPBACK);
729 if (!BindListenPort(CService(in6addr_loopback, GetListenPort()), strError))
730 return InitError(strError);
732 if (!BindListenPort(CService(inaddr_loopback, GetListenPort()), strError))
733 return InitError(strError);
736 if (mapArgs.count("-externalip"))
738 for(string strAddr : mapMultiArgs["-externalip"]) {
739 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
740 if (!addrLocal.IsValid())
741 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
742 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
746 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
748 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
750 InitError(_("Invalid amount for -reservebalance=<amount>"));
755 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
757 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
758 InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
761 for(string strDest : mapMultiArgs["-seednode"])
764 // ********************************************************* Step 7: load blockchain
766 if (!bitdb.Open(GetDataDir()))
768 string msg = strprintf(_("Error initializing database environment %s!"
769 " To recover, BACKUP THAT DIRECTORY, then remove"
770 " everything from it except for wallet.dat."), strDataDir.c_str());
771 return InitError(msg);
774 if (GetBoolArg("-loadblockindextest"))
777 txdb.LoadBlockIndex();
783 printf("Loading block index...\n");
784 bool fLoaded = false;
787 std::string strLoadError;
788 uiInterface.InitMessage(_("Loading block index..."));
790 nStart = GetTimeMillis();
795 if (!LoadBlockIndex()) {
796 strLoadError = _("Error loading block database");
799 } catch(const std::exception&) {
800 strLoadError = _("Error opening block database");
809 // TODO: suggest reindex here
810 return InitError(strLoadError);
814 // as LoadBlockIndex can take several minutes, it's possible the user
815 // requested to kill bitcoin-qt during the last operation. If so, exit.
816 // As the program has not fully started yet, Shutdown() is possibly overkill.
817 if (fRequestShutdown)
819 printf("Shutdown requested. Exiting.\n");
822 printf(" block index %15" PRId64 "ms\n", GetTimeMillis() - nStart);
824 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
830 if (mapArgs.count("-printblock"))
832 auto strMatch = mapArgs["-printblock"];
834 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
836 auto hash = (*mi).first;
837 if (strMatch.compare(hash.ToString()) == 0)
839 auto pindex = (*mi).second;
841 block.ReadFromDisk(pindex);
842 block.BuildMerkleTree();
849 printf("No blocks matching %s were found\n", strMatch.c_str());
853 // ********************************************************* Step 8: load wallet
855 if (GetBoolArg("-zapwallettxes", false)) {
856 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
858 pwalletMain = new CWallet(strWalletFileName);
859 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
860 if (nZapWalletRet != DB_LOAD_OK) {
861 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
868 uiInterface.InitMessage(_("Loading wallet..."));
869 printf("Loading wallet...\n");
870 nStart = GetTimeMillis();
871 std::ostringstream strErrors;
872 bool fFirstRun = true;
873 pwalletMain = new CWallet(strWalletFileName);
874 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
875 if (nLoadWalletRet != DB_LOAD_OK)
877 if (nLoadWalletRet == DB_CORRUPT)
878 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
879 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
881 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
882 " or address book entries might be missing or incorrect."));
883 uiInterface.ThreadSafeMessageBox(msg, _("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
885 else if (nLoadWalletRet == DB_TOO_NEW)
886 strErrors << _("Error loading wallet.dat: Wallet requires newer version of NovaCoin") << "\n";
887 else if (nLoadWalletRet == DB_NEED_REWRITE)
889 strErrors << _("Wallet needed to be rewritten: restart NovaCoin to complete") << "\n";
890 printf("%s", strErrors.str().c_str());
891 return InitError(strErrors.str());
894 strErrors << _("Error loading wallet.dat") << "\n";
897 if (GetBoolArg("-upgradewallet", fFirstRun))
899 int nMaxVersion = GetArgInt("-upgradewallet", 0);
900 if (nMaxVersion == 0) // the -upgradewallet without argument case
902 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
903 nMaxVersion = CLIENT_VERSION;
904 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
907 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
908 if (nMaxVersion < pwalletMain->GetVersion())
909 strErrors << _("Cannot downgrade wallet") << "\n";
910 pwalletMain->SetMaxVersion(nMaxVersion);
915 // Create new keyUser and set as default key
916 RandAddSeedPerfmon();
918 CPubKey newDefaultKey;
919 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
920 strErrors << _("Cannot initialize keypool") << "\n";
921 pwalletMain->SetDefaultKey(newDefaultKey);
922 if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
923 strErrors << _("Cannot write default address") << "\n";
925 auto keyView = pwalletMain->GenerateNewMalleableKey();
927 if (!pwalletMain->GetMalleableKey(keyView, mKey))
928 strErrors << _("Unable to generate new malleable key");
929 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(keyView.GetMalleablePubKey()), ""))
930 strErrors << _("Cannot write default address") << "\n";
933 printf("%s", strErrors.str().c_str());
934 printf(" wallet %15" PRId64 "ms\n", GetTimeMillis() - nStart);
936 RegisterWallet(pwalletMain);
938 CBlockIndex *pindexRescan = pindexBest;
939 if (GetBoolArg("-rescan"))
940 pindexRescan = pindexGenesisBlock;
943 CWalletDB walletdb(strWalletFileName);
944 CBlockLocator locator;
945 if (walletdb.ReadBestBlock(locator))
946 pindexRescan = locator.GetBlockIndex();
948 if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
950 uiInterface.InitMessage(_("Rescanning..."));
951 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
952 nStart = GetTimeMillis();
953 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
954 printf(" rescan %15" PRId64 "ms\n", GetTimeMillis() - nStart);
957 // ********************************************************* Step 9: import blocks
959 if (mapArgs.count("-loadblock"))
961 uiInterface.InitMessage(_("Importing blockchain data file."));
963 for(string strFile : mapMultiArgs["-loadblock"])
965 FILE *file = fopen(strFile.c_str(), "rb");
967 LoadExternalBlockFile(file, uiInterface);
972 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
973 if (filesystem::exists(pathBootstrap)) {
974 uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
976 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
978 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
979 LoadExternalBlockFile(file, uiInterface);
980 RenameOver(pathBootstrap, pathBootstrapOld);
984 // ********************************************************* Step 10: load peers
986 uiInterface.InitMessage(_("Loading addresses..."));
987 printf("Loading addresses...\n");
988 nStart = GetTimeMillis();
992 if (!adb.Read(addrman))
993 printf("Invalid or missing peers.dat; recreating\n");
996 printf("Loaded %i addresses from peers.dat %" PRId64 "ms\n",
997 addrman.size(), GetTimeMillis() - nStart);
999 // ********************************************************* Step 11: start node
1001 if (!CheckDiskSpace())
1004 RandAddSeedPerfmon();
1007 printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
1008 printf("nBestHeight = %d\n", nBestHeight);
1009 printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
1010 printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
1011 printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
1013 if (!NewThread(StartNode, NULL))
1014 InitError(_("Error: could not start node"));
1017 NewThread(ThreadRPCServer, NULL);
1019 // ********************************************************* Step 13: IP collection thread
1020 strCollectorCommand = GetArg("-peercollector", "");
1021 if (!fTestNet && strCollectorCommand != "")
1022 NewThread(ThreadIPCollector, NULL);
1023 // ********************************************************* Step 14: finished
1025 uiInterface.InitMessage(_("Done loading"));
1026 printf("Done loading\n");
1028 if (!strErrors.str().empty())
1029 return InitError(strErrors.str());
1031 // Add wallet transactions that aren't already in a block to mapTransactions
1032 pwalletMain->ReacceptWalletTransactions();
1034 #if !defined(QT_GUI)
1035 // Loop until process is exit()ed from shutdown() function,
1036 // called from ThreadRPCServer thread when a "stop" command is received.