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[])
77 for (int i = 1; i < argc; i++)
78 if (!IsSwitchChar(argv[i][0]))
80 fDaemon = !fCommandLine;
89 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
93 pthread_exit((void*)0);
97 if (!AppInit(argc, argv))
106 bool AppInit(int argc, char* argv[])
111 fRet = AppInit2(argc, argv);
113 catch (std::exception& e) {
114 PrintException(&e, "AppInit()");
116 PrintException(NULL, "AppInit()");
123 bool AppInit2(int argc, char* argv[])
126 // Turn off microsoft heap dump noise
127 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
128 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
131 // Disable confusing "helpful" text message on abort, ctrl-c
132 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
138 // Clean shutdown on SIGTERM
140 sa.sa_handler = HandleSIGTERM;
141 sigemptyset(&sa.sa_mask);
143 sigaction(SIGTERM, &sa, NULL);
149 ParseParameters(argc, argv);
151 if (mapArgs.count("-datadir"))
153 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
154 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
157 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
159 if (mapArgs.count("-?") || mapArgs.count("--help"))
161 string strUsage = string() +
162 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
163 " bitcoin [options] \t " + "\n" +
164 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
165 " bitcoin [options] help \t\t " + _("List commands\n") +
166 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
168 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
169 " -gen \t\t " + _("Generate coins\n") +
170 " -gen=0 \t\t " + _("Don't generate coins\n") +
171 " -min \t\t " + _("Start minimized\n") +
172 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
173 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
174 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
175 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
176 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
177 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
178 " -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>\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>\n") +
185 " -keypool=<n> \t " + _("Set key pool size to <n>\n") +
186 " -nolisten \t " + _("Don't accept connections from outside");
189 strUsage += string() +
190 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
191 " -rpcssl=1 \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
192 " -rpcsslcertificatchainfile=<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");
213 fPrintToDebugger = GetBoolArg("-printtodebugger");
215 fTestNet = GetBoolArg("-testnet");
217 fNoListen = GetBoolArg("-nolisten");
221 int ret = CommandLineRPC(argc, argv);
225 if (!fDebug && !pszSetDataDir[0])
227 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
228 printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer);
230 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
231 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
232 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
234 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
236 if (GetBoolArg("-loadblockindextest"))
239 txdb.LoadBlockIndex();
245 // Limit to single instance per user
246 // Required to protect the database files if we're going to keep deleting log.*
248 #if defined(__WXMSW__) && defined(GUI)
249 // wxSingleInstanceChecker doesn't work on Linux
250 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
251 for (int i = 0; i < strMutexName.size(); i++)
252 if (!isalnum(strMutexName[i]))
253 strMutexName[i] = '.';
254 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
255 if (psingleinstancechecker->IsAnotherRunning())
257 printf("Existing instance found\n");
258 unsigned int nStart = GetTime();
261 // Show the previous instance and exit
262 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
265 if (IsIconic(hwndPrev))
266 ShowWindow(hwndPrev, SW_RESTORE);
267 SetForegroundWindow(hwndPrev);
271 if (GetTime() > nStart + 60)
274 // Resume this instance if the other exits
275 delete psingleinstancechecker;
277 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
278 if (!psingleinstancechecker->IsAnotherRunning())
284 // Make sure only a single bitcoin process is using the data directory.
285 string strLockFile = GetDataDir() + "/.lock";
286 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
288 static boost::interprocess::file_lock lock(strLockFile.c_str());
289 if (!lock.try_lock())
291 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
295 // Bind to the port early so we can tell if another instance is already running.
299 if (!BindListenPort(strErrors))
301 wxMessageBox(strErrors, "Bitcoin");
310 fprintf(stdout, "bitcoin server starting\n");
314 printf("Loading addresses...\n");
315 nStart = GetTimeMillis();
316 if (!LoadAddresses())
317 strErrors += _("Error loading addr.dat \n");
318 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
320 printf("Loading block index...\n");
321 nStart = GetTimeMillis();
322 if (!LoadBlockIndex())
323 strErrors += _("Error loading blkindex.dat \n");
324 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
326 printf("Loading wallet...\n");
327 nStart = GetTimeMillis();
329 if (!LoadWallet(fFirstRun))
330 strErrors += _("Error loading wallet.dat \n");
331 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
333 if (GetBoolArg("-rescan"))
335 nStart = GetTimeMillis();
336 ScanForWalletTransactions(pindexGenesisBlock);
337 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
340 printf("Done loading\n");
343 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
344 printf("nBestHeight = %d\n", nBestHeight);
345 printf("mapKeys.size() = %d\n", mapKeys.size());
346 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
347 printf("mapWallet.size() = %d\n", mapWallet.size());
348 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
350 if (!strErrors.empty())
352 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
356 // Add wallet transactions that aren't already in a block to mapTransactions
357 ReacceptWalletTransactions();
362 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
368 if (mapArgs.count("-printblock"))
370 string strMatch = mapArgs["-printblock"];
372 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
374 uint256 hash = (*mi).first;
375 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
377 CBlockIndex* pindex = (*mi).second;
379 block.ReadFromDisk(pindex);
380 block.BuildMerkleTree();
387 printf("No blocks matching %s were found\n", strMatch.c_str());
391 fGenerateBitcoins = GetBoolArg("-gen");
393 if (mapArgs.count("-proxy"))
396 addrProxy = CAddress(mapArgs["-proxy"]);
397 if (!addrProxy.IsValid())
399 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
404 if (mapArgs.count("-addnode"))
406 foreach(string strAddr, mapMultiArgs["-addnode"])
408 CAddress addr(strAddr, NODE_NETWORK);
409 addr.nTime = 0; // so it won't relay unless successfully connected
415 if (mapArgs.count("-paytxfee"))
417 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
419 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
422 if (nTransactionFee > 0.25 * COIN)
423 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
427 // Create the main window and start the node
434 if (!CheckDiskSpace())
437 RandAddSeedPerfmon();
439 if (!CreateThread(StartNode, NULL))
440 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
442 if (GetBoolArg("-server") || fDaemon)
443 CreateThread(ThreadRPCServer, NULL);
445 #if defined(__WXMSW__) && defined(GUI)
447 SetStartOnSystemStartup(true);