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 #include <boost/filesystem/fstream.hpp>
11 #include <boost/interprocess/sync/file_lock.hpp>
14 using namespace boost;
18 //////////////////////////////////////////////////////////////////////////////
23 void ExitTimeout(void* parg)
31 void Shutdown(void* parg)
33 static CCriticalSection cs_Shutdown;
36 CRITICAL_BLOCK(cs_Shutdown)
38 fFirstThread = !fTaken;
45 nTransactionsUpdated++;
49 boost::filesystem::remove(GetPidFile());
50 UnregisterWallet(pwalletMain);
52 CreateThread(ExitTimeout, NULL);
54 printf("Bitcoin exiting\n\n");
67 void HandleSIGTERM(int)
69 fRequestShutdown = true;
77 //////////////////////////////////////////////////////////////////////////////
82 int main(int argc, char* argv[])
85 fRet = AppInit(argc, argv);
94 bool AppInit(int argc, char* argv[])
99 fRet = AppInit2(argc, argv);
101 catch (std::exception& e) {
102 PrintException(&e, "AppInit()");
104 PrintException(NULL, "AppInit()");
111 bool AppInit2(int argc, char* argv[])
114 // Turn off microsoft heap dump noise
115 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
116 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
119 // Disable confusing "helpful" text message on abort, ctrl-c
120 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
126 // Clean shutdown on SIGTERM
128 sa.sa_handler = HandleSIGTERM;
129 sigemptyset(&sa.sa_mask);
131 sigaction(SIGTERM, &sa, NULL);
132 sigaction(SIGINT, &sa, NULL);
133 sigaction(SIGHUP, &sa, NULL);
139 ParseParameters(argc, argv);
141 if (mapArgs.count("-datadir"))
143 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
144 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
147 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
149 if (mapArgs.count("-?") || mapArgs.count("--help"))
151 string strUsage = string() +
152 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
153 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
154 " bitcoin [options] \t " + "\n" +
155 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
156 " bitcoin [options] help \t\t " + _("List commands\n") +
157 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
159 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
160 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
161 " -gen \t\t " + _("Generate coins\n") +
162 " -gen=0 \t\t " + _("Don't generate coins\n") +
163 " -min \t\t " + _("Start minimized\n") +
164 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
165 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
166 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
167 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
168 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
169 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
170 " -nolisten \t " + _("Don't accept connections from outside\n") +
173 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
175 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
178 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
180 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
183 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
185 " -testnet \t\t " + _("Use the test network\n") +
186 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
187 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
188 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
189 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
190 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
191 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
192 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
195 strUsage += string() +
196 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
197 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
198 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
199 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
200 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
203 strUsage += string() +
204 " -? \t\t " + _("This help message\n");
206 #if defined(__WXMSW__) && defined(GUI)
207 // Tabs make the columns line up in the message box
208 wxMessageBox(strUsage, "Bitcoin", wxOK);
211 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
212 fprintf(stderr, "%s", strUsage.c_str());
217 fDebug = GetBoolArg("-debug");
218 fAllowDNS = GetBoolArg("-dns");
221 fDaemon = GetBoolArg("-daemon");
229 fServer = GetBoolArg("-server");
231 /* force fServer when running without GUI */
236 fPrintToConsole = GetBoolArg("-printtoconsole");
237 fPrintToDebugger = GetBoolArg("-printtodebugger");
239 fTestNet = GetBoolArg("-testnet");
240 fNoListen = GetBoolArg("-nolisten");
241 fLogTimestamps = GetBoolArg("-logtimestamps");
243 for (int i = 1; i < argc; i++)
244 if (!IsSwitchChar(argv[i][0]))
249 int ret = CommandLineRPC(argc, argv);
260 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
265 CreatePidFile(GetPidFile(), pid);
269 pid_t sid = setsid();
271 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
275 if (!fDebug && !pszSetDataDir[0])
277 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
278 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
280 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
281 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
282 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
284 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
286 if (GetBoolArg("-loadblockindextest"))
289 txdb.LoadBlockIndex();
295 // Limit to single instance per user
296 // Required to protect the database files if we're going to keep deleting log.*
298 #if defined(__WXMSW__) && defined(GUI)
299 // wxSingleInstanceChecker doesn't work on Linux
300 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
301 for (int i = 0; i < strMutexName.size(); i++)
302 if (!isalnum(strMutexName[i]))
303 strMutexName[i] = '.';
304 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
305 if (psingleinstancechecker->IsAnotherRunning())
307 printf("Existing instance found\n");
308 unsigned int nStart = GetTime();
311 // Show the previous instance and exit
312 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
315 if (IsIconic(hwndPrev))
316 ShowWindow(hwndPrev, SW_RESTORE);
317 SetForegroundWindow(hwndPrev);
321 if (GetTime() > nStart + 60)
324 // Resume this instance if the other exits
325 delete psingleinstancechecker;
327 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
328 if (!psingleinstancechecker->IsAnotherRunning())
334 // Make sure only a single bitcoin process is using the data directory.
335 string strLockFile = GetDataDir() + "/.lock";
336 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
337 if (file) fclose(file);
338 static boost::interprocess::file_lock lock(strLockFile.c_str());
339 if (!lock.try_lock())
341 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
345 // Bind to the port early so we can tell if another instance is already running.
349 if (!BindListenPort(strErrors))
351 wxMessageBox(strErrors, "Bitcoin");
360 fprintf(stdout, "bitcoin server starting\n");
364 printf("Loading addresses...\n");
365 nStart = GetTimeMillis();
366 if (!LoadAddresses())
367 strErrors += _("Error loading addr.dat \n");
368 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
370 printf("Loading block index...\n");
371 nStart = GetTimeMillis();
372 if (!LoadBlockIndex())
373 strErrors += _("Error loading blkindex.dat \n");
374 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
376 printf("Loading wallet...\n");
377 nStart = GetTimeMillis();
379 pwalletMain = new CWallet("wallet.dat");
380 if (!pwalletMain->LoadWallet(fFirstRun))
381 strErrors += _("Error loading wallet.dat \n");
382 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
384 RegisterWallet(pwalletMain);
386 CBlockIndex *pindexRescan = pindexBest;
387 if (GetBoolArg("-rescan"))
388 pindexRescan = pindexGenesisBlock;
391 CWalletDB walletdb("wallet.dat");
392 CBlockLocator locator;
393 if (walletdb.ReadBestBlock(locator))
394 pindexRescan = locator.GetBlockIndex();
396 if (pindexBest != pindexRescan)
398 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
399 nStart = GetTimeMillis();
400 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
401 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
404 printf("Done loading\n");
407 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
408 printf("nBestHeight = %d\n", nBestHeight);
409 printf("mapKeys.size() = %d\n", pwalletMain->mapKeys.size());
410 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
411 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
412 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
413 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
415 if (!strErrors.empty())
417 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
421 // Add wallet transactions that aren't already in a block to mapTransactions
422 pwalletMain->ReacceptWalletTransactions();
427 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
433 if (mapArgs.count("-timeout"))
435 int nNewTimeout = GetArg("-timeout", 5000);
436 if (nNewTimeout > 0 && nNewTimeout < 600000)
437 nConnectTimeout = nNewTimeout;
440 if (mapArgs.count("-printblock"))
442 string strMatch = mapArgs["-printblock"];
444 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
446 uint256 hash = (*mi).first;
447 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
449 CBlockIndex* pindex = (*mi).second;
451 block.ReadFromDisk(pindex);
452 block.BuildMerkleTree();
459 printf("No blocks matching %s were found\n", strMatch.c_str());
463 fGenerateBitcoins = GetBoolArg("-gen");
465 if (mapArgs.count("-proxy"))
468 addrProxy = CAddress(mapArgs["-proxy"]);
469 if (!addrProxy.IsValid())
471 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
476 if (mapArgs.count("-addnode"))
478 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
480 CAddress addr(strAddr, fAllowDNS);
481 addr.nTime = 0; // so it won't relay unless successfully connected
487 if (mapArgs.count("-dnsseed"))
490 if (mapArgs.count("-paytxfee"))
492 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
494 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
497 if (nTransactionFee > 0.25 * COIN)
498 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
504 if (GetBoolArg("-noupnp"))
507 if (GetBoolArg("-upnp"))
513 // Create the main window and start the node
520 if (!CheckDiskSpace())
523 RandAddSeedPerfmon();
525 if (!CreateThread(StartNode, NULL))
526 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
529 CreateThread(ThreadRPCServer, NULL);
531 #if defined(__WXMSW__) && defined(GUI)
533 SetStartOnSystemStartup(true);