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>
15 #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
16 #define _BITCOIN_QT_PLUGINS_INCLUDED
19 Q_IMPORT_PLUGIN(qcncodecs)
20 Q_IMPORT_PLUGIN(qjpcodecs)
21 Q_IMPORT_PLUGIN(qtwcodecs)
22 Q_IMPORT_PLUGIN(qkrcodecs)
26 using namespace boost;
30 //////////////////////////////////////////////////////////////////////////////
35 void ExitTimeout(void* parg)
43 void Shutdown(void* parg)
45 static CCriticalSection cs_Shutdown;
47 bool fFirstThread = false;
48 TRY_CRITICAL_BLOCK(cs_Shutdown)
50 fFirstThread = !fTaken;
57 nTransactionsUpdated++;
61 boost::filesystem::remove(GetPidFile());
62 UnregisterWallet(pwalletMain);
64 CreateThread(ExitTimeout, NULL);
66 printf("Bitcoin exiting\n\n");
79 void HandleSIGTERM(int)
81 fRequestShutdown = true;
89 //////////////////////////////////////////////////////////////////////////////
94 int main(int argc, char* argv[])
97 fRet = AppInit(argc, argv);
106 bool AppInit(int argc, char* argv[])
111 fRet = AppInit2(argc, argv);
113 catch (std::exception& e) {
114 PrintException(&e, "AppInit()");
116 PrintException(NULL, "AppInit()");
123 bool AppInit2(int argc, char* argv[])
126 // Turn off microsoft heap dump noise
127 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
128 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
131 // Disable confusing "helpful" text message on abort, ctrl-c
132 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
138 // Clean shutdown on SIGTERM
140 sa.sa_handler = HandleSIGTERM;
141 sigemptyset(&sa.sa_mask);
143 sigaction(SIGTERM, &sa, NULL);
144 sigaction(SIGINT, &sa, NULL);
145 sigaction(SIGHUP, &sa, NULL);
151 ParseParameters(argc, argv);
153 if (mapArgs.count("-datadir"))
155 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
157 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
158 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
162 fprintf(stderr, "Error: Specified directory does not exist\n");
168 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
170 if (mapArgs.count("-?") || mapArgs.count("--help"))
172 string strUsage = string() +
173 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
174 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
175 " bitcoin [options] \t " + "\n" +
176 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
177 " bitcoin [options] help \t\t " + _("List commands\n") +
178 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
180 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
181 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
182 " -gen \t\t " + _("Generate coins\n") +
183 " -gen=0 \t\t " + _("Don't generate coins\n") +
184 " -min \t\t " + _("Start minimized\n") +
185 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
186 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
187 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
188 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
189 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
190 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
191 " -nolisten \t " + _("Don't accept connections from outside\n") +
192 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
193 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
196 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
198 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
201 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
203 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
206 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
208 " -testnet \t\t " + _("Use the test network\n") +
209 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
210 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
211 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
212 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
213 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
214 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
215 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
218 strUsage += string() +
219 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
220 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
221 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
222 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
223 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
226 strUsage += string() +
227 " -? \t\t " + _("This help message\n");
230 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
231 fprintf(stderr, "%s", strUsage.c_str());
235 fDebug = GetBoolArg("-debug");
236 fAllowDNS = GetBoolArg("-dns");
239 fDaemon = GetBoolArg("-daemon");
247 fServer = GetBoolArg("-server");
249 /* force fServer when running without GUI */
253 fPrintToConsole = GetBoolArg("-printtoconsole");
254 fPrintToDebugger = GetBoolArg("-printtodebugger");
256 fTestNet = GetBoolArg("-testnet");
257 bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
258 fNoListen = GetBoolArg("-nolisten") || fTOR;
259 fLogTimestamps = GetBoolArg("-logtimestamps");
262 for (int i = 1; i < argc; i++)
263 if (!IsSwitchChar(argv[i][0]))
268 int ret = CommandLineRPC(argc, argv);
280 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
285 CreatePidFile(GetPidFile(), pid);
289 pid_t sid = setsid();
291 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
295 if (!fDebug && !pszSetDataDir[0])
297 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
298 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
299 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
301 if (GetBoolArg("-loadblockindextest"))
304 txdb.LoadBlockIndex();
309 // Make sure only a single bitcoin process is using the data directory.
310 string strLockFile = GetDataDir() + "/.lock";
311 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
312 if (file) fclose(file);
313 static boost::interprocess::file_lock lock(strLockFile.c_str());
314 if (!lock.try_lock())
316 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
320 // Bind to the port early so we can tell if another instance is already running.
324 if (!BindListenPort(strErrors))
326 wxMessageBox(strErrors, "Bitcoin");
335 fprintf(stdout, "bitcoin server starting\n");
339 InitMessage(_("Loading addresses..."));
340 printf("Loading addresses...\n");
341 nStart = GetTimeMillis();
342 if (!LoadAddresses())
343 strErrors += _("Error loading addr.dat \n");
344 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
346 InitMessage(_("Loading block index..."));
347 printf("Loading block index...\n");
348 nStart = GetTimeMillis();
349 if (!LoadBlockIndex())
350 strErrors += _("Error loading blkindex.dat \n");
351 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
353 InitMessage(_("Loading wallet..."));
354 printf("Loading wallet...\n");
355 nStart = GetTimeMillis();
357 pwalletMain = new CWallet("wallet.dat");
358 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
359 if (nLoadWalletRet != DB_LOAD_OK)
361 if (nLoadWalletRet == DB_CORRUPT)
362 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
363 else if (nLoadWalletRet == DB_TOO_NEW)
364 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
365 else if (nLoadWalletRet == DB_NEED_REWRITE)
367 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
368 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
372 strErrors += _("Error loading wallet.dat \n");
374 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
376 RegisterWallet(pwalletMain);
378 CBlockIndex *pindexRescan = pindexBest;
379 if (GetBoolArg("-rescan"))
380 pindexRescan = pindexGenesisBlock;
383 CWalletDB walletdb("wallet.dat");
384 CBlockLocator locator;
385 if (walletdb.ReadBestBlock(locator))
386 pindexRescan = locator.GetBlockIndex();
388 if (pindexBest != pindexRescan)
390 InitMessage(_("Rescanning..."));
391 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
392 nStart = GetTimeMillis();
393 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
394 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
397 InitMessage(_("Done loading"));
398 printf("Done loading\n");
401 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
402 printf("nBestHeight = %d\n", nBestHeight);
403 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
404 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
405 printf("mapAddressBook.size() = %d\n", pwalletMain->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 pwalletMain->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 (GetBoolArg("-nodnsseed"))
480 printf("DNS seeding disabled\n");
484 if (mapArgs.count("-paytxfee"))
486 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
488 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
491 if (nTransactionFee > 0.25 * COIN)
492 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
498 if (GetBoolArg("-noupnp"))
501 if (GetBoolArg("-upnp"))
509 if (!CheckDiskSpace())
512 RandAddSeedPerfmon();
514 if (!CreateThread(StartNode, NULL))
515 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
518 CreateThread(ThreadRPCServer, NULL);