Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #include "headers.h"
0006 #include "db.h"
0007 #include "bitcoinrpc.h"
0008 #include "net.h"
0009 #include "init.h"
0010 #include "strlcpy.h"
0011 #include <boost/filesystem.hpp>
0012 #include <boost/filesystem/fstream.hpp>
0013 #include <boost/interprocess/sync/file_lock.hpp>
0014 
0015 
0016 using namespace std;
0017 using namespace boost;
0018 
0019 CWallet* pwalletMain;
0020 
0021 //////////////////////////////////////////////////////////////////////////////
0022 //
0023 // Shutdown
0024 //
0025 
0026 void ExitTimeout(void* parg)
0027 {
0028 }
0029 
0030 void Shutdown(void* parg)
0031 {
0032     static CCriticalSection cs_Shutdown;
0033     static bool fTaken;
0034     bool fFirstThread = false;
0035     TRY_CRITICAL_BLOCK(cs_Shutdown)
0036     {
0037         fFirstThread = !fTaken;
0038         fTaken = true;
0039     }
0040     static bool fExit;
0041     if (fFirstThread)
0042     {
0043         fShutdown = true;
0044         nTransactionsUpdated++;
0045         DBFlush(false);
0046         StopNode();
0047         DBFlush(true);
0048         boost::filesystem::remove(GetPidFile());
0049         UnregisterWallet(pwalletMain);
0050         delete pwalletMain;
0051         CreateThread(ExitTimeout, NULL);
0052         Sleep(50);
0053         printf("Bitcoin exiting\n\n");
0054         fExit = true;
0055         exit(0);
0056     }
0057     else
0058     {
0059         while (!fExit)
0060             Sleep(500);
0061         Sleep(100);
0062         ExitThread(0);
0063     }
0064 }
0065 
0066 void HandleSIGTERM(int)
0067 {
0068     fRequestShutdown = true;
0069 }
0070 
0071 
0072 
0073 
0074 
0075 
0076 //////////////////////////////////////////////////////////////////////////////
0077 //
0078 // Start
0079 //
0080 
0081 int main(int argc, char* argv[])
0082 {
0083     bool fRet = false;
0084     fRet = AppInit(argc, argv);
0085 
0086     if (fRet && fDaemon)
0087         return 0;
0088 
0089     return 1;
0090 }
0091 
0092 
0093 bool AppInit(int argc, char* argv[])
0094 {
0095     bool fRet = false;
0096     try
0097     {
0098         fRet = AppInit2(argc, argv);
0099     }
0100     catch (std::exception& e) {
0101         PrintException(&e, "AppInit()");
0102     } catch (...) {
0103         PrintException(NULL, "AppInit()");
0104     }
0105     if (!fRet)
0106         Shutdown(NULL);
0107     return fRet;
0108 }
0109 
0110 bool AppInit2(int argc, char* argv[])
0111 {
0112     umask(077);
0113 
0114     // Clean shutdown on SIGTERM
0115     struct sigaction sa;
0116     sa.sa_handler = HandleSIGTERM;
0117     sigemptyset(&sa.sa_mask);
0118     sa.sa_flags = 0;
0119     sigaction(SIGTERM, &sa, NULL);
0120     sigaction(SIGINT, &sa, NULL);
0121     sigaction(SIGHUP, &sa, NULL);
0122 
0123     //
0124     // Parameters
0125     //
0126     ParseParameters(argc, argv);
0127 
0128     if (mapArgs.count("-datadir"))
0129     {
0130         if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
0131         {
0132             filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
0133             strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
0134         }
0135         else
0136         {
0137             fprintf(stderr, "Error: Specified directory does not exist\n");
0138             Shutdown(NULL);
0139         }
0140     }
0141 
0142 
0143     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
0144 
0145     if (mapArgs.count("-?") || mapArgs.count("--help"))
0146     {
0147         string strUsage = string() +
0148           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
0149           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
0150             "  bitcoind [options]                   \t  " + "\n" +
0151             "  bitcoind [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
0152             "  bitcoind [options] help              \t\t  " + _("List commands\n") +
0153             "  bitcoind [options] help <command>    \t\t  " + _("Get help for a command\n") +
0154           _("Options:\n") +
0155             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
0156             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +
0157             "  -gen             \t\t  " + _("Generate coins\n") +
0158             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
0159             "  -min             \t\t  " + _("Start minimized\n") +
0160             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
0161             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)\n") +
0162             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
0163             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect\n") +
0164             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
0165             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)\n") +
0166             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
0167             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
0168             "  -noirc           \t  "   + _("Don't find peers using internet relay chat\n") +
0169             "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
0170             "  -nodnsseed       \t  "   + _("Don't bootstrap list of peers using DNS\n") +
0171             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
0172             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
0173             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
0174             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
0175             "  -paytxfee=<amt>  \t  "   + _("Fee per kB to add to transactions you send\n") +
0176             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
0177             "  -testnet         \t\t  " + _("Use the test network\n") +
0178             "  -debug           \t\t  " + _("Output extra debugging information\n") +
0179             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp\n") +
0180             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file\n") +
0181             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
0182             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
0183             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
0184             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
0185             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
0186             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
0187             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");
0188 
0189         strUsage += string() +
0190             "  -?               \t\t  " + _("This help message\n");
0191 
0192         // Remove tabs
0193         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
0194         fprintf(stderr, "%s", strUsage.c_str());
0195         return false;
0196     }
0197 
0198     fTestNet = GetBoolArg("-testnet");
0199     fDebug = GetBoolArg("-debug");
0200     fDaemon = GetBoolArg("-daemon");
0201 
0202     if (fDaemon)
0203         fServer = true;
0204     else
0205         fServer = GetBoolArg("-server");
0206 
0207     /* force fServer when running without GUI */
0208     fServer = true;
0209     fPrintToConsole = GetBoolArg("-printtoconsole");
0210     fPrintToDebugger = GetBoolArg("-printtodebugger");
0211     fLogTimestamps = GetBoolArg("-logtimestamps");
0212 
0213     for (int i = 1; i < argc; i++)
0214         if (!IsSwitchChar(argv[i][0]))
0215             fCommandLine = true;
0216 
0217     if (fCommandLine)
0218     {
0219         int ret = CommandLineRPC(argc, argv);
0220         exit(ret);
0221     }
0222 
0223     if (fDaemon)
0224     {
0225         // Daemonize
0226         pid_t pid = fork();
0227         if (pid < 0)
0228         {
0229             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
0230             return false;
0231         }
0232         if (pid > 0)
0233         {
0234             CreatePidFile(GetPidFile(), pid);
0235             return true;
0236         }
0237 
0238         pid_t sid = setsid();
0239         if (sid < 0)
0240             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
0241     }
0242 
0243     if (!fDebug && !pszSetDataDir[0])
0244         ShrinkDebugFile();
0245     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
0246     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
0247     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
0248 
0249     if (GetBoolArg("-loadblockindextest"))
0250     {
0251         CTxDB txdb("r");
0252         txdb.LoadBlockIndex();
0253         PrintBlockTree();
0254         return false;
0255     }
0256 
0257     // Make sure only a single bitcoin process is using the data directory.
0258     string strLockFile = GetDataDir() + "/.lock";
0259     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
0260     if (file) fclose(file);
0261     static boost::interprocess::file_lock lock(strLockFile.c_str());
0262     if (!lock.try_lock())
0263     {
0264         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
0265         return false;
0266     }
0267 
0268     string strErrors;
0269 
0270     //
0271     // Load data files
0272     //
0273     if (fDaemon)
0274         fprintf(stdout, "bitcoin server starting\n");
0275     strErrors = "";
0276     int64 nStart;
0277 
0278     InitMessage(_("Loading addresses..."));
0279     printf("Loading addresses...\n");
0280     nStart = GetTimeMillis();
0281     if (!LoadAddresses())
0282         strErrors += _("Error loading addr.dat      \n");
0283     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
0284 
0285     InitMessage(_("Loading block index..."));
0286     printf("Loading block index...\n");
0287     nStart = GetTimeMillis();
0288     if (!LoadBlockIndex())
0289         strErrors += _("Error loading blkindex.dat      \n");
0290     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
0291 
0292     InitMessage(_("Loading wallet..."));
0293     printf("Loading wallet...\n");
0294     nStart = GetTimeMillis();
0295     bool fFirstRun;
0296     pwalletMain = new CWallet("wallet.dat");
0297     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
0298     if (nLoadWalletRet != DB_LOAD_OK)
0299     {
0300         if (nLoadWalletRet == DB_CORRUPT)
0301             strErrors += _("Error loading wallet.dat: Wallet corrupted      \n");
0302         else if (nLoadWalletRet == DB_TOO_NEW)
0303             strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin      \n");
0304         else if (nLoadWalletRet == DB_NEED_REWRITE)
0305         {
0306             strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete    \n");
0307             wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
0308             return false;
0309         }
0310         else
0311             strErrors += _("Error loading wallet.dat      \n");
0312     }
0313     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
0314 
0315     RegisterWallet(pwalletMain);
0316 
0317     CBlockIndex *pindexRescan = pindexBest;
0318     if (GetBoolArg("-rescan"))
0319         pindexRescan = pindexGenesisBlock;
0320     else
0321     {
0322         CWalletDB walletdb("wallet.dat");
0323         CBlockLocator locator;
0324         if (walletdb.ReadBestBlock(locator))
0325             pindexRescan = locator.GetBlockIndex();
0326     }
0327     if (pindexBest != pindexRescan)
0328     {
0329         InitMessage(_("Rescanning..."));
0330         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
0331         nStart = GetTimeMillis();
0332         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
0333         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
0334     }
0335 
0336     InitMessage(_("Done loading"));
0337     printf("Done loading\n");
0338 
0339         //// debug print
0340         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
0341         printf("nBestHeight = %d\n",            nBestHeight);
0342         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
0343         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
0344         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
0345 
0346     if (!strErrors.empty())
0347     {
0348         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
0349         return false;
0350     }
0351 
0352     // Add wallet transactions that aren't already in a block to mapTransactions
0353     pwalletMain->ReacceptWalletTransactions();
0354 
0355     // Note: Bitcoin-QT stores several settings in the wallet, so we want
0356     // to load the wallet BEFORE parsing command-line arguments, so
0357     // the command-line/bitcoin.conf settings override GUI setting.
0358 
0359     //
0360     // Parameters
0361     //
0362     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
0363     {
0364         PrintBlockTree();
0365         return false;
0366     }
0367 
0368     if (mapArgs.count("-timeout"))
0369     {
0370         int nNewTimeout = GetArg("-timeout", 5000);
0371         if (nNewTimeout > 0 && nNewTimeout < 600000)
0372             nConnectTimeout = nNewTimeout;
0373     }
0374 
0375     if (mapArgs.count("-printblock"))
0376     {
0377         string strMatch = mapArgs["-printblock"];
0378         int nFound = 0;
0379         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
0380         {
0381             uint256 hash = (*mi).first;
0382             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
0383             {
0384                 CBlockIndex* pindex = (*mi).second;
0385                 CBlock block;
0386                 block.ReadFromDisk(pindex);
0387                 block.BuildMerkleTree();
0388                 block.print();
0389                 printf("\n");
0390                 nFound++;
0391             }
0392         }
0393         if (nFound == 0)
0394             printf("No blocks matching %s were found\n", strMatch.c_str());
0395         return false;
0396     }
0397 
0398     fGenerateBitcoins = GetBoolArg("-gen");
0399 
0400     if (mapArgs.count("-proxy"))
0401     {
0402         fUseProxy = true;
0403         addrProxy = CAddress(mapArgs["-proxy"]);
0404         if (!addrProxy.IsValid())
0405         {
0406             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
0407             return false;
0408         }
0409     }
0410 
0411     bool fTor = (fUseProxy && addrProxy.port == htons(9050));
0412     if (fTor)
0413     {
0414         // Use SoftSetArg here so user can override any of these if they wish.
0415         // Note: the GetBoolArg() calls for all of these must happen later.
0416         SoftSetArg("-nolisten", true);
0417         SoftSetArg("-noirc", true);
0418         SoftSetArg("-nodnsseed", true);
0419         SoftSetArg("-dns", false);
0420     }
0421 
0422     fAllowDNS = GetBoolArg("-dns");
0423     fNoListen = GetBoolArg("-nolisten");
0424 
0425     // Command-line args override in-wallet settings:
0426 
0427     if (!fNoListen)
0428     {
0429         if (!BindListenPort(strErrors))
0430         {
0431             wxMessageBox(strErrors, "Bitcoin");
0432             return false;
0433         }
0434     }
0435 
0436     if (mapArgs.count("-addnode"))
0437     {
0438         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
0439         {
0440             CAddress addr(strAddr, fAllowDNS);
0441             addr.nTime = 0; // so it won't relay unless successfully connected
0442             if (addr.IsValid())
0443                 AddAddress(addr);
0444         }
0445     }
0446 
0447     if (mapArgs.count("-paytxfee"))
0448     {
0449         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
0450         {
0451             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
0452             return false;
0453         }
0454         if (nTransactionFee > 0.25 * COIN)
0455             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
0456     }
0457 
0458     //
0459     // Start the node
0460     //
0461     if (!CheckDiskSpace())
0462         return false;
0463 
0464     RandAddSeedPerfmon();
0465 
0466     if (!CreateThread(StartNode, NULL))
0467         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
0468 
0469     if (fServer)
0470         CreateThread(ThreadRPCServer, NULL);
0471 
0472     while (1)
0473         Sleep(5000);
0474 
0475     return true;
0476 }