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 license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include "bitcoinrpc.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/filesystem/convenience.hpp>
14 #include <boost/interprocess/sync/file_lock.hpp>
16 #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
17 #define _BITCOIN_QT_PLUGINS_INCLUDED
20 Q_IMPORT_PLUGIN(qcncodecs)
21 Q_IMPORT_PLUGIN(qjpcodecs)
22 Q_IMPORT_PLUGIN(qtwcodecs)
23 Q_IMPORT_PLUGIN(qkrcodecs)
24 Q_IMPORT_PLUGIN(qtaccessiblewidgets)
28 using namespace boost;
32 //////////////////////////////////////////////////////////////////////////////
37 void ExitTimeout(void* parg)
45 void Shutdown(void* parg)
47 static CCriticalSection cs_Shutdown;
49 bool fFirstThread = false;
50 TRY_CRITICAL_BLOCK(cs_Shutdown)
52 fFirstThread = !fTaken;
59 nTransactionsUpdated++;
63 boost::filesystem::remove(GetPidFile());
64 UnregisterWallet(pwalletMain);
66 CreateThread(ExitTimeout, NULL);
68 printf("Bitcoin exiting\n\n");
81 void HandleSIGTERM(int)
83 fRequestShutdown = true;
91 //////////////////////////////////////////////////////////////////////////////
96 int main(int argc, char* argv[])
99 fRet = AppInit(argc, argv);
108 bool AppInit(int argc, char* argv[])
113 fRet = AppInit2(argc, argv);
115 catch (std::exception& e) {
116 PrintException(&e, "AppInit()");
118 PrintException(NULL, "AppInit()");
125 bool AppInit2(int argc, char* argv[])
128 // Turn off microsoft heap dump noise
129 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
130 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
133 // Disable confusing "helpful" text message on abort, ctrl-c
134 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
140 // Clean shutdown on SIGTERM
142 sa.sa_handler = HandleSIGTERM;
143 sigemptyset(&sa.sa_mask);
145 sigaction(SIGTERM, &sa, NULL);
146 sigaction(SIGINT, &sa, NULL);
147 sigaction(SIGHUP, &sa, NULL);
153 // If Qt is used, parameters are parsed in qt/bitcoin.cpp's main()
155 ParseParameters(argc, argv);
158 if (mapArgs.count("-datadir"))
160 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
162 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
163 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
167 fprintf(stderr, "Error: Specified directory does not exist\n");
173 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
175 if (mapArgs.count("-?") || mapArgs.count("--help"))
177 string strUsage = string() +
178 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
179 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
180 " bitcoind [options] \t " + "\n" +
181 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
182 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
183 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
184 _("Options:") + "\n" +
185 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
186 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
187 " -gen \t\t " + _("Generate coins") + "\n" +
188 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
189 " -min \t\t " + _("Start minimized") + "\n" +
190 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
191 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
192 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
193 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
194 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
195 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
196 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
197 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
198 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
199 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
200 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
202 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
204 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
205 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
206 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
207 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
208 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
211 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
213 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
216 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
218 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
220 #if !defined(WIN32) && !defined(QT_GUI)
221 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
223 " -testnet \t\t " + _("Use the test network") + "\n" +
224 " -debug \t\t " + _("Output extra debugging information") + "\n" +
225 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
226 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
228 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
230 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
231 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
232 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
233 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
234 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
235 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
236 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
237 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n";
240 strUsage += string() +
241 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
242 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
243 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
244 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
245 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
248 strUsage += string() +
249 " -? \t\t " + _("This help message") + "\n";
252 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
253 #if defined(QT_GUI) && defined(WIN32)
254 // On windows, show a message box, as there is no stderr
255 wxMessageBox(strUsage, "Usage");
257 fprintf(stderr, "%s", strUsage.c_str());
262 fTestNet = GetBoolArg("-testnet");
265 SoftSetBoolArg("-irc", true);
268 fDebug = GetBoolArg("-debug");
270 #if !defined(WIN32) && !defined(QT_GUI)
271 fDaemon = GetBoolArg("-daemon");
279 fServer = GetBoolArg("-server");
281 /* force fServer when running without GUI */
285 fPrintToConsole = GetBoolArg("-printtoconsole");
286 fPrintToDebugger = GetBoolArg("-printtodebugger");
287 fLogTimestamps = GetBoolArg("-logtimestamps");
290 for (int i = 1; i < argc; i++)
291 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
296 int ret = CommandLineRPC(argc, argv);
301 #if !defined(WIN32) && !defined(QT_GUI)
308 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
313 CreatePidFile(GetPidFile(), pid);
317 pid_t sid = setsid();
319 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
323 if (!fDebug && !pszSetDataDir[0])
325 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
326 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
327 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
329 if (GetBoolArg("-loadblockindextest"))
332 txdb.LoadBlockIndex();
337 // Make sure only a single bitcoin process is using the data directory.
338 string strLockFile = GetDataDir() + "/.lock";
339 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
340 if (file) fclose(file);
341 static boost::interprocess::file_lock lock(strLockFile.c_str());
342 if (!lock.try_lock())
344 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
348 std::ostringstream strErrors;
353 fprintf(stdout, "bitcoin server starting\n");
356 InitMessage(_("Loading addresses..."));
357 printf("Loading addresses...\n");
358 nStart = GetTimeMillis();
359 if (!LoadAddresses())
360 strErrors << _("Error loading addr.dat") << "\n";
361 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
363 InitMessage(_("Loading block index..."));
364 printf("Loading block index...\n");
365 nStart = GetTimeMillis();
366 if (!LoadBlockIndex())
367 strErrors << _("Error loading blkindex.dat") << "\n";
368 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
370 InitMessage(_("Loading wallet..."));
371 printf("Loading wallet...\n");
372 nStart = GetTimeMillis();
374 pwalletMain = new CWallet("wallet.dat");
375 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
376 if (nLoadWalletRet != DB_LOAD_OK)
378 if (nLoadWalletRet == DB_CORRUPT)
379 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
380 else if (nLoadWalletRet == DB_TOO_NEW)
381 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
382 else if (nLoadWalletRet == DB_NEED_REWRITE)
384 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
385 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
389 strErrors << _("Error loading wallet.dat") << "\n";
391 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
393 RegisterWallet(pwalletMain);
395 CBlockIndex *pindexRescan = pindexBest;
396 if (GetBoolArg("-rescan"))
397 pindexRescan = pindexGenesisBlock;
400 CWalletDB walletdb("wallet.dat");
401 CBlockLocator locator;
402 if (walletdb.ReadBestBlock(locator))
403 pindexRescan = locator.GetBlockIndex();
405 if (pindexBest != pindexRescan)
407 InitMessage(_("Rescanning..."));
408 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
409 nStart = GetTimeMillis();
410 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
411 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
414 InitMessage(_("Done loading"));
415 printf("Done loading\n");
418 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
419 printf("nBestHeight = %d\n", nBestHeight);
420 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
421 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
422 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
424 if (!strErrors.str().empty())
426 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
430 // Add wallet transactions that aren't already in a block to mapTransactions
431 pwalletMain->ReacceptWalletTransactions();
433 // Note: Bitcoin-QT stores several settings in the wallet, so we want
434 // to load the wallet BEFORE parsing command-line arguments, so
435 // the command-line/bitcoin.conf settings override GUI setting.
440 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
446 if (mapArgs.count("-timeout"))
448 int nNewTimeout = GetArg("-timeout", 5000);
449 if (nNewTimeout > 0 && nNewTimeout < 600000)
450 nConnectTimeout = nNewTimeout;
453 if (mapArgs.count("-printblock"))
455 string strMatch = mapArgs["-printblock"];
457 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
459 uint256 hash = (*mi).first;
460 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
462 CBlockIndex* pindex = (*mi).second;
464 block.ReadFromDisk(pindex);
465 block.BuildMerkleTree();
472 printf("No blocks matching %s were found\n", strMatch.c_str());
476 fGenerateBitcoins = GetBoolArg("-gen");
478 if (mapArgs.count("-proxy"))
481 addrProxy = CService(mapArgs["-proxy"], 9050);
482 if (!addrProxy.IsValid())
484 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
489 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
492 // Use SoftSetBoolArg here so user can override any of these if they wish.
493 // Note: the GetBoolArg() calls for all of these must happen later.
494 SoftSetBoolArg("-listen", false);
495 SoftSetBoolArg("-irc", false);
496 SoftSetBoolArg("-dnsseed", false);
497 SoftSetBoolArg("-upnp", false);
498 SoftSetBoolArg("-dns", false);
501 fAllowDNS = GetBoolArg("-dns");
502 fNoListen = !GetBoolArg("-listen", true);
504 // This code can be removed once a super-majority of the network has upgraded.
505 if (GetBoolArg("-bip16", true))
508 SoftSetArg("-paytoscripthashtime", "1329264000"); // Feb 15
510 SoftSetArg("-paytoscripthashtime", "1330578000"); // Mar 1
512 // Put "/P2SH/" in the coinbase so everybody can tell when
513 // a majority of miners support it
514 const char* pszP2SH = "/P2SH/";
515 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
519 const char* pszP2SH = "NOP2SH";
520 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
523 // Command-line args override in-wallet settings:
525 fUseUPnP = GetBoolArg("-upnp", true);
527 fUseUPnP = GetBoolArg("-upnp", false);
532 std::string strError;
533 if (!BindListenPort(strError))
535 wxMessageBox(strError, "Bitcoin");
540 if (mapArgs.count("-addnode"))
542 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
544 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
545 addr.nTime = 0; // so it won't relay unless successfully connected
551 if (mapArgs.count("-paytxfee"))
553 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
555 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
558 if (nTransactionFee > 0.25 * COIN)
559 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
565 if (!CheckDiskSpace())
568 RandAddSeedPerfmon();
570 if (!CreateThread(StartNode, NULL))
571 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
574 CreateThread(ThreadRPCServer, NULL);
577 if(GetStartOnSystemStartup())
578 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
590 string StartupShortcutPath()
592 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
595 bool GetStartOnSystemStartup()
597 return filesystem::exists(StartupShortcutPath().c_str());
600 bool SetStartOnSystemStartup(bool fAutoStart)
602 // If the shortcut exists already, remove it for updating
603 remove(StartupShortcutPath().c_str());
609 // Get a pointer to the IShellLink interface.
610 IShellLink* psl = NULL;
611 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
612 CLSCTX_INPROC_SERVER, IID_IShellLink,
613 reinterpret_cast<void**>(&psl));
617 // Get the current executable path
618 TCHAR pszExePath[MAX_PATH];
619 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
621 TCHAR pszArgs[5] = TEXT("-min");
623 // Set the path to the shortcut target
624 psl->SetPath(pszExePath);
625 PathRemoveFileSpec(pszExePath);
626 psl->SetWorkingDirectory(pszExePath);
627 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
628 psl->SetArguments(pszArgs);
630 // Query IShellLink for the IPersistFile interface for
631 // saving the shortcut in persistent storage.
632 IPersistFile* ppf = NULL;
633 hres = psl->QueryInterface(IID_IPersistFile,
634 reinterpret_cast<void**>(&ppf));
637 WCHAR pwsz[MAX_PATH];
638 // Ensure that the string is ANSI.
639 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
640 // Save the link by calling IPersistFile::Save.
641 hres = ppf->Save(pwsz, TRUE);
657 // Follow the Desktop Application Autostart Spec:
658 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
660 boost::filesystem::path GetAutostartDir()
662 namespace fs = boost::filesystem;
664 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
665 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
666 char* pszHome = getenv("HOME");
667 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
671 boost::filesystem::path GetAutostartFilePath()
673 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
676 bool GetStartOnSystemStartup()
678 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
679 if (!optionFile.good())
681 // Scan through file for "Hidden=true":
683 while (!optionFile.eof())
685 getline(optionFile, line);
686 if (line.find("Hidden") != string::npos &&
687 line.find("true") != string::npos)
695 bool SetStartOnSystemStartup(bool fAutoStart)
699 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
700 unlink(GetAutostartFilePath().string().c_str());
702 unlink(GetAutostartFilePath().native_file_string().c_str());
707 char pszExePath[MAX_PATH+1];
708 memset(pszExePath, 0, sizeof(pszExePath));
709 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
712 boost::filesystem::create_directories(GetAutostartDir());
714 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
715 if (!optionFile.good())
717 // Write a bitcoin.desktop file to the autostart directory:
718 optionFile << "[Desktop Entry]\n";
719 optionFile << "Type=Application\n";
720 optionFile << "Name=Bitcoin\n";
721 optionFile << "Exec=" << pszExePath << " -min\n";
722 optionFile << "Terminal=false\n";
723 optionFile << "Hidden=false\n";
730 // TODO: OSX startup stuff; see:
731 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
733 bool GetStartOnSystemStartup() { return false; }
734 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }