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>
17 #define strncasecmp strnicmp
21 using namespace boost;
25 //////////////////////////////////////////////////////////////////////////////
30 void ExitTimeout(void* parg)
38 void Shutdown(void* parg)
40 static CCriticalSection cs_Shutdown;
42 bool fFirstThread = false;
44 TRY_LOCK(cs_Shutdown, lockShutdown);
47 fFirstThread = !fTaken;
55 nTransactionsUpdated++;
59 boost::filesystem::remove(GetPidFile());
60 UnregisterWallet(pwalletMain);
62 CreateThread(ExitTimeout, NULL);
64 printf("Bitcoin exiting\n\n");
77 void HandleSIGTERM(int)
79 fRequestShutdown = true;
87 //////////////////////////////////////////////////////////////////////////////
92 int main(int argc, char* argv[])
95 fRet = AppInit(argc, argv);
104 bool AppInit(int argc, char* argv[])
109 fRet = AppInit2(argc, argv);
111 catch (std::exception& e) {
112 PrintException(&e, "AppInit()");
114 PrintException(NULL, "AppInit()");
121 bool AppInit2(int argc, char* argv[])
124 // Turn off microsoft heap dump noise
125 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
126 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
129 // Disable confusing "helpful" text message on abort, ctrl-c
130 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
136 // Clean shutdown on SIGTERM
138 sa.sa_handler = HandleSIGTERM;
139 sigemptyset(&sa.sa_mask);
141 sigaction(SIGTERM, &sa, NULL);
142 sigaction(SIGINT, &sa, NULL);
143 sigaction(SIGHUP, &sa, NULL);
149 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
151 ParseParameters(argc, argv);
152 if (!ReadConfigFile(mapArgs, mapMultiArgs))
154 fprintf(stderr, "Error: Specified directory does not exist\n");
159 if (mapArgs.count("-?") || mapArgs.count("--help"))
161 string strUsage = string() +
162 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
163 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
164 " bitcoind [options] \t " + "\n" +
165 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
166 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
167 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
168 _("Options:") + "\n" +
169 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
170 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
171 " -gen \t\t " + _("Generate coins") + "\n" +
172 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
173 " -min \t\t " + _("Start minimized") + "\n" +
174 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
175 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
176 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
177 " -dblogsize=<n> \t\t " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
178 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
179 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
180 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
181 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
182 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
183 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
184 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
185 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
186 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
188 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
190 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
191 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
192 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
193 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
194 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
197 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
199 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
202 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
204 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
206 #if !defined(WIN32) && !defined(QT_GUI)
207 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
209 " -testnet \t\t " + _("Use the test network") + "\n" +
210 " -debug \t\t " + _("Output extra debugging information") + "\n" +
211 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
212 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
214 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
216 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
217 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
218 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
219 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
220 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
221 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
222 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
223 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
224 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
225 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
226 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\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";
235 strUsage += string() +
236 " -? \t\t " + _("This help message") + "\n";
239 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
240 #if defined(QT_GUI) && defined(WIN32)
241 // On windows, show a message box, as there is no stderr
242 ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
244 fprintf(stderr, "%s", strUsage.c_str());
249 fTestNet = GetBoolArg("-testnet");
252 SoftSetBoolArg("-irc", true);
255 fDebug = GetBoolArg("-debug");
257 #if !defined(WIN32) && !defined(QT_GUI)
258 fDaemon = GetBoolArg("-daemon");
266 fServer = GetBoolArg("-server");
268 /* force fServer when running without GUI */
272 fPrintToConsole = GetBoolArg("-printtoconsole");
273 fPrintToDebugger = GetBoolArg("-printtodebugger");
274 fLogTimestamps = GetBoolArg("-logtimestamps");
277 for (int i = 1; i < argc; i++)
278 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
283 int ret = CommandLineRPC(argc, argv);
288 #if !defined(WIN32) && !defined(QT_GUI)
295 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
300 CreatePidFile(GetPidFile(), pid);
304 pid_t sid = setsid();
306 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
312 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
313 printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
314 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
316 if (GetBoolArg("-loadblockindextest"))
319 txdb.LoadBlockIndex();
324 // Make sure only a single bitcoin process is using the data directory.
325 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
326 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
327 if (file) fclose(file);
328 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
329 if (!lock.try_lock())
331 ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().string().c_str()), _("Bitcoin"), wxOK|wxMODAL);
335 std::ostringstream strErrors;
340 fprintf(stdout, "bitcoin server starting\n");
343 InitMessage(_("Loading addresses..."));
344 printf("Loading addresses...\n");
345 nStart = GetTimeMillis();
346 if (!LoadAddresses())
347 strErrors << _("Error loading addr.dat") << "\n";
348 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
350 InitMessage(_("Loading block index..."));
351 printf("Loading block index...\n");
352 nStart = GetTimeMillis();
353 if (!LoadBlockIndex())
354 strErrors << _("Error loading blkindex.dat") << "\n";
355 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
357 InitMessage(_("Loading wallet..."));
358 printf("Loading wallet...\n");
359 nStart = GetTimeMillis();
361 pwalletMain = new CWallet("wallet.dat");
362 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
363 if (nLoadWalletRet != DB_LOAD_OK)
365 if (nLoadWalletRet == DB_CORRUPT)
366 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
367 else if (nLoadWalletRet == DB_TOO_NEW)
368 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
369 else if (nLoadWalletRet == DB_NEED_REWRITE)
371 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
372 printf("%s", strErrors.str().c_str());
373 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
377 strErrors << _("Error loading wallet.dat") << "\n";
380 if (GetBoolArg("-upgradewallet", fFirstRun))
382 int nMaxVersion = GetArg("-upgradewallet", 0);
383 if (nMaxVersion == 0) // the -walletupgrade without argument case
385 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
386 nMaxVersion = CLIENT_VERSION;
387 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
390 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
391 if (nMaxVersion < pwalletMain->GetVersion())
392 strErrors << _("Cannot downgrade wallet") << "\n";
393 pwalletMain->SetMaxVersion(nMaxVersion);
398 // Create new keyUser and set as default key
399 RandAddSeedPerfmon();
401 std::vector<unsigned char> newDefaultKey;
402 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
403 strErrors << _("Cannot initialize keypool") << "\n";
404 pwalletMain->SetDefaultKey(newDefaultKey);
405 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
406 strErrors << _("Cannot write default address") << "\n";
409 printf("%s", strErrors.str().c_str());
410 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
412 RegisterWallet(pwalletMain);
414 CBlockIndex *pindexRescan = pindexBest;
415 if (GetBoolArg("-rescan"))
416 pindexRescan = pindexGenesisBlock;
419 CWalletDB walletdb("wallet.dat");
420 CBlockLocator locator;
421 if (walletdb.ReadBestBlock(locator))
422 pindexRescan = locator.GetBlockIndex();
424 if (pindexBest != pindexRescan)
426 InitMessage(_("Rescanning..."));
427 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
428 nStart = GetTimeMillis();
429 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
430 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
433 InitMessage(_("Done loading"));
434 printf("Done loading\n");
437 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
438 printf("nBestHeight = %d\n", nBestHeight);
439 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
440 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
441 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
443 if (!strErrors.str().empty())
445 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
449 // Add wallet transactions that aren't already in a block to mapTransactions
450 pwalletMain->ReacceptWalletTransactions();
452 // Note: Bitcoin-QT stores several settings in the wallet, so we want
453 // to load the wallet BEFORE parsing command-line arguments, so
454 // the command-line/bitcoin.conf settings override GUI setting.
459 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
465 if (mapArgs.count("-timeout"))
467 int nNewTimeout = GetArg("-timeout", 5000);
468 if (nNewTimeout > 0 && nNewTimeout < 600000)
469 nConnectTimeout = nNewTimeout;
472 if (mapArgs.count("-printblock"))
474 string strMatch = mapArgs["-printblock"];
476 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
478 uint256 hash = (*mi).first;
479 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
481 CBlockIndex* pindex = (*mi).second;
483 block.ReadFromDisk(pindex);
484 block.BuildMerkleTree();
491 printf("No blocks matching %s were found\n", strMatch.c_str());
495 if (mapArgs.count("-proxy"))
498 addrProxy = CService(mapArgs["-proxy"], 9050);
499 if (!addrProxy.IsValid())
501 ThreadSafeMessageBox(_("Invalid -proxy address"), _("Bitcoin"), wxOK | wxMODAL);
506 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
509 // Use SoftSetBoolArg here so user can override any of these if they wish.
510 // Note: the GetBoolArg() calls for all of these must happen later.
511 SoftSetBoolArg("-listen", false);
512 SoftSetBoolArg("-irc", false);
513 SoftSetBoolArg("-dnsseed", false);
514 SoftSetBoolArg("-upnp", false);
515 SoftSetBoolArg("-dns", false);
518 fAllowDNS = GetBoolArg("-dns");
519 fNoListen = !GetBoolArg("-listen", true);
521 // Continue to put "/P2SH/" in the coinbase to monitor
523 // This can be removed eventually...
524 const char* pszP2SH = "/P2SH/";
525 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
529 std::string strError;
530 if (!BindListenPort(strError))
532 ThreadSafeMessageBox(strError, _("Bitcoin"), wxOK | wxMODAL);
537 if (mapArgs.count("-addnode"))
539 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
541 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
542 addr.nTime = 0; // so it won't relay unless successfully connected
544 addrman.Add(addr, CNetAddr("127.0.0.1"));
548 if (mapArgs.count("-paytxfee"))
550 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
552 ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("Bitcoin"), wxOK | wxMODAL);
555 if (nTransactionFee > 0.25 * COIN)
556 ThreadSafeMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), _("Bitcoin"), wxOK | wxICON_EXCLAMATION | wxMODAL);
562 if (!CheckDiskSpace())
565 RandAddSeedPerfmon();
567 if (!CreateThread(StartNode, NULL))
568 ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("Bitcoin"), wxOK | wxMODAL);
571 CreateThread(ThreadRPCServer, NULL);
574 if(GetStartOnSystemStartup())
575 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
587 boost::filesystem::path StartupShortcutPath()
589 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "Bitcoin.lnk";
592 bool GetStartOnSystemStartup()
594 return filesystem::exists(StartupShortcutPath());
597 bool SetStartOnSystemStartup(bool fAutoStart)
599 // If the shortcut exists already, remove it for updating
600 boost::filesystem::remove(StartupShortcutPath());
606 // Get a pointer to the IShellLink interface.
607 IShellLink* psl = NULL;
608 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
609 CLSCTX_INPROC_SERVER, IID_IShellLink,
610 reinterpret_cast<void**>(&psl));
614 // Get the current executable path
615 TCHAR pszExePath[MAX_PATH];
616 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
618 TCHAR pszArgs[5] = TEXT("-min");
620 // Set the path to the shortcut target
621 psl->SetPath(pszExePath);
622 PathRemoveFileSpec(pszExePath);
623 psl->SetWorkingDirectory(pszExePath);
624 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
625 psl->SetArguments(pszArgs);
627 // Query IShellLink for the IPersistFile interface for
628 // saving the shortcut in persistent storage.
629 IPersistFile* ppf = NULL;
630 hres = psl->QueryInterface(IID_IPersistFile,
631 reinterpret_cast<void**>(&ppf));
634 WCHAR pwsz[MAX_PATH];
635 // Ensure that the string is ANSI.
636 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
637 // Save the link by calling IPersistFile::Save.
638 hres = ppf->Save(pwsz, TRUE);
654 // Follow the Desktop Application Autostart Spec:
655 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
657 boost::filesystem::path GetAutostartDir()
659 namespace fs = boost::filesystem;
661 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
662 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
663 char* pszHome = getenv("HOME");
664 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
668 boost::filesystem::path GetAutostartFilePath()
670 return GetAutostartDir() / "bitcoin.desktop";
673 bool GetStartOnSystemStartup()
675 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
676 if (!optionFile.good())
678 // Scan through file for "Hidden=true":
680 while (!optionFile.eof())
682 getline(optionFile, line);
683 if (line.find("Hidden") != string::npos &&
684 line.find("true") != string::npos)
692 bool SetStartOnSystemStartup(bool fAutoStart)
695 boost::filesystem::remove(GetAutostartFilePath());
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; }