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 CreateThread(ExitTimeout, NULL);
46 printf("Bitcoin exiting\n\n");
59 void HandleSIGTERM(int)
61 fRequestShutdown = true;
69 //////////////////////////////////////////////////////////////////////////////
75 int main(int argc, char* argv[])
78 fRet = AppInit(argc, argv);
81 pthread_exit((void*)0);
85 bool AppInit(int argc, char* argv[])
90 fRet = AppInit2(argc, argv);
92 catch (std::exception& e) {
93 PrintException(&e, "AppInit()");
95 PrintException(NULL, "AppInit()");
102 bool AppInit2(int argc, char* argv[])
105 // Turn off microsoft heap dump noise
106 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
107 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
110 // Disable confusing "helpful" text message on abort, ctrl-c
111 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
117 // Clean shutdown on SIGTERM
119 sa.sa_handler = HandleSIGTERM;
120 sigemptyset(&sa.sa_mask);
122 sigaction(SIGTERM, &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 beta = VERSION_IS_BETA ? _(" beta") : "";
141 string strUsage = string() +
142 _("Bitcoin version") + " " + FormatVersion(VERSION) + pszSubVer + beta + "\n\n" +
143 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
144 " bitcoin [options] \t " + "\n" +
145 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
146 " bitcoin [options] help \t\t " + _("List commands\n") +
147 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
149 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\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 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
156 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
157 " -nolisten \t " + _("Don't accept connections from outside\n") +
158 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
159 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
160 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
161 " -testnet \t\t " + _("Use the test network\n") +
162 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
163 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
164 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
165 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
166 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
167 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
168 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
171 strUsage += string() +
172 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
173 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
174 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
175 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
176 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
179 strUsage += string() +
180 " -? \t\t " + _("This help message\n");
182 #if defined(__WXMSW__) && defined(GUI)
183 // Tabs make the columns line up in the message box
184 wxMessageBox(strUsage, "Bitcoin", wxOK);
187 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
188 fprintf(stderr, "%s", strUsage.c_str());
193 fDebug = GetBoolArg("-debug");
195 fDaemon = GetBoolArg("-daemon");
200 fServer = GetBoolArg("-server");
202 /* force fServer and fDaemon when running without GUI */
208 fPrintToConsole = GetBoolArg("-printtoconsole");
209 fPrintToDebugger = GetBoolArg("-printtodebugger");
211 fTestNet = GetBoolArg("-testnet");
213 fNoListen = GetBoolArg("-nolisten");
215 for (int i = 1; i < argc; i++)
216 if (!IsSwitchChar(argv[i][0]))
221 int ret = CommandLineRPC(argc, argv);
232 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
240 if (!fDebug && !pszSetDataDir[0])
242 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
243 printf("Bitcoin version %s%s%s\n", FormatVersion(VERSION).c_str(), pszSubVer, VERSION_IS_BETA ? _(" beta") : "");
245 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
246 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
247 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
249 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
251 if (GetBoolArg("-loadblockindextest"))
254 txdb.LoadBlockIndex();
260 // Limit to single instance per user
261 // Required to protect the database files if we're going to keep deleting log.*
263 #if defined(__WXMSW__) && defined(GUI)
264 // wxSingleInstanceChecker doesn't work on Linux
265 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
266 for (int i = 0; i < strMutexName.size(); i++)
267 if (!isalnum(strMutexName[i]))
268 strMutexName[i] = '.';
269 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
270 if (psingleinstancechecker->IsAnotherRunning())
272 printf("Existing instance found\n");
273 unsigned int nStart = GetTime();
276 // Show the previous instance and exit
277 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
280 if (IsIconic(hwndPrev))
281 ShowWindow(hwndPrev, SW_RESTORE);
282 SetForegroundWindow(hwndPrev);
286 if (GetTime() > nStart + 60)
289 // Resume this instance if the other exits
290 delete psingleinstancechecker;
292 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
293 if (!psingleinstancechecker->IsAnotherRunning())
299 // Make sure only a single bitcoin process is using the data directory.
300 string strLockFile = GetDataDir() + "/.lock";
301 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
303 static boost::interprocess::file_lock lock(strLockFile.c_str());
304 if (!lock.try_lock())
306 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
310 // Bind to the port early so we can tell if another instance is already running.
314 if (!BindListenPort(strErrors))
316 wxMessageBox(strErrors, "Bitcoin");
325 fprintf(stdout, "bitcoin server starting\n");
329 printf("Loading addresses...\n");
330 nStart = GetTimeMillis();
331 if (!LoadAddresses())
332 strErrors += _("Error loading addr.dat \n");
333 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
335 printf("Loading block index...\n");
336 nStart = GetTimeMillis();
337 if (!LoadBlockIndex())
338 strErrors += _("Error loading blkindex.dat \n");
339 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
341 printf("Loading wallet...\n");
342 nStart = GetTimeMillis();
344 if (!LoadWallet(fFirstRun))
345 strErrors += _("Error loading wallet.dat \n");
346 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
348 if (GetBoolArg("-rescan"))
350 nStart = GetTimeMillis();
351 ScanForWalletTransactions(pindexGenesisBlock);
352 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
355 printf("Done loading\n");
358 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
359 printf("nBestHeight = %d\n", nBestHeight);
360 printf("mapKeys.size() = %d\n", mapKeys.size());
361 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
362 printf("mapWallet.size() = %d\n", mapWallet.size());
363 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
365 if (!strErrors.empty())
367 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
371 // Add wallet transactions that aren't already in a block to mapTransactions
372 ReacceptWalletTransactions();
377 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
383 if (mapArgs.count("-printblock"))
385 string strMatch = mapArgs["-printblock"];
387 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
389 uint256 hash = (*mi).first;
390 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
392 CBlockIndex* pindex = (*mi).second;
394 block.ReadFromDisk(pindex);
395 block.BuildMerkleTree();
402 printf("No blocks matching %s were found\n", strMatch.c_str());
406 fGenerateBitcoins = GetBoolArg("-gen");
408 if (mapArgs.count("-proxy"))
411 addrProxy = CAddress(mapArgs["-proxy"]);
412 if (!addrProxy.IsValid())
414 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
419 if (mapArgs.count("-addnode"))
421 foreach(string strAddr, mapMultiArgs["-addnode"])
423 CAddress addr(strAddr, NODE_NETWORK);
424 addr.nTime = 0; // so it won't relay unless successfully connected
430 if (mapArgs.count("-paytxfee"))
432 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
434 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
437 if (nTransactionFee > 0.25 * COIN)
438 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
442 // Create the main window and start the node
449 if (!CheckDiskSpace())
452 RandAddSeedPerfmon();
454 if (!CreateThread(StartNode, NULL))
455 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
458 CreateThread(ThreadRPCServer, NULL);
460 #if defined(__WXMSW__) && defined(GUI)
462 SetStartOnSystemStartup(true);