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 COPYING 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)
23 Q_IMPORT_PLUGIN(qtaccessiblewidgets)
27 using namespace boost;
31 //////////////////////////////////////////////////////////////////////////////
36 void ExitTimeout(void* parg)
44 void Shutdown(void* parg)
46 static CCriticalSection cs_Shutdown;
48 bool fFirstThread = false;
49 TRY_CRITICAL_BLOCK(cs_Shutdown)
51 fFirstThread = !fTaken;
58 nTransactionsUpdated++;
62 boost::filesystem::remove(GetPidFile());
63 UnregisterWallet(pwalletMain);
65 CreateThread(ExitTimeout, NULL);
67 printf("Bitcoin exiting\n\n");
80 void HandleSIGTERM(int)
82 fRequestShutdown = true;
90 //////////////////////////////////////////////////////////////////////////////
95 int main(int argc, char* argv[])
98 fRet = AppInit(argc, argv);
107 bool AppInit(int argc, char* argv[])
112 fRet = AppInit2(argc, argv);
114 catch (std::exception& e) {
115 PrintException(&e, "AppInit()");
117 PrintException(NULL, "AppInit()");
124 bool AppInit2(int argc, char* argv[])
127 // Turn off microsoft heap dump noise
128 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
129 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
132 // Disable confusing "helpful" text message on abort, ctrl-c
133 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
139 // Clean shutdown on SIGTERM
141 sa.sa_handler = HandleSIGTERM;
142 sigemptyset(&sa.sa_mask);
144 sigaction(SIGTERM, &sa, NULL);
145 sigaction(SIGINT, &sa, NULL);
146 sigaction(SIGHUP, &sa, NULL);
152 ParseParameters(argc, argv);
154 if (mapArgs.count("-datadir"))
156 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
158 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
159 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
163 fprintf(stderr, "Error: Specified directory does not exist\n");
169 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
171 if (mapArgs.count("-?") || mapArgs.count("--help"))
173 string strUsage = string() +
174 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
175 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
176 " bitcoind [options] \t " + "\n" +
177 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
178 " bitcoind [options] help \t\t " + _("List commands\n") +
179 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
181 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
182 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
183 " -gen \t\t " + _("Generate coins\n") +
184 " -gen=0 \t\t " + _("Don't generate coins\n") +
185 " -min \t\t " + _("Start minimized\n") +
186 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
187 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
188 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
189 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
190 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
191 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
192 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
193 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
194 " -noirc \t " + _("Don't find peers using internet relay chat\n") +
195 " -nolisten \t " + _("Don't accept connections from outside\n") +
196 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS\n") +
197 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
198 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
199 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
200 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
203 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
205 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
208 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
210 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
212 #if !defined(WIN32) && !defined(QT_GUI)
213 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
215 " -testnet \t\t " + _("Use the test network\n") +
216 " -debug \t\t " + _("Output extra debugging information\n") +
217 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
218 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
220 " -printtodebugger \t " + _("Send trace/debug info to debugger\n") +
222 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
223 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
224 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
225 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
226 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
227 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
228 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
231 strUsage += string() +
232 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
233 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
234 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
235 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
236 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
239 strUsage += string() +
240 " -? \t\t " + _("This help message\n");
243 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
244 #if defined(QT_GUI) && defined(WIN32)
245 // On windows, show a message box, as there is no stderr
246 wxMessageBox(strUsage, "Usage");
248 fprintf(stderr, "%s", strUsage.c_str());
253 fTestNet = GetBoolArg("-testnet");
254 fDebug = GetBoolArg("-debug");
256 #if !defined(WIN32) && !defined(QT_GUI)
257 fDaemon = GetBoolArg("-daemon");
265 fServer = GetBoolArg("-server");
267 /* force fServer when running without GUI */
271 fPrintToConsole = GetBoolArg("-printtoconsole");
272 fPrintToDebugger = GetBoolArg("-printtodebugger");
273 fLogTimestamps = GetBoolArg("-logtimestamps");
276 for (int i = 1; i < argc; i++)
277 if (!IsSwitchChar(argv[i][0]))
282 int ret = CommandLineRPC(argc, argv);
287 #if !defined(WIN32) && !defined(QT_GUI)
294 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
299 CreatePidFile(GetPidFile(), pid);
303 pid_t sid = setsid();
305 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
309 if (!fDebug && !pszSetDataDir[0])
311 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
312 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
313 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
315 if (GetBoolArg("-loadblockindextest"))
318 txdb.LoadBlockIndex();
323 // Make sure only a single bitcoin process is using the data directory.
324 string strLockFile = GetDataDir() + "/.lock";
325 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
326 if (file) fclose(file);
327 static boost::interprocess::file_lock lock(strLockFile.c_str());
328 if (!lock.try_lock())
330 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
340 fprintf(stdout, "bitcoin server starting\n");
344 InitMessage(_("Loading addresses..."));
345 printf("Loading addresses...\n");
346 nStart = GetTimeMillis();
347 if (!LoadAddresses())
348 strErrors += _("Error loading addr.dat \n");
349 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
351 InitMessage(_("Loading block index..."));
352 printf("Loading block index...\n");
353 nStart = GetTimeMillis();
354 if (!LoadBlockIndex())
355 strErrors += _("Error loading blkindex.dat \n");
356 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
358 InitMessage(_("Loading wallet..."));
359 printf("Loading wallet...\n");
360 nStart = GetTimeMillis();
362 pwalletMain = new CWallet("wallet.dat");
363 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
364 if (nLoadWalletRet != DB_LOAD_OK)
366 if (nLoadWalletRet == DB_CORRUPT)
367 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
368 else if (nLoadWalletRet == DB_TOO_NEW)
369 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
370 else if (nLoadWalletRet == DB_NEED_REWRITE)
372 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
373 printf("%s", strErrors.c_str());
374 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
378 strErrors += _("Error loading wallet.dat \n");
380 printf("%s", strErrors.c_str());
381 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
383 RegisterWallet(pwalletMain);
385 CBlockIndex *pindexRescan = pindexBest;
386 if (GetBoolArg("-rescan"))
387 pindexRescan = pindexGenesisBlock;
390 CWalletDB walletdb("wallet.dat");
391 CBlockLocator locator;
392 if (walletdb.ReadBestBlock(locator))
393 pindexRescan = locator.GetBlockIndex();
395 if (pindexBest != pindexRescan)
397 InitMessage(_("Rescanning..."));
398 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
399 nStart = GetTimeMillis();
400 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
401 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
404 InitMessage(_("Done loading"));
405 printf("Done loading\n");
408 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
409 printf("nBestHeight = %d\n", nBestHeight);
410 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
411 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
412 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
414 if (!strErrors.empty())
416 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
420 // Add wallet transactions that aren't already in a block to mapTransactions
421 pwalletMain->ReacceptWalletTransactions();
423 // Note: Bitcoin-QT stores several settings in the wallet, so we want
424 // to load the wallet BEFORE parsing command-line arguments, so
425 // the command-line/bitcoin.conf settings override GUI setting.
430 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
436 if (mapArgs.count("-timeout"))
438 int nNewTimeout = GetArg("-timeout", 5000);
439 if (nNewTimeout > 0 && nNewTimeout < 600000)
440 nConnectTimeout = nNewTimeout;
443 if (mapArgs.count("-printblock"))
445 string strMatch = mapArgs["-printblock"];
447 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
449 uint256 hash = (*mi).first;
450 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
452 CBlockIndex* pindex = (*mi).second;
454 block.ReadFromDisk(pindex);
455 block.BuildMerkleTree();
462 printf("No blocks matching %s were found\n", strMatch.c_str());
466 fGenerateBitcoins = GetBoolArg("-gen");
468 if (mapArgs.count("-proxy"))
471 addrProxy = CAddress(mapArgs["-proxy"]);
472 if (!addrProxy.IsValid())
474 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
479 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
482 // Use SoftSetArg here so user can override any of these if they wish.
483 // Note: the GetBoolArg() calls for all of these must happen later.
484 SoftSetArg("-nolisten", true);
485 SoftSetArg("-noirc", true);
486 SoftSetArg("-nodnsseed", true);
487 SoftSetArg("-noupnp", true);
488 SoftSetArg("-upnp", false);
489 SoftSetArg("-dns", false);
492 fAllowDNS = GetBoolArg("-dns");
493 fNoListen = GetBoolArg("-nolisten");
495 // Command-line args override in-wallet settings:
496 if (mapArgs.count("-upnp"))
497 fUseUPnP = GetBoolArg("-upnp");
498 else if (mapArgs.count("-noupnp"))
499 fUseUPnP = !GetBoolArg("-noupnp");
503 if (!BindListenPort(strErrors))
505 wxMessageBox(strErrors, "Bitcoin");
510 if (mapArgs.count("-addnode"))
512 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
514 CAddress addr(strAddr, fAllowDNS);
515 addr.nTime = 0; // so it won't relay unless successfully connected
521 if (mapArgs.count("-paytxfee"))
523 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
525 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
528 if (nTransactionFee > 0.25 * COIN)
529 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
535 if (!CheckDiskSpace())
538 RandAddSeedPerfmon();
540 if (!CreateThread(StartNode, NULL))
541 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
544 CreateThread(ThreadRPCServer, NULL);