1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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 " bitcoind [options] \t " + "\n" +
176 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
177 " bitcoind [options] help \t\t " + _("List commands\n") +
178 " bitcoind [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 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
190 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
191 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
192 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
193 " -noirc \t " + _("Don't find peers using internet relay chat\n") +
194 " -nolisten \t " + _("Don't accept connections from outside\n") +
195 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS\n") +
196 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
197 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
198 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
199 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
202 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
204 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
207 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
209 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
212 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
214 " -testnet \t\t " + _("Use the test network\n") +
215 " -debug \t\t " + _("Output extra debugging information\n") +
216 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
217 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
219 " -printtodebugger \t " + _("Send trace/debug info to debugger\n") +
221 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
222 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
223 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
224 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
225 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
226 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
227 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
230 strUsage += string() +
231 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
232 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
233 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
234 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
235 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
238 strUsage += string() +
239 " -? \t\t " + _("This help message\n");
242 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
243 fprintf(stderr, "%s", strUsage.c_str());
247 fTestNet = GetBoolArg("-testnet");
248 fDebug = GetBoolArg("-debug");
251 fDaemon = GetBoolArg("-daemon");
259 fServer = GetBoolArg("-server");
261 /* force fServer when running without GUI */
265 fPrintToConsole = GetBoolArg("-printtoconsole");
266 fPrintToDebugger = GetBoolArg("-printtodebugger");
267 fLogTimestamps = GetBoolArg("-logtimestamps");
270 for (int i = 1; i < argc; i++)
271 if (!IsSwitchChar(argv[i][0]))
276 int ret = CommandLineRPC(argc, argv);
288 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
293 CreatePidFile(GetPidFile(), pid);
297 pid_t sid = setsid();
299 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
303 if (!fDebug && !pszSetDataDir[0])
305 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
306 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
307 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
309 if (GetBoolArg("-loadblockindextest"))
312 txdb.LoadBlockIndex();
317 // Make sure only a single bitcoin process is using the data directory.
318 string strLockFile = GetDataDir() + "/.lock";
319 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
320 if (file) fclose(file);
321 static boost::interprocess::file_lock lock(strLockFile.c_str());
322 if (!lock.try_lock())
324 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
334 fprintf(stdout, "bitcoin server starting\n");
338 InitMessage(_("Loading addresses..."));
339 printf("Loading addresses...\n");
340 nStart = GetTimeMillis();
341 if (!LoadAddresses())
342 strErrors += _("Error loading addr.dat \n");
343 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
345 InitMessage(_("Loading block index..."));
346 printf("Loading block index...\n");
347 nStart = GetTimeMillis();
348 if (!LoadBlockIndex())
349 strErrors += _("Error loading blkindex.dat \n");
350 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
352 InitMessage(_("Loading wallet..."));
353 printf("Loading wallet...\n");
354 nStart = GetTimeMillis();
356 pwalletMain = new CWallet("wallet.dat");
357 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
358 if (nLoadWalletRet != DB_LOAD_OK)
360 if (nLoadWalletRet == DB_CORRUPT)
361 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
362 else if (nLoadWalletRet == DB_TOO_NEW)
363 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
364 else if (nLoadWalletRet == DB_NEED_REWRITE)
366 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
367 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
371 strErrors += _("Error loading wallet.dat \n");
373 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375 RegisterWallet(pwalletMain);
377 CBlockIndex *pindexRescan = pindexBest;
378 if (GetBoolArg("-rescan"))
379 pindexRescan = pindexGenesisBlock;
382 CWalletDB walletdb("wallet.dat");
383 CBlockLocator locator;
384 if (walletdb.ReadBestBlock(locator))
385 pindexRescan = locator.GetBlockIndex();
387 if (pindexBest != pindexRescan)
389 InitMessage(_("Rescanning..."));
390 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
391 nStart = GetTimeMillis();
392 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
393 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
396 InitMessage(_("Done loading"));
397 printf("Done loading\n");
400 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
401 printf("nBestHeight = %d\n", nBestHeight);
402 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
403 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
404 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
406 if (!strErrors.empty())
408 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
412 // Add wallet transactions that aren't already in a block to mapTransactions
413 pwalletMain->ReacceptWalletTransactions();
415 // Note: Bitcoin-QT stores several settings in the wallet, so we want
416 // to load the wallet BEFORE parsing command-line arguments, so
417 // the command-line/bitcoin.conf settings override GUI setting.
422 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
428 if (mapArgs.count("-timeout"))
430 int nNewTimeout = GetArg("-timeout", 5000);
431 if (nNewTimeout > 0 && nNewTimeout < 600000)
432 nConnectTimeout = nNewTimeout;
435 if (mapArgs.count("-printblock"))
437 string strMatch = mapArgs["-printblock"];
439 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
441 uint256 hash = (*mi).first;
442 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
444 CBlockIndex* pindex = (*mi).second;
446 block.ReadFromDisk(pindex);
447 block.BuildMerkleTree();
454 printf("No blocks matching %s were found\n", strMatch.c_str());
458 fGenerateBitcoins = GetBoolArg("-gen");
460 if (mapArgs.count("-proxy"))
463 addrProxy = CAddress(mapArgs["-proxy"]);
464 if (!addrProxy.IsValid())
466 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
471 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
474 // Use SoftSetArg here so user can override any of these if they wish.
475 // Note: the GetBoolArg() calls for all of these must happen later.
476 SoftSetArg("-nolisten", true);
477 SoftSetArg("-noirc", true);
478 SoftSetArg("-nodnsseed", true);
479 SoftSetArg("-noupnp", true);
480 SoftSetArg("-upnp", false);
481 SoftSetArg("-dns", false);
484 fAllowDNS = GetBoolArg("-dns");
485 fNoListen = GetBoolArg("-nolisten");
487 // Command-line args override in-wallet settings:
488 if (mapArgs.count("-upnp"))
489 fUseUPnP = GetBoolArg("-upnp");
490 else if (mapArgs.count("-noupnp"))
491 fUseUPnP = !GetBoolArg("-noupnp");
495 if (!BindListenPort(strErrors))
497 wxMessageBox(strErrors, "Bitcoin");
502 if (mapArgs.count("-addnode"))
504 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
506 CAddress addr(strAddr, fAllowDNS);
507 addr.nTime = 0; // so it won't relay unless successfully connected
513 if (mapArgs.count("-paytxfee"))
515 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
517 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
520 if (nTransactionFee > 0.25 * COIN)
521 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
527 if (!CheckDiskSpace())
530 RandAddSeedPerfmon();
532 if (!CreateThread(StartNode, NULL))
533 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
536 CreateThread(ThreadRPCServer, NULL);