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 COPYING 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)
48 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
51 // Without UI, Shutdown() can simply be started in a new thread
52 CreateThread(Shutdown, NULL);
56 void Shutdown(void* parg)
58 static CCriticalSection cs_Shutdown;
60 bool fFirstThread = false;
61 TRY_CRITICAL_BLOCK(cs_Shutdown)
63 fFirstThread = !fTaken;
70 nTransactionsUpdated++;
74 boost::filesystem::remove(GetPidFile());
75 UnregisterWallet(pwalletMain);
77 CreateThread(ExitTimeout, NULL);
79 printf("Bitcoin exiting\n\n");
82 // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
95 void HandleSIGTERM(int)
97 fRequestShutdown = true;
105 //////////////////////////////////////////////////////////////////////////////
110 int main(int argc, char* argv[])
113 fRet = AppInit(argc, argv);
122 bool AppInit(int argc, char* argv[])
127 fRet = AppInit2(argc, argv);
129 catch (std::exception& e) {
130 PrintException(&e, "AppInit()");
132 PrintException(NULL, "AppInit()");
139 bool AppInit2(int argc, char* argv[])
142 // Turn off microsoft heap dump noise
143 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
144 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
147 // Disable confusing "helpful" text message on abort, ctrl-c
148 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
154 // Clean shutdown on SIGTERM
156 sa.sa_handler = HandleSIGTERM;
157 sigemptyset(&sa.sa_mask);
159 sigaction(SIGTERM, &sa, NULL);
160 sigaction(SIGINT, &sa, NULL);
161 sigaction(SIGHUP, &sa, NULL);
167 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
169 ParseParameters(argc, argv);
170 if (!ReadConfigFile(mapArgs, mapMultiArgs))
172 fprintf(stderr, "Error: Specified directory does not exist\n");
177 if (mapArgs.count("-?") || mapArgs.count("--help"))
179 string strUsage = string() +
180 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
181 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
182 " bitcoind [options] \t " + "\n" +
183 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
184 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
185 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
186 _("Options:") + "\n" +
187 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
188 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
189 " -gen \t\t " + _("Generate coins") + "\n" +
190 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
191 " -min \t\t " + _("Start minimized") + "\n" +
192 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
193 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
194 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
195 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
196 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
197 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
198 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
199 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
200 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
201 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
202 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
203 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
205 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
207 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
208 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
209 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
210 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
211 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
214 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
216 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
219 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
221 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
223 #if !defined(WIN32) && !defined(QT_GUI)
224 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
226 " -testnet \t\t " + _("Use the test network") + "\n" +
227 " -debug \t\t " + _("Output extra debugging information") + "\n" +
228 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
229 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
231 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
233 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
234 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
235 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
236 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
237 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
238 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
239 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
240 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
241 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
242 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
243 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
246 strUsage += string() +
247 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
248 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
249 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
250 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
251 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
254 strUsage += string() +
255 " -? \t\t " + _("This help message") + "\n";
258 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
259 #if defined(QT_GUI) && defined(WIN32)
260 // On windows, show a message box, as there is no stderr
261 wxMessageBox(strUsage, "Usage");
263 fprintf(stderr, "%s", strUsage.c_str());
268 fTestNet = GetBoolArg("-testnet");
271 SoftSetBoolArg("-irc", true);
274 fDebug = GetBoolArg("-debug");
276 #if !defined(WIN32) && !defined(QT_GUI)
277 fDaemon = GetBoolArg("-daemon");
285 fServer = GetBoolArg("-server");
287 /* force fServer when running without GUI */
291 fPrintToConsole = GetBoolArg("-printtoconsole");
292 fPrintToDebugger = GetBoolArg("-printtodebugger");
293 fLogTimestamps = GetBoolArg("-logtimestamps");
296 for (int i = 1; i < argc; i++)
297 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
302 int ret = CommandLineRPC(argc, argv);
307 #if !defined(WIN32) && !defined(QT_GUI)
314 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
319 CreatePidFile(GetPidFile(), pid);
323 pid_t sid = setsid();
325 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
329 if (!fDebug && !pszSetDataDir[0])
331 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
332 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
333 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
335 if (GetBoolArg("-loadblockindextest"))
338 txdb.LoadBlockIndex();
343 // Make sure only a single bitcoin process is using the data directory.
344 string strLockFile = GetDataDir() + "/.lock";
345 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
346 if (file) fclose(file);
347 static boost::interprocess::file_lock lock(strLockFile.c_str());
348 if (!lock.try_lock())
350 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
354 std::ostringstream strErrors;
359 fprintf(stdout, "bitcoin server starting\n");
362 InitMessage(_("Loading addresses..."));
363 printf("Loading addresses...\n");
364 nStart = GetTimeMillis();
365 if (!LoadAddresses())
366 strErrors << _("Error loading addr.dat") << "\n";
367 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
369 InitMessage(_("Loading block index..."));
370 printf("Loading block index...\n");
371 nStart = GetTimeMillis();
372 if (!LoadBlockIndex())
373 strErrors << _("Error loading blkindex.dat") << "\n";
374 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
376 InitMessage(_("Loading wallet..."));
377 printf("Loading wallet...\n");
378 nStart = GetTimeMillis();
380 pwalletMain = new CWallet("wallet.dat");
381 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
382 if (nLoadWalletRet != DB_LOAD_OK)
384 if (nLoadWalletRet == DB_CORRUPT)
385 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
386 else if (nLoadWalletRet == DB_TOO_NEW)
387 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
388 else if (nLoadWalletRet == DB_NEED_REWRITE)
390 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
391 printf("%s", strErrors.str().c_str());
392 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
396 strErrors << _("Error loading wallet.dat") << "\n";
399 if (GetBoolArg("-upgradewallet", fFirstRun))
401 int nMaxVersion = GetArg("-upgradewallet", 0);
402 if (nMaxVersion == 0) // the -walletupgrade without argument case
404 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
405 nMaxVersion = CLIENT_VERSION;
406 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
409 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
410 if (nMaxVersion < pwalletMain->GetVersion())
411 strErrors << _("Cannot downgrade wallet") << "\n";
412 pwalletMain->SetMaxVersion(nMaxVersion);
417 // Create new keyUser and set as default key
418 RandAddSeedPerfmon();
420 std::vector<unsigned char> newDefaultKey;
421 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
422 strErrors << _("Cannot initialize keypool") << "\n";
423 pwalletMain->SetDefaultKey(newDefaultKey);
424 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
425 strErrors << _("Cannot write default address") << "\n";
428 printf("%s", strErrors.str().c_str());
429 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
431 RegisterWallet(pwalletMain);
433 CBlockIndex *pindexRescan = pindexBest;
434 if (GetBoolArg("-rescan"))
435 pindexRescan = pindexGenesisBlock;
438 CWalletDB walletdb("wallet.dat");
439 CBlockLocator locator;
440 if (walletdb.ReadBestBlock(locator))
441 pindexRescan = locator.GetBlockIndex();
443 if (pindexBest != pindexRescan)
445 InitMessage(_("Rescanning..."));
446 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
447 nStart = GetTimeMillis();
448 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
449 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
452 InitMessage(_("Done loading"));
453 printf("Done loading\n");
456 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
457 printf("nBestHeight = %d\n", nBestHeight);
458 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
459 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
460 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
462 if (!strErrors.str().empty())
464 wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
468 // Add wallet transactions that aren't already in a block to mapTransactions
469 pwalletMain->ReacceptWalletTransactions();
471 // Note: Bitcoin-QT stores several settings in the wallet, so we want
472 // to load the wallet BEFORE parsing command-line arguments, so
473 // the command-line/bitcoin.conf settings override GUI setting.
478 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
484 if (mapArgs.count("-timeout"))
486 int nNewTimeout = GetArg("-timeout", 5000);
487 if (nNewTimeout > 0 && nNewTimeout < 600000)
488 nConnectTimeout = nNewTimeout;
491 if (mapArgs.count("-printblock"))
493 string strMatch = mapArgs["-printblock"];
495 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
497 uint256 hash = (*mi).first;
498 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
500 CBlockIndex* pindex = (*mi).second;
502 block.ReadFromDisk(pindex);
503 block.BuildMerkleTree();
510 printf("No blocks matching %s were found\n", strMatch.c_str());
514 if (mapArgs.count("-proxy"))
517 addrProxy = CService(mapArgs["-proxy"], 9050);
518 if (!addrProxy.IsValid())
520 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
525 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
528 // Use SoftSetBoolArg here so user can override any of these if they wish.
529 // Note: the GetBoolArg() calls for all of these must happen later.
530 SoftSetBoolArg("-listen", false);
531 SoftSetBoolArg("-irc", false);
532 SoftSetBoolArg("-dnsseed", false);
533 SoftSetBoolArg("-upnp", false);
534 SoftSetBoolArg("-dns", false);
537 fAllowDNS = GetBoolArg("-dns");
538 fNoListen = !GetBoolArg("-listen", true);
540 // Continue to put "/P2SH/" in the coinbase to monitor
542 // This can be removed eventually...
543 const char* pszP2SH = "/P2SH/";
544 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
548 std::string strError;
549 if (!BindListenPort(strError))
551 wxMessageBox(strError, "Bitcoin");
556 if (mapArgs.count("-addnode"))
558 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
560 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
561 addr.nTime = 0; // so it won't relay unless successfully connected
563 addrman.Add(addr, CNetAddr("127.0.0.1"));
567 if (mapArgs.count("-paytxfee"))
569 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
571 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
574 if (nTransactionFee > 0.25 * COIN)
575 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
581 if (!CheckDiskSpace())
584 RandAddSeedPerfmon();
586 if (!CreateThread(StartNode, NULL))
587 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
590 CreateThread(ThreadRPCServer, NULL);
593 if(GetStartOnSystemStartup())
594 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
606 string StartupShortcutPath()
608 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
611 bool GetStartOnSystemStartup()
613 return filesystem::exists(StartupShortcutPath().c_str());
616 bool SetStartOnSystemStartup(bool fAutoStart)
618 // If the shortcut exists already, remove it for updating
619 remove(StartupShortcutPath().c_str());
625 // Get a pointer to the IShellLink interface.
626 IShellLink* psl = NULL;
627 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
628 CLSCTX_INPROC_SERVER, IID_IShellLink,
629 reinterpret_cast<void**>(&psl));
633 // Get the current executable path
634 TCHAR pszExePath[MAX_PATH];
635 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
637 TCHAR pszArgs[5] = TEXT("-min");
639 // Set the path to the shortcut target
640 psl->SetPath(pszExePath);
641 PathRemoveFileSpec(pszExePath);
642 psl->SetWorkingDirectory(pszExePath);
643 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
644 psl->SetArguments(pszArgs);
646 // Query IShellLink for the IPersistFile interface for
647 // saving the shortcut in persistent storage.
648 IPersistFile* ppf = NULL;
649 hres = psl->QueryInterface(IID_IPersistFile,
650 reinterpret_cast<void**>(&ppf));
653 WCHAR pwsz[MAX_PATH];
654 // Ensure that the string is ANSI.
655 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
656 // Save the link by calling IPersistFile::Save.
657 hres = ppf->Save(pwsz, TRUE);
673 // Follow the Desktop Application Autostart Spec:
674 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
676 boost::filesystem::path GetAutostartDir()
678 namespace fs = boost::filesystem;
680 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
681 if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
682 char* pszHome = getenv("HOME");
683 if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
687 boost::filesystem::path GetAutostartFilePath()
689 return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
692 bool GetStartOnSystemStartup()
694 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
695 if (!optionFile.good())
697 // Scan through file for "Hidden=true":
699 while (!optionFile.eof())
701 getline(optionFile, line);
702 if (line.find("Hidden") != string::npos &&
703 line.find("true") != string::npos)
711 bool SetStartOnSystemStartup(bool fAutoStart)
715 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
716 unlink(GetAutostartFilePath().string().c_str());
718 unlink(GetAutostartFilePath().native_file_string().c_str());
723 char pszExePath[MAX_PATH+1];
724 memset(pszExePath, 0, sizeof(pszExePath));
725 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
728 boost::filesystem::create_directories(GetAutostartDir());
730 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
731 if (!optionFile.good())
733 // Write a bitcoin.desktop file to the autostart directory:
734 optionFile << "[Desktop Entry]\n";
735 optionFile << "Type=Application\n";
736 optionFile << "Name=Bitcoin\n";
737 optionFile << "Exec=" << pszExePath << " -min\n";
738 optionFile << "Terminal=false\n";
739 optionFile << "Hidden=false\n";
746 // TODO: OSX startup stuff; see:
747 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
749 bool GetStartOnSystemStartup() { return false; }
750 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }