1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include "bitcoinrpc.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/interprocess/sync/file_lock.hpp>
16 using namespace boost;
20 //////////////////////////////////////////////////////////////////////////////
25 void ExitTimeout(void* parg)
33 void Shutdown(void* parg)
35 static CCriticalSection cs_Shutdown;
38 CRITICAL_BLOCK(cs_Shutdown)
40 fFirstThread = !fTaken;
47 nTransactionsUpdated++;
51 boost::filesystem::remove(GetPidFile());
52 UnregisterWallet(pwalletMain);
54 CreateThread(ExitTimeout, NULL);
56 printf("Bitcoin exiting\n\n");
69 void HandleSIGTERM(int)
71 fRequestShutdown = true;
79 //////////////////////////////////////////////////////////////////////////////
84 int main(int argc, char* argv[])
87 fRet = AppInit(argc, argv);
96 bool AppInit(int argc, char* argv[])
101 fRet = AppInit2(argc, argv);
103 catch (std::exception& e) {
104 PrintException(&e, "AppInit()");
106 PrintException(NULL, "AppInit()");
113 bool AppInit2(int argc, char* argv[])
116 // Turn off microsoft heap dump noise
117 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
118 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
121 // Disable confusing "helpful" text message on abort, ctrl-c
122 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
128 // Clean shutdown on SIGTERM
130 sa.sa_handler = HandleSIGTERM;
131 sigemptyset(&sa.sa_mask);
133 sigaction(SIGTERM, &sa, NULL);
134 sigaction(SIGINT, &sa, NULL);
135 sigaction(SIGHUP, &sa, NULL);
141 ParseParameters(argc, argv);
143 if (mapArgs.count("-datadir"))
145 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
147 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
148 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
152 fprintf(stderr, "Error: Specified directory does not exist\n");
158 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
160 if (mapArgs.count("-?") || mapArgs.count("--help"))
162 string strUsage = string() +
163 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
164 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
165 " bitcoin [options] \t " + "\n" +
166 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
167 " bitcoin [options] help \t\t " + _("List commands\n") +
168 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
170 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
171 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
172 " -gen \t\t " + _("Generate coins\n") +
173 " -gen=0 \t\t " + _("Don't generate coins\n") +
174 " -min \t\t " + _("Start minimized\n") +
175 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
176 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
177 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
178 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
179 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
180 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
181 " -nolisten \t " + _("Don't accept connections from outside\n") +
182 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
183 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
186 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
188 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
191 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
193 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
196 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
198 " -testnet \t\t " + _("Use the test network\n") +
199 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
200 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
201 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
202 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
203 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
204 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
205 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
208 strUsage += string() +
209 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
210 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
211 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
212 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
213 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
216 strUsage += string() +
217 " -? \t\t " + _("This help message\n");
220 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
221 fprintf(stderr, "%s", strUsage.c_str());
225 fDebug = GetBoolArg("-debug");
226 fAllowDNS = GetBoolArg("-dns");
229 fDaemon = GetBoolArg("-daemon");
237 fServer = GetBoolArg("-server");
239 /* force fServer when running without GUI */
243 fPrintToConsole = GetBoolArg("-printtoconsole");
244 fPrintToDebugger = GetBoolArg("-printtodebugger");
246 fTestNet = GetBoolArg("-testnet");
247 bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
248 fNoListen = GetBoolArg("-nolisten") || fTOR;
249 fLogTimestamps = GetBoolArg("-logtimestamps");
252 for (int i = 1; i < argc; i++)
253 if (!IsSwitchChar(argv[i][0]))
258 int ret = CommandLineRPC(argc, argv);
270 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
275 CreatePidFile(GetPidFile(), pid);
279 pid_t sid = setsid();
281 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
285 if (!fDebug && !pszSetDataDir[0])
287 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
288 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
289 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
291 if (GetBoolArg("-loadblockindextest"))
294 txdb.LoadBlockIndex();
299 // Make sure only a single bitcoin process is using the data directory.
300 string strLockFile = GetDataDir() + "/.lock";
301 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
302 if (file) fclose(file);
303 static boost::interprocess::file_lock lock(strLockFile.c_str());
304 if (!lock.try_lock())
306 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
310 // Bind to the port early so we can tell if another instance is already running.
314 if (!BindListenPort(strErrors))
316 wxMessageBox(strErrors, "Bitcoin");
325 fprintf(stdout, "bitcoin server starting\n");
329 InitMessage(_("Loading addresses..."));
330 printf("Loading addresses...\n");
331 nStart = GetTimeMillis();
332 if (!LoadAddresses())
333 strErrors += _("Error loading addr.dat \n");
334 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
336 InitMessage(_("Loading block index..."));
337 printf("Loading block index...\n");
338 nStart = GetTimeMillis();
339 if (!LoadBlockIndex())
340 strErrors += _("Error loading blkindex.dat \n");
341 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
343 InitMessage(_("Loading wallet..."));
344 printf("Loading wallet...\n");
345 nStart = GetTimeMillis();
347 pwalletMain = new CWallet("wallet.dat");
348 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
349 if (nLoadWalletRet != DB_LOAD_OK)
351 if (nLoadWalletRet == DB_CORRUPT)
352 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
353 else if (nLoadWalletRet == DB_TOO_NEW)
354 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
356 strErrors += _("Error loading wallet.dat \n");
358 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
360 RegisterWallet(pwalletMain);
362 CBlockIndex *pindexRescan = pindexBest;
363 if (GetBoolArg("-rescan"))
364 pindexRescan = pindexGenesisBlock;
367 CWalletDB walletdb("wallet.dat");
368 CBlockLocator locator;
369 if (walletdb.ReadBestBlock(locator))
370 pindexRescan = locator.GetBlockIndex();
372 if (pindexBest != pindexRescan)
374 InitMessage(_("Rescanning..."));
375 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
376 nStart = GetTimeMillis();
377 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
378 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
381 InitMessage(_("Done loading"));
382 printf("Done loading\n");
385 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
386 printf("nBestHeight = %d\n", nBestHeight);
387 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
388 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
389 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
391 if (!strErrors.empty())
393 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
397 // Add wallet transactions that aren't already in a block to mapTransactions
398 pwalletMain->ReacceptWalletTransactions();
403 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
409 if (mapArgs.count("-timeout"))
411 int nNewTimeout = GetArg("-timeout", 5000);
412 if (nNewTimeout > 0 && nNewTimeout < 600000)
413 nConnectTimeout = nNewTimeout;
416 if (mapArgs.count("-printblock"))
418 string strMatch = mapArgs["-printblock"];
420 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
422 uint256 hash = (*mi).first;
423 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
425 CBlockIndex* pindex = (*mi).second;
427 block.ReadFromDisk(pindex);
428 block.BuildMerkleTree();
435 printf("No blocks matching %s were found\n", strMatch.c_str());
439 fGenerateBitcoins = GetBoolArg("-gen");
441 if (mapArgs.count("-proxy"))
444 addrProxy = CAddress(mapArgs["-proxy"]);
445 if (!addrProxy.IsValid())
447 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
452 if (mapArgs.count("-addnode"))
454 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
456 CAddress addr(strAddr, fAllowDNS);
457 addr.nTime = 0; // so it won't relay unless successfully connected
463 if (GetBoolArg("-nodnsseed"))
464 printf("DNS seeding disabled\n");
468 if (mapArgs.count("-paytxfee"))
470 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
472 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
475 if (nTransactionFee > 0.25 * COIN)
476 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
482 if (GetBoolArg("-noupnp"))
485 if (GetBoolArg("-upnp"))
493 if (!CheckDiskSpace())
496 RandAddSeedPerfmon();
498 if (!CreateThread(StartNode, NULL))
499 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
502 CreateThread(ThreadRPCServer, NULL);