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;
16 //////////////////////////////////////////////////////////////////////////////
21 void ExitTimeout(void* parg)
29 void Shutdown(void* parg)
31 static CCriticalSection cs_Shutdown;
34 CRITICAL_BLOCK(cs_Shutdown)
36 fFirstThread = !fTaken;
43 nTransactionsUpdated++;
47 boost::filesystem::remove(GetPidFile());
48 CreateThread(ExitTimeout, NULL);
50 printf("Bitcoin exiting\n\n");
63 void HandleSIGTERM(int)
65 fRequestShutdown = true;
73 //////////////////////////////////////////////////////////////////////////////
79 int main(int argc, char* argv[])
82 fRet = AppInit(argc, argv);
92 bool AppInit(int argc, char* argv[])
97 fRet = AppInit2(argc, argv);
99 catch (std::exception& e) {
100 PrintException(&e, "AppInit()");
102 PrintException(NULL, "AppInit()");
109 bool AppInit2(int argc, char* argv[])
112 // Turn off microsoft heap dump noise
113 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
114 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
117 // Disable confusing "helpful" text message on abort, ctrl-c
118 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
124 // Clean shutdown on SIGTERM
126 sa.sa_handler = HandleSIGTERM;
127 sigemptyset(&sa.sa_mask);
129 sigaction(SIGTERM, &sa, NULL);
130 sigaction(SIGINT, &sa, NULL);
131 sigaction(SIGHUP, &sa, NULL);
137 ParseParameters(argc, argv);
139 if (mapArgs.count("-datadir"))
141 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
142 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
145 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
147 if (mapArgs.count("-?") || mapArgs.count("--help"))
149 string strUsage = string() +
150 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
151 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
152 " bitcoin [options] \t " + "\n" +
153 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
154 " bitcoin [options] help \t\t " + _("List commands\n") +
155 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
157 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
158 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
159 " -gen \t\t " + _("Generate coins\n") +
160 " -gen=0 \t\t " + _("Don't generate coins\n") +
161 " -min \t\t " + _("Start minimized\n") +
162 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
163 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
164 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
165 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
166 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
167 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
168 " -nolisten \t " + _("Don't accept connections from outside\n") +
171 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
173 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
176 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
178 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
181 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
183 " -testnet \t\t " + _("Use the test network\n") +
184 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
185 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
186 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
187 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
188 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
189 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
190 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
193 strUsage += string() +
194 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
195 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
196 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
197 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
198 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
201 strUsage += string() +
202 " -? \t\t " + _("This help message\n");
204 #if defined(__WXMSW__) && defined(GUI)
205 // Tabs make the columns line up in the message box
206 wxMessageBox(strUsage, "Bitcoin", wxOK);
209 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
210 fprintf(stderr, "%s", strUsage.c_str());
215 fDebug = GetBoolArg("-debug");
216 fAllowDNS = GetBoolArg("-dns");
219 fDaemon = GetBoolArg("-daemon");
227 fServer = GetBoolArg("-server");
229 /* force fServer when running without GUI */
235 fPrintToConsole = GetBoolArg("-printtoconsole");
236 fPrintToDebugger = GetBoolArg("-printtodebugger");
238 fTestNet = GetBoolArg("-testnet");
239 fNoListen = GetBoolArg("-nolisten");
240 fLogTimestamps = GetBoolArg("-logtimestamps");
242 for (int i = 1; i < argc; i++)
243 if (!IsSwitchChar(argv[i][0]))
248 int ret = CommandLineRPC(argc, argv);
259 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
264 CreatePidFile(GetPidFile(), pid);
268 pid_t sid = setsid();
270 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
274 if (!fDebug && !pszSetDataDir[0])
276 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
277 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
279 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
280 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
281 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
283 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
285 if (GetBoolArg("-loadblockindextest"))
288 txdb.LoadBlockIndex();
294 // Limit to single instance per user
295 // Required to protect the database files if we're going to keep deleting log.*
297 #if defined(__WXMSW__) && defined(GUI)
298 // wxSingleInstanceChecker doesn't work on Linux
299 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
300 for (int i = 0; i < strMutexName.size(); i++)
301 if (!isalnum(strMutexName[i]))
302 strMutexName[i] = '.';
303 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
304 if (psingleinstancechecker->IsAnotherRunning())
306 printf("Existing instance found\n");
307 unsigned int nStart = GetTime();
310 // Show the previous instance and exit
311 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
314 if (IsIconic(hwndPrev))
315 ShowWindow(hwndPrev, SW_RESTORE);
316 SetForegroundWindow(hwndPrev);
320 if (GetTime() > nStart + 60)
323 // Resume this instance if the other exits
324 delete psingleinstancechecker;
326 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
327 if (!psingleinstancechecker->IsAnotherRunning())
333 // Make sure only a single bitcoin process is using the data directory.
334 string strLockFile = GetDataDir() + "/.lock";
335 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
336 if (file) fclose(file);
337 static boost::interprocess::file_lock lock(strLockFile.c_str());
338 if (!lock.try_lock())
340 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
344 // Bind to the port early so we can tell if another instance is already running.
348 if (!BindListenPort(strErrors))
350 wxMessageBox(strErrors, "Bitcoin");
359 fprintf(stdout, "bitcoin server starting\n");
363 printf("Loading addresses...\n");
364 nStart = GetTimeMillis();
365 if (!LoadAddresses())
366 strErrors += _("Error loading addr.dat \n");
367 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
369 printf("Loading block index...\n");
370 nStart = GetTimeMillis();
371 if (!LoadBlockIndex())
372 strErrors += _("Error loading blkindex.dat \n");
373 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375 printf("Loading wallet...\n");
376 nStart = GetTimeMillis();
378 if (!LoadWallet(fFirstRun))
379 strErrors += _("Error loading wallet.dat \n");
380 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
382 CBlockIndex *pindexRescan = pindexBest;
383 if (GetBoolArg("-rescan"))
384 pindexRescan = pindexGenesisBlock;
388 CBlockLocator locator;
389 if (walletdb.ReadBestBlock(locator))
390 pindexRescan = locator.GetBlockIndex();
392 if (pindexBest != pindexRescan)
394 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
395 nStart = GetTimeMillis();
396 ScanForWalletTransactions(pindexRescan, true);
397 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
400 printf("Done loading\n");
403 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
404 printf("nBestHeight = %d\n", nBestHeight);
405 printf("mapKeys.size() = %d\n", mapKeys.size());
406 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
407 printf("mapWallet.size() = %d\n", mapWallet.size());
408 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
410 if (!strErrors.empty())
412 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
416 // Add wallet transactions that aren't already in a block to mapTransactions
417 ReacceptWalletTransactions();
422 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
428 if (mapArgs.count("-timeout"))
430 int nNewTimeout = GetArg("-timeout", 5000);
431 if (nNewTimeout > 0 && nNewTimeout < 600000)
432 nConnectTimeout = nNewTimeout;
435 if (mapArgs.count("-printblock"))
437 string strMatch = mapArgs["-printblock"];
439 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
441 uint256 hash = (*mi).first;
442 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
444 CBlockIndex* pindex = (*mi).second;
446 block.ReadFromDisk(pindex);
447 block.BuildMerkleTree();
454 printf("No blocks matching %s were found\n", strMatch.c_str());
458 fGenerateBitcoins = GetBoolArg("-gen");
460 if (mapArgs.count("-proxy"))
463 addrProxy = CAddress(mapArgs["-proxy"]);
464 if (!addrProxy.IsValid())
466 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
471 if (mapArgs.count("-addnode"))
473 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
475 CAddress addr(strAddr, fAllowDNS);
476 addr.nTime = 0; // so it won't relay unless successfully connected
482 if (mapArgs.count("-dnsseed"))
485 if (mapArgs.count("-paytxfee"))
487 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
489 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
492 if (nTransactionFee > 0.25 * COIN)
493 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
499 if (GetBoolArg("-noupnp"))
502 if (GetBoolArg("-upnp"))
508 // Create the main window and start the node
515 if (!CheckDiskSpace())
518 RandAddSeedPerfmon();
520 if (!CreateThread(StartNode, NULL))
521 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
524 CreateThread(ThreadRPCServer, NULL);
526 #if defined(__WXMSW__) && defined(GUI)
528 SetStartOnSystemStartup(true);