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 //////////////////////////////////////////////////////////////////////////////
78 int main(int argc, char* argv[])
81 fRet = AppInit(argc, argv);
90 bool AppInit(int argc, char* argv[])
95 fRet = AppInit2(argc, argv);
97 catch (std::exception& e) {
98 PrintException(&e, "AppInit()");
100 PrintException(NULL, "AppInit()");
107 bool AppInit2(int argc, char* argv[])
110 // Turn off microsoft heap dump noise
111 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
112 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
115 // Disable confusing "helpful" text message on abort, ctrl-c
116 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
122 // Clean shutdown on SIGTERM
124 sa.sa_handler = HandleSIGTERM;
125 sigemptyset(&sa.sa_mask);
127 sigaction(SIGTERM, &sa, NULL);
128 sigaction(SIGINT, &sa, NULL);
129 sigaction(SIGHUP, &sa, NULL);
135 ParseParameters(argc, argv);
137 if (mapArgs.count("-datadir"))
139 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
140 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
143 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
145 if (mapArgs.count("-?") || mapArgs.count("--help"))
147 string strUsage = string() +
148 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
149 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
150 " bitcoin [options] \t " + "\n" +
151 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
152 " bitcoin [options] help \t\t " + _("List commands\n") +
153 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
155 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
156 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
157 " -gen \t\t " + _("Generate coins\n") +
158 " -gen=0 \t\t " + _("Don't generate coins\n") +
159 " -min \t\t " + _("Start minimized\n") +
160 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
161 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
162 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
163 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
164 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
165 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
166 " -nolisten \t " + _("Don't accept connections from outside\n") +
169 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
171 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
174 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
176 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
179 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
181 " -testnet \t\t " + _("Use the test network\n") +
182 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
183 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
184 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
185 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
186 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
187 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
188 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
191 strUsage += string() +
192 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
193 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
194 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
195 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
196 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
199 strUsage += string() +
200 " -? \t\t " + _("This help message\n");
202 #if defined(__WXMSW__) && defined(GUI)
203 // Tabs make the columns line up in the message box
204 wxMessageBox(strUsage, "Bitcoin", wxOK);
207 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
208 fprintf(stderr, "%s", strUsage.c_str());
213 fDebug = GetBoolArg("-debug");
214 fAllowDNS = GetBoolArg("-dns");
217 fDaemon = GetBoolArg("-daemon");
225 fServer = GetBoolArg("-server");
227 /* force fServer when running without GUI */
232 fPrintToConsole = GetBoolArg("-printtoconsole");
233 fPrintToDebugger = GetBoolArg("-printtodebugger");
235 fTestNet = GetBoolArg("-testnet");
236 fNoListen = GetBoolArg("-nolisten");
237 fLogTimestamps = GetBoolArg("-logtimestamps");
239 for (int i = 1; i < argc; i++)
240 if (!IsSwitchChar(argv[i][0]))
245 int ret = CommandLineRPC(argc, argv);
256 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
261 CreatePidFile(GetPidFile(), pid);
265 pid_t sid = setsid();
267 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
271 if (!fDebug && !pszSetDataDir[0])
273 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
274 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
276 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
277 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
278 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
280 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
282 if (GetBoolArg("-loadblockindextest"))
285 txdb.LoadBlockIndex();
291 // Limit to single instance per user
292 // Required to protect the database files if we're going to keep deleting log.*
294 #if defined(__WXMSW__) && defined(GUI)
295 // wxSingleInstanceChecker doesn't work on Linux
296 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
297 for (int i = 0; i < strMutexName.size(); i++)
298 if (!isalnum(strMutexName[i]))
299 strMutexName[i] = '.';
300 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
301 if (psingleinstancechecker->IsAnotherRunning())
303 printf("Existing instance found\n");
304 unsigned int nStart = GetTime();
307 // Show the previous instance and exit
308 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
311 if (IsIconic(hwndPrev))
312 ShowWindow(hwndPrev, SW_RESTORE);
313 SetForegroundWindow(hwndPrev);
317 if (GetTime() > nStart + 60)
320 // Resume this instance if the other exits
321 delete psingleinstancechecker;
323 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
324 if (!psingleinstancechecker->IsAnotherRunning())
330 // Make sure only a single bitcoin process is using the data directory.
331 string strLockFile = GetDataDir() + "/.lock";
332 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
333 if (file) fclose(file);
334 static boost::interprocess::file_lock lock(strLockFile.c_str());
335 if (!lock.try_lock())
337 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
341 // Bind to the port early so we can tell if another instance is already running.
345 if (!BindListenPort(strErrors))
347 wxMessageBox(strErrors, "Bitcoin");
356 fprintf(stdout, "bitcoin server starting\n");
360 printf("Loading addresses...\n");
361 nStart = GetTimeMillis();
362 if (!LoadAddresses())
363 strErrors += _("Error loading addr.dat \n");
364 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
366 printf("Loading block index...\n");
367 nStart = GetTimeMillis();
368 if (!LoadBlockIndex())
369 strErrors += _("Error loading blkindex.dat \n");
370 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
372 printf("Loading wallet...\n");
373 nStart = GetTimeMillis();
375 if (!LoadWallet(fFirstRun))
376 strErrors += _("Error loading wallet.dat \n");
377 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
379 CBlockIndex *pindexRescan = pindexBest;
380 if (GetBoolArg("-rescan"))
381 pindexRescan = pindexGenesisBlock;
385 CBlockLocator locator;
386 if (walletdb.ReadBestBlock(locator))
387 pindexRescan = locator.GetBlockIndex();
389 if (pindexBest != pindexRescan)
391 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
392 nStart = GetTimeMillis();
393 ScanForWalletTransactions(pindexRescan, true);
394 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
397 printf("Done loading\n");
400 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
401 printf("nBestHeight = %d\n", nBestHeight);
402 printf("mapKeys.size() = %d\n", mapKeys.size());
403 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
404 printf("mapWallet.size() = %d\n", mapWallet.size());
405 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
407 if (!strErrors.empty())
409 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
413 // Add wallet transactions that aren't already in a block to mapTransactions
414 ReacceptWalletTransactions();
419 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
425 if (mapArgs.count("-timeout"))
427 int nNewTimeout = GetArg("-timeout", 5000);
428 if (nNewTimeout > 0 && nNewTimeout < 600000)
429 nConnectTimeout = nNewTimeout;
432 if (mapArgs.count("-printblock"))
434 string strMatch = mapArgs["-printblock"];
436 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
438 uint256 hash = (*mi).first;
439 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
441 CBlockIndex* pindex = (*mi).second;
443 block.ReadFromDisk(pindex);
444 block.BuildMerkleTree();
451 printf("No blocks matching %s were found\n", strMatch.c_str());
455 fGenerateBitcoins = GetBoolArg("-gen");
457 if (mapArgs.count("-proxy"))
460 addrProxy = CAddress(mapArgs["-proxy"]);
461 if (!addrProxy.IsValid())
463 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
468 if (mapArgs.count("-addnode"))
470 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
472 CAddress addr(strAddr, fAllowDNS);
473 addr.nTime = 0; // so it won't relay unless successfully connected
479 if (mapArgs.count("-dnsseed"))
482 if (mapArgs.count("-paytxfee"))
484 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
486 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
489 if (nTransactionFee > 0.25 * COIN)
490 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
496 if (GetBoolArg("-noupnp"))
499 if (GetBoolArg("-upnp"))
505 // Create the main window and start the node
512 if (!CheckDiskSpace())
515 RandAddSeedPerfmon();
517 if (!CreateThread(StartNode, NULL))
518 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
521 CreateThread(ThreadRPCServer, NULL);
523 #if defined(__WXMSW__) && defined(GUI)
525 SetStartOnSystemStartup(true);