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.
13 //////////////////////////////////////////////////////////////////////////////
18 void ExitTimeout(void* parg)
26 void Shutdown(void* parg)
28 static CCriticalSection cs_Shutdown;
31 CRITICAL_BLOCK(cs_Shutdown)
33 fFirstThread = !fTaken;
40 nTransactionsUpdated++;
44 boost::filesystem::remove(GetPidFile());
45 CreateThread(ExitTimeout, NULL);
47 printf("Bitcoin exiting\n\n");
60 void HandleSIGTERM(int)
62 fRequestShutdown = true;
70 //////////////////////////////////////////////////////////////////////////////
76 int main(int argc, char* argv[])
79 fRet = AppInit(argc, argv);
88 bool AppInit(int argc, char* argv[])
93 fRet = AppInit2(argc, argv);
95 catch (std::exception& e) {
96 PrintException(&e, "AppInit()");
98 PrintException(NULL, "AppInit()");
105 bool AppInit2(int argc, char* argv[])
108 // Turn off microsoft heap dump noise
109 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
110 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
113 // Disable confusing "helpful" text message on abort, ctrl-c
114 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
120 // Clean shutdown on SIGTERM
122 sa.sa_handler = HandleSIGTERM;
123 sigemptyset(&sa.sa_mask);
125 sigaction(SIGTERM, &sa, NULL);
126 sigaction(SIGINT, &sa, NULL);
127 sigaction(SIGHUP, &sa, NULL);
133 ParseParameters(argc, argv);
135 if (mapArgs.count("-datadir"))
137 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
138 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
141 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
143 if (mapArgs.count("-?") || mapArgs.count("--help"))
145 string beta = VERSION_IS_BETA ? _(" beta") : "";
146 string strUsage = string() +
147 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
148 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
149 " bitcoin [options] \t " + "\n" +
150 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
151 " bitcoin [options] help \t\t " + _("List commands\n") +
152 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
154 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
155 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
156 " -gen \t\t " + _("Generate coins\n") +
157 " -gen=0 \t\t " + _("Don't generate coins\n") +
158 " -min \t\t " + _("Start minimized\n") +
159 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
160 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
161 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
162 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
163 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
164 " -nolisten \t " + _("Don't accept connections from outside\n") +
167 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
169 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
172 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
174 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
177 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
179 " -testnet \t\t " + _("Use the test network\n") +
180 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
181 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
182 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
183 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
184 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
185 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
186 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
189 strUsage += string() +
190 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
191 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
192 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
193 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
194 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
197 strUsage += string() +
198 " -? \t\t " + _("This help message\n");
200 #if defined(__WXMSW__) && defined(GUI)
201 // Tabs make the columns line up in the message box
202 wxMessageBox(strUsage, "Bitcoin", wxOK);
205 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
206 fprintf(stderr, "%s", strUsage.c_str());
211 fDebug = GetBoolArg("-debug");
212 fAllowDNS = GetBoolArg("-dns");
215 fDaemon = GetBoolArg("-daemon");
223 fServer = GetBoolArg("-server");
225 /* force fServer when running without GUI */
230 fPrintToConsole = GetBoolArg("-printtoconsole");
231 fPrintToDebugger = GetBoolArg("-printtodebugger");
233 fTestNet = GetBoolArg("-testnet");
234 fNoListen = GetBoolArg("-nolisten");
235 fLogTimestamps = GetBoolArg("-logtimestamps");
237 for (int i = 1; i < argc; i++)
238 if (!IsSwitchChar(argv[i][0]))
243 int ret = CommandLineRPC(argc, argv);
254 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
259 CreatePidFile(GetPidFile(), pid);
263 pid_t sid = setsid();
265 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
269 if (!fDebug && !pszSetDataDir[0])
271 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
272 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
274 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
275 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
276 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
278 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
280 if (GetBoolArg("-loadblockindextest"))
283 txdb.LoadBlockIndex();
289 // Limit to single instance per user
290 // Required to protect the database files if we're going to keep deleting log.*
292 #if defined(__WXMSW__) && defined(GUI)
293 // wxSingleInstanceChecker doesn't work on Linux
294 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
295 for (int i = 0; i < strMutexName.size(); i++)
296 if (!isalnum(strMutexName[i]))
297 strMutexName[i] = '.';
298 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
299 if (psingleinstancechecker->IsAnotherRunning())
301 printf("Existing instance found\n");
302 unsigned int nStart = GetTime();
305 // Show the previous instance and exit
306 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
309 if (IsIconic(hwndPrev))
310 ShowWindow(hwndPrev, SW_RESTORE);
311 SetForegroundWindow(hwndPrev);
315 if (GetTime() > nStart + 60)
318 // Resume this instance if the other exits
319 delete psingleinstancechecker;
321 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
322 if (!psingleinstancechecker->IsAnotherRunning())
328 // Make sure only a single bitcoin process is using the data directory.
329 string strLockFile = GetDataDir() + "/.lock";
330 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
331 if (file) fclose(file);
332 static boost::interprocess::file_lock lock(strLockFile.c_str());
333 if (!lock.try_lock())
335 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
339 // Bind to the port early so we can tell if another instance is already running.
343 if (!BindListenPort(strErrors))
345 wxMessageBox(strErrors, "Bitcoin");
354 fprintf(stdout, "bitcoin server starting\n");
358 printf("Loading addresses...\n");
359 nStart = GetTimeMillis();
360 if (!LoadAddresses())
361 strErrors += _("Error loading addr.dat \n");
362 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
364 printf("Loading block index...\n");
365 nStart = GetTimeMillis();
366 if (!LoadBlockIndex())
367 strErrors += _("Error loading blkindex.dat \n");
368 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
370 printf("Loading wallet...\n");
371 nStart = GetTimeMillis();
373 if (!LoadWallet(fFirstRun))
374 strErrors += _("Error loading wallet.dat \n");
375 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
377 CBlockIndex *pindexRescan = pindexBest;
378 if (GetBoolArg("-rescan"))
379 pindexRescan = pindexGenesisBlock;
383 CBlockLocator locator;
384 if (walletdb.ReadBestBlock(locator))
385 pindexRescan = locator.GetBlockIndex();
387 if (pindexBest != pindexRescan)
389 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
390 nStart = GetTimeMillis();
391 ScanForWalletTransactions(pindexRescan);
392 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
395 printf("Done loading\n");
398 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
399 printf("nBestHeight = %d\n", nBestHeight);
400 printf("mapKeys.size() = %d\n", mapKeys.size());
401 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
402 printf("mapWallet.size() = %d\n", mapWallet.size());
403 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
405 if (!strErrors.empty())
407 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
411 // Add wallet transactions that aren't already in a block to mapTransactions
412 ReacceptWalletTransactions();
417 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
423 if (mapArgs.count("-printblock"))
425 string strMatch = mapArgs["-printblock"];
427 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
429 uint256 hash = (*mi).first;
430 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
432 CBlockIndex* pindex = (*mi).second;
434 block.ReadFromDisk(pindex);
435 block.BuildMerkleTree();
442 printf("No blocks matching %s were found\n", strMatch.c_str());
446 fGenerateBitcoins = GetBoolArg("-gen");
448 if (mapArgs.count("-proxy"))
451 addrProxy = CAddress(mapArgs["-proxy"]);
452 if (!addrProxy.IsValid())
454 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
459 if (mapArgs.count("-addnode"))
461 foreach(string strAddr, mapMultiArgs["-addnode"])
463 CAddress addr(strAddr, fAllowDNS);
464 addr.nTime = 0; // so it won't relay unless successfully connected
470 if (mapArgs.count("-dnsseed"))
473 if (mapArgs.count("-paytxfee"))
475 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
477 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
480 if (nTransactionFee > 0.25 * COIN)
481 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
487 if (GetBoolArg("-noupnp"))
490 if (GetBoolArg("-upnp"))
496 // Create the main window and start the node
503 if (!CheckDiskSpace())
506 RandAddSeedPerfmon();
508 if (!CreateThread(StartNode, NULL))
509 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
512 CreateThread(ThreadRPCServer, NULL);
514 #if defined(__WXMSW__) && defined(GUI)
516 SetStartOnSystemStartup(true);