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 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
191 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
192 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
193 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
194 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
195 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
196 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
197 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
198 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
199 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
200 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
201 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
202 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
203 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
204 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
207 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
209 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
212 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
214 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
216 #if !defined(WIN32) && !defined(GUI)
217 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
219 " -testnet \t\t " + _("Use the test network") + "\n" +
220 " -debug \t\t " + _("Output extra debugging information") + "\n" +
221 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
222 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
224 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
226 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
227 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
228 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
229 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
230 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
231 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\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 #if defined(QT_GUI) && defined(WIN32)
250 // On windows, show a message box, as there is no stderr
251 wxMessageBox(strUsage, "Usage");
253 fprintf(stderr, "%s", strUsage.c_str());
258 fTestNet = GetBoolArg("-testnet");
259 fDebug = GetBoolArg("-debug");
261 #if !defined(WIN32) && !defined(GUI)
262 fDaemon = GetBoolArg("-daemon");
270 fServer = GetBoolArg("-server");
272 /* force fServer when running without GUI */
276 fPrintToConsole = GetBoolArg("-printtoconsole");
277 fPrintToDebugger = GetBoolArg("-printtodebugger");
278 fLogTimestamps = GetBoolArg("-logtimestamps");
281 for (int i = 1; i < argc; i++)
282 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
287 int ret = CommandLineRPC(argc, argv);
292 #if !defined(WIN32) && !defined(GUI)
299 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
304 CreatePidFile(GetPidFile(), pid);
308 pid_t sid = setsid();
310 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
314 if (!fDebug && !pszSetDataDir[0])
316 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
317 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
318 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
320 if (GetBoolArg("-loadblockindextest"))
323 txdb.LoadBlockIndex();
328 // Make sure only a single bitcoin process is using the data directory.
329 string strLockFile = GetDataDir() + "/.lock";
330 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
331 if (file) fclose(file);
332 static boost::interprocess::file_lock lock(strLockFile.c_str());
333 if (!lock.try_lock())
335 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
339 std::ostringstream strErrors;
344 fprintf(stdout, "bitcoin server starting\n");
347 InitMessage(_("Loading addresses..."));
348 printf("Loading addresses...\n");
349 nStart = GetTimeMillis();
350 if (!LoadAddresses())
351 strErrors << _("Error loading addr.dat") << "\n";
352 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
354 InitMessage(_("Loading block index..."));
355 printf("Loading block index...\n");
356 nStart = GetTimeMillis();
357 if (!LoadBlockIndex())
358 strErrors << _("Error loading blkindex.dat") << "\n";
359 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
361 InitMessage(_("Loading wallet..."));
362 printf("Loading wallet...\n");
363 nStart = GetTimeMillis();
365 pwalletMain = new CWallet("wallet.dat");
366 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
367 if (nLoadWalletRet != DB_LOAD_OK)
369 if (nLoadWalletRet == DB_CORRUPT)
370 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
371 else if (nLoadWalletRet == DB_TOO_NEW)
372 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
373 else if (nLoadWalletRet == DB_NEED_REWRITE)
375 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
376 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
380 strErrors << _("Error loading wallet.dat") << "\n";
382 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
384 RegisterWallet(pwalletMain);
386 CBlockIndex *pindexRescan = pindexBest;
387 if (GetBoolArg("-rescan"))
388 pindexRescan = pindexGenesisBlock;
391 CWalletDB walletdb("wallet.dat");
392 CBlockLocator locator;
393 if (walletdb.ReadBestBlock(locator))
394 pindexRescan = locator.GetBlockIndex();
396 if (pindexBest != pindexRescan)
398 InitMessage(_("Rescanning..."));
399 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
400 nStart = GetTimeMillis();
401 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
402 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
405 InitMessage(_("Done loading"));
406 printf("Done loading\n");
409 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
410 printf("nBestHeight = %d\n", nBestHeight);
411 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
412 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
413 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
415 if (!strErrors.str().empty())
417 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
421 // Add wallet transactions that aren't already in a block to mapTransactions
422 pwalletMain->ReacceptWalletTransactions();
424 // Note: Bitcoin-QT stores several settings in the wallet, so we want
425 // to load the wallet BEFORE parsing command-line arguments, so
426 // the command-line/bitcoin.conf settings override GUI setting.
431 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
437 if (mapArgs.count("-timeout"))
439 int nNewTimeout = GetArg("-timeout", 5000);
440 if (nNewTimeout > 0 && nNewTimeout < 600000)
441 nConnectTimeout = nNewTimeout;
444 if (mapArgs.count("-printblock"))
446 string strMatch = mapArgs["-printblock"];
448 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
450 uint256 hash = (*mi).first;
451 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
453 CBlockIndex* pindex = (*mi).second;
455 block.ReadFromDisk(pindex);
456 block.BuildMerkleTree();
463 printf("No blocks matching %s were found\n", strMatch.c_str());
467 fGenerateBitcoins = GetBoolArg("-gen");
469 if (mapArgs.count("-proxy"))
472 addrProxy = CService(mapArgs["-proxy"], 9050);
473 if (!addrProxy.IsValid())
475 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
480 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
483 // Use SoftSetBoolArg here so user can override any of these if they wish.
484 // Note: the GetBoolArg() calls for all of these must happen later.
485 SoftSetBoolArg("-listen", false);
486 SoftSetBoolArg("-irc", false);
487 SoftSetBoolArg("-dnsseed", false);
488 SoftSetBoolArg("-upnp", false);
489 SoftSetBoolArg("-dns", false);
492 fAllowDNS = GetBoolArg("-dns");
493 fNoListen = !GetBoolArg("-listen", true);
495 // This code can be removed once a super-majority of the network has upgraded.
496 if (GetBoolArg("-bip16", true))
499 SoftSetArg("-paytoscripthashtime", "1329264000"); // Feb 15
501 SoftSetArg("-paytoscripthashtime", "1330578000"); // Mar 1
503 // Put "/P2SH/" in the coinbase so everybody can tell when
504 // a majority of miners support it
505 const char* pszP2SH = "/P2SH/";
506 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
510 const char* pszP2SH = "NOP2SH";
511 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
514 // Command-line args override in-wallet settings:
516 fUseUPnP = GetBoolArg("-upnp", true);
518 fUseUPnP = GetBoolArg("-upnp", false);
523 std::string strError;
524 if (!BindListenPort(strError))
526 wxMessageBox(strError, "Bitcoin");
531 if (mapArgs.count("-addnode"))
533 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
535 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
536 addr.nTime = 0; // so it won't relay unless successfully connected
542 if (mapArgs.count("-paytxfee"))
544 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
546 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
549 if (nTransactionFee > 0.25 * COIN)
550 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
556 if (!CheckDiskSpace())
559 RandAddSeedPerfmon();
561 if (!CreateThread(StartNode, NULL))
562 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
565 CreateThread(ThreadRPCServer, NULL);
568 if(GetStartOnSystemStartup())
569 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
581 string StartupShortcutPath()
583 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
586 bool GetStartOnSystemStartup()
588 return filesystem::exists(StartupShortcutPath().c_str());
591 bool SetStartOnSystemStartup(bool fAutoStart)
593 // If the shortcut exists already, remove it for updating
594 remove(StartupShortcutPath().c_str());
600 // Get a pointer to the IShellLink interface.
601 IShellLink* psl = NULL;
602 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
603 CLSCTX_INPROC_SERVER, IID_IShellLink,
604 reinterpret_cast<void**>(&psl));
608 // Get the current executable path
609 TCHAR pszExePath[MAX_PATH];
610 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
612 TCHAR pszArgs[5] = TEXT("-min");
614 // Set the path to the shortcut target
615 psl->SetPath(pszExePath);
616 PathRemoveFileSpec(pszExePath);
617 psl->SetWorkingDirectory(pszExePath);
618 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
619 psl->SetArguments(pszArgs);
621 // Query IShellLink for the IPersistFile interface for
622 // saving the shortcut in persistent storage.
623 IPersistFile* ppf = NULL;
624 hres = psl->QueryInterface(IID_IPersistFile,
625 reinterpret_cast<void**>(&ppf));
628 WCHAR pwsz[MAX_PATH];
629 // Ensure that the string is ANSI.
630 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
631 // Save the link by calling IPersistFile::Save.
632 hres = ppf->Save(pwsz, TRUE);
648 // Follow the Desktop Application Autostart Spec:
649 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
651 boost::filesystem::path GetAutostartDir()
653 namespace fs = boost::filesystem;
655 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
656 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
657 char* pszHome = getenv("HOME");
658 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
662 boost::filesystem::path GetAutostartFilePath()
664 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
667 bool GetStartOnSystemStartup()
669 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
670 if (!optionFile.good())
672 // Scan through file for "Hidden=true":
674 while (!optionFile.eof())
676 getline(optionFile, line);
677 if (line.find("Hidden") != string::npos &&
678 line.find("true") != string::npos)
686 bool SetStartOnSystemStartup(bool fAutoStart)
690 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
691 unlink(GetAutostartFilePath().string().c_str());
693 unlink(GetAutostartFilePath().native_file_string().c_str());
698 char pszExePath[MAX_PATH+1];
699 memset(pszExePath, 0, sizeof(pszExePath));
700 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
703 boost::filesystem::create_directories(GetAutostartDir());
705 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
706 if (!optionFile.good())
708 // Write a bitcoin.desktop file to the autostart directory:
709 optionFile << "[Desktop Entry]\n";
710 optionFile << "Type=Application\n";
711 optionFile << "Name=Bitcoin\n";
712 optionFile << "Exec=" << pszExePath << " -min\n";
713 optionFile << "Terminal=false\n";
714 optionFile << "Hidden=false\n";
721 // TODO: OSX startup stuff; see:
722 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
724 bool GetStartOnSystemStartup() { return false; }
725 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }