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;
43 TRY_CRITICAL_BLOCK(cs_Shutdown)
45 fFirstThread = !fTaken;
52 nTransactionsUpdated++;
56 boost::filesystem::remove(GetPidFile());
57 UnregisterWallet(pwalletMain);
59 CreateThread(ExitTimeout, NULL);
61 printf("Bitcoin exiting\n\n");
74 void HandleSIGTERM(int)
76 fRequestShutdown = true;
84 //////////////////////////////////////////////////////////////////////////////
89 int main(int argc, char* argv[])
92 fRet = AppInit(argc, argv);
101 bool AppInit(int argc, char* argv[])
106 fRet = AppInit2(argc, argv);
108 catch (std::exception& e) {
109 PrintException(&e, "AppInit()");
111 PrintException(NULL, "AppInit()");
118 bool AppInit2(int argc, char* argv[])
121 // Turn off microsoft heap dump noise
122 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
123 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
126 // Disable confusing "helpful" text message on abort, ctrl-c
127 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
133 // Clean shutdown on SIGTERM
135 sa.sa_handler = HandleSIGTERM;
136 sigemptyset(&sa.sa_mask);
138 sigaction(SIGTERM, &sa, NULL);
139 sigaction(SIGINT, &sa, NULL);
140 sigaction(SIGHUP, &sa, NULL);
146 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
148 ParseParameters(argc, argv);
149 if (!ReadConfigFile(mapArgs, mapMultiArgs))
151 fprintf(stderr, "Error: Specified directory does not exist\n");
156 if (mapArgs.count("-?") || mapArgs.count("--help"))
158 string strUsage = string() +
159 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
160 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
161 " bitcoind [options] \t " + "\n" +
162 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
163 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
164 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
165 _("Options:") + "\n" +
166 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
167 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
168 " -gen \t\t " + _("Generate coins") + "\n" +
169 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
170 " -min \t\t " + _("Start minimized") + "\n" +
171 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
172 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
173 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
174 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
175 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
176 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
177 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
178 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
179 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
180 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
181 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
182 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
184 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
186 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
187 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
188 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
189 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
190 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
193 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
195 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
198 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
200 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
202 #if !defined(WIN32) && !defined(QT_GUI)
203 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
205 " -testnet \t\t " + _("Use the test network") + "\n" +
206 " -debug \t\t " + _("Output extra debugging information") + "\n" +
207 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
208 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
210 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
212 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
213 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
214 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
215 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
216 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
217 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
218 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
219 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
220 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
221 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
222 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
224 strUsage += string() +
225 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
226 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
227 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
228 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
229 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
231 strUsage += string() +
232 " -? \t\t " + _("This help message") + "\n";
235 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
236 #if defined(QT_GUI) && defined(WIN32)
237 // On windows, show a message box, as there is no stderr
238 ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
240 fprintf(stderr, "%s", strUsage.c_str());
245 fTestNet = GetBoolArg("-testnet");
248 SoftSetBoolArg("-irc", true);
251 fDebug = GetBoolArg("-debug");
253 #if !defined(WIN32) && !defined(QT_GUI)
254 fDaemon = GetBoolArg("-daemon");
262 fServer = GetBoolArg("-server");
264 /* force fServer when running without GUI */
268 fPrintToConsole = GetBoolArg("-printtoconsole");
269 fPrintToDebugger = GetBoolArg("-printtodebugger");
270 fLogTimestamps = GetBoolArg("-logtimestamps");
273 for (int i = 1; i < argc; i++)
274 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
279 int ret = CommandLineRPC(argc, argv);
284 #if !defined(WIN32) && !defined(QT_GUI)
291 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
296 CreatePidFile(GetPidFile(), pid);
300 pid_t sid = setsid();
302 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
306 if (!fDebug && !pszSetDataDir[0])
308 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
309 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
310 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
312 if (GetBoolArg("-loadblockindextest"))
315 txdb.LoadBlockIndex();
320 // Make sure only a single bitcoin process is using the data directory.
321 string strLockFile = GetDataDir() + "/.lock";
322 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
323 if (file) fclose(file);
324 static boost::interprocess::file_lock lock(strLockFile.c_str());
325 if (!lock.try_lock())
327 ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), _("Bitcoin"), wxOK|wxMODAL);
331 std::ostringstream strErrors;
336 fprintf(stdout, "bitcoin server starting\n");
339 InitMessage(_("Loading addresses..."));
340 printf("Loading addresses...\n");
341 nStart = GetTimeMillis();
342 if (!LoadAddresses())
343 strErrors << _("Error loading addr.dat") << "\n";
344 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
346 InitMessage(_("Loading block index..."));
347 printf("Loading block index...\n");
348 nStart = GetTimeMillis();
349 if (!LoadBlockIndex())
350 strErrors << _("Error loading blkindex.dat") << "\n";
351 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
353 InitMessage(_("Loading wallet..."));
354 printf("Loading wallet...\n");
355 nStart = GetTimeMillis();
357 pwalletMain = new CWallet("wallet.dat");
358 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
359 if (nLoadWalletRet != DB_LOAD_OK)
361 if (nLoadWalletRet == DB_CORRUPT)
362 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
363 else if (nLoadWalletRet == DB_TOO_NEW)
364 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
365 else if (nLoadWalletRet == DB_NEED_REWRITE)
367 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
368 printf("%s", strErrors.str().c_str());
369 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
373 strErrors << _("Error loading wallet.dat") << "\n";
376 if (GetBoolArg("-upgradewallet", fFirstRun))
378 int nMaxVersion = GetArg("-upgradewallet", 0);
379 if (nMaxVersion == 0) // the -walletupgrade without argument case
381 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
382 nMaxVersion = CLIENT_VERSION;
383 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
386 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
387 if (nMaxVersion < pwalletMain->GetVersion())
388 strErrors << _("Cannot downgrade wallet") << "\n";
389 pwalletMain->SetMaxVersion(nMaxVersion);
394 // Create new keyUser and set as default key
395 RandAddSeedPerfmon();
397 std::vector<unsigned char> newDefaultKey;
398 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
399 strErrors << _("Cannot initialize keypool") << "\n";
400 pwalletMain->SetDefaultKey(newDefaultKey);
401 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
402 strErrors << _("Cannot write default address") << "\n";
405 printf("%s", strErrors.str().c_str());
406 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
408 RegisterWallet(pwalletMain);
410 CBlockIndex *pindexRescan = pindexBest;
411 if (GetBoolArg("-rescan"))
412 pindexRescan = pindexGenesisBlock;
415 CWalletDB walletdb("wallet.dat");
416 CBlockLocator locator;
417 if (walletdb.ReadBestBlock(locator))
418 pindexRescan = locator.GetBlockIndex();
420 if (pindexBest != pindexRescan)
422 InitMessage(_("Rescanning..."));
423 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
424 nStart = GetTimeMillis();
425 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
426 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
429 InitMessage(_("Done loading"));
430 printf("Done loading\n");
433 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
434 printf("nBestHeight = %d\n", nBestHeight);
435 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
436 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
437 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
439 if (!strErrors.str().empty())
441 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
445 // Add wallet transactions that aren't already in a block to mapTransactions
446 pwalletMain->ReacceptWalletTransactions();
448 // Note: Bitcoin-QT stores several settings in the wallet, so we want
449 // to load the wallet BEFORE parsing command-line arguments, so
450 // the command-line/bitcoin.conf settings override GUI setting.
455 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
461 if (mapArgs.count("-timeout"))
463 int nNewTimeout = GetArg("-timeout", 5000);
464 if (nNewTimeout > 0 && nNewTimeout < 600000)
465 nConnectTimeout = nNewTimeout;
468 if (mapArgs.count("-printblock"))
470 string strMatch = mapArgs["-printblock"];
472 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
474 uint256 hash = (*mi).first;
475 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
477 CBlockIndex* pindex = (*mi).second;
479 block.ReadFromDisk(pindex);
480 block.BuildMerkleTree();
487 printf("No blocks matching %s were found\n", strMatch.c_str());
491 if (mapArgs.count("-proxy"))
494 addrProxy = CService(mapArgs["-proxy"], 9050);
495 if (!addrProxy.IsValid())
497 ThreadSafeMessageBox(_("Invalid -proxy address"), _("Bitcoin"), wxOK | wxMODAL);
502 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
505 // Use SoftSetBoolArg here so user can override any of these if they wish.
506 // Note: the GetBoolArg() calls for all of these must happen later.
507 SoftSetBoolArg("-listen", false);
508 SoftSetBoolArg("-irc", false);
509 SoftSetBoolArg("-dnsseed", false);
510 SoftSetBoolArg("-upnp", false);
511 SoftSetBoolArg("-dns", false);
514 fAllowDNS = GetBoolArg("-dns");
515 fNoListen = !GetBoolArg("-listen", true);
517 // Continue to put "/P2SH/" in the coinbase to monitor
519 // This can be removed eventually...
520 const char* pszP2SH = "/P2SH/";
521 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
525 std::string strError;
526 if (!BindListenPort(strError))
528 ThreadSafeMessageBox(strError, _("Bitcoin"), wxOK | wxMODAL);
533 if (mapArgs.count("-addnode"))
535 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
537 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
538 addr.nTime = 0; // so it won't relay unless successfully connected
540 addrman.Add(addr, CNetAddr("127.0.0.1"));
544 if (mapArgs.count("-paytxfee"))
546 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
548 ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("Bitcoin"), wxOK | wxMODAL);
551 if (nTransactionFee > 0.25 * COIN)
552 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);
558 if (!CheckDiskSpace())
561 RandAddSeedPerfmon();
563 if (!CreateThread(StartNode, NULL))
564 ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("Bitcoin"), wxOK | wxMODAL);
567 CreateThread(ThreadRPCServer, NULL);
570 if(GetStartOnSystemStartup())
571 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
583 string StartupShortcutPath()
585 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
588 bool GetStartOnSystemStartup()
590 return filesystem::exists(StartupShortcutPath().c_str());
593 bool SetStartOnSystemStartup(bool fAutoStart)
595 // If the shortcut exists already, remove it for updating
596 remove(StartupShortcutPath().c_str());
602 // Get a pointer to the IShellLink interface.
603 IShellLink* psl = NULL;
604 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
605 CLSCTX_INPROC_SERVER, IID_IShellLink,
606 reinterpret_cast<void**>(&psl));
610 // Get the current executable path
611 TCHAR pszExePath[MAX_PATH];
612 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
614 TCHAR pszArgs[5] = TEXT("-min");
616 // Set the path to the shortcut target
617 psl->SetPath(pszExePath);
618 PathRemoveFileSpec(pszExePath);
619 psl->SetWorkingDirectory(pszExePath);
620 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
621 psl->SetArguments(pszArgs);
623 // Query IShellLink for the IPersistFile interface for
624 // saving the shortcut in persistent storage.
625 IPersistFile* ppf = NULL;
626 hres = psl->QueryInterface(IID_IPersistFile,
627 reinterpret_cast<void**>(&ppf));
630 WCHAR pwsz[MAX_PATH];
631 // Ensure that the string is ANSI.
632 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
633 // Save the link by calling IPersistFile::Save.
634 hres = ppf->Save(pwsz, TRUE);
650 // Follow the Desktop Application Autostart Spec:
651 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
653 boost::filesystem::path GetAutostartDir()
655 namespace fs = boost::filesystem;
657 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
658 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
659 char* pszHome = getenv("HOME");
660 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
664 boost::filesystem::path GetAutostartFilePath()
666 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
669 bool GetStartOnSystemStartup()
671 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
672 if (!optionFile.good())
674 // Scan through file for "Hidden=true":
676 while (!optionFile.eof())
678 getline(optionFile, line);
679 if (line.find("Hidden") != string::npos &&
680 line.find("true") != string::npos)
688 bool SetStartOnSystemStartup(bool fAutoStart)
692 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
693 unlink(GetAutostartFilePath().string().c_str());
695 unlink(GetAutostartFilePath().native_file_string().c_str());
700 char pszExePath[MAX_PATH+1];
701 memset(pszExePath, 0, sizeof(pszExePath));
702 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
705 boost::filesystem::create_directories(GetAutostartDir());
707 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
708 if (!optionFile.good())
710 // Write a bitcoin.desktop file to the autostart directory:
711 optionFile << "[Desktop Entry]\n";
712 optionFile << "Type=Application\n";
713 optionFile << "Name=Bitcoin\n";
714 optionFile << "Exec=" << pszExePath << " -min\n";
715 optionFile << "Terminal=false\n";
716 optionFile << "Hidden=false\n";
723 // TODO: OSX startup stuff; see:
724 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
726 bool GetStartOnSystemStartup() { return false; }
727 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }