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 boost::filesystem::remove(GetPidFile());
45 CreateThread(ExitTimeout, NULL);
47 printf("Bitcoin exiting\n\n");
60 void HandleSIGTERM(int)
62 fRequestShutdown = true;
70 //////////////////////////////////////////////////////////////////////////////
76 int main(int argc, char* argv[])
79 fRet = AppInit(argc, argv);
88 bool AppInit(int argc, char* argv[])
93 fRet = AppInit2(argc, argv);
95 catch (std::exception& e) {
96 PrintException(&e, "AppInit()");
98 PrintException(NULL, "AppInit()");
105 bool AppInit2(int argc, char* argv[])
108 // Turn off microsoft heap dump noise
109 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
110 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
113 // Disable confusing "helpful" text message on abort, ctrl-c
114 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
120 // Clean shutdown on SIGTERM
122 sa.sa_handler = HandleSIGTERM;
123 sigemptyset(&sa.sa_mask);
125 sigaction(SIGTERM, &sa, NULL);
126 sigaction(SIGINT, &sa, NULL);
127 sigaction(SIGHUP, &sa, NULL);
133 ParseParameters(argc, argv);
135 if (mapArgs.count("-datadir"))
137 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
138 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
141 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
143 if (mapArgs.count("-?") || mapArgs.count("--help"))
145 string beta = VERSION_IS_BETA ? _(" beta") : "";
146 string strUsage = string() +
147 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
148 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
149 " bitcoin [options] \t " + "\n" +
150 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
151 " bitcoin [options] help \t\t " + _("List commands\n") +
152 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
154 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
155 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
156 " -gen \t\t " + _("Generate coins\n") +
157 " -gen=0 \t\t " + _("Don't generate coins\n") +
158 " -min \t\t " + _("Start minimized\n") +
159 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
160 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
161 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
162 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
163 " -nolisten \t " + _("Don't accept connections from outside\n") +
166 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
168 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
171 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
173 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
176 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
178 " -testnet \t\t " + _("Use the test network\n") +
179 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
180 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
181 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
182 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
183 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
184 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
185 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
188 strUsage += string() +
189 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
190 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
191 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
192 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
193 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
196 strUsage += string() +
197 " -? \t\t " + _("This help message\n");
199 #if defined(__WXMSW__) && defined(GUI)
200 // Tabs make the columns line up in the message box
201 wxMessageBox(strUsage, "Bitcoin", wxOK);
204 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
205 fprintf(stderr, "%s", strUsage.c_str());
210 fDebug = GetBoolArg("-debug");
213 fDaemon = GetBoolArg("-daemon");
221 fServer = GetBoolArg("-server");
223 /* force fServer when running without GUI */
228 fPrintToConsole = GetBoolArg("-printtoconsole");
229 fPrintToDebugger = GetBoolArg("-printtodebugger");
231 fTestNet = GetBoolArg("-testnet");
232 fNoListen = GetBoolArg("-nolisten");
233 fLogTimestamps = GetBoolArg("-logtimestamps");
235 for (int i = 1; i < argc; i++)
236 if (!IsSwitchChar(argv[i][0]))
241 int ret = CommandLineRPC(argc, argv);
252 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
257 CreatePidFile(GetPidFile(), pid);
261 pid_t sid = setsid();
263 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
267 if (!fDebug && !pszSetDataDir[0])
269 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
270 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
272 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
273 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
274 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
276 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
278 if (GetBoolArg("-loadblockindextest"))
281 txdb.LoadBlockIndex();
287 // Limit to single instance per user
288 // Required to protect the database files if we're going to keep deleting log.*
290 #if defined(__WXMSW__) && defined(GUI)
291 // wxSingleInstanceChecker doesn't work on Linux
292 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
293 for (int i = 0; i < strMutexName.size(); i++)
294 if (!isalnum(strMutexName[i]))
295 strMutexName[i] = '.';
296 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
297 if (psingleinstancechecker->IsAnotherRunning())
299 printf("Existing instance found\n");
300 unsigned int nStart = GetTime();
303 // Show the previous instance and exit
304 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
307 if (IsIconic(hwndPrev))
308 ShowWindow(hwndPrev, SW_RESTORE);
309 SetForegroundWindow(hwndPrev);
313 if (GetTime() > nStart + 60)
316 // Resume this instance if the other exits
317 delete psingleinstancechecker;
319 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
320 if (!psingleinstancechecker->IsAnotherRunning())
326 // Make sure only a single bitcoin process is using the data directory.
327 string strLockFile = GetDataDir() + "/.lock";
328 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
330 static boost::interprocess::file_lock lock(strLockFile.c_str());
331 if (!lock.try_lock())
333 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
337 // Bind to the port early so we can tell if another instance is already running.
341 if (!BindListenPort(strErrors))
343 wxMessageBox(strErrors, "Bitcoin");
352 fprintf(stdout, "bitcoin server starting\n");
356 printf("Loading addresses...\n");
357 nStart = GetTimeMillis();
358 if (!LoadAddresses())
359 strErrors += _("Error loading addr.dat \n");
360 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
362 printf("Loading block index...\n");
363 nStart = GetTimeMillis();
364 if (!LoadBlockIndex())
365 strErrors += _("Error loading blkindex.dat \n");
366 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
368 printf("Loading wallet...\n");
369 nStart = GetTimeMillis();
371 if (!LoadWallet(fFirstRun))
372 strErrors += _("Error loading wallet.dat \n");
373 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375 if (GetBoolArg("-rescan"))
377 nStart = GetTimeMillis();
378 ScanForWalletTransactions(pindexGenesisBlock);
379 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
382 printf("Done loading\n");
385 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
386 printf("nBestHeight = %d\n", nBestHeight);
387 printf("mapKeys.size() = %d\n", mapKeys.size());
388 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
389 printf("mapWallet.size() = %d\n", mapWallet.size());
390 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
392 if (!strErrors.empty())
394 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
398 // Add wallet transactions that aren't already in a block to mapTransactions
399 ReacceptWalletTransactions();
404 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
410 if (mapArgs.count("-printblock"))
412 string strMatch = mapArgs["-printblock"];
414 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
416 uint256 hash = (*mi).first;
417 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
419 CBlockIndex* pindex = (*mi).second;
421 block.ReadFromDisk(pindex);
422 block.BuildMerkleTree();
429 printf("No blocks matching %s were found\n", strMatch.c_str());
433 fGenerateBitcoins = GetBoolArg("-gen");
435 if (mapArgs.count("-proxy"))
438 addrProxy = CAddress(mapArgs["-proxy"]);
439 if (!addrProxy.IsValid())
441 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
446 if (mapArgs.count("-addnode"))
448 foreach(string strAddr, mapMultiArgs["-addnode"])
450 CAddress addr(strAddr, NODE_NETWORK);
451 addr.nTime = 0; // so it won't relay unless successfully connected
457 if (mapArgs.count("-dnsseed"))
460 if (mapArgs.count("-paytxfee"))
462 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
464 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
467 if (nTransactionFee > 0.25 * COIN)
468 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
474 if (GetBoolArg("-noupnp"))
477 if (GetBoolArg("-upnp"))
483 // Create the main window and start the node
490 if (!CheckDiskSpace())
493 RandAddSeedPerfmon();
495 if (!CreateThread(StartNode, NULL))
496 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
499 CreateThread(ThreadRPCServer, NULL);
501 #if defined(__WXMSW__) && defined(GUI)
503 SetStartOnSystemStartup(true);