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 //////////////////////////////////////////////////////////////////////////////
72 int main(int argc, char* argv[])
75 fRet = AppInit(argc, argv);
85 bool AppInit(int argc, char* argv[])
90 fRet = AppInit2(argc, argv);
92 catch (std::exception& e) {
93 PrintException(&e, "AppInit()");
95 PrintException(NULL, "AppInit()");
102 bool AppInit2(int argc, char* argv[])
105 // Turn off microsoft heap dump noise
106 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
107 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
110 // Disable confusing "helpful" text message on abort, ctrl-c
111 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
117 // Clean shutdown on SIGTERM
119 sa.sa_handler = HandleSIGTERM;
120 sigemptyset(&sa.sa_mask);
122 sigaction(SIGTERM, &sa, NULL);
123 sigaction(SIGINT, &sa, NULL);
124 sigaction(SIGHUP, &sa, NULL);
130 ParseParameters(argc, argv);
132 if (mapArgs.count("-datadir"))
134 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
135 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
138 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
140 if (mapArgs.count("-?") || mapArgs.count("--help"))
142 string strUsage = string() +
143 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
144 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
145 " bitcoin [options] \t " + "\n" +
146 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
147 " bitcoin [options] help \t\t " + _("List commands\n") +
148 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
150 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
151 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
152 " -gen \t\t " + _("Generate coins\n") +
153 " -gen=0 \t\t " + _("Don't generate coins\n") +
154 " -min \t\t " + _("Start minimized\n") +
155 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
156 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
157 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
158 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
159 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
160 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
161 " -nolisten \t " + _("Don't accept connections from outside\n") +
164 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
166 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
169 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
171 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
174 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
176 " -testnet \t\t " + _("Use the test network\n") +
177 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
178 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
179 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
180 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
181 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
182 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
183 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
186 strUsage += string() +
187 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
188 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
189 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
190 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
191 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
194 strUsage += string() +
195 " -? \t\t " + _("This help message\n");
197 #if defined(__WXMSW__) && defined(GUI)
198 // Tabs make the columns line up in the message box
199 wxMessageBox(strUsage, "Bitcoin", wxOK);
202 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
203 fprintf(stderr, "%s", strUsage.c_str());
208 fDebug = GetBoolArg("-debug");
209 fAllowDNS = GetBoolArg("-dns");
212 fDaemon = GetBoolArg("-daemon");
220 fServer = GetBoolArg("-server");
222 /* force fServer when running without GUI */
228 fPrintToConsole = GetBoolArg("-printtoconsole");
229 fPrintToDebugger = GetBoolArg("-printtodebugger");
231 fTestNet = GetBoolArg("-testnet");
232 fNoListen = GetBoolArg("-nolisten");
233 fLogTimestamps = GetBoolArg("-logtimestamps");
235 for (int i = 1; i < argc; i++)
236 if (!IsSwitchChar(argv[i][0]))
241 int ret = CommandLineRPC(argc, argv);
252 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
257 CreatePidFile(GetPidFile(), pid);
261 pid_t sid = setsid();
263 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
267 if (!fDebug && !pszSetDataDir[0])
269 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
270 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
272 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
273 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
274 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
276 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
278 if (GetBoolArg("-loadblockindextest"))
281 txdb.LoadBlockIndex();
287 // Limit to single instance per user
288 // Required to protect the database files if we're going to keep deleting log.*
290 #if defined(__WXMSW__) && defined(GUI)
291 // wxSingleInstanceChecker doesn't work on Linux
292 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
293 for (int i = 0; i < strMutexName.size(); i++)
294 if (!isalnum(strMutexName[i]))
295 strMutexName[i] = '.';
296 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
297 if (psingleinstancechecker->IsAnotherRunning())
299 printf("Existing instance found\n");
300 unsigned int nStart = GetTime();
303 // Show the previous instance and exit
304 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
307 if (IsIconic(hwndPrev))
308 ShowWindow(hwndPrev, SW_RESTORE);
309 SetForegroundWindow(hwndPrev);
313 if (GetTime() > nStart + 60)
316 // Resume this instance if the other exits
317 delete psingleinstancechecker;
319 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
320 if (!psingleinstancechecker->IsAnotherRunning())
326 // Make sure only a single bitcoin process is using the data directory.
327 string strLockFile = GetDataDir() + "/.lock";
328 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
329 if (file) fclose(file);
330 static boost::interprocess::file_lock lock(strLockFile.c_str());
331 if (!lock.try_lock())
333 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
337 // Bind to the port early so we can tell if another instance is already running.
341 if (!BindListenPort(strErrors))
343 wxMessageBox(strErrors, "Bitcoin");
352 fprintf(stdout, "bitcoin server starting\n");
356 printf("Loading addresses...\n");
357 nStart = GetTimeMillis();
358 if (!LoadAddresses())
359 strErrors += _("Error loading addr.dat \n");
360 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
362 printf("Loading block index...\n");
363 nStart = GetTimeMillis();
364 if (!LoadBlockIndex())
365 strErrors += _("Error loading blkindex.dat \n");
366 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
368 printf("Loading wallet...\n");
369 nStart = GetTimeMillis();
371 if (!LoadWallet(fFirstRun))
372 strErrors += _("Error loading wallet.dat \n");
373 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375 CBlockIndex *pindexRescan = pindexBest;
376 if (GetBoolArg("-rescan"))
377 pindexRescan = pindexGenesisBlock;
381 CBlockLocator locator;
382 if (walletdb.ReadBestBlock(locator))
383 pindexRescan = locator.GetBlockIndex();
385 if (pindexBest != pindexRescan)
387 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
388 nStart = GetTimeMillis();
389 ScanForWalletTransactions(pindexRescan, true);
390 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
393 printf("Done loading\n");
396 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
397 printf("nBestHeight = %d\n", nBestHeight);
398 printf("mapKeys.size() = %d\n", mapKeys.size());
399 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
400 printf("mapWallet.size() = %d\n", mapWallet.size());
401 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
403 if (!strErrors.empty())
405 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
409 // Add wallet transactions that aren't already in a block to mapTransactions
410 ReacceptWalletTransactions();
415 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
421 if (mapArgs.count("-timeout"))
423 int nNewTimeout = GetArg("-timeout", 5000);
424 if (nNewTimeout > 0 && nNewTimeout < 600000)
425 nConnectTimeout = nNewTimeout;
428 if (mapArgs.count("-printblock"))
430 string strMatch = mapArgs["-printblock"];
432 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
434 uint256 hash = (*mi).first;
435 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
437 CBlockIndex* pindex = (*mi).second;
439 block.ReadFromDisk(pindex);
440 block.BuildMerkleTree();
447 printf("No blocks matching %s were found\n", strMatch.c_str());
451 fGenerateBitcoins = GetBoolArg("-gen");
453 if (mapArgs.count("-proxy"))
456 addrProxy = CAddress(mapArgs["-proxy"]);
457 if (!addrProxy.IsValid())
459 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
464 if (mapArgs.count("-addnode"))
466 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
468 CAddress addr(strAddr, fAllowDNS);
469 addr.nTime = 0; // so it won't relay unless successfully connected
475 if (mapArgs.count("-dnsseed"))
478 if (mapArgs.count("-paytxfee"))
480 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
482 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
485 if (nTransactionFee > 0.25 * COIN)
486 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
492 if (GetBoolArg("-noupnp"))
495 if (GetBoolArg("-upnp"))
501 // Create the main window and start the node
508 if (!CheckDiskSpace())
511 RandAddSeedPerfmon();
513 if (!CreateThread(StartNode, NULL))
514 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
517 CreateThread(ThreadRPCServer, NULL);
519 #if defined(__WXMSW__) && defined(GUI)
521 SetStartOnSystemStartup(true);