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.
9 //////////////////////////////////////////////////////////////////////////////
14 void ExitTimeout(void* parg)
22 void Shutdown(void* parg)
24 static CCriticalSection cs_Shutdown;
27 CRITICAL_BLOCK(cs_Shutdown)
29 fFirstThread = !fTaken;
36 nTransactionsUpdated++;
40 boost::filesystem::remove(GetPidFile());
41 CreateThread(ExitTimeout, NULL);
43 printf("Bitcoin exiting\n\n");
56 void HandleSIGTERM(int)
58 fRequestShutdown = true;
66 //////////////////////////////////////////////////////////////////////////////
71 int main(int argc, char* argv[])
74 fRet = AppInit(argc, argv);
83 bool AppInit(int argc, char* argv[])
88 fRet = AppInit2(argc, argv);
90 catch (std::exception& e) {
91 PrintException(&e, "AppInit()");
93 PrintException(NULL, "AppInit()");
100 bool AppInit2(int argc, char* argv[])
103 // Turn off microsoft heap dump noise
104 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
105 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
108 // Disable confusing "helpful" text message on abort, ctrl-c
109 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
115 // Clean shutdown on SIGTERM
117 sa.sa_handler = HandleSIGTERM;
118 sigemptyset(&sa.sa_mask);
120 sigaction(SIGTERM, &sa, NULL);
121 sigaction(SIGINT, &sa, NULL);
122 sigaction(SIGHUP, &sa, NULL);
128 ParseParameters(argc, argv);
130 if (mapArgs.count("-datadir"))
132 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
133 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
136 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
138 if (mapArgs.count("-?") || mapArgs.count("--help"))
140 string strUsage = string() +
141 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
142 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
143 " bitcoin [options] \t " + "\n" +
144 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
145 " bitcoin [options] help \t\t " + _("List commands\n") +
146 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
148 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
149 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
150 " -gen \t\t " + _("Generate coins\n") +
151 " -gen=0 \t\t " + _("Don't generate coins\n") +
152 " -min \t\t " + _("Start minimized\n") +
153 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
154 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
155 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
156 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
157 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
158 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
159 " -nolisten \t " + _("Don't accept connections from outside\n") +
162 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
164 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
167 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
169 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
172 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
174 " -testnet \t\t " + _("Use the test network\n") +
175 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
176 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
177 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
178 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
179 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
180 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
181 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
184 strUsage += string() +
185 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
186 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
187 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
188 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
189 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
192 strUsage += string() +
193 " -? \t\t " + _("This help message\n");
195 #if defined(__WXMSW__) && defined(GUI)
196 // Tabs make the columns line up in the message box
197 wxMessageBox(strUsage, "Bitcoin", wxOK);
200 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
201 fprintf(stderr, "%s", strUsage.c_str());
206 fDebug = GetBoolArg("-debug");
207 fAllowDNS = GetBoolArg("-dns");
210 fDaemon = GetBoolArg("-daemon");
218 fServer = GetBoolArg("-server");
220 /* force fServer when running without GUI */
225 fPrintToConsole = GetBoolArg("-printtoconsole");
226 fPrintToDebugger = GetBoolArg("-printtodebugger");
228 fTestNet = GetBoolArg("-testnet");
229 fNoListen = GetBoolArg("-nolisten");
230 fLogTimestamps = GetBoolArg("-logtimestamps");
232 for (int i = 1; i < argc; i++)
233 if (!IsSwitchChar(argv[i][0]))
238 int ret = CommandLineRPC(argc, argv);
249 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
254 CreatePidFile(GetPidFile(), pid);
258 pid_t sid = setsid();
260 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
264 if (!fDebug && !pszSetDataDir[0])
266 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
267 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
269 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
270 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
271 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
273 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
275 if (GetBoolArg("-loadblockindextest"))
278 txdb.LoadBlockIndex();
284 // Limit to single instance per user
285 // Required to protect the database files if we're going to keep deleting log.*
287 #if defined(__WXMSW__) && defined(GUI)
288 // wxSingleInstanceChecker doesn't work on Linux
289 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
290 for (int i = 0; i < strMutexName.size(); i++)
291 if (!isalnum(strMutexName[i]))
292 strMutexName[i] = '.';
293 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
294 if (psingleinstancechecker->IsAnotherRunning())
296 printf("Existing instance found\n");
297 unsigned int nStart = GetTime();
300 // Show the previous instance and exit
301 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
304 if (IsIconic(hwndPrev))
305 ShowWindow(hwndPrev, SW_RESTORE);
306 SetForegroundWindow(hwndPrev);
310 if (GetTime() > nStart + 60)
313 // Resume this instance if the other exits
314 delete psingleinstancechecker;
316 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
317 if (!psingleinstancechecker->IsAnotherRunning())
323 // Make sure only a single bitcoin process is using the data directory.
324 string strLockFile = GetDataDir() + "/.lock";
325 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
326 if (file) fclose(file);
327 static boost::interprocess::file_lock lock(strLockFile.c_str());
328 if (!lock.try_lock())
330 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
334 // Bind to the port early so we can tell if another instance is already running.
338 if (!BindListenPort(strErrors))
340 wxMessageBox(strErrors, "Bitcoin");
349 fprintf(stdout, "bitcoin server starting\n");
353 printf("Loading addresses...\n");
354 nStart = GetTimeMillis();
355 if (!LoadAddresses())
356 strErrors += _("Error loading addr.dat \n");
357 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
359 printf("Loading block index...\n");
360 nStart = GetTimeMillis();
361 if (!LoadBlockIndex())
362 strErrors += _("Error loading blkindex.dat \n");
363 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
365 printf("Loading wallet...\n");
366 nStart = GetTimeMillis();
368 if (!LoadWallet(fFirstRun))
369 strErrors += _("Error loading wallet.dat \n");
370 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
372 CBlockIndex *pindexRescan = pindexBest;
373 if (GetBoolArg("-rescan"))
374 pindexRescan = pindexGenesisBlock;
378 CBlockLocator locator;
379 if (walletdb.ReadBestBlock(locator))
380 pindexRescan = locator.GetBlockIndex();
382 if (pindexBest != pindexRescan)
384 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
385 nStart = GetTimeMillis();
386 ScanForWalletTransactions(pindexRescan, true);
387 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
390 printf("Done loading\n");
393 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
394 printf("nBestHeight = %d\n", nBestHeight);
395 printf("mapKeys.size() = %d\n", mapKeys.size());
396 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
397 printf("mapWallet.size() = %d\n", mapWallet.size());
398 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
400 if (!strErrors.empty())
402 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
406 // Add wallet transactions that aren't already in a block to mapTransactions
407 ReacceptWalletTransactions();
412 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
418 if (mapArgs.count("-timeout"))
420 int nNewTimeout = GetArg("-timeout", 5000);
421 if (nNewTimeout > 0 && nNewTimeout < 600000)
422 nConnectTimeout = nNewTimeout;
425 if (mapArgs.count("-printblock"))
427 string strMatch = mapArgs["-printblock"];
429 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
431 uint256 hash = (*mi).first;
432 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
434 CBlockIndex* pindex = (*mi).second;
436 block.ReadFromDisk(pindex);
437 block.BuildMerkleTree();
444 printf("No blocks matching %s were found\n", strMatch.c_str());
448 fGenerateBitcoins = GetBoolArg("-gen");
450 if (mapArgs.count("-proxy"))
453 addrProxy = CAddress(mapArgs["-proxy"]);
454 if (!addrProxy.IsValid())
456 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
461 if (mapArgs.count("-addnode"))
463 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
465 CAddress addr(strAddr, fAllowDNS);
466 addr.nTime = 0; // so it won't relay unless successfully connected
472 if (mapArgs.count("-dnsseed"))
475 if (mapArgs.count("-paytxfee"))
477 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
479 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
482 if (nTransactionFee > 0.25 * COIN)
483 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
489 if (GetBoolArg("-noupnp"))
492 if (GetBoolArg("-upnp"))
498 // Create the main window and start the node
505 if (!CheckDiskSpace())
508 RandAddSeedPerfmon();
510 if (!CreateThread(StartNode, NULL))
511 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
514 CreateThread(ThreadRPCServer, NULL);
516 #if defined(__WXMSW__) && defined(GUI)
518 SetStartOnSystemStartup(true);