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");
70 // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
83 void HandleSIGTERM(int)
85 fRequestShutdown = true;
93 //////////////////////////////////////////////////////////////////////////////
98 int main(int argc, char* argv[])
101 fRet = AppInit(argc, argv);
110 bool AppInit(int argc, char* argv[])
115 fRet = AppInit2(argc, argv);
117 catch (std::exception& e) {
118 PrintException(&e, "AppInit()");
120 PrintException(NULL, "AppInit()");
127 bool AppInit2(int argc, char* argv[])
130 // Turn off microsoft heap dump noise
131 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
132 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
135 // Disable confusing "helpful" text message on abort, ctrl-c
136 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
142 // Clean shutdown on SIGTERM
144 sa.sa_handler = HandleSIGTERM;
145 sigemptyset(&sa.sa_mask);
147 sigaction(SIGTERM, &sa, NULL);
148 sigaction(SIGINT, &sa, NULL);
149 sigaction(SIGHUP, &sa, NULL);
155 ParseParameters(argc, argv);
157 if (mapArgs.count("-datadir"))
159 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
161 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
162 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
166 fprintf(stderr, "Error: Specified directory does not exist\n");
172 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
174 if (mapArgs.count("-?") || mapArgs.count("--help"))
176 string strUsage = string() +
177 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
178 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
179 " bitcoind [options] \t " + "\n" +
180 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
181 " bitcoind [options] help \t\t " + _("List commands\n") +
182 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
184 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
185 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
186 " -gen \t\t " + _("Generate coins\n") +
187 " -gen=0 \t\t " + _("Don't generate coins\n") +
188 " -min \t\t " + _("Start minimized\n") +
189 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
190 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
191 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
192 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
193 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
194 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
195 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
196 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
197 " -noirc \t " + _("Don't find peers using internet relay chat\n") +
198 " -nolisten \t " + _("Don't accept connections from outside\n") +
199 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS\n") +
200 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
201 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
202 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
203 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
206 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
208 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
211 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
213 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
215 #if !defined(WIN32) && !defined(QT_GUI)
216 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
218 " -testnet \t\t " + _("Use the test network\n") +
219 " -debug \t\t " + _("Output extra debugging information\n") +
220 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
221 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
223 " -printtodebugger \t " + _("Send trace/debug info to debugger\n") +
225 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
226 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
227 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
228 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
229 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
230 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
231 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
234 strUsage += string() +
235 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
236 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
237 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
238 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
239 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
242 strUsage += string() +
243 " -? \t\t " + _("This help message\n");
246 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
247 #if defined(QT_GUI) && defined(WIN32)
248 // On windows, show a message box, as there is no stderr
249 wxMessageBox(strUsage, "Usage");
251 fprintf(stderr, "%s", strUsage.c_str());
256 fTestNet = GetBoolArg("-testnet");
257 fDebug = GetBoolArg("-debug");
259 #if !defined(WIN32) && !defined(QT_GUI)
260 fDaemon = GetBoolArg("-daemon");
268 fServer = GetBoolArg("-server");
270 /* force fServer when running without GUI */
274 fPrintToConsole = GetBoolArg("-printtoconsole");
275 fPrintToDebugger = GetBoolArg("-printtodebugger");
276 fLogTimestamps = GetBoolArg("-logtimestamps");
279 for (int i = 1; i < argc; i++)
280 if (!IsSwitchChar(argv[i][0]))
285 int ret = CommandLineRPC(argc, argv);
290 #if !defined(WIN32) && !defined(QT_GUI)
297 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
302 CreatePidFile(GetPidFile(), pid);
306 pid_t sid = setsid();
308 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
312 if (!fDebug && !pszSetDataDir[0])
314 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
315 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
316 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
318 if (GetBoolArg("-loadblockindextest"))
321 txdb.LoadBlockIndex();
326 // Make sure only a single bitcoin process is using the data directory.
327 string strLockFile = GetDataDir() + "/.lock";
328 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
329 if (file) fclose(file);
330 static boost::interprocess::file_lock lock(strLockFile.c_str());
331 if (!lock.try_lock())
333 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
343 fprintf(stdout, "bitcoin server starting\n");
347 InitMessage(_("Loading addresses..."));
348 printf("Loading addresses...\n");
349 nStart = GetTimeMillis();
350 if (!LoadAddresses())
351 strErrors += _("Error loading addr.dat \n");
352 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
354 InitMessage(_("Loading block index..."));
355 printf("Loading block index...\n");
356 nStart = GetTimeMillis();
357 if (!LoadBlockIndex())
358 strErrors += _("Error loading blkindex.dat \n");
359 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
361 InitMessage(_("Loading wallet..."));
362 printf("Loading wallet...\n");
363 nStart = GetTimeMillis();
365 pwalletMain = new CWallet("wallet.dat");
366 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
367 if (nLoadWalletRet != DB_LOAD_OK)
369 if (nLoadWalletRet == DB_CORRUPT)
370 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
371 else if (nLoadWalletRet == DB_TOO_NEW)
372 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
373 else if (nLoadWalletRet == DB_NEED_REWRITE)
375 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
376 printf("%s", strErrors.c_str());
377 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
381 strErrors += _("Error loading wallet.dat \n");
383 printf("%s", strErrors.c_str());
384 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
386 RegisterWallet(pwalletMain);
388 CBlockIndex *pindexRescan = pindexBest;
389 if (GetBoolArg("-rescan"))
390 pindexRescan = pindexGenesisBlock;
393 CWalletDB walletdb("wallet.dat");
394 CBlockLocator locator;
395 if (walletdb.ReadBestBlock(locator))
396 pindexRescan = locator.GetBlockIndex();
398 if (pindexBest != pindexRescan)
400 InitMessage(_("Rescanning..."));
401 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
402 nStart = GetTimeMillis();
403 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
404 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
407 InitMessage(_("Done loading"));
408 printf("Done loading\n");
411 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
412 printf("nBestHeight = %d\n", nBestHeight);
413 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
414 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
415 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
417 if (!strErrors.empty())
419 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
423 // Add wallet transactions that aren't already in a block to mapTransactions
424 pwalletMain->ReacceptWalletTransactions();
426 // Note: Bitcoin-QT stores several settings in the wallet, so we want
427 // to load the wallet BEFORE parsing command-line arguments, so
428 // the command-line/bitcoin.conf settings override GUI setting.
433 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
439 if (mapArgs.count("-timeout"))
441 int nNewTimeout = GetArg("-timeout", 5000);
442 if (nNewTimeout > 0 && nNewTimeout < 600000)
443 nConnectTimeout = nNewTimeout;
446 if (mapArgs.count("-printblock"))
448 string strMatch = mapArgs["-printblock"];
450 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
452 uint256 hash = (*mi).first;
453 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
455 CBlockIndex* pindex = (*mi).second;
457 block.ReadFromDisk(pindex);
458 block.BuildMerkleTree();
465 printf("No blocks matching %s were found\n", strMatch.c_str());
469 fGenerateBitcoins = GetBoolArg("-gen");
471 if (mapArgs.count("-proxy"))
474 addrProxy = CAddress(mapArgs["-proxy"]);
475 if (!addrProxy.IsValid())
477 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
482 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
485 // Use SoftSetArg here so user can override any of these if they wish.
486 // Note: the GetBoolArg() calls for all of these must happen later.
487 SoftSetArg("-nolisten", true);
488 SoftSetArg("-noirc", true);
489 SoftSetArg("-nodnsseed", true);
490 SoftSetArg("-noupnp", true);
491 SoftSetArg("-upnp", false);
492 SoftSetArg("-dns", false);
495 fAllowDNS = GetBoolArg("-dns");
496 fNoListen = GetBoolArg("-nolisten");
498 // Command-line args override in-wallet settings:
499 if (mapArgs.count("-upnp"))
500 fUseUPnP = GetBoolArg("-upnp");
501 else if (mapArgs.count("-noupnp"))
502 fUseUPnP = !GetBoolArg("-noupnp");
506 if (!BindListenPort(strErrors))
508 wxMessageBox(strErrors, "Bitcoin");
513 if (mapArgs.count("-addnode"))
515 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
517 CAddress addr(strAddr, fAllowDNS);
518 addr.nTime = 0; // so it won't relay unless successfully connected
524 if (mapArgs.count("-paytxfee"))
526 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
528 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
531 if (nTransactionFee > 0.25 * COIN)
532 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
538 if (!CheckDiskSpace())
541 RandAddSeedPerfmon();
543 if (!CreateThread(StartNode, NULL))
544 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
547 CreateThread(ThreadRPCServer, NULL);