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);
87 bool AppInit(int argc, char* argv[])
92 fRet = AppInit2(argc, argv);
94 catch (std::exception& e) {
95 PrintException(&e, "AppInit()");
97 PrintException(NULL, "AppInit()");
104 bool AppInit2(int argc, char* argv[])
107 // Turn off microsoft heap dump noise
108 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
109 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
112 // Disable confusing "helpful" text message on abort, ctrl-c
113 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
119 // Clean shutdown on SIGTERM
121 sa.sa_handler = HandleSIGTERM;
122 sigemptyset(&sa.sa_mask);
124 sigaction(SIGTERM, &sa, NULL);
125 sigaction(SIGINT, &sa, NULL);
126 sigaction(SIGHUP, &sa, NULL);
132 ParseParameters(argc, argv);
134 if (mapArgs.count("-datadir"))
136 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
137 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
140 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
142 if (mapArgs.count("-?") || mapArgs.count("--help"))
144 string beta = VERSION_IS_BETA ? _(" beta") : "";
145 string strUsage = string() +
146 _("Bitcoin version") + " " + FormatVersion(VERSION) + pszSubVer + beta + "\n\n" +
147 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
148 " bitcoin [options] \t " + "\n" +
149 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
150 " bitcoin [options] help \t\t " + _("List commands\n") +
151 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
153 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
154 " -gen \t\t " + _("Generate coins\n") +
155 " -gen=0 \t\t " + _("Don't generate coins\n") +
156 " -min \t\t " + _("Start minimized\n") +
157 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
158 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
159 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
160 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
161 " -nolisten \t " + _("Don't accept connections from outside\n") +
164 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
166 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
169 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
171 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
174 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
176 " -testnet \t\t " + _("Use the test network\n") +
177 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
178 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
179 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
180 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
181 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
182 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
183 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
186 strUsage += string() +
187 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
188 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
189 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
190 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
191 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
194 strUsage += string() +
195 " -? \t\t " + _("This help message\n");
197 #if defined(__WXMSW__) && defined(GUI)
198 // Tabs make the columns line up in the message box
199 wxMessageBox(strUsage, "Bitcoin", wxOK);
202 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
203 fprintf(stderr, "%s", strUsage.c_str());
208 fDebug = GetBoolArg("-debug");
211 fDaemon = GetBoolArg("-daemon");
219 fServer = GetBoolArg("-server");
221 /* force fServer when running without GUI */
226 fPrintToConsole = GetBoolArg("-printtoconsole");
227 fPrintToDebugger = GetBoolArg("-printtodebugger");
229 fTestNet = GetBoolArg("-testnet");
230 fNoListen = GetBoolArg("-nolisten");
231 fLogTimestamps = GetBoolArg("-logtimestamps");
233 for (int i = 1; i < argc; i++)
234 if (!IsSwitchChar(argv[i][0]))
239 int ret = CommandLineRPC(argc, argv);
250 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
256 pid_t sid = setsid();
258 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
262 if (!fDebug && !pszSetDataDir[0])
264 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
265 printf("Bitcoin version %s%s%s\n", FormatVersion(VERSION).c_str(), pszSubVer, VERSION_IS_BETA ? _(" beta") : "");
267 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
268 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
269 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
271 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
273 if (GetBoolArg("-loadblockindextest"))
276 txdb.LoadBlockIndex();
282 // Limit to single instance per user
283 // Required to protect the database files if we're going to keep deleting log.*
285 #if defined(__WXMSW__) && defined(GUI)
286 // wxSingleInstanceChecker doesn't work on Linux
287 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
288 for (int i = 0; i < strMutexName.size(); i++)
289 if (!isalnum(strMutexName[i]))
290 strMutexName[i] = '.';
291 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
292 if (psingleinstancechecker->IsAnotherRunning())
294 printf("Existing instance found\n");
295 unsigned int nStart = GetTime();
298 // Show the previous instance and exit
299 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
302 if (IsIconic(hwndPrev))
303 ShowWindow(hwndPrev, SW_RESTORE);
304 SetForegroundWindow(hwndPrev);
308 if (GetTime() > nStart + 60)
311 // Resume this instance if the other exits
312 delete psingleinstancechecker;
314 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
315 if (!psingleinstancechecker->IsAnotherRunning())
321 // Make sure only a single bitcoin process is using the data directory.
322 string strLockFile = GetDataDir() + "/.lock";
323 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
325 static boost::interprocess::file_lock lock(strLockFile.c_str());
326 if (!lock.try_lock())
328 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
332 // Bind to the port early so we can tell if another instance is already running.
336 if (!BindListenPort(strErrors))
338 wxMessageBox(strErrors, "Bitcoin");
347 fprintf(stdout, "bitcoin server starting\n");
351 printf("Loading addresses...\n");
352 nStart = GetTimeMillis();
353 if (!LoadAddresses())
354 strErrors += _("Error loading addr.dat \n");
355 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
357 printf("Loading block index...\n");
358 nStart = GetTimeMillis();
359 if (!LoadBlockIndex())
360 strErrors += _("Error loading blkindex.dat \n");
361 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
363 printf("Loading wallet...\n");
364 nStart = GetTimeMillis();
366 if (!LoadWallet(fFirstRun))
367 strErrors += _("Error loading wallet.dat \n");
368 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
370 if (GetBoolArg("-rescan"))
372 nStart = GetTimeMillis();
373 ScanForWalletTransactions(pindexGenesisBlock);
374 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
377 printf("Done loading\n");
380 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
381 printf("nBestHeight = %d\n", nBestHeight);
382 printf("mapKeys.size() = %d\n", mapKeys.size());
383 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
384 printf("mapWallet.size() = %d\n", mapWallet.size());
385 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
387 if (!strErrors.empty())
389 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
393 // Add wallet transactions that aren't already in a block to mapTransactions
394 ReacceptWalletTransactions();
399 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
405 if (mapArgs.count("-printblock"))
407 string strMatch = mapArgs["-printblock"];
409 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
411 uint256 hash = (*mi).first;
412 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
414 CBlockIndex* pindex = (*mi).second;
416 block.ReadFromDisk(pindex);
417 block.BuildMerkleTree();
424 printf("No blocks matching %s were found\n", strMatch.c_str());
428 fGenerateBitcoins = GetBoolArg("-gen");
430 if (mapArgs.count("-proxy"))
433 addrProxy = CAddress(mapArgs["-proxy"]);
434 if (!addrProxy.IsValid())
436 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
441 if (mapArgs.count("-addnode"))
443 foreach(string strAddr, mapMultiArgs["-addnode"])
445 CAddress addr(strAddr, NODE_NETWORK);
446 addr.nTime = 0; // so it won't relay unless successfully connected
452 if (mapArgs.count("-dnsseed"))
455 if (mapArgs.count("-paytxfee"))
457 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
459 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
462 if (nTransactionFee > 0.25 * COIN)
463 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
469 if (GetBoolArg("-noupnp"))
472 if (GetBoolArg("-upnp"))
478 // Create the main window and start the node
485 if (!CheckDiskSpace())
488 RandAddSeedPerfmon();
490 if (!CreateThread(StartNode, NULL))
491 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
494 CreateThread(ThreadRPCServer, NULL);
496 #if defined(__WXMSW__) && defined(GUI)
498 SetStartOnSystemStartup(true);