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.
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
14 #include <boost/interprocess/sync/file_lock.hpp>
17 using namespace boost;
21 //////////////////////////////////////////////////////////////////////////////
26 void ExitTimeout(void* parg)
34 void Shutdown(void* parg)
36 static CCriticalSection cs_Shutdown;
39 CRITICAL_BLOCK(cs_Shutdown)
41 fFirstThread = !fTaken;
48 nTransactionsUpdated++;
52 boost::filesystem::remove(GetPidFile());
53 UnregisterWallet(pwalletMain);
55 CreateThread(ExitTimeout, NULL);
57 printf("Bitcoin exiting\n\n");
70 void HandleSIGTERM(int)
72 fRequestShutdown = true;
80 //////////////////////////////////////////////////////////////////////////////
85 #if !defined(PPCOIN_GENESIS)
86 int main(int argc, char* argv[])
89 fRet = AppInit(argc, argv);
99 bool AppInit(int argc, char* argv[])
104 fRet = AppInit2(argc, argv);
106 catch (std::exception& e) {
107 PrintException(&e, "AppInit()");
109 PrintException(NULL, "AppInit()");
116 bool AppInit2(int argc, char* argv[])
119 // Turn off microsoft heap dump noise
120 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
121 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
124 // Disable confusing "helpful" text message on abort, ctrl-c
125 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
131 // Clean shutdown on SIGTERM
133 sa.sa_handler = HandleSIGTERM;
134 sigemptyset(&sa.sa_mask);
136 sigaction(SIGTERM, &sa, NULL);
137 sigaction(SIGINT, &sa, NULL);
138 sigaction(SIGHUP, &sa, NULL);
144 ParseParameters(argc, argv);
146 if (mapArgs.count("-datadir"))
148 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
150 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
151 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
155 fprintf(stderr, "Error: Specified directory does not exist\n");
161 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
163 if (mapArgs.count("-?") || mapArgs.count("--help"))
165 string strUsage = string() +
166 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
167 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
168 " bitcoin [options] \t " + "\n" +
169 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
170 " bitcoin [options] help \t\t " + _("List commands\n") +
171 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
173 " -conf=<file> \t\t " + _("Specify configuration file (default: ppcoin.conf)\n") +
174 " -pid=<file> \t\t " + _("Specify pid file (default: ppcoind.pid)\n") +
175 " -gen \t\t " + _("Generate coins\n") +
176 " -gen=0 \t\t " + _("Don't generate coins\n") +
177 " -min \t\t " + _("Start minimized\n") +
178 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
179 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
180 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
181 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
182 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
183 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
184 " -nolisten \t " + _("Don't accept connections from outside\n") +
187 " -noupnp \t " + _("Don't attempt to use UPnP to map the listening port\n") +
189 " -upnp \t " + _("Attempt to use UPnP to map the listening port\n") +
192 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
194 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
197 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
199 " -testnet \t\t " + _("Use the test network\n") +
200 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
201 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
202 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
203 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
204 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
205 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
206 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
209 strUsage += string() +
210 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
211 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
212 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
213 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
214 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
217 strUsage += string() +
218 " -? \t\t " + _("This help message\n");
220 #if defined(__WXMSW__) && defined(GUI)
221 // Tabs make the columns line up in the message box
222 wxMessageBox(strUsage, "Bitcoin", wxOK);
225 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
226 fprintf(stderr, "%s", strUsage.c_str());
231 fDebug = GetBoolArg("-debug");
232 fAllowDNS = GetBoolArg("-dns");
235 fDaemon = GetBoolArg("-daemon");
243 fServer = GetBoolArg("-server");
245 /* force fServer when running without GUI */
250 fPrintToConsole = GetBoolArg("-printtoconsole");
251 fPrintToDebugger = GetBoolArg("-printtodebugger");
253 fTestNet = GetBoolArg("-testnet");
254 bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
255 fNoListen = GetBoolArg("-nolisten") || fTOR;
256 fLogTimestamps = GetBoolArg("-logtimestamps");
258 for (int i = 1; i < argc; i++)
259 if (!IsSwitchChar(argv[i][0]))
264 int ret = CommandLineRPC(argc, argv);
275 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
280 CreatePidFile(GetPidFile(), pid);
284 pid_t sid = setsid();
286 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
290 if (!fDebug && !pszSetDataDir[0])
292 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
293 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
295 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
296 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
297 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
299 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
301 if (GetBoolArg("-loadblockindextest"))
304 txdb.LoadBlockIndex();
310 // Limit to single instance per user
311 // Required to protect the database files if we're going to keep deleting log.*
313 #if defined(__WXMSW__) && defined(GUI)
314 // wxSingleInstanceChecker doesn't work on Linux
315 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
316 for (int i = 0; i < strMutexName.size(); i++)
317 if (!isalnum(strMutexName[i]))
318 strMutexName[i] = '.';
319 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
320 if (psingleinstancechecker->IsAnotherRunning())
322 printf("Existing instance found\n");
323 unsigned int nStart = GetTime();
326 // Show the previous instance and exit
327 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
330 if (IsIconic(hwndPrev))
331 ShowWindow(hwndPrev, SW_RESTORE);
332 SetForegroundWindow(hwndPrev);
336 if (GetTime() > nStart + 60)
339 // Resume this instance if the other exits
340 delete psingleinstancechecker;
342 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
343 if (!psingleinstancechecker->IsAnotherRunning())
349 // Make sure only a single bitcoin process is using the data directory.
350 string strLockFile = GetDataDir() + "/.lock";
351 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
352 if (file) fclose(file);
353 static boost::interprocess::file_lock lock(strLockFile.c_str());
354 if (!lock.try_lock())
356 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
360 // Bind to the port early so we can tell if another instance is already running.
364 if (!BindListenPort(strErrors))
366 wxMessageBox(strErrors, "Bitcoin");
375 fprintf(stdout, "bitcoin server starting\n");
379 printf("Loading addresses...\n");
380 nStart = GetTimeMillis();
381 if (!LoadAddresses())
382 strErrors += _("Error loading addr.dat \n");
383 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
385 printf("Loading block index...\n");
386 nStart = GetTimeMillis();
387 if (!LoadBlockIndex())
388 strErrors += _("Error loading blkindex.dat \n");
389 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
391 printf("Loading wallet...\n");
392 nStart = GetTimeMillis();
394 pwalletMain = new CWallet("wallet.dat");
395 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
396 if (nLoadWalletRet != DB_LOAD_OK)
398 if (nLoadWalletRet == DB_CORRUPT)
399 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
400 else if (nLoadWalletRet == DB_TOO_NEW)
401 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
403 strErrors += _("Error loading wallet.dat \n");
405 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
407 RegisterWallet(pwalletMain);
409 CBlockIndex *pindexRescan = pindexBest;
410 if (GetBoolArg("-rescan"))
411 pindexRescan = pindexGenesisBlock;
414 CWalletDB walletdb("wallet.dat");
415 CBlockLocator locator;
416 if (walletdb.ReadBestBlock(locator))
417 pindexRescan = locator.GetBlockIndex();
419 if (pindexBest != pindexRescan)
421 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
422 nStart = GetTimeMillis();
423 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
424 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
427 printf("Done loading\n");
430 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
431 printf("nBestHeight = %d\n", nBestHeight);
432 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
433 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
434 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
436 if (!strErrors.empty())
438 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
442 // Add wallet transactions that aren't already in a block to mapTransactions
443 pwalletMain->ReacceptWalletTransactions();
448 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
454 if (mapArgs.count("-timeout"))
456 int nNewTimeout = GetArg("-timeout", 5000);
457 if (nNewTimeout > 0 && nNewTimeout < 600000)
458 nConnectTimeout = nNewTimeout;
461 if (mapArgs.count("-printblock"))
463 string strMatch = mapArgs["-printblock"];
465 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
467 uint256 hash = (*mi).first;
468 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
470 CBlockIndex* pindex = (*mi).second;
472 block.ReadFromDisk(pindex);
473 block.BuildMerkleTree();
480 printf("No blocks matching %s were found\n", strMatch.c_str());
484 fGenerateBitcoins = GetBoolArg("-gen");
486 if (mapArgs.count("-proxy"))
489 addrProxy = CAddress(mapArgs["-proxy"]);
490 if (!addrProxy.IsValid())
492 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
497 if (mapArgs.count("-addnode"))
499 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
501 CAddress addr(strAddr, fAllowDNS);
502 addr.nTime = 0; // so it won't relay unless successfully connected
508 if (GetBoolArg("-nodnsseed"))
509 printf("DNS seeding disabled\n");
513 if (mapArgs.count("-paytxfee"))
515 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
517 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
520 if (nTransactionFee >= 10 * COIN)
521 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
527 if (GetBoolArg("-noupnp"))
530 if (GetBoolArg("-upnp"))
536 // Create the main window and start the node
543 if (!CheckDiskSpace())
546 RandAddSeedPerfmon();
548 if (!CreateThread(StartNode, NULL))
549 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
552 CreateThread(ThreadRPCServer, NULL);
554 #if defined(__WXMSW__) && defined(GUI)
556 SetStartOnSystemStartup(true);