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)
47 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
50 // Without UI, Shutdown() can simply be started in a new thread
51 CreateThread(Shutdown, NULL);
55 void Shutdown(void* parg)
57 static CCriticalSection cs_Shutdown;
59 bool fFirstThread = false;
60 TRY_CRITICAL_BLOCK(cs_Shutdown)
62 fFirstThread = !fTaken;
69 nTransactionsUpdated++;
73 boost::filesystem::remove(GetPidFile());
74 UnregisterWallet(pwalletMain);
76 CreateThread(ExitTimeout, NULL);
78 printf("Bitcoin exiting\n\n");
81 // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
94 void HandleSIGTERM(int)
96 fRequestShutdown = true;
104 //////////////////////////////////////////////////////////////////////////////
109 int main(int argc, char* argv[])
112 fRet = AppInit(argc, argv);
121 bool AppInit(int argc, char* argv[])
126 fRet = AppInit2(argc, argv);
128 catch (std::exception& e) {
129 PrintException(&e, "AppInit()");
131 PrintException(NULL, "AppInit()");
138 bool AppInit2(int argc, char* argv[])
141 // Turn off microsoft heap dump noise
142 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
143 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
146 // Disable confusing "helpful" text message on abort, ctrl-c
147 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
153 // Clean shutdown on SIGTERM
155 sa.sa_handler = HandleSIGTERM;
156 sigemptyset(&sa.sa_mask);
158 sigaction(SIGTERM, &sa, NULL);
159 sigaction(SIGINT, &sa, NULL);
160 sigaction(SIGHUP, &sa, NULL);
166 ParseParameters(argc, argv);
168 if (mapArgs.count("-datadir"))
170 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
172 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
173 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
177 fprintf(stderr, "Error: Specified directory does not exist\n");
183 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
185 if (mapArgs.count("-?") || mapArgs.count("--help"))
187 string strUsage = string() +
188 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
189 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
190 " bitcoind [options] \t " + "\n" +
191 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
192 " bitcoind [options] help \t\t " + _("List commands\n") +
193 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
195 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
196 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
197 " -gen \t\t " + _("Generate coins\n") +
198 " -gen=0 \t\t " + _("Don't generate coins\n") +
199 " -min \t\t " + _("Start minimized\n") +
200 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
201 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
202 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
203 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
204 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
205 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
206 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
207 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
208 " -noirc \t " + _("Don't find peers using internet relay chat\n") +
209 " -nolisten \t " + _("Don't accept connections from outside\n") +
210 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS\n") +
211 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
212 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
213 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
214 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
217 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
219 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
222 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
224 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
226 #if !defined(WIN32) && !defined(QT_GUI)
227 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
229 " -testnet \t\t " + _("Use the test network\n") +
230 " -debug \t\t " + _("Output extra debugging information\n") +
231 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
232 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
234 " -printtodebugger \t " + _("Send trace/debug info to debugger\n") +
236 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
237 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
238 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
239 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
240 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
241 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
242 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
245 strUsage += string() +
246 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
247 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
248 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
249 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
250 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
253 strUsage += string() +
254 " -? \t\t " + _("This help message\n");
257 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
258 #if defined(QT_GUI) && defined(WIN32)
259 // On windows, show a message box, as there is no stderr
260 wxMessageBox(strUsage, "Usage");
262 fprintf(stderr, "%s", strUsage.c_str());
267 fTestNet = GetBoolArg("-testnet");
268 fDebug = GetBoolArg("-debug");
270 #if !defined(WIN32) && !defined(QT_GUI)
271 fDaemon = GetBoolArg("-daemon");
279 fServer = GetBoolArg("-server");
281 /* force fServer when running without GUI */
285 fPrintToConsole = GetBoolArg("-printtoconsole");
286 fPrintToDebugger = GetBoolArg("-printtodebugger");
287 fLogTimestamps = GetBoolArg("-logtimestamps");
290 for (int i = 1; i < argc; i++)
291 if (!IsSwitchChar(argv[i][0]))
296 int ret = CommandLineRPC(argc, argv);
301 #if !defined(WIN32) && !defined(QT_GUI)
308 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
313 CreatePidFile(GetPidFile(), pid);
317 pid_t sid = setsid();
319 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
323 if (!fDebug && !pszSetDataDir[0])
325 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
326 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
327 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
329 if (GetBoolArg("-loadblockindextest"))
332 txdb.LoadBlockIndex();
337 // Make sure only a single bitcoin process is using the data directory.
338 string strLockFile = GetDataDir() + "/.lock";
339 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
340 if (file) fclose(file);
341 static boost::interprocess::file_lock lock(strLockFile.c_str());
342 if (!lock.try_lock())
344 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
354 fprintf(stdout, "bitcoin server starting\n");
358 InitMessage(_("Loading addresses..."));
359 printf("Loading addresses...\n");
360 nStart = GetTimeMillis();
361 if (!LoadAddresses())
362 strErrors += _("Error loading addr.dat \n");
363 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
365 InitMessage(_("Loading block index..."));
366 printf("Loading block index...\n");
367 nStart = GetTimeMillis();
368 if (!LoadBlockIndex())
369 strErrors += _("Error loading blkindex.dat \n");
370 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
372 InitMessage(_("Loading wallet..."));
373 printf("Loading wallet...\n");
374 nStart = GetTimeMillis();
376 pwalletMain = new CWallet("wallet.dat");
377 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
378 if (nLoadWalletRet != DB_LOAD_OK)
380 if (nLoadWalletRet == DB_CORRUPT)
381 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
382 else if (nLoadWalletRet == DB_TOO_NEW)
383 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
384 else if (nLoadWalletRet == DB_NEED_REWRITE)
386 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
387 printf("%s", strErrors.c_str());
388 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
392 strErrors += _("Error loading wallet.dat \n");
394 printf("%s", strErrors.c_str());
395 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
397 RegisterWallet(pwalletMain);
399 CBlockIndex *pindexRescan = pindexBest;
400 if (GetBoolArg("-rescan"))
401 pindexRescan = pindexGenesisBlock;
404 CWalletDB walletdb("wallet.dat");
405 CBlockLocator locator;
406 if (walletdb.ReadBestBlock(locator))
407 pindexRescan = locator.GetBlockIndex();
409 if (pindexBest != pindexRescan)
411 InitMessage(_("Rescanning..."));
412 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
413 nStart = GetTimeMillis();
414 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
415 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
418 InitMessage(_("Done loading"));
419 printf("Done loading\n");
422 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
423 printf("nBestHeight = %d\n", nBestHeight);
424 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
425 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
426 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
428 if (!strErrors.empty())
430 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
434 // Add wallet transactions that aren't already in a block to mapTransactions
435 pwalletMain->ReacceptWalletTransactions();
437 // Note: Bitcoin-QT stores several settings in the wallet, so we want
438 // to load the wallet BEFORE parsing command-line arguments, so
439 // the command-line/bitcoin.conf settings override GUI setting.
444 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
450 if (mapArgs.count("-timeout"))
452 int nNewTimeout = GetArg("-timeout", 5000);
453 if (nNewTimeout > 0 && nNewTimeout < 600000)
454 nConnectTimeout = nNewTimeout;
457 if (mapArgs.count("-printblock"))
459 string strMatch = mapArgs["-printblock"];
461 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
463 uint256 hash = (*mi).first;
464 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
466 CBlockIndex* pindex = (*mi).second;
468 block.ReadFromDisk(pindex);
469 block.BuildMerkleTree();
476 printf("No blocks matching %s were found\n", strMatch.c_str());
480 fGenerateBitcoins = GetBoolArg("-gen");
482 if (mapArgs.count("-proxy"))
485 addrProxy = CAddress(mapArgs["-proxy"]);
486 if (!addrProxy.IsValid())
488 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
493 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
496 // Use SoftSetArg here so user can override any of these if they wish.
497 // Note: the GetBoolArg() calls for all of these must happen later.
498 SoftSetArg("-nolisten", true);
499 SoftSetArg("-noirc", true);
500 SoftSetArg("-nodnsseed", true);
501 SoftSetArg("-noupnp", true);
502 SoftSetArg("-upnp", false);
503 SoftSetArg("-dns", false);
506 fAllowDNS = GetBoolArg("-dns");
507 fNoListen = GetBoolArg("-nolisten");
509 // Command-line args override in-wallet settings:
510 if (mapArgs.count("-upnp"))
511 fUseUPnP = GetBoolArg("-upnp");
512 else if (mapArgs.count("-noupnp"))
513 fUseUPnP = !GetBoolArg("-noupnp");
517 if (!BindListenPort(strErrors))
519 wxMessageBox(strErrors, "Bitcoin");
524 if (mapArgs.count("-addnode"))
526 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
528 CAddress addr(strAddr, fAllowDNS);
529 addr.nTime = 0; // so it won't relay unless successfully connected
535 if (mapArgs.count("-paytxfee"))
537 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
539 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
542 if (nTransactionFee > 0.25 * COIN)
543 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
549 if (!CheckDiskSpace())
552 RandAddSeedPerfmon();
554 if (!CreateThread(StartNode, NULL))
555 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
558 CreateThread(ThreadRPCServer, NULL);