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 "checkpoints.h"
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/filesystem/convenience.hpp>
17 #include <boost/interprocess/sync/file_lock.hpp>
24 using namespace boost;
28 //////////////////////////////////////////////////////////////////////////////
33 void ExitTimeout(void* parg)
44 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
47 // Without UI, Shutdown() can simply be started in a new thread
48 CreateThread(Shutdown, NULL);
52 void Shutdown(void* parg)
54 static CCriticalSection cs_Shutdown;
56 bool fFirstThread = false;
58 TRY_LOCK(cs_Shutdown, lockShutdown);
61 fFirstThread = !fTaken;
69 nTransactionsUpdated++;
73 boost::filesystem::remove(GetPidFile());
74 UnregisterWallet(pwalletMain);
76 CreateThread(ExitTimeout, NULL);
78 printf("PPCoin 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 #if !defined(PPCOIN_GENESIS)
110 int main(int argc, char* argv[])
113 fRet = AppInit(argc, argv);
123 bool AppInit(int argc, char* argv[])
128 fRet = AppInit2(argc, argv);
130 catch (std::exception& e) {
131 PrintException(&e, "AppInit()");
133 PrintException(NULL, "AppInit()");
140 bool AppInit2(int argc, char* argv[])
143 // Turn off microsoft heap dump noise
144 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
145 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
148 // Disable confusing "helpful" text message on abort, ctrl-c
149 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
155 // Clean shutdown on SIGTERM
157 sa.sa_handler = HandleSIGTERM;
158 sigemptyset(&sa.sa_mask);
160 sigaction(SIGTERM, &sa, NULL);
161 sigaction(SIGINT, &sa, NULL);
162 sigaction(SIGHUP, &sa, NULL);
168 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
170 ParseParameters(argc, argv);
171 if (!boost::filesystem::is_directory(GetDataDir(false)))
173 fprintf(stderr, "Error: Specified directory does not exist\n");
176 ReadConfigFile(mapArgs, mapMultiArgs);
179 if (mapArgs.count("-?") || mapArgs.count("--help"))
181 string strUsage = string() +
182 _("PPCoin version") + " " + FormatFullVersion() + "\n\n" +
183 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
184 " ppcoind [options] \t " + "\n" +
185 " ppcoind [options] <command> [params]\t " + _("Send command to -server or ppcoind") + "\n" +
186 " ppcoind [options] help \t\t " + _("List commands") + "\n" +
187 " ppcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
188 _("Options:") + "\n" +
189 " -conf=<file> \t\t " + _("Specify configuration file (default: ppcoin.conf)") + "\n" +
190 " -pid=<file> \t\t " + _("Specify pid file (default: ppcoind.pid)") + "\n" +
191 " -gen \t\t " + _("Generate coins") + "\n" +
192 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
193 " -min \t\t " + _("Start minimized") + "\n" +
194 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
195 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
196 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
197 " -dblogsize=<n> \t\t " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
198 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
199 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
200 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
201 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 9901 or testnet: 9903)") + "\n" +
202 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
203 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
204 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
205 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
207 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
209 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
210 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
211 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
212 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
213 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
216 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
218 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
220 " -detachdb \t " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\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: 9902)") + "\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 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
242 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
243 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
244 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
245 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
246 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
248 strUsage += string() +
249 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
250 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
251 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
252 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
253 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
255 strUsage += string() +
256 " -? \t\t " + _("This help message") + "\n";
259 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
260 #if defined(QT_GUI) && defined(WIN32)
261 // On windows, show a message box, as there is no stderr
262 ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
264 fprintf(stderr, "%s", strUsage.c_str());
269 fTestNet = GetBoolArg("-testnet");
272 SoftSetBoolArg("-irc", true);
275 fDebug = GetBoolArg("-debug");
276 fDetachDB = GetBoolArg("-detachdb", false);
278 #if !defined(WIN32) && !defined(QT_GUI)
279 fDaemon = GetBoolArg("-daemon");
287 fServer = GetBoolArg("-server");
289 /* force fServer when running without GUI */
293 fPrintToConsole = GetBoolArg("-printtoconsole");
294 fPrintToDebugger = GetBoolArg("-printtodebugger");
295 fLogTimestamps = GetBoolArg("-logtimestamps");
298 for (int i = 1; i < argc; i++)
299 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
304 int ret = CommandLineRPC(argc, argv);
309 #if !defined(WIN32) && !defined(QT_GUI)
316 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
321 CreatePidFile(GetPidFile(), pid);
325 pid_t sid = setsid();
327 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
333 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
334 printf("PPCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
335 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
337 if (GetBoolArg("-loadblockindextest"))
340 txdb.LoadBlockIndex();
345 // Make sure only a single bitcoin process is using the data directory.
346 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
347 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
348 if (file) fclose(file);
349 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
350 if (!lock.try_lock())
352 ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. PPCoin is probably already running."), GetDataDir().string().c_str()), _("PPCoin"), wxOK|wxMODAL);
356 std::ostringstream strErrors;
361 fprintf(stdout, "ppcoin server starting\n");
364 InitMessage(_("Loading addresses..."));
365 printf("Loading addresses...\n");
366 nStart = GetTimeMillis();
367 if (!LoadAddresses())
368 strErrors << _("Error loading addr.dat") << "\n";
369 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
371 InitMessage(_("Loading block index..."));
372 printf("Loading block index...\n");
373 nStart = GetTimeMillis();
374 if (!LoadBlockIndex())
375 strErrors << _("Error loading blkindex.dat") << "\n";
377 // as LoadBlockIndex can take several minutes, it's possible the user
378 // requested to kill bitcoin-qt during the last operation. If so, exit.
379 // As the program has not fully started yet, Shutdown() is possibly overkill.
380 if (fRequestShutdown)
382 printf("Shutdown requested. Exiting.\n");
385 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
387 InitMessage(_("Loading wallet..."));
388 printf("Loading wallet...\n");
389 nStart = GetTimeMillis();
391 pwalletMain = new CWallet("wallet.dat");
392 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
393 if (nLoadWalletRet != DB_LOAD_OK)
395 if (nLoadWalletRet == DB_CORRUPT)
396 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
397 else if (nLoadWalletRet == DB_TOO_NEW)
398 strErrors << _("Error loading wallet.dat: Wallet requires newer version of PPCoin") << "\n";
399 else if (nLoadWalletRet == DB_NEED_REWRITE)
401 strErrors << _("Wallet needed to be rewritten: restart PPCoin to complete") << "\n";
402 printf("%s", strErrors.str().c_str());
403 ThreadSafeMessageBox(strErrors.str(), _("PPCoin"), wxOK | wxICON_ERROR | wxMODAL);
407 strErrors << _("Error loading wallet.dat") << "\n";
410 if (GetBoolArg("-upgradewallet", fFirstRun))
412 int nMaxVersion = GetArg("-upgradewallet", 0);
413 if (nMaxVersion == 0) // the -walletupgrade without argument case
415 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
416 nMaxVersion = CLIENT_VERSION;
417 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
420 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
421 if (nMaxVersion < pwalletMain->GetVersion())
422 strErrors << _("Cannot downgrade wallet") << "\n";
423 pwalletMain->SetMaxVersion(nMaxVersion);
428 // Create new keyUser and set as default key
429 RandAddSeedPerfmon();
431 std::vector<unsigned char> newDefaultKey;
432 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
433 strErrors << _("Cannot initialize keypool") << "\n";
434 pwalletMain->SetDefaultKey(newDefaultKey);
435 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
436 strErrors << _("Cannot write default address") << "\n";
439 printf("%s", strErrors.str().c_str());
440 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
442 RegisterWallet(pwalletMain);
444 CBlockIndex *pindexRescan = pindexBest;
445 if (GetBoolArg("-rescan"))
446 pindexRescan = pindexGenesisBlock;
449 CWalletDB walletdb("wallet.dat");
450 CBlockLocator locator;
451 if (walletdb.ReadBestBlock(locator))
452 pindexRescan = locator.GetBlockIndex();
454 if (pindexBest != pindexRescan)
456 InitMessage(_("Rescanning..."));
457 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
458 nStart = GetTimeMillis();
459 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
460 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
463 InitMessage(_("Done loading"));
464 printf("Done loading\n");
467 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
468 printf("nBestHeight = %d\n", nBestHeight);
469 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
470 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
471 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
473 if (!strErrors.str().empty())
475 ThreadSafeMessageBox(strErrors.str(), _("PPCoin"), wxOK | wxICON_ERROR | wxMODAL);
479 // Add wallet transactions that aren't already in a block to mapTransactions
480 pwalletMain->ReacceptWalletTransactions();
482 // Note: Bitcoin-QT stores several settings in the wallet, so we want
483 // to load the wallet BEFORE parsing command-line arguments, so
484 // the command-line/bitcoin.conf settings override GUI setting.
489 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
495 if (mapArgs.count("-timeout"))
497 int nNewTimeout = GetArg("-timeout", 5000);
498 if (nNewTimeout > 0 && nNewTimeout < 600000)
499 nConnectTimeout = nNewTimeout;
502 if (mapArgs.count("-printblock"))
504 string strMatch = mapArgs["-printblock"];
506 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
508 uint256 hash = (*mi).first;
509 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
511 CBlockIndex* pindex = (*mi).second;
513 block.ReadFromDisk(pindex);
514 block.BuildMerkleTree();
521 printf("No blocks matching %s were found\n", strMatch.c_str());
525 if (mapArgs.count("-proxy"))
528 addrProxy = CService(mapArgs["-proxy"], 9050);
529 if (!addrProxy.IsValid())
531 ThreadSafeMessageBox(_("Invalid -proxy address"), _("PPCcoin"), wxOK | wxMODAL);
536 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
539 // Use SoftSetBoolArg here so user can override any of these if they wish.
540 // Note: the GetBoolArg() calls for all of these must happen later.
541 SoftSetBoolArg("-listen", false);
542 SoftSetBoolArg("-irc", false);
543 SoftSetBoolArg("-dnsseed", false);
544 SoftSetBoolArg("-upnp", false);
545 SoftSetBoolArg("-dns", false);
548 fAllowDNS = GetBoolArg("-dns");
549 fNoListen = !GetBoolArg("-listen", true);
551 // Continue to put "/P2SH/" in the coinbase to monitor
553 // This can be removed eventually...
554 const char* pszP2SH = "/P2SH/";
555 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
559 std::string strError;
560 if (!BindListenPort(strError))
562 ThreadSafeMessageBox(strError, _("PPCoin"), wxOK | wxMODAL);
567 if (mapArgs.count("-addnode"))
569 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
571 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
572 addr.nTime = 0; // so it won't relay unless successfully connected
574 addrman.Add(addr, CNetAddr("127.0.0.1"));
578 if (mapArgs.count("-paytxfee"))
580 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee) || nTransactionFee < MIN_TX_FEE)
582 ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("PPCoin"), wxOK | wxMODAL);
585 if (nTransactionFee > 0.25 * COIN)
586 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);
589 if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
591 int64 nReserveBalance = 0;
592 if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
594 ThreadSafeMessageBox(_("Invalid amount for -reservebalance=<amount>"), _("PPCoin"), wxOK | wxMODAL);
599 if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
601 if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
602 ThreadSafeMessageBox(_("Unable to sign checkpoint, wrong checkpointkey?\n"), _("PPCoin"), wxOK | wxMODAL);
608 if (!CheckDiskSpace())
611 RandAddSeedPerfmon();
613 if (!CreateThread(StartNode, NULL))
614 ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("PPCoin"), wxOK | wxMODAL);
617 CreateThread(ThreadRPCServer, NULL);
620 if (GetStartOnSystemStartup())
621 SetStartOnSystemStartup(true); // Remove startup links