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 #define strncasecmp strnicmp
32 using namespace boost;
36 //////////////////////////////////////////////////////////////////////////////
41 void ExitTimeout(void* parg)
49 void Shutdown(void* parg)
51 static CCriticalSection cs_Shutdown;
53 bool fFirstThread = false;
54 TRY_CRITICAL_BLOCK(cs_Shutdown)
56 fFirstThread = !fTaken;
63 nTransactionsUpdated++;
67 boost::filesystem::remove(GetPidFile());
68 UnregisterWallet(pwalletMain);
70 CreateThread(ExitTimeout, NULL);
72 printf("Bitcoin exiting\n\n");
85 void HandleSIGTERM(int)
87 fRequestShutdown = true;
95 //////////////////////////////////////////////////////////////////////////////
100 int main(int argc, char* argv[])
103 fRet = AppInit(argc, argv);
112 bool AppInit(int argc, char* argv[])
117 fRet = AppInit2(argc, argv);
119 catch (std::exception& e) {
120 PrintException(&e, "AppInit()");
122 PrintException(NULL, "AppInit()");
129 bool AppInit2(int argc, char* argv[])
132 // Turn off microsoft heap dump noise
133 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
134 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
137 // Disable confusing "helpful" text message on abort, ctrl-c
138 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
144 // Clean shutdown on SIGTERM
146 sa.sa_handler = HandleSIGTERM;
147 sigemptyset(&sa.sa_mask);
149 sigaction(SIGTERM, &sa, NULL);
150 sigaction(SIGINT, &sa, NULL);
151 sigaction(SIGHUP, &sa, NULL);
157 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
159 ParseParameters(argc, argv);
160 if (!ReadConfigFile(mapArgs, mapMultiArgs))
162 fprintf(stderr, "Error: Specified directory does not exist\n");
167 if (mapArgs.count("-?") || mapArgs.count("--help"))
169 string strUsage = string() +
170 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
171 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
172 " bitcoind [options] \t " + "\n" +
173 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
174 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
175 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
176 _("Options:") + "\n" +
177 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
178 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
179 " -gen \t\t " + _("Generate coins") + "\n" +
180 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
181 " -min \t\t " + _("Start minimized") + "\n" +
182 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
183 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
184 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
185 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
186 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
187 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
188 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
189 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
190 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
191 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
192 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
193 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
195 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
197 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
198 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
199 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
200 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
201 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
204 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
206 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
209 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
211 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
213 #if !defined(WIN32) && !defined(QT_GUI)
214 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
216 " -testnet \t\t " + _("Use the test network") + "\n" +
217 " -debug \t\t " + _("Output extra debugging information") + "\n" +
218 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
219 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
221 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
223 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
224 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
225 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
226 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
227 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
228 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
229 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
230 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
231 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
232 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
233 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\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");
261 SoftSetBoolArg("-irc", true);
264 fDebug = GetBoolArg("-debug");
266 #if !defined(WIN32) && !defined(QT_GUI)
267 fDaemon = GetBoolArg("-daemon");
275 fServer = GetBoolArg("-server");
277 /* force fServer when running without GUI */
281 fPrintToConsole = GetBoolArg("-printtoconsole");
282 fPrintToDebugger = GetBoolArg("-printtodebugger");
283 fLogTimestamps = GetBoolArg("-logtimestamps");
286 for (int i = 1; i < argc; i++)
287 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
292 int ret = CommandLineRPC(argc, argv);
297 #if !defined(WIN32) && !defined(QT_GUI)
304 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
309 CreatePidFile(GetPidFile(), pid);
313 pid_t sid = setsid();
315 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
319 if (!fDebug && !pszSetDataDir[0])
321 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
322 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
323 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
325 if (GetBoolArg("-loadblockindextest"))
328 txdb.LoadBlockIndex();
333 // Make sure only a single bitcoin process is using the data directory.
334 string strLockFile = GetDataDir() + "/.lock";
335 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
336 if (file) fclose(file);
337 static boost::interprocess::file_lock lock(strLockFile.c_str());
338 if (!lock.try_lock())
340 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
344 std::ostringstream strErrors;
349 fprintf(stdout, "bitcoin server starting\n");
352 InitMessage(_("Loading addresses..."));
353 printf("Loading addresses...\n");
354 nStart = GetTimeMillis();
355 if (!LoadAddresses())
356 strErrors << _("Error loading addr.dat") << "\n";
357 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
359 InitMessage(_("Loading block index..."));
360 printf("Loading block index...\n");
361 nStart = GetTimeMillis();
362 if (!LoadBlockIndex())
363 strErrors << _("Error loading blkindex.dat") << "\n";
364 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
366 InitMessage(_("Loading wallet..."));
367 printf("Loading wallet...\n");
368 nStart = GetTimeMillis();
370 pwalletMain = new CWallet("wallet.dat");
371 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
372 if (nLoadWalletRet != DB_LOAD_OK)
374 if (nLoadWalletRet == DB_CORRUPT)
375 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
376 else if (nLoadWalletRet == DB_TOO_NEW)
377 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
378 else if (nLoadWalletRet == DB_NEED_REWRITE)
380 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
381 printf("%s", strErrors.str().c_str());
382 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
386 strErrors << _("Error loading wallet.dat") << "\n";
389 if (GetBoolArg("-upgradewallet", fFirstRun))
391 int nMaxVersion = GetArg("-upgradewallet", 0);
392 if (nMaxVersion == 0) // the -walletupgrade without argument case
394 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
395 nMaxVersion = CLIENT_VERSION;
396 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
399 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
400 if (nMaxVersion < pwalletMain->GetVersion())
401 strErrors << _("Cannot downgrade wallet") << "\n";
402 pwalletMain->SetMaxVersion(nMaxVersion);
407 // Create new keyUser and set as default key
408 RandAddSeedPerfmon();
410 std::vector<unsigned char> newDefaultKey;
411 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
412 strErrors << _("Cannot initialize keypool") << "\n";
413 pwalletMain->SetDefaultKey(newDefaultKey);
414 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
415 strErrors << _("Cannot write default address") << "\n";
418 printf("%s", strErrors.str().c_str());
419 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
421 RegisterWallet(pwalletMain);
423 CBlockIndex *pindexRescan = pindexBest;
424 if (GetBoolArg("-rescan"))
425 pindexRescan = pindexGenesisBlock;
428 CWalletDB walletdb("wallet.dat");
429 CBlockLocator locator;
430 if (walletdb.ReadBestBlock(locator))
431 pindexRescan = locator.GetBlockIndex();
433 if (pindexBest != pindexRescan)
435 InitMessage(_("Rescanning..."));
436 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
437 nStart = GetTimeMillis();
438 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
439 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
442 InitMessage(_("Done loading"));
443 printf("Done loading\n");
446 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
447 printf("nBestHeight = %d\n", nBestHeight);
448 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
449 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
450 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
452 if (!strErrors.str().empty())
454 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
458 // Add wallet transactions that aren't already in a block to mapTransactions
459 pwalletMain->ReacceptWalletTransactions();
461 // Note: Bitcoin-QT stores several settings in the wallet, so we want
462 // to load the wallet BEFORE parsing command-line arguments, so
463 // the command-line/bitcoin.conf settings override GUI setting.
468 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
474 if (mapArgs.count("-timeout"))
476 int nNewTimeout = GetArg("-timeout", 5000);
477 if (nNewTimeout > 0 && nNewTimeout < 600000)
478 nConnectTimeout = nNewTimeout;
481 if (mapArgs.count("-printblock"))
483 string strMatch = mapArgs["-printblock"];
485 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
487 uint256 hash = (*mi).first;
488 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
490 CBlockIndex* pindex = (*mi).second;
492 block.ReadFromDisk(pindex);
493 block.BuildMerkleTree();
500 printf("No blocks matching %s were found\n", strMatch.c_str());
504 if (mapArgs.count("-proxy"))
507 addrProxy = CService(mapArgs["-proxy"], 9050);
508 if (!addrProxy.IsValid())
510 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
515 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
518 // Use SoftSetBoolArg here so user can override any of these if they wish.
519 // Note: the GetBoolArg() calls for all of these must happen later.
520 SoftSetBoolArg("-listen", false);
521 SoftSetBoolArg("-irc", false);
522 SoftSetBoolArg("-dnsseed", false);
523 SoftSetBoolArg("-upnp", false);
524 SoftSetBoolArg("-dns", false);
527 fAllowDNS = GetBoolArg("-dns");
528 fNoListen = !GetBoolArg("-listen", true);
530 // Continue to put "/P2SH/" in the coinbase to monitor
532 // This can be removed eventually...
533 const char* pszP2SH = "/P2SH/";
534 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
538 std::string strError;
539 if (!BindListenPort(strError))
541 wxMessageBox(strError, "Bitcoin");
546 if (mapArgs.count("-addnode"))
548 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
550 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
551 addr.nTime = 0; // so it won't relay unless successfully connected
553 addrman.Add(addr, CNetAddr("127.0.0.1"));
557 if (mapArgs.count("-paytxfee"))
559 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
561 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
564 if (nTransactionFee > 0.25 * COIN)
565 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
571 if (!CheckDiskSpace())
574 RandAddSeedPerfmon();
576 if (!CreateThread(StartNode, NULL))
577 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
580 CreateThread(ThreadRPCServer, NULL);
583 if(GetStartOnSystemStartup())
584 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
596 string StartupShortcutPath()
598 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
601 bool GetStartOnSystemStartup()
603 return filesystem::exists(StartupShortcutPath().c_str());
606 bool SetStartOnSystemStartup(bool fAutoStart)
608 // If the shortcut exists already, remove it for updating
609 remove(StartupShortcutPath().c_str());
615 // Get a pointer to the IShellLink interface.
616 IShellLink* psl = NULL;
617 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
618 CLSCTX_INPROC_SERVER, IID_IShellLink,
619 reinterpret_cast<void**>(&psl));
623 // Get the current executable path
624 TCHAR pszExePath[MAX_PATH];
625 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
627 TCHAR pszArgs[5] = TEXT("-min");
629 // Set the path to the shortcut target
630 psl->SetPath(pszExePath);
631 PathRemoveFileSpec(pszExePath);
632 psl->SetWorkingDirectory(pszExePath);
633 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
634 psl->SetArguments(pszArgs);
636 // Query IShellLink for the IPersistFile interface for
637 // saving the shortcut in persistent storage.
638 IPersistFile* ppf = NULL;
639 hres = psl->QueryInterface(IID_IPersistFile,
640 reinterpret_cast<void**>(&ppf));
643 WCHAR pwsz[MAX_PATH];
644 // Ensure that the string is ANSI.
645 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
646 // Save the link by calling IPersistFile::Save.
647 hres = ppf->Save(pwsz, TRUE);
663 // Follow the Desktop Application Autostart Spec:
664 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
666 boost::filesystem::path GetAutostartDir()
668 namespace fs = boost::filesystem;
670 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
671 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
672 char* pszHome = getenv("HOME");
673 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
677 boost::filesystem::path GetAutostartFilePath()
679 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
682 bool GetStartOnSystemStartup()
684 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
685 if (!optionFile.good())
687 // Scan through file for "Hidden=true":
689 while (!optionFile.eof())
691 getline(optionFile, line);
692 if (line.find("Hidden") != string::npos &&
693 line.find("true") != string::npos)
701 bool SetStartOnSystemStartup(bool fAutoStart)
705 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
706 unlink(GetAutostartFilePath().string().c_str());
708 unlink(GetAutostartFilePath().native_file_string().c_str());
713 char pszExePath[MAX_PATH+1];
714 memset(pszExePath, 0, sizeof(pszExePath));
715 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
718 boost::filesystem::create_directories(GetAutostartDir());
720 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
721 if (!optionFile.good())
723 // Write a bitcoin.desktop file to the autostart directory:
724 optionFile << "[Desktop Entry]\n";
725 optionFile << "Type=Application\n";
726 optionFile << "Name=Bitcoin\n";
727 optionFile << "Exec=" << pszExePath << " -min\n";
728 optionFile << "Terminal=false\n";
729 optionFile << "Hidden=false\n";
736 // TODO: OSX startup stuff; see:
737 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
739 bool GetStartOnSystemStartup() { return false; }
740 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }