1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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.
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/interprocess/sync/file_lock.hpp>
16 using namespace boost;
20 //////////////////////////////////////////////////////////////////////////////
25 void ExitTimeout(void* parg)
33 void Shutdown(void* parg)
35 static CCriticalSection cs_Shutdown;
37 bool fFirstThread = false;
38 TRY_CRITICAL_BLOCK(cs_Shutdown)
40 fFirstThread = !fTaken;
47 nTransactionsUpdated++;
51 boost::filesystem::remove(GetPidFile());
52 UnregisterWallet(pwalletMain);
54 CreateThread(ExitTimeout, NULL);
56 printf("Bitcoin exiting\n\n");
69 void HandleSIGTERM(int)
71 fRequestShutdown = true;
79 //////////////////////////////////////////////////////////////////////////////
84 int main(int argc, char* argv[])
87 fRet = AppInit(argc, argv);
96 bool AppInit(int argc, char* argv[])
101 fRet = AppInit2(argc, argv);
103 catch (std::exception& e) {
104 PrintException(&e, "AppInit()");
106 PrintException(NULL, "AppInit()");
113 bool AppInit2(int argc, char* argv[])
116 // Turn off microsoft heap dump noise
117 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
118 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
121 // Disable confusing "helpful" text message on abort, ctrl-c
122 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
128 // Clean shutdown on SIGTERM
130 sa.sa_handler = HandleSIGTERM;
131 sigemptyset(&sa.sa_mask);
133 sigaction(SIGTERM, &sa, NULL);
134 sigaction(SIGINT, &sa, NULL);
135 sigaction(SIGHUP, &sa, NULL);
141 ParseParameters(argc, argv);
143 if (mapArgs.count("-datadir"))
145 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
147 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
148 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
152 fprintf(stderr, "Error: Specified directory does not exist\n");
158 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
160 if (mapArgs.count("-?") || mapArgs.count("--help"))
162 string strUsage = string() +
163 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
164 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
165 " bitcoind [options] \t " + "\n" +
166 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
167 " bitcoind [options] help \t\t " + _("List commands\n") +
168 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
170 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
171 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
172 " -gen \t\t " + _("Generate coins\n") +
173 " -gen=0 \t\t " + _("Don't generate coins\n") +
174 " -min \t\t " + _("Start minimized\n") +
175 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
176 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
177 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
178 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
179 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
180 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
181 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
182 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
183 " -noirc \t " + _("Don't find peers using internet relay chat\n") +
184 " -nolisten \t " + _("Don't accept connections from outside\n") +
185 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS\n") +
186 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
187 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
190 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
192 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
195 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
197 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
200 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
202 " -testnet \t\t " + _("Use the test network\n") +
203 " -debug \t\t " + _("Output extra debugging information\n") +
204 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
205 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
207 " -printtodebugger \t " + _("Send trace/debug info to debugger\n") +
209 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
210 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
211 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
212 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
213 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
214 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
215 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
218 strUsage += string() +
219 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
220 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
221 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
222 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
223 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
226 strUsage += string() +
227 " -? \t\t " + _("This help message\n");
229 #if defined(__WXMSW__) && defined(GUI)
230 // Tabs make the columns line up in the message box
231 wxMessageBox(strUsage, "Bitcoin", wxOK);
234 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
235 fprintf(stderr, "%s", strUsage.c_str());
240 fDebug = GetBoolArg("-debug");
243 fDaemon = GetBoolArg("-daemon");
251 fServer = GetBoolArg("-server");
253 /* force fServer when running without GUI */
258 fPrintToConsole = GetBoolArg("-printtoconsole");
259 fPrintToDebugger = GetBoolArg("-printtodebugger");
260 fLogTimestamps = GetBoolArg("-logtimestamps");
262 for (int i = 1; i < argc; i++)
263 if (!IsSwitchChar(argv[i][0]))
268 int ret = CommandLineRPC(argc, argv);
279 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
284 CreatePidFile(GetPidFile(), pid);
288 pid_t sid = setsid();
290 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
294 if (!fDebug && !pszSetDataDir[0])
296 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
297 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
299 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
300 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
301 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
303 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
305 if (GetBoolArg("-loadblockindextest"))
308 txdb.LoadBlockIndex();
314 // Limit to single instance per user
315 // Required to protect the database files if we're going to keep deleting log.*
317 #if defined(__WXMSW__) && defined(GUI)
318 // wxSingleInstanceChecker doesn't work on Linux
319 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
320 for (int i = 0; i < strMutexName.size(); i++)
321 if (!isalnum(strMutexName[i]))
322 strMutexName[i] = '.';
323 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
324 if (psingleinstancechecker->IsAnotherRunning())
326 printf("Existing instance found\n");
327 unsigned int nStart = GetTime();
330 // Show the previous instance and exit
331 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
334 if (IsIconic(hwndPrev))
335 ShowWindow(hwndPrev, SW_RESTORE);
336 SetForegroundWindow(hwndPrev);
340 if (GetTime() > nStart + 60)
343 // Resume this instance if the other exits
344 delete psingleinstancechecker;
346 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
347 if (!psingleinstancechecker->IsAnotherRunning())
353 // Make sure only a single bitcoin process is using the data directory.
354 string strLockFile = GetDataDir() + "/.lock";
355 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
356 if (file) fclose(file);
357 static boost::interprocess::file_lock lock(strLockFile.c_str());
358 if (!lock.try_lock())
360 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
370 fprintf(stdout, "bitcoin server starting\n");
374 printf("Loading addresses...\n");
375 nStart = GetTimeMillis();
376 if (!LoadAddresses())
377 strErrors += _("Error loading addr.dat \n");
378 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
380 printf("Loading block index...\n");
381 nStart = GetTimeMillis();
382 if (!LoadBlockIndex())
383 strErrors += _("Error loading blkindex.dat \n");
384 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
386 printf("Loading wallet...\n");
387 nStart = GetTimeMillis();
389 pwalletMain = new CWallet("wallet.dat");
390 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
391 if (nLoadWalletRet != DB_LOAD_OK)
393 if (nLoadWalletRet == DB_CORRUPT)
394 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
395 else if (nLoadWalletRet == DB_TOO_NEW)
396 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
397 else if (nLoadWalletRet == DB_NEED_REWRITE)
399 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
400 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
404 strErrors += _("Error loading wallet.dat \n");
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 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
423 nStart = GetTimeMillis();
424 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
425 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
428 printf("Done loading\n");
431 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
432 printf("nBestHeight = %d\n", nBestHeight);
433 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
434 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
435 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
437 if (!strErrors.empty())
439 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
443 // Add wallet transactions that aren't already in a block to mapTransactions
444 pwalletMain->ReacceptWalletTransactions();
446 // Note: Bitcoin-QT stores several settings in the wallet, so we want
447 // to load the wallet BEFORE parsing command-line arguments, so
448 // the command-line/bitcoin.conf settings override GUI setting.
453 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
459 if (mapArgs.count("-timeout"))
461 int nNewTimeout = GetArg("-timeout", 5000);
462 if (nNewTimeout > 0 && nNewTimeout < 600000)
463 nConnectTimeout = nNewTimeout;
466 if (mapArgs.count("-printblock"))
468 string strMatch = mapArgs["-printblock"];
470 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
472 uint256 hash = (*mi).first;
473 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
475 CBlockIndex* pindex = (*mi).second;
477 block.ReadFromDisk(pindex);
478 block.BuildMerkleTree();
485 printf("No blocks matching %s were found\n", strMatch.c_str());
489 fGenerateBitcoins = GetBoolArg("-gen");
491 if (mapArgs.count("-proxy"))
494 addrProxy = CAddress(mapArgs["-proxy"]);
495 if (!addrProxy.IsValid())
497 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
502 fTestNet = GetBoolArg("-testnet");
503 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
506 // Use SoftSetArg here so user can override any of these if they wish.
507 // Note: the GetBoolArg() calls for all of these must happen later.
508 SoftSetArg("-nolisten", true);
509 SoftSetArg("-noirc", true);
510 SoftSetArg("-nodnsseed", true);
511 SoftSetArg("-noupnp", true);
512 SoftSetArg("-upnp", false);
513 SoftSetArg("-dns", false);
516 fAllowDNS = GetBoolArg("-dns");
517 fNoListen = GetBoolArg("-nolisten");
522 if (GetBoolArg("-noupnp"))
525 if (GetBoolArg("-upnp"))
532 if (!BindListenPort(strErrors))
534 wxMessageBox(strErrors, "Bitcoin");
539 if (mapArgs.count("-addnode"))
541 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
543 CAddress addr(strAddr, fAllowDNS);
544 addr.nTime = 0; // so it won't relay unless successfully connected
550 if (mapArgs.count("-paytxfee"))
552 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
554 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
557 if (nTransactionFee > 0.25 * COIN)
558 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
562 // Create the main window and start the node
569 if (!CheckDiskSpace())
572 RandAddSeedPerfmon();
574 if (!CreateThread(StartNode, NULL))
575 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
578 CreateThread(ThreadRPCServer, NULL);
580 #if defined(__WXMSW__) && defined(GUI)
582 SetStartOnSystemStartup(true);