1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include "bitcoinrpc.h"
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
14 #include <boost/interprocess/sync/file_lock.hpp>
16 #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
17 #define _BITCOIN_QT_PLUGINS_INCLUDED
20 Q_IMPORT_PLUGIN(qcncodecs)
21 Q_IMPORT_PLUGIN(qjpcodecs)
22 Q_IMPORT_PLUGIN(qtwcodecs)
23 Q_IMPORT_PLUGIN(qkrcodecs)
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 #if !defined(PPCOIN_GENESIS)
96 int main(int argc, char* argv[])
99 fRet = AppInit(argc, argv);
109 bool AppInit(int argc, char* argv[])
114 fRet = AppInit2(argc, argv);
116 catch (std::exception& e) {
117 PrintException(&e, "AppInit()");
119 PrintException(NULL, "AppInit()");
126 bool AppInit2(int argc, char* argv[])
129 // Turn off microsoft heap dump noise
130 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
131 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
134 // Disable confusing "helpful" text message on abort, ctrl-c
135 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
141 // Clean shutdown on SIGTERM
143 sa.sa_handler = HandleSIGTERM;
144 sigemptyset(&sa.sa_mask);
146 sigaction(SIGTERM, &sa, NULL);
147 sigaction(SIGINT, &sa, NULL);
148 sigaction(SIGHUP, &sa, NULL);
154 ParseParameters(argc, argv);
156 if (mapArgs.count("-datadir"))
158 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
160 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
161 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
165 fprintf(stderr, "Error: Specified directory does not exist\n");
171 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
173 if (mapArgs.count("-?") || mapArgs.count("--help"))
175 string strUsage = string() +
176 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
177 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
178 " bitcoind [options] \t " + "\n" +
179 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
180 " bitcoind [options] help \t\t " + _("List commands\n") +
181 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
183 " -conf=<file> \t\t " + _("Specify configuration file (default: ppcoin.conf)\n") +
184 " -pid=<file> \t\t " + _("Specify pid file (default: ppcoind.pid)\n") +
185 " -gen \t\t " + _("Generate coins\n") +
186 " -gen=0 \t\t " + _("Don't generate coins\n") +
187 " -min \t\t " + _("Start minimized\n") +
188 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
189 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
190 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
191 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
192 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
193 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
194 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
195 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
196 " -nolisten \t " + _("Don't accept connections from outside\n") +
197 " -nodnsseed \t " + _("Don't bootstrap list of peers using DNS\n") +
198 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
199 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
200 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
201 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
204 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
206 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
209 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
211 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
214 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
216 " -testnet \t\t " + _("Use the test network\n") +
217 " -debug \t\t " + _("Output extra debugging information\n") +
218 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
219 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
221 " -printtodebugger \t " + _("Send trace/debug info to debugger\n") +
223 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
224 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
225 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
226 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
227 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
228 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
229 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
232 strUsage += string() +
233 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
234 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
235 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
236 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
237 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
240 strUsage += string() +
241 " -? \t\t " + _("This help message\n");
244 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
245 fprintf(stderr, "%s", strUsage.c_str());
249 fDebug = GetBoolArg("-debug");
250 fAllowDNS = GetBoolArg("-dns");
253 fDaemon = GetBoolArg("-daemon");
261 fServer = GetBoolArg("-server");
263 /* force fServer when running without GUI */
267 fPrintToConsole = GetBoolArg("-printtoconsole");
268 fPrintToDebugger = GetBoolArg("-printtodebugger");
270 fTestNet = GetBoolArg("-testnet");
271 bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
272 fNoListen = GetBoolArg("-nolisten") || fTOR;
273 fLogTimestamps = GetBoolArg("-logtimestamps");
276 for (int i = 1; i < argc; i++)
277 if (!IsSwitchChar(argv[i][0]))
282 int ret = CommandLineRPC(argc, argv);
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");
334 // Bind to the port early so we can tell if another instance is already running.
338 if (!BindListenPort(strErrors))
340 wxMessageBox(strErrors, "Bitcoin");
349 fprintf(stdout, "bitcoin server starting\n");
353 InitMessage(_("Loading addresses..."));
354 printf("Loading addresses...\n");
355 nStart = GetTimeMillis();
356 if (!LoadAddresses())
357 strErrors += _("Error loading addr.dat \n");
358 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
360 InitMessage(_("Loading block index..."));
361 printf("Loading block index...\n");
362 nStart = GetTimeMillis();
363 if (!LoadBlockIndex())
364 strErrors += _("Error loading blkindex.dat \n");
365 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
367 InitMessage(_("Loading wallet..."));
368 printf("Loading wallet...\n");
369 nStart = GetTimeMillis();
371 pwalletMain = new CWallet("wallet.dat");
372 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
373 if (nLoadWalletRet != DB_LOAD_OK)
375 if (nLoadWalletRet == DB_CORRUPT)
376 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
377 else if (nLoadWalletRet == DB_TOO_NEW)
378 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
379 else if (nLoadWalletRet == DB_NEED_REWRITE)
381 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
382 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
386 strErrors += _("Error loading wallet.dat \n");
388 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
390 RegisterWallet(pwalletMain);
392 CBlockIndex *pindexRescan = pindexBest;
393 if (GetBoolArg("-rescan"))
394 pindexRescan = pindexGenesisBlock;
397 CWalletDB walletdb("wallet.dat");
398 CBlockLocator locator;
399 if (walletdb.ReadBestBlock(locator))
400 pindexRescan = locator.GetBlockIndex();
402 if (pindexBest != pindexRescan)
404 InitMessage(_("Rescanning..."));
405 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
406 nStart = GetTimeMillis();
407 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
408 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
411 InitMessage(_("Done loading"));
412 printf("Done loading\n");
415 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
416 printf("nBestHeight = %d\n", nBestHeight);
417 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
418 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
419 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
421 if (!strErrors.empty())
423 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
427 // Add wallet transactions that aren't already in a block to mapTransactions
428 pwalletMain->ReacceptWalletTransactions();
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 if (mapArgs.count("-addnode"))
484 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
486 CAddress addr(strAddr, fAllowDNS);
487 addr.nTime = 0; // so it won't relay unless successfully connected
493 if (mapArgs.count("-paytxfee"))
495 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
497 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
500 if (nTransactionFee >= 10 * COIN)
501 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
507 if (GetBoolArg("-noupnp"))
510 if (GetBoolArg("-upnp"))
518 if (!CheckDiskSpace())
521 RandAddSeedPerfmon();
523 if (!CreateThread(StartNode, NULL))
524 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
527 CreateThread(ThreadRPCServer, NULL);