1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include "bitcoinrpc.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>
19 #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
20 #define _BITCOIN_QT_PLUGINS_INCLUDED
23 Q_IMPORT_PLUGIN(qcncodecs)
24 Q_IMPORT_PLUGIN(qjpcodecs)
25 Q_IMPORT_PLUGIN(qtwcodecs)
26 Q_IMPORT_PLUGIN(qkrcodecs)
30 using namespace boost;
34 //////////////////////////////////////////////////////////////////////////////
39 void ExitTimeout(void* parg)
47 void Shutdown(void* parg)
49 static CCriticalSection cs_Shutdown;
51 bool fFirstThread = false;
52 TRY_CRITICAL_BLOCK(cs_Shutdown)
54 fFirstThread = !fTaken;
61 nTransactionsUpdated++;
65 boost::filesystem::remove(GetPidFile());
66 UnregisterWallet(pwalletMain);
68 CreateThread(ExitTimeout, NULL);
70 printf("Bitcoin exiting\n\n");
83 void HandleSIGTERM(int)
85 fRequestShutdown = true;
93 //////////////////////////////////////////////////////////////////////////////
98 int main(int argc, char* argv[])
101 fRet = AppInit(argc, argv);
110 bool AppInit(int argc, char* argv[])
115 fRet = AppInit2(argc, argv);
117 catch (std::exception& e) {
118 PrintException(&e, "AppInit()");
120 PrintException(NULL, "AppInit()");
127 bool AppInit2(int argc, char* argv[])
130 // Turn off microsoft heap dump noise
131 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
132 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
135 // Disable confusing "helpful" text message on abort, ctrl-c
136 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
142 // Clean shutdown on SIGTERM
144 sa.sa_handler = HandleSIGTERM;
145 sigemptyset(&sa.sa_mask);
147 sigaction(SIGTERM, &sa, NULL);
148 sigaction(SIGINT, &sa, NULL);
149 sigaction(SIGHUP, &sa, NULL);
155 // If Qt is used, parameters are parsed in qt/bitcoin.cpp's main()
157 ParseParameters(argc, argv);
160 if (mapArgs.count("-datadir"))
162 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
164 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
165 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
169 fprintf(stderr, "Error: Specified directory does not exist\n");
175 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
177 if (mapArgs.count("-?") || mapArgs.count("--help"))
179 string strUsage = string() +
180 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
181 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
182 " bitcoind [options] \t " + "\n" +
183 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
184 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
185 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
186 _("Options:") + "\n" +
187 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
188 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
189 " -gen \t\t " + _("Generate coins") + "\n" +
190 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
191 " -min \t\t " + _("Start minimized") + "\n" +
192 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
193 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
194 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
195 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
196 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
197 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
198 " -addnode=<ip> \t " + _("Add a node to connect to") + "\n" +
199 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
200 " -nolisten \t " + _("Don't accept connections from outside") + "\n" +
201 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS") + "\n" +
202 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
203 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
204 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
205 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
208 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port") + "\n" +
210 " -upnp \t " + _("Attempt to use UPnP to map the listening port") + "\n" +
213 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
215 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
218 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
220 " -testnet \t\t " + _("Use the test network") + "\n" +
221 " -debug \t\t " + _("Output extra debugging information") + "\n" +
222 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
223 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
225 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
227 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
228 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
229 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
230 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
231 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
232 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
233 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n";
236 strUsage += string() +
237 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
238 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
239 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
240 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
241 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
244 strUsage += string() +
245 " -? \t\t " + _("This help message") + "\n";
248 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
249 fprintf(stderr, "%s", strUsage.c_str());
253 fDebug = GetBoolArg("-debug");
254 fAllowDNS = GetBoolArg("-dns");
257 fDaemon = GetBoolArg("-daemon");
265 fServer = GetBoolArg("-server");
267 /* force fServer when running without GUI */
271 fPrintToConsole = GetBoolArg("-printtoconsole");
272 fPrintToDebugger = GetBoolArg("-printtodebugger");
274 fTestNet = GetBoolArg("-testnet");
275 bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
276 fNoListen = GetBoolArg("-nolisten") || fTOR;
277 fLogTimestamps = GetBoolArg("-logtimestamps");
280 for (int i = 1; i < argc; i++)
281 if (!IsSwitchChar(argv[i][0]))
286 int ret = CommandLineRPC(argc, argv);
298 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
303 CreatePidFile(GetPidFile(), pid);
307 pid_t sid = setsid();
309 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
313 if (!fDebug && !pszSetDataDir[0])
315 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
316 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
317 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
319 if (GetBoolArg("-loadblockindextest"))
322 txdb.LoadBlockIndex();
327 // Make sure only a single bitcoin process is using the data directory.
328 string strLockFile = GetDataDir() + "/.lock";
329 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
330 if (file) fclose(file);
331 static boost::interprocess::file_lock lock(strLockFile.c_str());
332 if (!lock.try_lock())
334 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
338 // Bind to the port early so we can tell if another instance is already running.
341 std::string strError;
342 if (!BindListenPort(strError))
344 wxMessageBox(strError, "Bitcoin");
349 std::ostringstream strErrors;
354 fprintf(stdout, "bitcoin server starting\n");
357 InitMessage(_("Loading addresses..."));
358 printf("Loading addresses...\n");
359 nStart = GetTimeMillis();
360 if (!LoadAddresses())
361 strErrors << _("Error loading addr.dat") << "\n";
362 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
364 InitMessage(_("Loading block index..."));
365 printf("Loading block index...\n");
366 nStart = GetTimeMillis();
367 if (!LoadBlockIndex())
368 strErrors << _("Error loading blkindex.dat") << "\n";
369 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
371 InitMessage(_("Loading wallet..."));
372 printf("Loading wallet...\n");
373 nStart = GetTimeMillis();
375 pwalletMain = new CWallet("wallet.dat");
376 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
377 if (nLoadWalletRet != DB_LOAD_OK)
379 if (nLoadWalletRet == DB_CORRUPT)
380 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
381 else if (nLoadWalletRet == DB_TOO_NEW)
382 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
383 else if (nLoadWalletRet == DB_NEED_REWRITE)
385 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
386 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
390 strErrors << _("Error loading wallet.dat") << "\n";
392 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
394 RegisterWallet(pwalletMain);
396 CBlockIndex *pindexRescan = pindexBest;
397 if (GetBoolArg("-rescan"))
398 pindexRescan = pindexGenesisBlock;
401 CWalletDB walletdb("wallet.dat");
402 CBlockLocator locator;
403 if (walletdb.ReadBestBlock(locator))
404 pindexRescan = locator.GetBlockIndex();
406 if (pindexBest != pindexRescan)
408 InitMessage(_("Rescanning..."));
409 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
410 nStart = GetTimeMillis();
411 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
412 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
415 InitMessage(_("Done loading"));
416 printf("Done loading\n");
419 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
420 printf("nBestHeight = %d\n", nBestHeight);
421 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
422 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
423 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
425 if (!strErrors.str().empty())
427 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
431 // Add wallet transactions that aren't already in a block to mapTransactions
432 pwalletMain->ReacceptWalletTransactions();
437 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
443 if (mapArgs.count("-timeout"))
445 int nNewTimeout = GetArg("-timeout", 5000);
446 if (nNewTimeout > 0 && nNewTimeout < 600000)
447 nConnectTimeout = nNewTimeout;
450 if (mapArgs.count("-printblock"))
452 string strMatch = mapArgs["-printblock"];
454 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
456 uint256 hash = (*mi).first;
457 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
459 CBlockIndex* pindex = (*mi).second;
461 block.ReadFromDisk(pindex);
462 block.BuildMerkleTree();
469 printf("No blocks matching %s were found\n", strMatch.c_str());
473 fGenerateBitcoins = GetBoolArg("-gen");
475 if (mapArgs.count("-proxy"))
478 addrProxy = CAddress(mapArgs["-proxy"]);
479 if (!addrProxy.IsValid())
481 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
486 if (mapArgs.count("-addnode"))
488 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
490 CAddress addr(strAddr, fAllowDNS);
491 addr.nTime = 0; // so it won't relay unless successfully connected
497 if (mapArgs.count("-paytxfee"))
499 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
501 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
504 if (nTransactionFee > 0.25 * COIN)
505 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
511 if (GetBoolArg("-noupnp"))
514 if (GetBoolArg("-upnp"))
522 if (!CheckDiskSpace())
525 RandAddSeedPerfmon();
527 if (!CreateThread(StartNode, NULL))
528 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
531 CreateThread(ThreadRPCServer, NULL);
534 if(GetStartOnSystemStartup())
535 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
547 string StartupShortcutPath()
549 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
552 bool GetStartOnSystemStartup()
554 return filesystem::exists(StartupShortcutPath().c_str());
557 bool SetStartOnSystemStartup(bool fAutoStart)
559 // If the shortcut exists already, remove it for updating
560 remove(StartupShortcutPath().c_str());
566 // Get a pointer to the IShellLink interface.
567 IShellLink* psl = NULL;
568 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
569 CLSCTX_INPROC_SERVER, IID_IShellLink,
570 reinterpret_cast<void**>(&psl));
574 // Get the current executable path
575 TCHAR pszExePath[MAX_PATH];
576 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
578 TCHAR pszArgs[5] = TEXT("-min");
580 // Set the path to the shortcut target
581 psl->SetPath(pszExePath);
582 PathRemoveFileSpec(pszExePath);
583 psl->SetWorkingDirectory(pszExePath);
584 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
585 psl->SetArguments(pszArgs);
587 // Query IShellLink for the IPersistFile interface for
588 // saving the shortcut in persistent storage.
589 IPersistFile* ppf = NULL;
590 hres = psl->QueryInterface(IID_IPersistFile,
591 reinterpret_cast<void**>(&ppf));
594 WCHAR pwsz[MAX_PATH];
595 // Ensure that the string is ANSI.
596 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
597 // Save the link by calling IPersistFile::Save.
598 hres = ppf->Save(pwsz, TRUE);
614 // Follow the Desktop Application Autostart Spec:
615 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
617 boost::filesystem::path GetAutostartDir()
619 namespace fs = boost::filesystem;
621 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
622 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
623 char* pszHome = getenv("HOME");
624 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
628 boost::filesystem::path GetAutostartFilePath()
630 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
633 bool GetStartOnSystemStartup()
635 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
636 if (!optionFile.good())
638 // Scan through file for "Hidden=true":
640 while (!optionFile.eof())
642 getline(optionFile, line);
643 if (line.find("Hidden") != string::npos &&
644 line.find("true") != string::npos)
652 bool SetStartOnSystemStartup(bool fAutoStart)
656 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
657 unlink(GetAutostartFilePath().string().c_str());
659 unlink(GetAutostartFilePath().native_file_string().c_str());
664 char pszExePath[MAX_PATH+1];
665 memset(pszExePath, 0, sizeof(pszExePath));
666 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
669 boost::filesystem::create_directories(GetAutostartDir());
671 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
672 if (!optionFile.good())
674 // Write a bitcoin.desktop file to the autostart directory:
675 optionFile << "[Desktop Entry]\n";
676 optionFile << "Type=Application\n";
677 optionFile << "Name=Bitcoin\n";
678 optionFile << "Exec=" << pszExePath << " -min\n";
679 optionFile << "Terminal=false\n";
680 optionFile << "Hidden=false\n";
687 // TODO: OSX startup stuff; see:
688 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
690 bool GetStartOnSystemStartup() { return false; }
691 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }