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/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
155 ParseParameters(argc, argv);
156 if (!ReadConfigFile(mapArgs, mapMultiArgs))
158 fprintf(stderr, "Error: Specified directory does not exist\n");
163 if (mapArgs.count("-?") || mapArgs.count("--help"))
165 string strUsage = string() +
166 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
167 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
168 " bitcoind [options] \t " + "\n" +
169 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
170 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
171 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
172 _("Options:") + "\n" +
173 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
174 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
175 " -gen \t\t " + _("Generate coins") + "\n" +
176 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
177 " -min \t\t " + _("Start minimized") + "\n" +
178 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
179 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
180 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
181 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
182 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
183 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
184 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
185 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
186 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
187 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
188 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
190 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
192 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
193 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
194 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
195 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
196 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
199 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
201 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
204 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
206 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
208 #if !defined(WIN32) && !defined(QT_GUI)
209 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
211 " -testnet \t\t " + _("Use the test network") + "\n" +
212 " -debug \t\t " + _("Output extra debugging information") + "\n" +
213 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
214 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
216 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
218 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
219 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
220 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
221 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
222 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
223 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
224 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
225 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n";
228 strUsage += string() +
229 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
230 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
231 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
232 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
233 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
236 strUsage += string() +
237 " -? \t\t " + _("This help message") + "\n";
240 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
241 #if defined(QT_GUI) && defined(WIN32)
242 // On windows, show a message box, as there is no stderr
243 wxMessageBox(strUsage, "Usage");
245 fprintf(stderr, "%s", strUsage.c_str());
250 fTestNet = GetBoolArg("-testnet");
253 SoftSetBoolArg("-irc", true);
256 fDebug = GetBoolArg("-debug");
258 #if !defined(WIN32) && !defined(QT_GUI)
259 fDaemon = GetBoolArg("-daemon");
267 fServer = GetBoolArg("-server");
269 /* force fServer when running without GUI */
273 fPrintToConsole = GetBoolArg("-printtoconsole");
274 fPrintToDebugger = GetBoolArg("-printtodebugger");
275 fLogTimestamps = GetBoolArg("-logtimestamps");
278 for (int i = 1; i < argc; i++)
279 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
284 int ret = CommandLineRPC(argc, argv);
289 #if !defined(WIN32) && !defined(QT_GUI)
296 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
301 CreatePidFile(GetPidFile(), pid);
305 pid_t sid = setsid();
307 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
311 if (!fDebug && !pszSetDataDir[0])
313 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
314 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
315 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
317 if (GetBoolArg("-loadblockindextest"))
320 txdb.LoadBlockIndex();
325 // Make sure only a single bitcoin process is using the data directory.
326 string strLockFile = GetDataDir() + "/.lock";
327 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
328 if (file) fclose(file);
329 static boost::interprocess::file_lock lock(strLockFile.c_str());
330 if (!lock.try_lock())
332 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
336 std::ostringstream strErrors;
341 fprintf(stdout, "bitcoin server starting\n");
344 InitMessage(_("Loading addresses..."));
345 printf("Loading addresses...\n");
346 nStart = GetTimeMillis();
347 if (!LoadAddresses())
348 strErrors << _("Error loading addr.dat") << "\n";
349 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
351 InitMessage(_("Loading block index..."));
352 printf("Loading block index...\n");
353 nStart = GetTimeMillis();
354 if (!LoadBlockIndex())
355 strErrors << _("Error loading blkindex.dat") << "\n";
356 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
358 InitMessage(_("Loading wallet..."));
359 printf("Loading wallet...\n");
360 nStart = GetTimeMillis();
362 pwalletMain = new CWallet("wallet.dat");
363 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
364 if (nLoadWalletRet != DB_LOAD_OK)
366 if (nLoadWalletRet == DB_CORRUPT)
367 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
368 else if (nLoadWalletRet == DB_TOO_NEW)
369 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
370 else if (nLoadWalletRet == DB_NEED_REWRITE)
372 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
373 printf("%s", strErrors.str().c_str());
374 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
378 strErrors << _("Error loading wallet.dat") << "\n";
380 printf("%s", strErrors.str().c_str());
381 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
383 RegisterWallet(pwalletMain);
385 CBlockIndex *pindexRescan = pindexBest;
386 if (GetBoolArg("-rescan"))
387 pindexRescan = pindexGenesisBlock;
390 CWalletDB walletdb("wallet.dat");
391 CBlockLocator locator;
392 if (walletdb.ReadBestBlock(locator))
393 pindexRescan = locator.GetBlockIndex();
395 if (pindexBest != pindexRescan)
397 InitMessage(_("Rescanning..."));
398 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
399 nStart = GetTimeMillis();
400 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
401 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
404 InitMessage(_("Done loading"));
405 printf("Done loading\n");
408 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
409 printf("nBestHeight = %d\n", nBestHeight);
410 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
411 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
412 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
414 if (!strErrors.str().empty())
416 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
420 // Add wallet transactions that aren't already in a block to mapTransactions
421 pwalletMain->ReacceptWalletTransactions();
423 // Note: Bitcoin-QT stores several settings in the wallet, so we want
424 // to load the wallet BEFORE parsing command-line arguments, so
425 // the command-line/bitcoin.conf settings override GUI setting.
430 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
436 if (mapArgs.count("-timeout"))
438 int nNewTimeout = GetArg("-timeout", 5000);
439 if (nNewTimeout > 0 && nNewTimeout < 600000)
440 nConnectTimeout = nNewTimeout;
443 if (mapArgs.count("-printblock"))
445 string strMatch = mapArgs["-printblock"];
447 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
449 uint256 hash = (*mi).first;
450 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
452 CBlockIndex* pindex = (*mi).second;
454 block.ReadFromDisk(pindex);
455 block.BuildMerkleTree();
462 printf("No blocks matching %s were found\n", strMatch.c_str());
466 if (mapArgs.count("-proxy"))
469 addrProxy = CService(mapArgs["-proxy"], 9050);
470 if (!addrProxy.IsValid())
472 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
477 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
480 // Use SoftSetBoolArg here so user can override any of these if they wish.
481 // Note: the GetBoolArg() calls for all of these must happen later.
482 SoftSetBoolArg("-listen", false);
483 SoftSetBoolArg("-irc", false);
484 SoftSetBoolArg("-dnsseed", false);
485 SoftSetBoolArg("-upnp", false);
486 SoftSetBoolArg("-dns", false);
489 fAllowDNS = GetBoolArg("-dns");
490 fNoListen = !GetBoolArg("-listen", true);
492 // This code can be removed once a super-majority of the network has upgraded.
493 if (GetBoolArg("-bip16", true))
496 SoftSetArg("-paytoscripthashtime", "1329264000"); // Feb 15
498 SoftSetArg("-paytoscripthashtime", "1333238400"); // April 1 2012
500 // Put "/P2SH/" in the coinbase so everybody can tell when
501 // a majority of miners support it
502 const char* pszP2SH = "/P2SH/";
503 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
507 const char* pszP2SH = "NOP2SH";
508 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
513 std::string strError;
514 if (!BindListenPort(strError))
516 wxMessageBox(strError, "Bitcoin");
521 if (mapArgs.count("-addnode"))
523 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
525 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
526 addr.nTime = 0; // so it won't relay unless successfully connected
532 if (mapArgs.count("-paytxfee"))
534 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
536 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
539 if (nTransactionFee > 0.25 * COIN)
540 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
546 if (!CheckDiskSpace())
549 RandAddSeedPerfmon();
551 if (!CreateThread(StartNode, NULL))
552 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
555 CreateThread(ThreadRPCServer, NULL);
558 if(GetStartOnSystemStartup())
559 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
571 string StartupShortcutPath()
573 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
576 bool GetStartOnSystemStartup()
578 return filesystem::exists(StartupShortcutPath().c_str());
581 bool SetStartOnSystemStartup(bool fAutoStart)
583 // If the shortcut exists already, remove it for updating
584 remove(StartupShortcutPath().c_str());
590 // Get a pointer to the IShellLink interface.
591 IShellLink* psl = NULL;
592 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
593 CLSCTX_INPROC_SERVER, IID_IShellLink,
594 reinterpret_cast<void**>(&psl));
598 // Get the current executable path
599 TCHAR pszExePath[MAX_PATH];
600 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
602 TCHAR pszArgs[5] = TEXT("-min");
604 // Set the path to the shortcut target
605 psl->SetPath(pszExePath);
606 PathRemoveFileSpec(pszExePath);
607 psl->SetWorkingDirectory(pszExePath);
608 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
609 psl->SetArguments(pszArgs);
611 // Query IShellLink for the IPersistFile interface for
612 // saving the shortcut in persistent storage.
613 IPersistFile* ppf = NULL;
614 hres = psl->QueryInterface(IID_IPersistFile,
615 reinterpret_cast<void**>(&ppf));
618 WCHAR pwsz[MAX_PATH];
619 // Ensure that the string is ANSI.
620 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
621 // Save the link by calling IPersistFile::Save.
622 hres = ppf->Save(pwsz, TRUE);
638 // Follow the Desktop Application Autostart Spec:
639 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
641 boost::filesystem::path GetAutostartDir()
643 namespace fs = boost::filesystem;
645 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
646 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
647 char* pszHome = getenv("HOME");
648 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
652 boost::filesystem::path GetAutostartFilePath()
654 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
657 bool GetStartOnSystemStartup()
659 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
660 if (!optionFile.good())
662 // Scan through file for "Hidden=true":
664 while (!optionFile.eof())
666 getline(optionFile, line);
667 if (line.find("Hidden") != string::npos &&
668 line.find("true") != string::npos)
676 bool SetStartOnSystemStartup(bool fAutoStart)
680 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
681 unlink(GetAutostartFilePath().string().c_str());
683 unlink(GetAutostartFilePath().native_file_string().c_str());
688 char pszExePath[MAX_PATH+1];
689 memset(pszExePath, 0, sizeof(pszExePath));
690 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
693 boost::filesystem::create_directories(GetAutostartDir());
695 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
696 if (!optionFile.good())
698 // Write a bitcoin.desktop file to the autostart directory:
699 optionFile << "[Desktop Entry]\n";
700 optionFile << "Type=Application\n";
701 optionFile << "Name=Bitcoin\n";
702 optionFile << "Exec=" << pszExePath << " -min\n";
703 optionFile << "Terminal=false\n";
704 optionFile << "Hidden=false\n";
711 // TODO: OSX startup stuff; see:
712 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
714 bool GetStartOnSystemStartup() { return false; }
715 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }