1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12 #include <boost/interprocess/sync/file_lock.hpp>
15 using namespace boost;
19 //////////////////////////////////////////////////////////////////////////////
24 void ExitTimeout(void* parg)
32 void Shutdown(void* parg)
34 static CCriticalSection cs_Shutdown;
37 CRITICAL_BLOCK(cs_Shutdown)
39 fFirstThread = !fTaken;
46 nTransactionsUpdated++;
50 boost::filesystem::remove(GetPidFile());
51 UnregisterWallet(pwalletMain);
53 CreateThread(ExitTimeout, NULL);
55 printf("Bitcoin exiting\n\n");
68 void HandleSIGTERM(int)
70 fRequestShutdown = true;
78 //////////////////////////////////////////////////////////////////////////////
83 int main(int argc, char* argv[])
86 fRet = AppInit(argc, argv);
95 bool AppInit(int argc, char* argv[])
100 fRet = AppInit2(argc, argv);
102 catch (std::exception& e) {
103 PrintException(&e, "AppInit()");
105 PrintException(NULL, "AppInit()");
112 bool AppInit2(int argc, char* argv[])
115 // Turn off microsoft heap dump noise
116 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
117 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
120 // Disable confusing "helpful" text message on abort, ctrl-c
121 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
127 // Clean shutdown on SIGTERM
129 sa.sa_handler = HandleSIGTERM;
130 sigemptyset(&sa.sa_mask);
132 sigaction(SIGTERM, &sa, NULL);
133 sigaction(SIGINT, &sa, NULL);
134 sigaction(SIGHUP, &sa, NULL);
140 ParseParameters(argc, argv);
142 if (mapArgs.count("-datadir"))
144 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
146 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
147 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
151 fprintf(stderr, "Error: Specified directory does not exist\n");
157 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
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 " bitcoin [options] \t " + "\n" +
165 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
166 " bitcoin [options] help \t\t " + _("List commands\n") +
167 " bitcoin [options] help <command> \t\t " + _("Get help for a command\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 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
175 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
176 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
177 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
178 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
179 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
180 " -nolisten \t " + _("Don't accept connections from outside\n") +
183 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
185 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
188 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
190 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
193 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
195 " -testnet \t\t " + _("Use the test network\n") +
196 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
197 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
198 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
199 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
200 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
201 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
202 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
205 strUsage += string() +
206 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
207 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
208 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
209 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
210 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
213 strUsage += string() +
214 " -? \t\t " + _("This help message\n");
216 #if defined(__WXMSW__) && defined(GUI)
217 // Tabs make the columns line up in the message box
218 wxMessageBox(strUsage, "Bitcoin", wxOK);
221 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
222 fprintf(stderr, "%s", strUsage.c_str());
227 fDebug = GetBoolArg("-debug");
228 fAllowDNS = GetBoolArg("-dns");
231 fDaemon = GetBoolArg("-daemon");
239 fServer = GetBoolArg("-server");
241 /* force fServer when running without GUI */
246 fPrintToConsole = GetBoolArg("-printtoconsole");
247 fPrintToDebugger = GetBoolArg("-printtodebugger");
249 fTestNet = GetBoolArg("-testnet");
250 fNoListen = GetBoolArg("-nolisten");
251 fLogTimestamps = GetBoolArg("-logtimestamps");
253 for (int i = 1; i < argc; i++)
254 if (!IsSwitchChar(argv[i][0]))
259 int ret = CommandLineRPC(argc, argv);
270 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
275 CreatePidFile(GetPidFile(), pid);
279 pid_t sid = setsid();
281 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
285 if (!fDebug && !pszSetDataDir[0])
287 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
288 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
290 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
291 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
292 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
294 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
296 if (GetBoolArg("-loadblockindextest"))
299 txdb.LoadBlockIndex();
305 // Limit to single instance per user
306 // Required to protect the database files if we're going to keep deleting log.*
308 #if defined(__WXMSW__) && defined(GUI)
309 // wxSingleInstanceChecker doesn't work on Linux
310 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
311 for (int i = 0; i < strMutexName.size(); i++)
312 if (!isalnum(strMutexName[i]))
313 strMutexName[i] = '.';
314 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
315 if (psingleinstancechecker->IsAnotherRunning())
317 printf("Existing instance found\n");
318 unsigned int nStart = GetTime();
321 // Show the previous instance and exit
322 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
325 if (IsIconic(hwndPrev))
326 ShowWindow(hwndPrev, SW_RESTORE);
327 SetForegroundWindow(hwndPrev);
331 if (GetTime() > nStart + 60)
334 // Resume this instance if the other exits
335 delete psingleinstancechecker;
337 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
338 if (!psingleinstancechecker->IsAnotherRunning())
344 // Make sure only a single bitcoin process is using the data directory.
345 string strLockFile = GetDataDir() + "/.lock";
346 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
347 if (file) fclose(file);
348 static boost::interprocess::file_lock lock(strLockFile.c_str());
349 if (!lock.try_lock())
351 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
355 // Bind to the port early so we can tell if another instance is already running.
359 if (!BindListenPort(strErrors))
361 wxMessageBox(strErrors, "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 if (!pwalletMain->LoadWallet(fFirstRun))
391 strErrors += _("Error loading wallet.dat \n");
392 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
394 RegisterWallet(pwalletMain);
396 CBlockIndex *pindexRescan = pindexBest;
397 if (GetBoolArg("-rescan"))
398 pindexRescan = pindexGenesisBlock;
401 CWalletDB walletdb("wallet.dat");
402 CBlockLocator locator;
403 if (walletdb.ReadBestBlock(locator))
404 pindexRescan = locator.GetBlockIndex();
406 if (pindexBest != pindexRescan)
408 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
409 nStart = GetTimeMillis();
410 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
411 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
414 printf("Done loading\n");
417 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
418 printf("nBestHeight = %d\n", nBestHeight);
419 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
420 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
421 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
422 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
424 if (!strErrors.empty())
426 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
430 // Add wallet transactions that aren't already in a block to mapTransactions
431 pwalletMain->ReacceptWalletTransactions();
436 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
442 if (mapArgs.count("-timeout"))
444 int nNewTimeout = GetArg("-timeout", 5000);
445 if (nNewTimeout > 0 && nNewTimeout < 600000)
446 nConnectTimeout = nNewTimeout;
449 if (mapArgs.count("-printblock"))
451 string strMatch = mapArgs["-printblock"];
453 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
455 uint256 hash = (*mi).first;
456 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
458 CBlockIndex* pindex = (*mi).second;
460 block.ReadFromDisk(pindex);
461 block.BuildMerkleTree();
468 printf("No blocks matching %s were found\n", strMatch.c_str());
472 fGenerateBitcoins = GetBoolArg("-gen");
474 if (mapArgs.count("-proxy"))
477 addrProxy = CAddress(mapArgs["-proxy"]);
478 if (!addrProxy.IsValid())
480 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
485 if (mapArgs.count("-addnode"))
487 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
489 CAddress addr(strAddr, fAllowDNS);
490 addr.nTime = 0; // so it won't relay unless successfully connected
496 if (GetBoolArg("-nodnsseed"))
497 printf("DNS seeding disabled\n");
501 if (mapArgs.count("-paytxfee"))
503 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
505 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
508 if (nTransactionFee > 0.25 * COIN)
509 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
515 if (GetBoolArg("-noupnp"))
518 if (GetBoolArg("-upnp"))
524 // Create the main window and start the node
531 if (!CheckDiskSpace())
534 RandAddSeedPerfmon();
536 if (!CreateThread(StartNode, NULL))
537 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
540 CreateThread(ThreadRPCServer, NULL);
542 #if defined(__WXMSW__) && defined(GUI)
544 SetStartOnSystemStartup(true);