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 //////////////////////////////////////////////////////////////////////////////
15 void ExitTimeout(void* parg)
23 void Shutdown(void* parg)
25 static CCriticalSection cs_Shutdown;
28 CRITICAL_BLOCK(cs_Shutdown)
30 fFirstThread = !fTaken;
37 nTransactionsUpdated++;
41 boost::filesystem::remove(GetPidFile());
42 CreateThread(ExitTimeout, NULL);
44 printf("Bitcoin exiting\n\n");
57 void HandleSIGTERM(int)
59 fRequestShutdown = true;
67 //////////////////////////////////////////////////////////////////////////////
72 int main(int argc, char* argv[])
75 fRet = AppInit(argc, argv);
84 bool AppInit(int argc, char* argv[])
89 fRet = AppInit2(argc, argv);
91 catch (std::exception& e) {
92 PrintException(&e, "AppInit()");
94 PrintException(NULL, "AppInit()");
101 bool AppInit2(int argc, char* argv[])
104 // Turn off microsoft heap dump noise
105 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
106 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
109 // Disable confusing "helpful" text message on abort, ctrl-c
110 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
116 // Clean shutdown on SIGTERM
118 sa.sa_handler = HandleSIGTERM;
119 sigemptyset(&sa.sa_mask);
121 sigaction(SIGTERM, &sa, NULL);
122 sigaction(SIGINT, &sa, NULL);
123 sigaction(SIGHUP, &sa, NULL);
129 ParseParameters(argc, argv);
131 if (mapArgs.count("-datadir"))
133 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
134 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
137 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
139 if (mapArgs.count("-?") || mapArgs.count("--help"))
141 string beta = VERSION_IS_BETA ? _(" beta") : "";
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 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
157 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
158 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
159 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
160 " -nolisten \t " + _("Don't accept connections from outside\n") +
163 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
165 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
168 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
170 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
173 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
175 " -testnet \t\t " + _("Use the test network\n") +
176 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
177 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
178 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
179 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
180 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
181 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
182 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
185 strUsage += string() +
186 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
187 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
188 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
189 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
190 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
193 strUsage += string() +
194 " -? \t\t " + _("This help message\n");
196 #if defined(__WXMSW__) && defined(GUI)
197 // Tabs make the columns line up in the message box
198 wxMessageBox(strUsage, "Bitcoin", wxOK);
201 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
202 fprintf(stderr, "%s", strUsage.c_str());
207 fDebug = GetBoolArg("-debug");
208 fAllowDNS = GetBoolArg("-dns");
211 fDaemon = GetBoolArg("-daemon");
219 fServer = GetBoolArg("-server");
221 /* force fServer when running without GUI */
226 fPrintToConsole = GetBoolArg("-printtoconsole");
227 fPrintToDebugger = GetBoolArg("-printtodebugger");
229 fTestNet = GetBoolArg("-testnet");
230 fNoListen = GetBoolArg("-nolisten");
231 fLogTimestamps = GetBoolArg("-logtimestamps");
233 for (int i = 1; i < argc; i++)
234 if (!IsSwitchChar(argv[i][0]))
239 int ret = CommandLineRPC(argc, argv);
250 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
255 CreatePidFile(GetPidFile(), pid);
259 pid_t sid = setsid();
261 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
265 if (!fDebug && !pszSetDataDir[0])
267 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
268 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
270 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
271 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
272 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
274 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
276 if (GetBoolArg("-loadblockindextest"))
279 txdb.LoadBlockIndex();
285 // Limit to single instance per user
286 // Required to protect the database files if we're going to keep deleting log.*
288 #if defined(__WXMSW__) && defined(GUI)
289 // wxSingleInstanceChecker doesn't work on Linux
290 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
291 for (int i = 0; i < strMutexName.size(); i++)
292 if (!isalnum(strMutexName[i]))
293 strMutexName[i] = '.';
294 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
295 if (psingleinstancechecker->IsAnotherRunning())
297 printf("Existing instance found\n");
298 unsigned int nStart = GetTime();
301 // Show the previous instance and exit
302 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
305 if (IsIconic(hwndPrev))
306 ShowWindow(hwndPrev, SW_RESTORE);
307 SetForegroundWindow(hwndPrev);
311 if (GetTime() > nStart + 60)
314 // Resume this instance if the other exits
315 delete psingleinstancechecker;
317 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
318 if (!psingleinstancechecker->IsAnotherRunning())
324 // Make sure only a single bitcoin process is using the data directory.
325 string strLockFile = GetDataDir() + "/.lock";
326 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
327 if (file) fclose(file);
328 static boost::interprocess::file_lock lock(strLockFile.c_str());
329 if (!lock.try_lock())
331 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
335 // Bind to the port early so we can tell if another instance is already running.
339 if (!BindListenPort(strErrors))
341 wxMessageBox(strErrors, "Bitcoin");
350 fprintf(stdout, "bitcoin server starting\n");
354 printf("Loading addresses...\n");
355 nStart = GetTimeMillis();
356 if (!LoadAddresses())
357 strErrors += _("Error loading addr.dat \n");
358 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
360 printf("Loading block index...\n");
361 nStart = GetTimeMillis();
362 if (!LoadBlockIndex())
363 strErrors += _("Error loading blkindex.dat \n");
364 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
366 printf("Loading wallet...\n");
367 nStart = GetTimeMillis();
369 if (!LoadWallet(fFirstRun))
370 strErrors += _("Error loading wallet.dat \n");
371 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
373 CBlockIndex *pindexRescan = pindexBest;
374 if (GetBoolArg("-rescan"))
375 pindexRescan = pindexGenesisBlock;
379 CBlockLocator locator;
380 if (walletdb.ReadBestBlock(locator))
381 pindexRescan = locator.GetBlockIndex();
383 if (pindexBest != pindexRescan)
385 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
386 nStart = GetTimeMillis();
387 ScanForWalletTransactions(pindexRescan);
388 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
391 printf("Done loading\n");
394 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
395 printf("nBestHeight = %d\n", nBestHeight);
396 printf("mapKeys.size() = %d\n", mapKeys.size());
397 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
398 printf("mapWallet.size() = %d\n", mapWallet.size());
399 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
401 if (!strErrors.empty())
403 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
407 // Add wallet transactions that aren't already in a block to mapTransactions
408 ReacceptWalletTransactions();
413 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
419 if (mapArgs.count("-printblock"))
421 string strMatch = mapArgs["-printblock"];
423 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
425 uint256 hash = (*mi).first;
426 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
428 CBlockIndex* pindex = (*mi).second;
430 block.ReadFromDisk(pindex);
431 block.BuildMerkleTree();
438 printf("No blocks matching %s were found\n", strMatch.c_str());
442 fGenerateBitcoins = GetBoolArg("-gen");
444 if (mapArgs.count("-proxy"))
447 addrProxy = CAddress(mapArgs["-proxy"]);
448 if (!addrProxy.IsValid())
450 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
455 if (mapArgs.count("-addnode"))
457 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
459 CAddress addr(strAddr, fAllowDNS);
460 addr.nTime = 0; // so it won't relay unless successfully connected
466 if (mapArgs.count("-dnsseed"))
469 if (mapArgs.count("-paytxfee"))
471 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
473 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
476 if (nTransactionFee > 0.25 * COIN)
477 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
483 if (GetBoolArg("-noupnp"))
486 if (GetBoolArg("-upnp"))
492 // Create the main window and start the node
499 if (!CheckDiskSpace())
502 RandAddSeedPerfmon();
504 if (!CreateThread(StartNode, NULL))
505 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
508 CreateThread(ThreadRPCServer, NULL);
510 #if defined(__WXMSW__) && defined(GUI)
512 SetStartOnSystemStartup(true);