diff options
Diffstat (limited to 'src/init.cpp')
-rw-r--r-- | src/init.cpp | 485 |
1 files changed, 198 insertions, 287 deletions
diff --git a/src/init.cpp b/src/init.cpp index 78f838f7cb..daa12d8995 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1,14 +1,22 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2012 The Bitcoin developers +// Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#if defined(HAVE_CONFIG_H) +#include "bitcoin-config.h" +#endif + +#include "init.h" +#include "main.h" +#include "core.h" +#include "chainparams.h" #include "txdb.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "net.h" -#include "init.h" #include "util.h" +#include "miner.h" #include "ui_interface.h" #include "checkpoints.h" @@ -26,6 +34,7 @@ using namespace std; using namespace boost; +std::string strWalletFile; CWallet* pwalletMain; CClientUIInterface uiInterface; @@ -45,6 +54,7 @@ enum BindFlags { BF_REPORT_ERROR = (1U << 1) }; + ////////////////////////////////////////////////////////////////////////////// // // Shutdown @@ -90,6 +100,7 @@ static CCoinsViewDB *pcoinsdbview; void Shutdown() { + LogPrintf("Shutdown : In progress...\n"); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; @@ -98,12 +109,14 @@ void Shutdown() nTransactionsUpdated++; StopRPCThreads(); ShutdownRPCMining(); - bitdb.Flush(false); + if (pwalletMain) + bitdb.Flush(false); + GenerateBitcoins(false, NULL); StopNode(); { LOCK(cs_main); if (pwalletMain) - pwalletMain->SetBestChain(CBlockLocator(pindexBest)); + pwalletMain->SetBestChain(chainActive.GetLocator()); if (pblocktree) pblocktree->Flush(); if (pcoinsTip) @@ -112,26 +125,18 @@ void Shutdown() delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; } - bitdb.Flush(true); + if (pwalletMain) + bitdb.Flush(true); boost::filesystem::remove(GetPidFile()); - UnregisterWallet(pwalletMain); - delete pwalletMain; + UnregisterAllWallets(); + if (pwalletMain) + delete pwalletMain; + LogPrintf("Shutdown : done\n"); } // // Signal handlers are very limited in what they are allowed to do, so: // -void DetectShutdownThread(boost::thread_group* threadGroup) -{ - // Tell the main threads to shutdown. - while (!fRequestShutdown) - { - MilliSleep(200); - if (fRequestShutdown) - threadGroup->interrupt_all(); - } -} - void HandleSIGTERM(int) { fRequestShutdown = true; @@ -142,127 +147,6 @@ void HandleSIGHUP(int) fReopenDebugLog = true; } - - - - -////////////////////////////////////////////////////////////////////////////// -// -// Start -// -#if !defined(QT_GUI) -bool AppInit(int argc, char* argv[]) -{ - boost::thread_group threadGroup; - boost::thread* detectShutdownThread = NULL; - - bool fRet = false; - try - { - // - // Parameters - // - // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() - ParseParameters(argc, argv); - if (!boost::filesystem::is_directory(GetDataDir(false))) - { - fprintf(stderr, "Error: Specified directory does not exist\n"); - Shutdown(); - } - ReadConfigFile(mapArgs, mapMultiArgs); - - if (mapArgs.count("-?") || mapArgs.count("--help")) - { - // First part of help message is specific to bitcoind / RPC client - std::string strUsage = _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" + - _("Usage:") + "\n" + - " bitcoind [options] " + "\n" + - " bitcoind [options] <command> [params] " + _("Send command to -server or bitcoind") + "\n" + - " bitcoind [options] help " + _("List commands") + "\n" + - " bitcoind [options] help <command> " + _("Get help for a command") + "\n"; - - strUsage += "\n" + HelpMessage(); - - fprintf(stdout, "%s", strUsage.c_str()); - return false; - } - - // Command-line RPC - for (int i = 1; i < argc; i++) - if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:")) - fCommandLine = true; - - if (fCommandLine) - { - int ret = CommandLineRPC(argc, argv); - exit(ret); - } -#if !defined(WIN32) - fDaemon = GetBoolArg("-daemon", false); - if (fDaemon) - { - // Daemonize - pid_t pid = fork(); - if (pid < 0) - { - fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); - return false; - } - if (pid > 0) // Parent process, pid is child process id - { - CreatePidFile(GetPidFile(), pid); - return true; - } - // Child process falls through to rest of initialization - - pid_t sid = setsid(); - if (sid < 0) - fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); - } -#endif - - detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup)); - fRet = AppInit2(threadGroup); - } - catch (std::exception& e) { - PrintExceptionContinue(&e, "AppInit()"); - } catch (...) { - PrintExceptionContinue(NULL, "AppInit()"); - } - if (!fRet) { - if (detectShutdownThread) - detectShutdownThread->interrupt(); - threadGroup.interrupt_all(); - } - - if (detectShutdownThread) - { - detectShutdownThread->join(); - delete detectShutdownThread; - detectShutdownThread = NULL; - } - Shutdown(); - - return fRet; -} - -extern void noui_connect(); -int main(int argc, char* argv[]) -{ - bool fRet = false; - - // Connect bitcoind signal handlers - noui_connect(); - - fRet = AppInit(argc, argv); - - if (fRet && fDaemon) - return 0; - - return (fRet ? 0 : 1); -} -#endif - bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); @@ -290,89 +174,91 @@ bool static Bind(const CService &addr, unsigned int flags) { // Core-specific options shared between UI and daemon std::string HelpMessage() { - string strUsage = _("Options:") + "\n" + - " -? " + _("This help message") + "\n" + - " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n" + - " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n" + - " -gen " + _("Generate coins (default: 0)") + "\n" + - " -datadir=<dir> " + _("Specify data directory") + "\n" + - " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" + - " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" + - " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" + - " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" + - " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n" - " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" + - " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" + - " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" + - " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + - " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" + - " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" + - " -externalip=<ip> " + _("Specify your own public address") + "\n" + - " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" + - " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" + - " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" + - " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" + - " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" + - " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" + - " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" + - " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" + - " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" + - " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" + + string strUsage = _("Options:") + "\n"; + strUsage += " -? " + _("This help message") + "\n"; + strUsage += " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n"; + strUsage += " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n"; + strUsage += " -gen " + _("Generate coins (default: 0)") + "\n"; + strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; + strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n"; + strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n"; + strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n"; + strUsage += " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n"; + strUsage += " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n"; + strUsage += " -onion=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"; + strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n"; + strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n"; + strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n"; + strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n"; + strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n"; + strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n"; + strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n"; + strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n"; + strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n"; + strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n"; + strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n"; + strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n"; + strUsage += " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n"; + strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n"; + strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n"; + strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n"; + strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n"; #ifdef USE_UPNP #if USE_UPNP - " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" + + strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n"; #else - " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" + -#endif + strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n"; #endif - " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" + -#ifdef QT_GUI - " -server " + _("Accept command line and JSON-RPC commands") + "\n" + #endif -#if !defined(WIN32) && !defined(QT_GUI) - " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" + + strUsage += " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n"; + if (fHaveGUI) + strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n"; +#if !defined(WIN32) + if (fHaveGUI) + strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n"; #endif - " -testnet " + _("Use the test network") + "\n" + - " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" + - " -debugnet " + _("Output extra network debugging information") + "\n" + - " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" + - " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" + - " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" + + strUsage += " -testnet " + _("Use the test network") + "\n"; + strUsage += " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n"; + strUsage += " -debugnet " + _("Output extra network debugging information") + "\n"; + strUsage += " -logtimestamps " + _("Prepend debug output with timestamp") + "\n"; + strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n"; + strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n"; + strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be " + "solved instantly. This is intended for regression testing tools and app development.") + "\n"; #ifdef WIN32 - " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" + + strUsage += " -printtodebugger " + _("Send trace/debug info to debugger") + "\n"; #endif - " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" + - " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" + - " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n" + - " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" + -#ifndef QT_GUI - " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" + -#endif - " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" + - " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" + - " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" + - " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" + - " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" + - " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" + - " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" + - " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" + - " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" + - " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" + - " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" + - " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" + - " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" + - " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" + - - "\n" + _("Block creation options:") + "\n" + - " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" + - " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" + - " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" + - - "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" + - " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" + - " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" + - " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" + - " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n"; + strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; + strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; + strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n"; + strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n"; + if (!fHaveGUI) + strUsage += " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n"; + strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n"; + strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n"; + strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n"; + strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)") + "\n"; + strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n"; + strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n"; + strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n"; + strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n"; + strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n"; + strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n"; + strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n"; + strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n"; + strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n"; + strUsage += " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n"; + + strUsage += "\n" + _("Block creation options:") + "\n"; + strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n"; + strUsage += " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n"; + strUsage += " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n"; + + strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; + strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; + strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n"; + strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n"; + strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n"; return strUsage; } @@ -403,13 +289,13 @@ void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) FILE *file = OpenBlockFile(pos, true); if (!file) break; - printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); + LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; - printf("Reindexing finished\n"); + LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); } @@ -421,7 +307,7 @@ void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) if (file) { CImportingNow imp; filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; - printf("Importing bootstrap.dat...\n"); + LogPrintf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); } @@ -432,7 +318,7 @@ void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) FILE *file = fopen(path.string().c_str(), "rb"); if (file) { CImportingNow imp; - printf("Importing %s...\n", path.string().c_str()); + LogPrintf("Importing %s...\n", path.string().c_str()); LoadExternalBlockFile(file); } } @@ -458,8 +344,8 @@ bool AppInit2(boost::thread_group& threadGroup) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE -// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), -// which is not correct. Can be removed, when GCCs winbase.h is fixed! + // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), + // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); @@ -491,13 +377,15 @@ bool AppInit2(boost::thread_group& threadGroup) sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); + +#if defined (__SVR4) && defined (__sun) + // ignore SIGPIPE on Solaris + signal(SIGPIPE, SIG_IGN); +#endif #endif // ********************************************************* Step 2: parameter interactions - fTestNet = GetBoolArg("-testnet", false); - Checkpoints::fEnabled = GetBoolArg("-checkpoints", true); - if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified @@ -543,8 +431,10 @@ bool AppInit2(boost::thread_group& threadGroup) // ********************************************************* Step 3: parameter-to-internal-flags - fDebug = GetBoolArg("-debug", false); + if (mapMultiArgs.count("-debug")) fDebug = true; fBenchmark = GetBoolArg("-benchmark", false); + mempool.fChecks = GetBoolArg("-checkmempool", RegTest()); + Checkpoints::fEnabled = GetBoolArg("-checkpoints", true); // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", 0); @@ -567,9 +457,8 @@ bool AppInit2(boost::thread_group& threadGroup) fServer = GetBoolArg("-server", false); /* force fServer when running without GUI */ -#if !defined(QT_GUI) - fServer = true; -#endif + if (!fHaveGUI) + fServer = true; fPrintToConsole = GetBoolArg("-printtoconsole", false); fPrintToDebugger = GetBoolArg("-printtodebugger", false); fLogTimestamps = GetBoolArg("-logtimestamps", false); @@ -618,10 +507,16 @@ bool AppInit2(boost::thread_group& threadGroup) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } + strWalletFile = GetArg("-wallet", "wallet.dat"); + // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log std::string strDataDir = GetDataDir().string(); + // Wallet file must be a plain filename without a directory + if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) + return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile.c_str(), strDataDir.c_str())); + // Make sure only a single Bitcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. @@ -632,21 +527,21 @@ bool AppInit2(boost::thread_group& threadGroup) if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); - printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); - printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); - printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); + LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); + LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) - printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); - printf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); - printf("Using data directory %s\n", strDataDir.c_str()); - printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); + LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); + LogPrintf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); + LogPrintf("Using data directory %s\n", strDataDir.c_str()); + LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); std::ostringstream strErrors; if (fDaemon) fprintf(stdout, "Bitcoin server starting\n"); if (nScriptCheckThreads) { - printf("Using %u threads for script verification\n", nScriptCheckThreads); + LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } @@ -664,7 +559,7 @@ bool AppInit2(boost::thread_group& threadGroup) boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime()); try { boost::filesystem::rename(pathDatabase, pathDatabaseBak); - printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str()); + LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str()); } catch(boost::filesystem::filesystem_error &error) { // failure is ok (well, not really, but it's not worse than what we started with) } @@ -680,13 +575,13 @@ bool AppInit2(boost::thread_group& threadGroup) if (GetBoolArg("-salvagewallet", false)) { // Recover readable keypairs: - if (!CWalletDB::Recover(bitdb, "wallet.dat", true)) + if (!CWalletDB::Recover(bitdb, strWalletFile, true)) return false; } - if (filesystem::exists(GetDataDir() / "wallet.dat")) + if (filesystem::exists(GetDataDir() / strWalletFile)) { - CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover); + CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" @@ -701,6 +596,8 @@ bool AppInit2(boost::thread_group& threadGroup) // ********************************************************* Step 6: network initialization + RegisterNodeSignals(GetNodeSignals()); + int nSocksVersion = GetArg("-socks", 5); if (nSocksVersion != 4 && nSocksVersion != 5) return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion)); @@ -745,15 +642,20 @@ bool AppInit2(boost::thread_group& threadGroup) fProxy = true; } - // -tor can override normal proxy, -notor disables tor entirely - if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) { + // -onion can override normal proxy, -noonion disables tor entirely + // -tor here is a temporary backwards compatibility measure + if (mapArgs.count("-tor")) + printf("Notice: option -tor has been replaced with -onion and will be removed in a later version.\n"); + if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") && + !(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && + (fProxy || mapArgs.count("-onion") || mapArgs.count("-tor"))) { CService addrOnion; - if (!mapArgs.count("-tor")) + if (!mapArgs.count("-onion") && !mapArgs.count("-tor")) addrOnion = addrProxy; else - addrOnion = CService(mapArgs["-tor"], 9050); + addrOnion = mapArgs.count("-onion")?CService(mapArgs["-onion"], 9050):CService(mapArgs["-tor"], 9050); if (!addrOnion.IsValid()) - return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str())); + return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs.count("-onion")?mapArgs["-onion"].c_str():mapArgs["-tor"].c_str())); SetProxy(NET_TOR, addrOnion, 5); SetReachable(NET_TOR); } @@ -813,12 +715,12 @@ bool AppInit2(boost::thread_group& threadGroup) filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); try { filesystem::create_hard_link(source, dest); - printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str()); + LogPrintf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str()); linked = true; } catch (filesystem::filesystem_error & e) { // Note: hardlink creation failing is not a disaster, it just means // blocks will get re-downloaded from peers. - printf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); + LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); break; } } @@ -869,7 +771,7 @@ bool AppInit2(boost::thread_group& threadGroup) // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). - if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL) + if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL) return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); // Initialize the block index (no-op if non-empty database was already loaded) @@ -878,12 +780,20 @@ bool AppInit2(boost::thread_group& threadGroup) break; } + // Check for changed -txindex state + if (fTxIndex != GetBoolArg("-txindex", false)) { + strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); + break; + } + uiInterface.InitMessage(_("Verifying blocks...")); - if (!VerifyDB()) { + if (!VerifyDB(GetArg("-checklevel", 3), + GetArg("-checkblocks", 288))) { strLoadError = _("Corrupted block database detected"); break; } } catch(std::exception &e) { + if (fDebug) LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); break; } @@ -895,12 +805,13 @@ bool AppInit2(boost::thread_group& threadGroup) // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeMessageBox( - strLoadError + ".\n" + _("Do you want to rebuild the block database now?"), + strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; fRequestShutdown = false; } else { + LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { @@ -909,18 +820,15 @@ bool AppInit2(boost::thread_group& threadGroup) } } - if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false)) - return InitError(_("You need to rebuild the databases using -reindex to change -txindex")); - // as LoadBlockIndex can take several minutes, it's possible the user // requested to kill bitcoin-qt during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { - printf("Shutdown requested. Exiting.\n"); + LogPrintf("Shutdown requested. Exiting.\n"); return false; } - printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart); + LogPrintf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false)) { @@ -939,15 +847,15 @@ bool AppInit2(boost::thread_group& threadGroup) { CBlockIndex* pindex = (*mi).second; CBlock block; - block.ReadFromDisk(pindex); + ReadBlockFromDisk(block, pindex); block.BuildMerkleTree(); block.print(); - printf("\n"); + LogPrintf("\n"); nFound++; } } if (nFound == 0) - printf("No blocks matching %s were found\n", strMatch.c_str()); + LogPrintf("No blocks matching %s were found\n", strMatch.c_str()); return false; } @@ -957,7 +865,7 @@ bool AppInit2(boost::thread_group& threadGroup) nStart = GetTimeMillis(); bool fFirstRun = true; - pwalletMain = new CWallet("wallet.dat"); + pwalletMain = new CWallet(strWalletFile); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { @@ -974,7 +882,7 @@ bool AppInit2(boost::thread_group& threadGroup) else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n"; - printf("%s", strErrors.str().c_str()); + LogPrintf("%s", strErrors.str().c_str()); return InitError(strErrors.str()); } else @@ -986,12 +894,12 @@ bool AppInit2(boost::thread_group& threadGroup) int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { - printf("Performing wallet upgrade to %i\n", FEATURE_LATEST); + LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else - printf("Allowing wallet upgrade up to %i\n", nMaxVersion); + LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); @@ -1003,40 +911,40 @@ bool AppInit2(boost::thread_group& threadGroup) RandAddSeedPerfmon(); CPubKey newDefaultKey; - if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) { + if (pwalletMain->GetKeyFromPool(newDefaultKey)) { pwalletMain->SetDefaultKey(newDefaultKey); - if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), "")) + if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive")) strErrors << _("Cannot write default address") << "\n"; } - pwalletMain->SetBestChain(CBlockLocator(pindexBest)); + pwalletMain->SetBestChain(chainActive.GetLocator()); } - printf("%s", strErrors.str().c_str()); - printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart); + LogPrintf("%s", strErrors.str().c_str()); + LogPrintf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); - CBlockIndex *pindexRescan = pindexBest; + CBlockIndex *pindexRescan = chainActive.Tip(); if (GetBoolArg("-rescan", false)) - pindexRescan = pindexGenesisBlock; + pindexRescan = chainActive.Genesis(); else { - CWalletDB walletdb("wallet.dat"); + CWalletDB walletdb(strWalletFile); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) - pindexRescan = locator.GetBlockIndex(); + pindexRescan = chainActive.FindFork(locator); else - pindexRescan = pindexGenesisBlock; + pindexRescan = chainActive.Genesis(); } - if (pindexBest && pindexBest != pindexRescan) + if (chainActive.Tip() && chainActive.Tip() != pindexRescan) { uiInterface.InitMessage(_("Rescanning...")); - printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight); + LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); - printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart); - pwalletMain->SetBestChain(CBlockLocator(pindexBest)); + LogPrintf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart); + pwalletMain->SetBestChain(chainActive.GetLocator()); nWalletDBUpdated++; } @@ -1064,10 +972,10 @@ bool AppInit2(boost::thread_group& threadGroup) { CAddrDB adb; if (!adb.Read(addrman)) - printf("Invalid or missing peers.dat; recreating\n"); + LogPrintf("Invalid or missing peers.dat; recreating\n"); } - printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n", + LogPrintf("Loaded %i addresses from peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 11: start node @@ -1081,11 +989,11 @@ bool AppInit2(boost::thread_group& threadGroup) RandAddSeedPerfmon(); //// debug print - printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size()); - printf("nBestHeight = %d\n", nBestHeight); - printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size()); - printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size()); - printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size()); + LogPrintf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size()); + LogPrintf("nBestHeight = %d\n", chainActive.Height()); + LogPrintf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); + LogPrintf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); + LogPrintf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0); StartNode(threadGroup); @@ -1095,17 +1003,20 @@ bool AppInit2(boost::thread_group& threadGroup) StartRPCThreads(); // Generate coins in the background - GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain); + if (pwalletMain) + GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain); // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); - // Add wallet transactions that aren't already in a block to mapTransactions - pwalletMain->ReacceptWalletTransactions(); + if (pwalletMain) { + // Add wallet transactions that aren't already in a block to mapTransactions + pwalletMain->ReacceptWalletTransactions(); - // Run a thread to flush wallet periodically - threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); + // Run a thread to flush wallet periodically + threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); + } return !fRequestShutdown; } |