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 "ui_interface.h"
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
14 #include <boost/filesystem/convenience.hpp>
15 #include <boost/interprocess/sync/file_lock.hpp>
22 using namespace boost;
26 //////////////////////////////////////////////////////////////////////////////
31 void ExitTimeout(void* parg)
42 // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
45 // Without UI, Shutdown() can simply be started in a new thread
46 CreateThread(Shutdown, NULL);
50 void Shutdown(void* parg)
52 static CCriticalSection cs_Shutdown;
54 bool fFirstThread = false;
56 TRY_LOCK(cs_Shutdown, lockShutdown);
59 fFirstThread = !fTaken;
67 nTransactionsUpdated++;
71 boost::filesystem::remove(GetPidFile());
72 UnregisterWallet(pwalletMain);
74 CreateThread(ExitTimeout, NULL);
76 printf("Bitcoin exiting\n\n");
79 // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
92 void HandleSIGTERM(int)
94 fRequestShutdown = true;
102 //////////////////////////////////////////////////////////////////////////////
107 int main(int argc, char* argv[])
110 fRet = AppInit(argc, argv);
119 bool AppInit(int argc, char* argv[])
124 fRet = AppInit2(argc, argv);
126 catch (std::exception& e) {
127 PrintException(&e, "AppInit()");
129 PrintException(NULL, "AppInit()");
136 bool AppInit2(int argc, char* argv[])
139 // Turn off microsoft heap dump noise
140 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
141 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
144 // Disable confusing "helpful" text message on abort, ctrl-c
145 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
151 // Clean shutdown on SIGTERM
153 sa.sa_handler = HandleSIGTERM;
154 sigemptyset(&sa.sa_mask);
156 sigaction(SIGTERM, &sa, NULL);
157 sigaction(SIGINT, &sa, NULL);
158 sigaction(SIGHUP, &sa, NULL);
164 // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
166 ParseParameters(argc, argv);
167 if (!boost::filesystem::is_directory(GetDataDir(false)))
169 fprintf(stderr, "Error: Specified directory does not exist\n");
172 ReadConfigFile(mapArgs, mapMultiArgs);
175 if (mapArgs.count("-?") || mapArgs.count("--help"))
177 string strUsage = string() +
178 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
179 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
180 " bitcoind [options] \t " + "\n" +
181 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
182 " bitcoind [options] help \t\t " + _("List commands") + "\n" +
183 " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
184 _("Options:") + "\n" +
185 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
186 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
187 " -gen \t\t " + _("Generate coins") + "\n" +
188 " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
189 " -min \t\t " + _("Start minimized") + "\n" +
190 " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
191 " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
192 " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
193 " -dblogsize=<n> \t\t " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
194 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
195 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
196 " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
197 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
198 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
199 " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
200 " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
201 " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
202 " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
204 " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
206 " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
207 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
208 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
209 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
210 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
213 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
215 " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
217 " -detachdb \t " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
219 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
221 " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
223 #if !defined(WIN32) && !defined(QT_GUI)
224 " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
226 " -testnet \t\t " + _("Use the test network") + "\n" +
227 " -debug \t\t " + _("Output extra debugging information") + "\n" +
228 " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
229 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
231 " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
233 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
234 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
235 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
236 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
237 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
238 " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
239 " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
240 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
241 " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
242 " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
243 " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\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";
252 strUsage += string() +
253 " -? \t\t " + _("This help message") + "\n";
256 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
257 #if defined(QT_GUI) && defined(WIN32)
258 // On windows, show a message box, as there is no stderr
259 ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
261 fprintf(stderr, "%s", strUsage.c_str());
266 fTestNet = GetBoolArg("-testnet");
269 SoftSetBoolArg("-irc", true);
272 fDebug = GetBoolArg("-debug");
273 fDetachDB = GetBoolArg("-detachdb", false);
275 #if !defined(WIN32) && !defined(QT_GUI)
276 fDaemon = GetBoolArg("-daemon");
284 fServer = GetBoolArg("-server");
286 /* force fServer when running without GUI */
290 fPrintToConsole = GetBoolArg("-printtoconsole");
291 fPrintToDebugger = GetBoolArg("-printtodebugger");
292 fLogTimestamps = GetBoolArg("-logtimestamps");
295 for (int i = 1; i < argc; i++)
296 if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
301 int ret = CommandLineRPC(argc, argv);
306 #if !defined(WIN32) && !defined(QT_GUI)
313 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
318 CreatePidFile(GetPidFile(), pid);
322 pid_t sid = setsid();
324 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
330 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
331 printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
332 printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
334 if (GetBoolArg("-loadblockindextest"))
337 txdb.LoadBlockIndex();
342 // Make sure only a single bitcoin process is using the data directory.
343 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
344 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
345 if (file) fclose(file);
346 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
347 if (!lock.try_lock())
349 ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().string().c_str()), _("Bitcoin"), wxOK|wxMODAL);
353 std::ostringstream strErrors;
358 fprintf(stdout, "bitcoin server starting\n");
361 InitMessage(_("Loading addresses..."));
362 printf("Loading addresses...\n");
363 nStart = GetTimeMillis();
364 if (!LoadAddresses())
365 strErrors << _("Error loading addr.dat") << "\n";
366 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
368 InitMessage(_("Loading block index..."));
369 printf("Loading block index...\n");
370 nStart = GetTimeMillis();
371 if (!LoadBlockIndex())
372 strErrors << _("Error loading blkindex.dat") << "\n";
374 // as LoadBlockIndex can take several minutes, it's possible the user
375 // requested to kill bitcoin-qt during the last operation. If so, exit.
376 // As the program has not fully started yet, Shutdown() is possibly overkill.
377 if (fRequestShutdown)
379 printf("Shutdown requested. Exiting.\n");
382 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
384 InitMessage(_("Loading wallet..."));
385 printf("Loading wallet...\n");
386 nStart = GetTimeMillis();
388 pwalletMain = new CWallet("wallet.dat");
389 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
390 if (nLoadWalletRet != DB_LOAD_OK)
392 if (nLoadWalletRet == DB_CORRUPT)
393 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
394 else if (nLoadWalletRet == DB_TOO_NEW)
395 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
396 else if (nLoadWalletRet == DB_NEED_REWRITE)
398 strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
399 printf("%s", strErrors.str().c_str());
400 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
404 strErrors << _("Error loading wallet.dat") << "\n";
407 if (GetBoolArg("-upgradewallet", fFirstRun))
409 int nMaxVersion = GetArg("-upgradewallet", 0);
410 if (nMaxVersion == 0) // the -walletupgrade without argument case
412 printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
413 nMaxVersion = CLIENT_VERSION;
414 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
417 printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
418 if (nMaxVersion < pwalletMain->GetVersion())
419 strErrors << _("Cannot downgrade wallet") << "\n";
420 pwalletMain->SetMaxVersion(nMaxVersion);
425 // Create new keyUser and set as default key
426 RandAddSeedPerfmon();
428 std::vector<unsigned char> newDefaultKey;
429 if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
430 strErrors << _("Cannot initialize keypool") << "\n";
431 pwalletMain->SetDefaultKey(newDefaultKey);
432 if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
433 strErrors << _("Cannot write default address") << "\n";
436 printf("%s", strErrors.str().c_str());
437 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
439 RegisterWallet(pwalletMain);
441 CBlockIndex *pindexRescan = pindexBest;
442 if (GetBoolArg("-rescan"))
443 pindexRescan = pindexGenesisBlock;
446 CWalletDB walletdb("wallet.dat");
447 CBlockLocator locator;
448 if (walletdb.ReadBestBlock(locator))
449 pindexRescan = locator.GetBlockIndex();
451 if (pindexBest != pindexRescan)
453 InitMessage(_("Rescanning..."));
454 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
455 nStart = GetTimeMillis();
456 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
457 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
460 InitMessage(_("Done loading"));
461 printf("Done loading\n");
464 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
465 printf("nBestHeight = %d\n", nBestHeight);
466 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
467 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
468 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
470 if (!strErrors.str().empty())
472 ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
476 // Add wallet transactions that aren't already in a block to mapTransactions
477 pwalletMain->ReacceptWalletTransactions();
479 // Note: Bitcoin-QT stores several settings in the wallet, so we want
480 // to load the wallet BEFORE parsing command-line arguments, so
481 // the command-line/bitcoin.conf settings override GUI setting.
486 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
492 if (mapArgs.count("-timeout"))
494 int nNewTimeout = GetArg("-timeout", 5000);
495 if (nNewTimeout > 0 && nNewTimeout < 600000)
496 nConnectTimeout = nNewTimeout;
499 if (mapArgs.count("-printblock"))
501 string strMatch = mapArgs["-printblock"];
503 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
505 uint256 hash = (*mi).first;
506 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
508 CBlockIndex* pindex = (*mi).second;
510 block.ReadFromDisk(pindex);
511 block.BuildMerkleTree();
518 printf("No blocks matching %s were found\n", strMatch.c_str());
522 if (mapArgs.count("-proxy"))
525 addrProxy = CService(mapArgs["-proxy"], 9050);
526 if (!addrProxy.IsValid())
528 ThreadSafeMessageBox(_("Invalid -proxy address"), _("Bitcoin"), wxOK | wxMODAL);
533 bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
536 // Use SoftSetBoolArg here so user can override any of these if they wish.
537 // Note: the GetBoolArg() calls for all of these must happen later.
538 SoftSetBoolArg("-listen", false);
539 SoftSetBoolArg("-irc", false);
540 SoftSetBoolArg("-dnsseed", false);
541 SoftSetBoolArg("-upnp", false);
542 SoftSetBoolArg("-dns", false);
545 fAllowDNS = GetBoolArg("-dns");
546 fNoListen = !GetBoolArg("-listen", true);
548 // Continue to put "/P2SH/" in the coinbase to monitor
550 // This can be removed eventually...
551 const char* pszP2SH = "/P2SH/";
552 COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
556 std::string strError;
557 if (!BindListenPort(strError))
559 ThreadSafeMessageBox(strError, _("Bitcoin"), wxOK | wxMODAL);
564 if (mapArgs.count("-addnode"))
566 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
568 CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
569 addr.nTime = 0; // so it won't relay unless successfully connected
571 addrman.Add(addr, CNetAddr("127.0.0.1"));
575 if (mapArgs.count("-paytxfee"))
577 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
579 ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("Bitcoin"), wxOK | wxMODAL);
582 if (nTransactionFee > 0.25 * COIN)
583 ThreadSafeMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), _("Bitcoin"), wxOK | wxICON_EXCLAMATION | wxMODAL);
589 if (!CheckDiskSpace())
592 RandAddSeedPerfmon();
594 if (!CreateThread(StartNode, NULL))
595 ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("Bitcoin"), wxOK | wxMODAL);
598 CreateThread(ThreadRPCServer, NULL);
601 if (GetStartOnSystemStartup())
602 SetStartOnSystemStartup(true); // Remove startup links