1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include "bitcoinrpc.h"
12 #include "ui_interface.h"
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
15 #include <boost/filesystem/convenience.hpp>
16 #include <boost/interprocess/sync/file_lock.hpp>
23 using namespace boost;
27 //////////////////////////////////////////////////////////////////////////////
32 void ExitTimeout(void* parg)
43 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
46 // Without UI, Shutdown() can simply be started in a new thread
47 CreateThread(Shutdown, NULL);
51 void Shutdown(void* parg)
53 static CCriticalSection cs_Shutdown;
55 bool fFirstThread = false;
57 TRY_LOCK(cs_Shutdown, lockShutdown);
60 fFirstThread = !fTaken;
68 nTransactionsUpdated++;
72 boost::filesystem::remove(GetPidFile());
73 UnregisterWallet(pwalletMain);
75 CreateThread(ExitTimeout, NULL);
77 printf("PPCoin exiting\n\n");
80 // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
93 void HandleSIGTERM(int)
95 fRequestShutdown = true;
103 //////////////////////////////////////////////////////////////////////////////
108 #if !defined(PPCOIN_GENESIS)
109 int main(int argc, char* argv[])
112 fRet = AppInit(argc, argv);
122 bool AppInit(int argc, char* argv[])
127 fRet = AppInit2(argc, argv);
129 catch (std::exception& e) {
130 PrintException(&e, "AppInit()");
132 PrintException(NULL, "AppInit()");
139 bool AppInit2(int argc, char* argv[])
142 // Turn off microsoft heap dump noise
143 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
144 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
147 // Disable confusing "helpful" text message on abort, ctrl-c
148 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
154 // Clean shutdown on SIGTERM
156 sa.sa_handler = HandleSIGTERM;
157 sigemptyset(&sa.sa_mask);
159 sigaction(SIGTERM, &sa, NULL);
160 sigaction(SIGINT, &sa, NULL);
161 sigaction(SIGHUP, &sa, NULL);
167 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
169 ParseParameters(argc, argv);
170 if (!boost::filesystem::is_directory(GetDataDir(false)))
172 fprintf(stderr, "Error: Specified directory does not exist\n");
175 ReadConfigFile(mapArgs, mapMultiArgs);
178 if (mapArgs.count("-?") || mapArgs.count("--help"))
180 string strUsage = string() +
181 _("PPCoin version") + " " + FormatFullVersion() + "\n\n" +
182 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
183 " ppcoind [options] \t " + "\n" +
184 " ppcoind [options] <command> [params]\t " + _("Send command to -server or ppcoind") + "\n" +
185 " ppcoind [options] help \t\t " + _("List commands") + "\n" +
186 " ppcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
187 _("Options:") + "\n" +
188 " -conf=<file> \t\t " + _("Specify configuration file (default: ppcoin.conf)") + "\n" +
189 " -pid=<file> \t\t " + _("Specify pid file (default: ppcoind.pid)") + "\n" +
190 " -gen \t\t " + _("Generate coins") + "\n" +
191 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
192 " -min \t\t " + _("Start minimized") + "\n" +
193 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
194 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
195 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
196 " -dblogsize=<n> \t\t " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
197 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
198 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
199 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
200 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 9901 or testnet: 9903)") + "\n" +
201 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
202 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
203 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
204 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
206 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
208 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
209 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
210 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
211 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
212 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
215 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
217 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
219 " -detachdb \t " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
221 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
223 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
225 #if !defined(WIN32) && !defined(QT_GUI)
226 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
228 " -testnet \t\t " + _("Use the test network") + "\n" +
229 " -debug \t\t " + _("Output extra debugging information") + "\n" +
230 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
231 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
233 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
235 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
236 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
237 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 9902)") + "\n" +
238 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
239 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
240 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
241 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
242 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
243 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
244 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
245 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
247 strUsage += string() +
248 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
249 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
250 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
251 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
252 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
254 strUsage += string() +
255 " -? \t\t " + _("This help message") + "\n";
258 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
259 #if defined(QT_GUI) && defined(WIN32)
260 // On windows, show a message box, as there is no stderr
261 ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
263 fprintf(stderr, "%s", strUsage.c_str());
268 fTestNet = GetBoolArg("-testnet");
271 SoftSetBoolArg("-irc", true);
274 fDebug = GetBoolArg("-debug");
275 fDetachDB = GetBoolArg("-detachdb", false);
277 #if !defined(WIN32) && !defined(QT_GUI)
278 fDaemon = GetBoolArg("-daemon");
286 fServer = GetBoolArg("-server");
288 /* force fServer when running without GUI */
292 fPrintToConsole = GetBoolArg("-printtoconsole");
293 fPrintToDebugger = GetBoolArg("-printtodebugger");
294 fLogTimestamps = GetBoolArg("-logtimestamps");
297 for (int i = 1; i < argc; i++)
298 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
303 int ret = CommandLineRPC(argc, argv);
308 #if !defined(WIN32) && !defined(QT_GUI)
315 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
320 CreatePidFile(GetPidFile(), pid);
324 pid_t sid = setsid();
326 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
332 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
333 printf("PPCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
334 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
336 if (GetBoolArg("-loadblockindextest"))
339 txdb.LoadBlockIndex();
344 // Make sure only a single bitcoin process is using the data directory.
345 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
346 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
347 if (file) fclose(file);
348 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
349 if (!lock.try_lock())
351 ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. PPCoin is probably already running."), GetDataDir().string().c_str()), _("PPCoin"), wxOK|wxMODAL);
355 std::ostringstream strErrors;
360 fprintf(stdout, "ppcoin server starting\n");
363 InitMessage(_("Loading addresses..."));
364 printf("Loading addresses...\n");
365 nStart = GetTimeMillis();
366 if (!LoadAddresses())
367 strErrors << _("Error loading addr.dat") << "\n";
368 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
370 InitMessage(_("Loading block index..."));
371 printf("Loading block index...\n");
372 nStart = GetTimeMillis();
373 if (!LoadBlockIndex())
374 strErrors << _("Error loading blkindex.dat") << "\n";
376 // as LoadBlockIndex can take several minutes, it's possible the user
377 // requested to kill bitcoin-qt during the last operation. If so, exit.
378 // As the program has not fully started yet, Shutdown() is possibly overkill.
379 if (fRequestShutdown)
381 printf("Shutdown requested. Exiting.\n");
384 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
386 InitMessage(_("Loading wallet..."));
387 printf("Loading wallet...\n");
388 nStart = GetTimeMillis();
390 pwalletMain = new CWallet("wallet.dat");
391 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
392 if (nLoadWalletRet != DB_LOAD_OK)
394 if (nLoadWalletRet == DB_CORRUPT)
395 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
396 else if (nLoadWalletRet == DB_TOO_NEW)
397 strErrors << _("Error loading wallet.dat: Wallet requires newer version of PPCoin") << "\n";
398 else if (nLoadWalletRet == DB_NEED_REWRITE)
400 strErrors << _("Wallet needed to be rewritten: restart PPCoin to complete") << "\n";
401 printf("%s", strErrors.str().c_str());
402 ThreadSafeMessageBox(strErrors.str(), _("PPCoin"), wxOK | wxICON_ERROR | wxMODAL);
406 strErrors << _("Error loading wallet.dat") << "\n";
409 if (GetBoolArg("-upgradewallet", fFirstRun))
411 int nMaxVersion = GetArg("-upgradewallet", 0);
412 if (nMaxVersion == 0) // the -walletupgrade without argument case
414 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
415 nMaxVersion = CLIENT_VERSION;
416 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
419 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
420 if (nMaxVersion < pwalletMain->GetVersion())
421 strErrors << _("Cannot downgrade wallet") << "\n";
422 pwalletMain->SetMaxVersion(nMaxVersion);
427 // Create new keyUser and set as default key
428 RandAddSeedPerfmon();
430 std::vector<unsigned char> newDefaultKey;
431 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
432 strErrors << _("Cannot initialize keypool") << "\n";
433 pwalletMain->SetDefaultKey(newDefaultKey);
434 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
435 strErrors << _("Cannot write default address") << "\n";
438 printf("%s", strErrors.str().c_str());
439 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
441 RegisterWallet(pwalletMain);
443 CBlockIndex *pindexRescan = pindexBest;
444 if (GetBoolArg("-rescan"))
445 pindexRescan = pindexGenesisBlock;
448 CWalletDB walletdb("wallet.dat");
449 CBlockLocator locator;
450 if (walletdb.ReadBestBlock(locator))
451 pindexRescan = locator.GetBlockIndex();
453 if (pindexBest != pindexRescan)
455 InitMessage(_("Rescanning..."));
456 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
457 nStart = GetTimeMillis();
458 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
459 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
462 InitMessage(_("Done loading"));
463 printf("Done loading\n");
466 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
467 printf("nBestHeight = %d\n", nBestHeight);
468 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
469 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
470 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
472 if (!strErrors.str().empty())
474 ThreadSafeMessageBox(strErrors.str(), _("PPCoin"), wxOK | wxICON_ERROR | wxMODAL);
478 // Add wallet transactions that aren't already in a block to mapTransactions
479 pwalletMain->ReacceptWalletTransactions();
481 // Note: Bitcoin-QT stores several settings in the wallet, so we want
482 // to load the wallet BEFORE parsing command-line arguments, so
483 // the command-line/bitcoin.conf settings override GUI setting.
488 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
494 if (mapArgs.count("-timeout"))
496 int nNewTimeout = GetArg("-timeout", 5000);
497 if (nNewTimeout > 0 && nNewTimeout < 600000)
498 nConnectTimeout = nNewTimeout;
501 if (mapArgs.count("-printblock"))
503 string strMatch = mapArgs["-printblock"];
505 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
507 uint256 hash = (*mi).first;
508 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
510 CBlockIndex* pindex = (*mi).second;
512 block.ReadFromDisk(pindex);
513 block.BuildMerkleTree();
520 printf("No blocks matching %s were found\n", strMatch.c_str());
524 if (mapArgs.count("-proxy"))
527 addrProxy = CService(mapArgs["-proxy"], 9050);
528 if (!addrProxy.IsValid())
530 ThreadSafeMessageBox(_("Invalid -proxy address"), _("PPCcoin"), wxOK | wxMODAL);
535 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
538 // Use SoftSetBoolArg here so user can override any of these if they wish.
539 // Note: the GetBoolArg() calls for all of these must happen later.
540 SoftSetBoolArg("-listen", false);
541 SoftSetBoolArg("-irc", false);
542 SoftSetBoolArg("-dnsseed", false);
543 SoftSetBoolArg("-upnp", false);
544 SoftSetBoolArg("-dns", false);
547 fAllowDNS = GetBoolArg("-dns");
548 fNoListen = !GetBoolArg("-listen", true);
550 // Continue to put "/P2SH/" in the coinbase to monitor
552 // This can be removed eventually...
553 const char* pszP2SH = "/P2SH/";
554 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
558 std::string strError;
559 if (!BindListenPort(strError))
561 ThreadSafeMessageBox(strError, _("PPCoin"), wxOK | wxMODAL);
566 if (mapArgs.count("-addnode"))
568 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
570 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
571 addr.nTime = 0; // so it won't relay unless successfully connected
573 addrman.Add(addr, CNetAddr("127.0.0.1"));
577 if (mapArgs.count("-paytxfee"))
579 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee) || nTransactionFee < MIN_TX_FEE)
581 ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("PPCoin"), wxOK | wxMODAL);
584 if (nTransactionFee > 0.25 * COIN)
585 ThreadSafeMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), _("PPCoin"), wxOK | wxICON_EXCLAMATION | wxMODAL);
591 if (!CheckDiskSpace())
594 RandAddSeedPerfmon();
596 if (!CreateThread(StartNode, NULL))
597 ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("PPCoin"), wxOK | wxMODAL);
600 CreateThread(ThreadRPCServer, NULL);
603 if (GetStartOnSystemStartup())
604 SetStartOnSystemStartup(true); // Remove startup links