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.hpp>
11 #include <boost/filesystem/fstream.hpp>
12 #include <boost/interprocess/sync/file_lock.hpp>
15 using namespace boost;
19 //////////////////////////////////////////////////////////////////////////////
24 void ExitTimeout(void* parg)
32 void Shutdown(void* parg)
34 static CCriticalSection cs_Shutdown;
37 CRITICAL_BLOCK(cs_Shutdown)
39 fFirstThread = !fTaken;
46 nTransactionsUpdated++;
50 boost::filesystem::remove(GetPidFile());
51 UnregisterWallet(pwalletMain);
53 CreateThread(ExitTimeout, NULL);
55 printf("Bitcoin exiting\n\n");
68 void HandleSIGTERM(int)
70 fRequestShutdown = true;
78 //////////////////////////////////////////////////////////////////////////////
83 int main(int argc, char* argv[])
86 fRet = AppInit(argc, argv);
95 bool AppInit(int argc, char* argv[])
100 fRet = AppInit2(argc, argv);
102 catch (std::exception& e) {
103 PrintException(&e, "AppInit()");
105 PrintException(NULL, "AppInit()");
112 bool AppInit2(int argc, char* argv[])
115 // Turn off microsoft heap dump noise
116 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
117 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
120 // Disable confusing "helpful" text message on abort, ctrl-c
121 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
127 // Clean shutdown on SIGTERM
129 sa.sa_handler = HandleSIGTERM;
130 sigemptyset(&sa.sa_mask);
132 sigaction(SIGTERM, &sa, NULL);
133 sigaction(SIGINT, &sa, NULL);
134 sigaction(SIGHUP, &sa, NULL);
140 ParseParameters(argc, argv);
142 if (mapArgs.count("-datadir"))
144 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
145 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
148 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
150 if (mapArgs.count("-?") || mapArgs.count("--help"))
152 string strUsage = string() +
153 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
154 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
155 " bitcoin [options] \t " + "\n" +
156 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
157 " bitcoin [options] help \t\t " + _("List commands\n") +
158 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
160 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
161 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
162 " -gen \t\t " + _("Generate coins\n") +
163 " -gen=0 \t\t " + _("Don't generate coins\n") +
164 " -min \t\t " + _("Start minimized\n") +
165 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
166 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
167 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
168 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
169 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
170 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
171 " -nolisten \t " + _("Don't accept connections from outside\n") +
174 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
176 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
179 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
181 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
184 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
186 " -testnet \t\t " + _("Use the test network\n") +
187 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
188 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
189 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
190 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
191 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
192 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
193 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
196 strUsage += string() +
197 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
198 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
199 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
200 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
201 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
204 strUsage += string() +
205 " -? \t\t " + _("This help message\n");
207 #if defined(__WXMSW__) && defined(GUI)
208 // Tabs make the columns line up in the message box
209 wxMessageBox(strUsage, "Bitcoin", wxOK);
212 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
213 fprintf(stderr, "%s", strUsage.c_str());
218 fDebug = GetBoolArg("-debug");
219 fAllowDNS = GetBoolArg("-dns");
222 fDaemon = GetBoolArg("-daemon");
230 fServer = GetBoolArg("-server");
232 /* force fServer when running without GUI */
237 fPrintToConsole = GetBoolArg("-printtoconsole");
238 fPrintToDebugger = GetBoolArg("-printtodebugger");
240 fTestNet = GetBoolArg("-testnet");
241 fNoListen = GetBoolArg("-nolisten");
242 fLogTimestamps = GetBoolArg("-logtimestamps");
244 for (int i = 1; i < argc; i++)
245 if (!IsSwitchChar(argv[i][0]))
250 int ret = CommandLineRPC(argc, argv);
261 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
266 CreatePidFile(GetPidFile(), pid);
270 pid_t sid = setsid();
272 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
276 if (!fDebug && !pszSetDataDir[0])
278 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
279 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
281 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
282 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
283 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
285 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
287 if (GetBoolArg("-loadblockindextest"))
290 txdb.LoadBlockIndex();
296 // Limit to single instance per user
297 // Required to protect the database files if we're going to keep deleting log.*
299 #if defined(__WXMSW__) && defined(GUI)
300 // wxSingleInstanceChecker doesn't work on Linux
301 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
302 for (int i = 0; i < strMutexName.size(); i++)
303 if (!isalnum(strMutexName[i]))
304 strMutexName[i] = '.';
305 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
306 if (psingleinstancechecker->IsAnotherRunning())
308 printf("Existing instance found\n");
309 unsigned int nStart = GetTime();
312 // Show the previous instance and exit
313 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
316 if (IsIconic(hwndPrev))
317 ShowWindow(hwndPrev, SW_RESTORE);
318 SetForegroundWindow(hwndPrev);
322 if (GetTime() > nStart + 60)
325 // Resume this instance if the other exits
326 delete psingleinstancechecker;
328 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
329 if (!psingleinstancechecker->IsAnotherRunning())
335 // Make sure only a single bitcoin process is using the data directory.
336 string strLockFile = GetDataDir() + "/.lock";
337 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
338 if (file) fclose(file);
339 static boost::interprocess::file_lock lock(strLockFile.c_str());
340 if (!lock.try_lock())
342 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
346 // Bind to the port early so we can tell if another instance is already running.
350 if (!BindListenPort(strErrors))
352 wxMessageBox(strErrors, "Bitcoin");
361 fprintf(stdout, "bitcoin server starting\n");
365 printf("Loading addresses...\n");
366 nStart = GetTimeMillis();
367 if (!LoadAddresses())
368 strErrors += _("Error loading addr.dat \n");
369 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
371 printf("Loading block index...\n");
372 nStart = GetTimeMillis();
373 if (!LoadBlockIndex())
374 strErrors += _("Error loading blkindex.dat \n");
375 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
377 printf("Loading wallet...\n");
378 nStart = GetTimeMillis();
380 pwalletMain = new CWallet("wallet.dat");
381 if (!pwalletMain->LoadWallet(fFirstRun))
382 strErrors += _("Error loading wallet.dat \n");
383 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
385 RegisterWallet(pwalletMain);
387 CBlockIndex *pindexRescan = pindexBest;
388 if (GetBoolArg("-rescan"))
389 pindexRescan = pindexGenesisBlock;
392 CWalletDB walletdb("wallet.dat");
393 CBlockLocator locator;
394 if (walletdb.ReadBestBlock(locator))
395 pindexRescan = locator.GetBlockIndex();
397 if (pindexBest != pindexRescan)
399 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
400 nStart = GetTimeMillis();
401 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
402 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
405 printf("Done loading\n");
408 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
409 printf("nBestHeight = %d\n", nBestHeight);
410 printf("mapKeys.size() = %d\n", pwalletMain->mapKeys.size());
411 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
412 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
413 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
414 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
416 if (!strErrors.empty())
418 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
422 // Add wallet transactions that aren't already in a block to mapTransactions
423 pwalletMain->ReacceptWalletTransactions();
428 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
434 if (mapArgs.count("-timeout"))
436 int nNewTimeout = GetArg("-timeout", 5000);
437 if (nNewTimeout > 0 && nNewTimeout < 600000)
438 nConnectTimeout = nNewTimeout;
441 if (mapArgs.count("-printblock"))
443 string strMatch = mapArgs["-printblock"];
445 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
447 uint256 hash = (*mi).first;
448 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
450 CBlockIndex* pindex = (*mi).second;
452 block.ReadFromDisk(pindex);
453 block.BuildMerkleTree();
460 printf("No blocks matching %s were found\n", strMatch.c_str());
464 fGenerateBitcoins = GetBoolArg("-gen");
466 if (mapArgs.count("-proxy"))
469 addrProxy = CAddress(mapArgs["-proxy"]);
470 if (!addrProxy.IsValid())
472 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
477 if (mapArgs.count("-addnode"))
479 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
481 CAddress addr(strAddr, fAllowDNS);
482 addr.nTime = 0; // so it won't relay unless successfully connected
488 if (mapArgs.count("-dnsseed"))
491 if (mapArgs.count("-paytxfee"))
493 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
495 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
498 if (nTransactionFee > 0.25 * COIN)
499 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
505 if (GetBoolArg("-noupnp"))
508 if (GetBoolArg("-upnp"))
514 // Create the main window and start the node
521 if (!CheckDiskSpace())
524 RandAddSeedPerfmon();
526 if (!CreateThread(StartNode, NULL))
527 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
530 CreateThread(ThreadRPCServer, NULL);
532 #if defined(__WXMSW__) && defined(GUI)
534 SetStartOnSystemStartup(true);