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.
6 #include "bitcoinrpc.h"
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12 #include <boost/interprocess/sync/file_lock.hpp>
15 using namespace boost;
19 //////////////////////////////////////////////////////////////////////////////
24 void ExitTimeout(void* parg)
32 void Shutdown(void* parg)
34 static CCriticalSection cs_Shutdown;
37 CRITICAL_BLOCK(cs_Shutdown)
39 fFirstThread = !fTaken;
46 nTransactionsUpdated++;
50 boost::filesystem::remove(GetPidFile());
51 UnregisterWallet(pwalletMain);
53 CreateThread(ExitTimeout, NULL);
55 printf("Bitcoin exiting\n\n");
68 void HandleSIGTERM(int)
70 fRequestShutdown = true;
78 //////////////////////////////////////////////////////////////////////////////
82 #if !defined(QT_GUI) && !defined(GUI)
83 int main(int argc, char* argv[])
86 fRet = AppInit(argc, argv);
95 bool AppInit(int argc, char* argv[])
100 fRet = AppInit2(argc, argv);
102 catch (std::exception& e) {
103 PrintException(&e, "AppInit()");
105 PrintException(NULL, "AppInit()");
112 bool AppInit2(int argc, char* argv[])
115 // Turn off microsoft heap dump noise
116 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
117 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
120 // Disable confusing "helpful" text message on abort, ctrl-c
121 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
127 // Clean shutdown on SIGTERM
129 sa.sa_handler = HandleSIGTERM;
130 sigemptyset(&sa.sa_mask);
132 sigaction(SIGTERM, &sa, NULL);
133 sigaction(SIGINT, &sa, NULL);
134 sigaction(SIGHUP, &sa, NULL);
140 ParseParameters(argc, argv);
142 if (mapArgs.count("-datadir"))
144 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
146 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
147 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
151 fprintf(stderr, "Error: Specified directory does not exist\n");
157 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
159 if (mapArgs.count("-?") || mapArgs.count("--help"))
161 string strUsage = string() +
162 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
163 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
164 " bitcoin [options] \t " + "\n" +
165 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
166 " bitcoin [options] help \t\t " + _("List commands\n") +
167 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
169 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
170 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
171 " -gen \t\t " + _("Generate coins\n") +
172 " -gen=0 \t\t " + _("Don't generate coins\n") +
173 " -min \t\t " + _("Start minimized\n") +
174 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
175 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
176 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
177 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
178 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
179 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
180 " -nolisten \t " + _("Don't accept connections from outside\n") +
183 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
185 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
188 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
190 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
193 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
195 " -testnet \t\t " + _("Use the test network\n") +
196 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
197 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
198 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
199 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
200 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
201 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
202 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
205 strUsage += string() +
206 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
207 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
208 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
209 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
210 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
213 strUsage += string() +
214 " -? \t\t " + _("This help message\n");
216 #if defined(__WXMSW__) && defined(GUI)
217 // Tabs make the columns line up in the message box
218 wxMessageBox(strUsage, "Bitcoin", wxOK);
221 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
222 fprintf(stderr, "%s", strUsage.c_str());
227 fDebug = GetBoolArg("-debug");
228 fAllowDNS = GetBoolArg("-dns");
231 fDaemon = GetBoolArg("-daemon");
239 fServer = GetBoolArg("-server");
241 /* force fServer when running without GUI */
242 #if !defined(QT_GUI) && !defined(GUI)
245 fPrintToConsole = GetBoolArg("-printtoconsole");
246 fPrintToDebugger = GetBoolArg("-printtodebugger");
248 fTestNet = GetBoolArg("-testnet");
249 fNoListen = GetBoolArg("-nolisten");
250 fLogTimestamps = GetBoolArg("-logtimestamps");
252 for (int i = 1; i < argc; i++)
253 if (!IsSwitchChar(argv[i][0]))
258 int ret = CommandLineRPC(argc, argv);
269 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
274 CreatePidFile(GetPidFile(), pid);
278 pid_t sid = setsid();
280 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
284 if (!fDebug && !pszSetDataDir[0])
286 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
287 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
289 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
290 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
291 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
293 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
295 if (GetBoolArg("-loadblockindextest"))
298 txdb.LoadBlockIndex();
304 // Limit to single instance per user
305 // Required to protect the database files if we're going to keep deleting log.*
307 #if defined(__WXMSW__) && defined(GUI)
308 // wxSingleInstanceChecker doesn't work on Linux
309 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
310 for (int i = 0; i < strMutexName.size(); i++)
311 if (!isalnum(strMutexName[i]))
312 strMutexName[i] = '.';
313 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
314 if (psingleinstancechecker->IsAnotherRunning())
316 printf("Existing instance found\n");
317 unsigned int nStart = GetTime();
320 // Show the previous instance and exit
321 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
324 if (IsIconic(hwndPrev))
325 ShowWindow(hwndPrev, SW_RESTORE);
326 SetForegroundWindow(hwndPrev);
330 if (GetTime() > nStart + 60)
333 // Resume this instance if the other exits
334 delete psingleinstancechecker;
336 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
337 if (!psingleinstancechecker->IsAnotherRunning())
343 // Make sure only a single bitcoin process is using the data directory.
344 string strLockFile = GetDataDir() + "/.lock";
345 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
346 if (file) fclose(file);
347 static boost::interprocess::file_lock lock(strLockFile.c_str());
348 if (!lock.try_lock())
350 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
354 // Bind to the port early so we can tell if another instance is already running.
358 if (!BindListenPort(strErrors))
360 wxMessageBox(strErrors, "Bitcoin");
369 fprintf(stdout, "bitcoin server starting\n");
373 printf("Loading addresses...\n");
374 nStart = GetTimeMillis();
375 if (!LoadAddresses())
376 strErrors += _("Error loading addr.dat \n");
377 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
379 printf("Loading block index...\n");
380 nStart = GetTimeMillis();
381 if (!LoadBlockIndex())
382 strErrors += _("Error loading blkindex.dat \n");
383 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
385 printf("Loading wallet...\n");
386 nStart = GetTimeMillis();
388 pwalletMain = new CWallet("wallet.dat");
389 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
390 if (nLoadWalletRet != DB_LOAD_OK)
392 if (nLoadWalletRet == DB_CORRUPT)
393 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
394 else if (nLoadWalletRet == DB_TOO_NEW)
395 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
397 strErrors += _("Error loading wallet.dat \n");
399 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
401 RegisterWallet(pwalletMain);
403 CBlockIndex *pindexRescan = pindexBest;
404 if (GetBoolArg("-rescan"))
405 pindexRescan = pindexGenesisBlock;
408 CWalletDB walletdb("wallet.dat");
409 CBlockLocator locator;
410 if (walletdb.ReadBestBlock(locator))
411 pindexRescan = locator.GetBlockIndex();
413 if (pindexBest != pindexRescan)
415 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
416 nStart = GetTimeMillis();
417 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
418 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
421 printf("Done loading\n");
424 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
425 printf("nBestHeight = %d\n", nBestHeight);
426 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
427 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
428 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
430 if (!strErrors.empty())
432 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
436 // Add wallet transactions that aren't already in a block to mapTransactions
437 pwalletMain->ReacceptWalletTransactions();
442 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
448 if (mapArgs.count("-timeout"))
450 int nNewTimeout = GetArg("-timeout", 5000);
451 if (nNewTimeout > 0 && nNewTimeout < 600000)
452 nConnectTimeout = nNewTimeout;
455 if (mapArgs.count("-printblock"))
457 string strMatch = mapArgs["-printblock"];
459 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
461 uint256 hash = (*mi).first;
462 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
464 CBlockIndex* pindex = (*mi).second;
466 block.ReadFromDisk(pindex);
467 block.BuildMerkleTree();
474 printf("No blocks matching %s were found\n", strMatch.c_str());
478 fGenerateBitcoins = GetBoolArg("-gen");
480 if (mapArgs.count("-proxy"))
483 addrProxy = CAddress(mapArgs["-proxy"]);
484 if (!addrProxy.IsValid())
486 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
491 if (mapArgs.count("-addnode"))
493 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
495 CAddress addr(strAddr, fAllowDNS);
496 addr.nTime = 0; // so it won't relay unless successfully connected
502 if (GetBoolArg("-nodnsseed"))
503 printf("DNS seeding disabled\n");
507 if (mapArgs.count("-paytxfee"))
509 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
511 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
514 if (nTransactionFee > 0.25 * COIN)
515 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
521 if (GetBoolArg("-noupnp"))
524 if (GetBoolArg("-upnp"))
530 // Create the main window and start the node
537 if (!CheckDiskSpace())
540 RandAddSeedPerfmon();
542 if (!CreateThread(StartNode, NULL))
543 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
546 CreateThread(ThreadRPCServer, NULL);
548 #if defined(__WXMSW__) && defined(GUI)
550 SetStartOnSystemStartup(true);
553 #if !defined(QT_GUI) && !defined(GUI)