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 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
155 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
156 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
157 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
158 " -nolisten \t " + _("Don't accept connections from outside\n") +
161 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
163 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
166 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
168 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
171 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
173 " -testnet \t\t " + _("Use the test network\n") +
174 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
175 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
176 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
177 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
178 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
179 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
180 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
183 strUsage += string() +
184 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
185 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
186 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
187 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
188 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
191 strUsage += string() +
192 " -? \t\t " + _("This help message\n");
194 #if defined(__WXMSW__) && defined(GUI)
195 // Tabs make the columns line up in the message box
196 wxMessageBox(strUsage, "Bitcoin", wxOK);
199 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
200 fprintf(stderr, "%s", strUsage.c_str());
205 fDebug = GetBoolArg("-debug");
206 fAllowDNS = GetBoolArg("-dns");
209 fDaemon = GetBoolArg("-daemon");
217 fServer = GetBoolArg("-server");
219 /* force fServer when running without GUI */
224 fPrintToConsole = GetBoolArg("-printtoconsole");
225 fPrintToDebugger = GetBoolArg("-printtodebugger");
227 fTestNet = GetBoolArg("-testnet");
228 fNoListen = GetBoolArg("-nolisten");
229 fLogTimestamps = GetBoolArg("-logtimestamps");
231 for (int i = 1; i < argc; i++)
232 if (!IsSwitchChar(argv[i][0]))
237 int ret = CommandLineRPC(argc, argv);
248 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
253 CreatePidFile(GetPidFile(), pid);
257 pid_t sid = setsid();
259 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
263 if (!fDebug && !pszSetDataDir[0])
265 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
266 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
268 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
269 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
270 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
272 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
274 if (GetBoolArg("-loadblockindextest"))
277 txdb.LoadBlockIndex();
283 // Limit to single instance per user
284 // Required to protect the database files if we're going to keep deleting log.*
286 #if defined(__WXMSW__) && defined(GUI)
287 // wxSingleInstanceChecker doesn't work on Linux
288 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
289 for (int i = 0; i < strMutexName.size(); i++)
290 if (!isalnum(strMutexName[i]))
291 strMutexName[i] = '.';
292 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
293 if (psingleinstancechecker->IsAnotherRunning())
295 printf("Existing instance found\n");
296 unsigned int nStart = GetTime();
299 // Show the previous instance and exit
300 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
303 if (IsIconic(hwndPrev))
304 ShowWindow(hwndPrev, SW_RESTORE);
305 SetForegroundWindow(hwndPrev);
309 if (GetTime() > nStart + 60)
312 // Resume this instance if the other exits
313 delete psingleinstancechecker;
315 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
316 if (!psingleinstancechecker->IsAnotherRunning())
322 // Make sure only a single bitcoin process is using the data directory.
323 string strLockFile = GetDataDir() + "/.lock";
324 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
325 if (file) fclose(file);
326 static boost::interprocess::file_lock lock(strLockFile.c_str());
327 if (!lock.try_lock())
329 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
333 // Bind to the port early so we can tell if another instance is already running.
337 if (!BindListenPort(strErrors))
339 wxMessageBox(strErrors, "Bitcoin");
348 fprintf(stdout, "bitcoin server starting\n");
352 printf("Loading addresses...\n");
353 nStart = GetTimeMillis();
354 if (!LoadAddresses())
355 strErrors += _("Error loading addr.dat \n");
356 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
358 printf("Loading block index...\n");
359 nStart = GetTimeMillis();
360 if (!LoadBlockIndex())
361 strErrors += _("Error loading blkindex.dat \n");
362 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
364 printf("Loading wallet...\n");
365 nStart = GetTimeMillis();
367 if (!LoadWallet(fFirstRun))
368 strErrors += _("Error loading wallet.dat \n");
369 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
371 CBlockIndex *pindexRescan = pindexBest;
372 if (GetBoolArg("-rescan"))
373 pindexRescan = pindexGenesisBlock;
377 CBlockLocator locator;
378 if (walletdb.ReadBestBlock(locator))
379 pindexRescan = locator.GetBlockIndex();
381 if (pindexBest != pindexRescan)
383 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
384 nStart = GetTimeMillis();
385 ScanForWalletTransactions(pindexRescan, true);
386 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
389 printf("Done loading\n");
392 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
393 printf("nBestHeight = %d\n", nBestHeight);
394 printf("mapKeys.size() = %d\n", mapKeys.size());
395 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
396 printf("mapWallet.size() = %d\n", mapWallet.size());
397 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
399 if (!strErrors.empty())
401 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
405 // Add wallet transactions that aren't already in a block to mapTransactions
406 ReacceptWalletTransactions();
411 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
417 if (mapArgs.count("-printblock"))
419 string strMatch = mapArgs["-printblock"];
421 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
423 uint256 hash = (*mi).first;
424 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
426 CBlockIndex* pindex = (*mi).second;
428 block.ReadFromDisk(pindex);
429 block.BuildMerkleTree();
436 printf("No blocks matching %s were found\n", strMatch.c_str());
440 fGenerateBitcoins = GetBoolArg("-gen");
442 if (mapArgs.count("-proxy"))
445 addrProxy = CAddress(mapArgs["-proxy"]);
446 if (!addrProxy.IsValid())
448 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
453 if (mapArgs.count("-addnode"))
455 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
457 CAddress addr(strAddr, fAllowDNS);
458 addr.nTime = 0; // so it won't relay unless successfully connected
464 if (mapArgs.count("-dnsseed"))
467 if (mapArgs.count("-paytxfee"))
469 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
471 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
474 if (nTransactionFee > 0.25 * COIN)
475 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
481 if (GetBoolArg("-noupnp"))
484 if (GetBoolArg("-upnp"))
490 // Create the main window and start the node
497 if (!CheckDiskSpace())
500 RandAddSeedPerfmon();
502 if (!CreateThread(StartNode, NULL))
503 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
506 CreateThread(ThreadRPCServer, NULL);
508 #if defined(__WXMSW__) && defined(GUI)
510 SetStartOnSystemStartup(true);