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"
12 #include "ui_interface.h"
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
15 #include <boost/filesystem/convenience.hpp>
16 #include <boost/interprocess/sync/file_lock.hpp>
23 using namespace boost;
27 //////////////////////////////////////////////////////////////////////////////
32 void ExitTimeout(void* parg)
40 void Shutdown(void* parg)
42 static CCriticalSection cs_Shutdown;
44 bool fFirstThread = false;
46 TRY_LOCK(cs_Shutdown, lockShutdown);
49 fFirstThread = !fTaken;
57 nTransactionsUpdated++;
61 boost::filesystem::remove(GetPidFile());
62 UnregisterWallet(pwalletMain);
64 CreateThread(ExitTimeout, NULL);
66 printf("Bitcoin exiting\n\n");
79 void HandleSIGTERM(int)
81 fRequestShutdown = true;
89 //////////////////////////////////////////////////////////////////////////////
94 int main(int argc, char* argv[])
97 fRet = AppInit(argc, argv);
106 bool AppInit(int argc, char* argv[])
111 fRet = AppInit2(argc, argv);
113 catch (std::exception& e) {
114 PrintException(&e, "AppInit()");
116 PrintException(NULL, "AppInit()");
123 bool AppInit2(int argc, char* argv[])
126 // Turn off microsoft heap dump noise
127 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
128 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
131 // Disable confusing "helpful" text message on abort, ctrl-c
132 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
138 // Clean shutdown on SIGTERM
140 sa.sa_handler = HandleSIGTERM;
141 sigemptyset(&sa.sa_mask);
143 sigaction(SIGTERM, &sa, NULL);
144 sigaction(SIGINT, &sa, NULL);
145 sigaction(SIGHUP, &sa, NULL);
151 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
153 ParseParameters(argc, argv);
154 if (!ReadConfigFile(mapArgs, mapMultiArgs))
156 fprintf(stderr, "Error: Specified directory does not exist\n");
161 if (mapArgs.count("-?") || mapArgs.count("--help"))
163 string strUsage = string() +
164 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
165 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
166 " bitcoind [options] \t " + "\n" +
167 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
168 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
169 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
170 _("Options:") + "\n" +
171 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
172 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
173 " -gen \t\t " + _("Generate coins") + "\n" +
174 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
175 " -min \t\t " + _("Start minimized") + "\n" +
176 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
177 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
178 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
179 " -dblogsize=<n> \t\t " + _("Set database disk log size in megabytes (default: 100)") + "\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 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
225 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
226 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
227 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
228 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
230 strUsage += string() +
231 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
232 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
233 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
234 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
235 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
237 strUsage += string() +
238 " -? \t\t " + _("This help message") + "\n";
241 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
242 #if defined(QT_GUI) && defined(WIN32)
243 // On windows, show a message box, as there is no stderr
244 ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
246 fprintf(stderr, "%s", strUsage.c_str());
251 fTestNet = GetBoolArg("-testnet");
254 SoftSetBoolArg("-irc", true);
257 fDebug = GetBoolArg("-debug");
259 #if !defined(WIN32) && !defined(QT_GUI)
260 fDaemon = GetBoolArg("-daemon");
268 fServer = GetBoolArg("-server");
270 /* force fServer when running without GUI */
274 fPrintToConsole = GetBoolArg("-printtoconsole");
275 fPrintToDebugger = GetBoolArg("-printtodebugger");
276 fLogTimestamps = GetBoolArg("-logtimestamps");
279 for (int i = 1; i < argc; i++)
280 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
285 int ret = CommandLineRPC(argc, argv);
290 #if !defined(WIN32) && !defined(QT_GUI)
297 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
302 CreatePidFile(GetPidFile(), pid);
306 pid_t sid = setsid();
308 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
314 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
315 printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
316 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
318 if (GetBoolArg("-loadblockindextest"))
321 txdb.LoadBlockIndex();
326 // Make sure only a single bitcoin process is using the data directory.
327 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
328 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
329 if (file) fclose(file);
330 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
331 if (!lock.try_lock())
333 ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().string().c_str()), _("Bitcoin"), wxOK|wxMODAL);
337 std::ostringstream strErrors;
342 fprintf(stdout, "bitcoin server starting\n");
345 InitMessage(_("Loading addresses..."));
346 printf("Loading addresses...\n");
347 nStart = GetTimeMillis();
348 if (!LoadAddresses())
349 strErrors << _("Error loading addr.dat") << "\n";
350 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
352 InitMessage(_("Loading block index..."));
353 printf("Loading block index...\n");
354 nStart = GetTimeMillis();
355 if (!LoadBlockIndex())
356 strErrors << _("Error loading blkindex.dat") << "\n";
357 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
359 InitMessage(_("Loading wallet..."));
360 printf("Loading wallet...\n");
361 nStart = GetTimeMillis();
363 pwalletMain = new CWallet("wallet.dat");
364 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
365 if (nLoadWalletRet != DB_LOAD_OK)
367 if (nLoadWalletRet == DB_CORRUPT)
368 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
369 else if (nLoadWalletRet == DB_TOO_NEW)
370 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
371 else if (nLoadWalletRet == DB_NEED_REWRITE)
373 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
374 printf("%s", strErrors.str().c_str());
375 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
379 strErrors << _("Error loading wallet.dat") << "\n";
382 if (GetBoolArg("-upgradewallet", fFirstRun))
384 int nMaxVersion = GetArg("-upgradewallet", 0);
385 if (nMaxVersion == 0) // the -walletupgrade without argument case
387 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
388 nMaxVersion = CLIENT_VERSION;
389 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
392 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
393 if (nMaxVersion < pwalletMain->GetVersion())
394 strErrors << _("Cannot downgrade wallet") << "\n";
395 pwalletMain->SetMaxVersion(nMaxVersion);
400 // Create new keyUser and set as default key
401 RandAddSeedPerfmon();
403 std::vector<unsigned char> newDefaultKey;
404 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
405 strErrors << _("Cannot initialize keypool") << "\n";
406 pwalletMain->SetDefaultKey(newDefaultKey);
407 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
408 strErrors << _("Cannot write default address") << "\n";
411 printf("%s", strErrors.str().c_str());
412 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
414 RegisterWallet(pwalletMain);
416 CBlockIndex *pindexRescan = pindexBest;
417 if (GetBoolArg("-rescan"))
418 pindexRescan = pindexGenesisBlock;
421 CWalletDB walletdb("wallet.dat");
422 CBlockLocator locator;
423 if (walletdb.ReadBestBlock(locator))
424 pindexRescan = locator.GetBlockIndex();
426 if (pindexBest != pindexRescan)
428 InitMessage(_("Rescanning..."));
429 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
430 nStart = GetTimeMillis();
431 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
432 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
435 InitMessage(_("Done loading"));
436 printf("Done loading\n");
439 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
440 printf("nBestHeight = %d\n", nBestHeight);
441 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
442 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
443 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
445 if (!strErrors.str().empty())
447 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
451 // Add wallet transactions that aren't already in a block to mapTransactions
452 pwalletMain->ReacceptWalletTransactions();
454 // Note: Bitcoin-QT stores several settings in the wallet, so we want
455 // to load the wallet BEFORE parsing command-line arguments, so
456 // the command-line/bitcoin.conf settings override GUI setting.
461 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
467 if (mapArgs.count("-timeout"))
469 int nNewTimeout = GetArg("-timeout", 5000);
470 if (nNewTimeout > 0 && nNewTimeout < 600000)
471 nConnectTimeout = nNewTimeout;
474 if (mapArgs.count("-printblock"))
476 string strMatch = mapArgs["-printblock"];
478 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
480 uint256 hash = (*mi).first;
481 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
483 CBlockIndex* pindex = (*mi).second;
485 block.ReadFromDisk(pindex);
486 block.BuildMerkleTree();
493 printf("No blocks matching %s were found\n", strMatch.c_str());
497 if (mapArgs.count("-proxy"))
500 addrProxy = CService(mapArgs["-proxy"], 9050);
501 if (!addrProxy.IsValid())
503 ThreadSafeMessageBox(_("Invalid -proxy address"), _("Bitcoin"), wxOK | wxMODAL);
508 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
511 // Use SoftSetBoolArg here so user can override any of these if they wish.
512 // Note: the GetBoolArg() calls for all of these must happen later.
513 SoftSetBoolArg("-listen", false);
514 SoftSetBoolArg("-irc", false);
515 SoftSetBoolArg("-dnsseed", false);
516 SoftSetBoolArg("-upnp", false);
517 SoftSetBoolArg("-dns", false);
520 fAllowDNS = GetBoolArg("-dns");
521 fNoListen = !GetBoolArg("-listen", true);
523 // Continue to put "/P2SH/" in the coinbase to monitor
525 // This can be removed eventually...
526 const char* pszP2SH = "/P2SH/";
527 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
531 std::string strError;
532 if (!BindListenPort(strError))
534 ThreadSafeMessageBox(strError, _("Bitcoin"), wxOK | wxMODAL);
539 if (mapArgs.count("-addnode"))
541 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
543 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
544 addr.nTime = 0; // so it won't relay unless successfully connected
546 addrman.Add(addr, CNetAddr("127.0.0.1"));
550 if (mapArgs.count("-paytxfee"))
552 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
554 ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("Bitcoin"), wxOK | wxMODAL);
557 if (nTransactionFee > 0.25 * COIN)
558 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);
564 if (!CheckDiskSpace())
567 RandAddSeedPerfmon();
569 if (!CreateThread(StartNode, NULL))
570 ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("Bitcoin"), wxOK | wxMODAL);
573 CreateThread(ThreadRPCServer, NULL);
576 if(GetStartOnSystemStartup())
577 SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx