You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.cpp 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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.
  5. #include "init.h"
  6. #include "main.h"
  7. #include "core.h"
  8. #include "chainparams.h"
  9. #include "txdb.h"
  10. #include "walletdb.h"
  11. #include "bitcoinrpc.h"
  12. #include "net.h"
  13. #include "util.h"
  14. #include "ui_interface.h"
  15. #include "checkpoints.h"
  16. #include "chainparams.h"
  17. #include <boost/filesystem.hpp>
  18. #include <boost/filesystem/fstream.hpp>
  19. #include <boost/filesystem/convenience.hpp>
  20. #include <boost/interprocess/sync/file_lock.hpp>
  21. #include <boost/algorithm/string/predicate.hpp>
  22. #include <openssl/crypto.h>
  23. #ifndef WIN32
  24. #include <signal.h>
  25. #endif
  26. using namespace std;
  27. using namespace boost;
  28. CWallet* pwalletMain;
  29. CClientUIInterface uiInterface;
  30. #ifdef WIN32
  31. // Win32 LevelDB doesn't use filedescriptors, and the ones used for
  32. // accessing block files, don't count towards to fd_set size limit
  33. // anyway.
  34. #define MIN_CORE_FILEDESCRIPTORS 0
  35. #else
  36. #define MIN_CORE_FILEDESCRIPTORS 150
  37. #endif
  38. // Used to pass flags to the Bind() function
  39. enum BindFlags {
  40. BF_NONE = 0,
  41. BF_EXPLICIT = (1U << 0),
  42. BF_REPORT_ERROR = (1U << 1)
  43. };
  44. //////////////////////////////////////////////////////////////////////////////
  45. //
  46. // Shutdown
  47. //
  48. //
  49. // Thread management and startup/shutdown:
  50. //
  51. // The network-processing threads are all part of a thread group
  52. // created by AppInit() or the Qt main() function.
  53. //
  54. // A clean exit happens when StartShutdown() or the SIGTERM
  55. // signal handler sets fRequestShutdown, which triggers
  56. // the DetectShutdownThread(), which interrupts the main thread group.
  57. // DetectShutdownThread() then exits, which causes AppInit() to
  58. // continue (it .joins the shutdown thread).
  59. // Shutdown() is then
  60. // called to clean up database connections, and stop other
  61. // threads that should only be stopped after the main network-processing
  62. // threads have exited.
  63. //
  64. // Note that if running -daemon the parent process returns from AppInit2
  65. // before adding any threads to the threadGroup, so .join_all() returns
  66. // immediately and the parent exits from main().
  67. //
  68. // Shutdown for Qt is very similar, only it uses a QTimer to detect
  69. // fRequestShutdown getting set, and then does the normal Qt
  70. // shutdown thing.
  71. //
  72. volatile bool fRequestShutdown = false;
  73. void StartShutdown()
  74. {
  75. fRequestShutdown = true;
  76. }
  77. bool ShutdownRequested()
  78. {
  79. return fRequestShutdown;
  80. }
  81. static CCoinsViewDB *pcoinsdbview;
  82. void Shutdown()
  83. {
  84. static CCriticalSection cs_Shutdown;
  85. TRY_LOCK(cs_Shutdown, lockShutdown);
  86. if (!lockShutdown) return;
  87. RenameThread("bitcoin-shutoff");
  88. nTransactionsUpdated++;
  89. StopRPCThreads();
  90. ShutdownRPCMining();
  91. bitdb.Flush(false);
  92. GenerateBitcoins(false, NULL);
  93. StopNode();
  94. {
  95. LOCK(cs_main);
  96. if (pwalletMain)
  97. pwalletMain->SetBestChain(CBlockLocator(pindexBest));
  98. if (pblocktree)
  99. pblocktree->Flush();
  100. if (pcoinsTip)
  101. pcoinsTip->Flush();
  102. delete pcoinsTip; pcoinsTip = NULL;
  103. delete pcoinsdbview; pcoinsdbview = NULL;
  104. delete pblocktree; pblocktree = NULL;
  105. }
  106. bitdb.Flush(true);
  107. boost::filesystem::remove(GetPidFile());
  108. UnregisterWallet(pwalletMain);
  109. delete pwalletMain;
  110. }
  111. //
  112. // Signal handlers are very limited in what they are allowed to do, so:
  113. //
  114. void HandleSIGTERM(int)
  115. {
  116. fRequestShutdown = true;
  117. }
  118. void HandleSIGHUP(int)
  119. {
  120. fReopenDebugLog = true;
  121. }
  122. bool static InitError(const std::string &str)
  123. {
  124. uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
  125. return false;
  126. }
  127. bool static InitWarning(const std::string &str)
  128. {
  129. uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
  130. return true;
  131. }
  132. bool static Bind(const CService &addr, unsigned int flags) {
  133. if (!(flags & BF_EXPLICIT) && IsLimited(addr))
  134. return false;
  135. std::string strError;
  136. if (!BindListenPort(addr, strError)) {
  137. if (flags & BF_REPORT_ERROR)
  138. return InitError(strError);
  139. return false;
  140. }
  141. return true;
  142. }
  143. // Core-specific options shared between UI and daemon
  144. std::string HelpMessage()
  145. {
  146. string strUsage = _("Options:") + "\n";
  147. strUsage += " -? " + _("This help message") + "\n";
  148. strUsage += " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n";
  149. strUsage += " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n";
  150. strUsage += " -gen " + _("Generate coins (default: 0)") + "\n";
  151. strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n";
  152. strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n";
  153. strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n";
  154. strUsage += " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n";
  155. strUsage += " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n";
  156. strUsage += " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n";
  157. strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n";
  158. strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n";
  159. strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n";
  160. strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n";
  161. strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n";
  162. strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n";
  163. strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n";
  164. strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n";
  165. strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n";
  166. strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n";
  167. strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n";
  168. strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n";
  169. strUsage += " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n";
  170. strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n";
  171. strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n";
  172. strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n";
  173. strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n";
  174. #ifdef USE_UPNP
  175. #if USE_UPNP
  176. strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n";
  177. #else
  178. strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n";
  179. #endif
  180. #endif
  181. strUsage += " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n";
  182. if (fHaveGUI)
  183. strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n";
  184. #if !defined(WIN32)
  185. if (fHaveGUI)
  186. strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n";
  187. #endif
  188. strUsage += " -testnet " + _("Use the test network") + "\n";
  189. strUsage += " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n";
  190. strUsage += " -debugnet " + _("Output extra network debugging information") + "\n";
  191. strUsage += " -logtimestamps " + _("Prepend debug output with timestamp") + "\n";
  192. strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n";
  193. strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n";
  194. strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be "
  195. "solved instantly. This is intended for regression testing tools and app development.") + "\n";
  196. #ifdef WIN32
  197. strUsage += " -printtodebugger " + _("Send trace/debug info to debugger") + "\n";
  198. #endif
  199. strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n";
  200. strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n";
  201. strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n";
  202. strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n";
  203. if (!fHaveGUI)
  204. strUsage += " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
  205. strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n";
  206. strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n";
  207. strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n";
  208. strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n";
  209. strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n";
  210. strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n";
  211. strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n";
  212. strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n";
  213. strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n";
  214. strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n";
  215. strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n";
  216. strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n";
  217. strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n";
  218. strUsage += " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n";
  219. strUsage += "\n"; _("Block creation options:") + "\n";
  220. strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n";
  221. strUsage += " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n";
  222. strUsage += " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n";
  223. strUsage += "\n"; _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
  224. strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
  225. strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n";
  226. strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n";
  227. strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
  228. return strUsage;
  229. }
  230. struct CImportingNow
  231. {
  232. CImportingNow() {
  233. assert(fImporting == false);
  234. fImporting = true;
  235. }
  236. ~CImportingNow() {
  237. assert(fImporting == true);
  238. fImporting = false;
  239. }
  240. };
  241. void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
  242. {
  243. RenameThread("bitcoin-loadblk");
  244. // -reindex
  245. if (fReindex) {
  246. CImportingNow imp;
  247. int nFile = 0;
  248. while (true) {
  249. CDiskBlockPos pos(nFile, 0);
  250. FILE *file = OpenBlockFile(pos, true);
  251. if (!file)
  252. break;
  253. printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
  254. LoadExternalBlockFile(file, &pos);
  255. nFile++;
  256. }
  257. pblocktree->WriteReindexing(false);
  258. fReindex = false;
  259. printf("Reindexing finished\n");
  260. // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
  261. InitBlockIndex();
  262. }
  263. // hardcoded $DATADIR/bootstrap.dat
  264. filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
  265. if (filesystem::exists(pathBootstrap)) {
  266. FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
  267. if (file) {
  268. CImportingNow imp;
  269. filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
  270. printf("Importing bootstrap.dat...\n");
  271. LoadExternalBlockFile(file);
  272. RenameOver(pathBootstrap, pathBootstrapOld);
  273. }
  274. }
  275. // -loadblock=
  276. BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
  277. FILE *file = fopen(path.string().c_str(), "rb");
  278. if (file) {
  279. CImportingNow imp;
  280. printf("Importing %s...\n", path.string().c_str());
  281. LoadExternalBlockFile(file);
  282. }
  283. }
  284. }
  285. /** Initialize bitcoin.
  286. * @pre Parameters should be parsed and config file should be read.
  287. */
  288. bool AppInit2(boost::thread_group& threadGroup)
  289. {
  290. // ********************************************************* Step 1: setup
  291. #ifdef _MSC_VER
  292. // Turn off Microsoft heap dump noise
  293. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  294. _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  295. #endif
  296. #if _MSC_VER >= 1400
  297. // Disable confusing "helpful" text message on abort, Ctrl-C
  298. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  299. #endif
  300. #ifdef WIN32
  301. // Enable Data Execution Prevention (DEP)
  302. // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
  303. // A failure is non-critical and needs no further attention!
  304. #ifndef PROCESS_DEP_ENABLE
  305. // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
  306. // which is not correct. Can be removed, when GCCs winbase.h is fixed!
  307. #define PROCESS_DEP_ENABLE 0x00000001
  308. #endif
  309. typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
  310. PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
  311. if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
  312. // Initialize Windows Sockets
  313. WSADATA wsadata;
  314. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  315. if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
  316. {
  317. return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
  318. }
  319. #endif
  320. #ifndef WIN32
  321. umask(077);
  322. // Clean shutdown on SIGTERM
  323. struct sigaction sa;
  324. sa.sa_handler = HandleSIGTERM;
  325. sigemptyset(&sa.sa_mask);
  326. sa.sa_flags = 0;
  327. sigaction(SIGTERM, &sa, NULL);
  328. sigaction(SIGINT, &sa, NULL);
  329. // Reopen debug.log on SIGHUP
  330. struct sigaction sa_hup;
  331. sa_hup.sa_handler = HandleSIGHUP;
  332. sigemptyset(&sa_hup.sa_mask);
  333. sa_hup.sa_flags = 0;
  334. sigaction(SIGHUP, &sa_hup, NULL);
  335. #endif
  336. // ********************************************************* Step 2: parameter interactions
  337. Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
  338. if (!SelectParamsFromCommandLine()) {
  339. return InitError("Invalid combination of -testnet and -regtest.");
  340. }
  341. if (mapArgs.count("-bind")) {
  342. // when specifying an explicit binding address, you want to listen on it
  343. // even when -connect or -proxy is specified
  344. SoftSetBoolArg("-listen", true);
  345. }
  346. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
  347. // when only connecting to trusted nodes, do not seed via DNS, or listen by default
  348. SoftSetBoolArg("-dnsseed", false);
  349. SoftSetBoolArg("-listen", false);
  350. }
  351. if (mapArgs.count("-proxy")) {
  352. // to protect privacy, do not listen by default if a proxy server is specified
  353. SoftSetBoolArg("-listen", false);
  354. }
  355. if (!GetBoolArg("-listen", true)) {
  356. // do not map ports or try to retrieve public IP when not listening (pointless)
  357. SoftSetBoolArg("-upnp", false);
  358. SoftSetBoolArg("-discover", false);
  359. }
  360. if (mapArgs.count("-externalip")) {
  361. // if an explicit public IP is specified, do not try to find others
  362. SoftSetBoolArg("-discover", false);
  363. }
  364. if (GetBoolArg("-salvagewallet", false)) {
  365. // Rewrite just private keys: rescan to find transactions
  366. SoftSetBoolArg("-rescan", true);
  367. }
  368. // Make sure enough file descriptors are available
  369. int nBind = std::max((int)mapArgs.count("-bind"), 1);
  370. nMaxConnections = GetArg("-maxconnections", 125);
  371. nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
  372. int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
  373. if (nFD < MIN_CORE_FILEDESCRIPTORS)
  374. return InitError(_("Not enough file descriptors available."));
  375. if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
  376. nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
  377. // ********************************************************* Step 3: parameter-to-internal-flags
  378. fDebug = GetBoolArg("-debug", false);
  379. fBenchmark = GetBoolArg("-benchmark", false);
  380. // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
  381. nScriptCheckThreads = GetArg("-par", 0);
  382. if (nScriptCheckThreads <= 0)
  383. nScriptCheckThreads += boost::thread::hardware_concurrency();
  384. if (nScriptCheckThreads <= 1)
  385. nScriptCheckThreads = 0;
  386. else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
  387. nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
  388. // -debug implies fDebug*
  389. if (fDebug)
  390. fDebugNet = true;
  391. else
  392. fDebugNet = GetBoolArg("-debugnet", false);
  393. if (fDaemon)
  394. fServer = true;
  395. else
  396. fServer = GetBoolArg("-server", false);
  397. /* force fServer when running without GUI */
  398. if (!fHaveGUI)
  399. fServer = true;
  400. fPrintToConsole = GetBoolArg("-printtoconsole", false);
  401. fPrintToDebugger = GetBoolArg("-printtodebugger", false);
  402. fLogTimestamps = GetBoolArg("-logtimestamps", false);
  403. if (mapArgs.count("-timeout"))
  404. {
  405. int nNewTimeout = GetArg("-timeout", 5000);
  406. if (nNewTimeout > 0 && nNewTimeout < 600000)
  407. nConnectTimeout = nNewTimeout;
  408. }
  409. // Continue to put "/P2SH/" in the coinbase to monitor
  410. // BIP16 support.
  411. // This can be removed eventually...
  412. const char* pszP2SH = "/P2SH/";
  413. COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
  414. // Fee-per-kilobyte amount considered the same as "free"
  415. // If you are mining, be careful setting this:
  416. // if you set it to zero then
  417. // a transaction spammer can cheaply fill blocks using
  418. // 1-satoshi-fee transactions. It should be set above the real
  419. // cost to you of processing a transaction.
  420. if (mapArgs.count("-mintxfee"))
  421. {
  422. int64 n = 0;
  423. if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
  424. CTransaction::nMinTxFee = n;
  425. else
  426. return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
  427. }
  428. if (mapArgs.count("-minrelaytxfee"))
  429. {
  430. int64 n = 0;
  431. if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
  432. CTransaction::nMinRelayTxFee = n;
  433. else
  434. return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
  435. }
  436. if (mapArgs.count("-paytxfee"))
  437. {
  438. if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
  439. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
  440. if (nTransactionFee > 0.25 * COIN)
  441. InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
  442. }
  443. // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
  444. std::string strDataDir = GetDataDir().string();
  445. // Make sure only a single Bitcoin process is using the data directory.
  446. boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
  447. FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
  448. if (file) fclose(file);
  449. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  450. if (!lock.try_lock())
  451. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), strDataDir.c_str()));
  452. if (GetBoolArg("-shrinkdebugfile", !fDebug))
  453. ShrinkDebugFile();
  454. printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  455. printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
  456. printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
  457. if (!fLogTimestamps)
  458. printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
  459. printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
  460. printf("Using data directory %s\n", strDataDir.c_str());
  461. printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
  462. std::ostringstream strErrors;
  463. if (fDaemon)
  464. fprintf(stdout, "Bitcoin server starting\n");
  465. if (nScriptCheckThreads) {
  466. printf("Using %u threads for script verification\n", nScriptCheckThreads);
  467. for (int i=0; i<nScriptCheckThreads-1; i++)
  468. threadGroup.create_thread(&ThreadScriptCheck);
  469. }
  470. int64 nStart;
  471. // ********************************************************* Step 5: verify wallet database integrity
  472. uiInterface.InitMessage(_("Verifying wallet..."));
  473. if (!bitdb.Open(GetDataDir()))
  474. {
  475. // try moving the database env out of the way
  476. boost::filesystem::path pathDatabase = GetDataDir() / "database";
  477. boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
  478. try {
  479. boost::filesystem::rename(pathDatabase, pathDatabaseBak);
  480. printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
  481. } catch(boost::filesystem::filesystem_error &error) {
  482. // failure is ok (well, not really, but it's not worse than what we started with)
  483. }
  484. // try again
  485. if (!bitdb.Open(GetDataDir())) {
  486. // if it still fails, it probably means we can't even create the database env
  487. string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
  488. return InitError(msg);
  489. }
  490. }
  491. if (GetBoolArg("-salvagewallet", false))
  492. {
  493. // Recover readable keypairs:
  494. if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
  495. return false;
  496. }
  497. if (filesystem::exists(GetDataDir() / "wallet.dat"))
  498. {
  499. CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
  500. if (r == CDBEnv::RECOVER_OK)
  501. {
  502. string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
  503. " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
  504. " your balance or transactions are incorrect you should"
  505. " restore from a backup."), strDataDir.c_str());
  506. InitWarning(msg);
  507. }
  508. if (r == CDBEnv::RECOVER_FAIL)
  509. return InitError(_("wallet.dat corrupt, salvage failed"));
  510. }
  511. // ********************************************************* Step 6: network initialization
  512. RegisterNodeSignals(GetNodeSignals());
  513. int nSocksVersion = GetArg("-socks", 5);
  514. if (nSocksVersion != 4 && nSocksVersion != 5)
  515. return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
  516. if (mapArgs.count("-onlynet")) {
  517. std::set<enum Network> nets;
  518. BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
  519. enum Network net = ParseNetwork(snet);
  520. if (net == NET_UNROUTABLE)
  521. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
  522. nets.insert(net);
  523. }
  524. for (int n = 0; n < NET_MAX; n++) {
  525. enum Network net = (enum Network)n;
  526. if (!nets.count(net))
  527. SetLimited(net);
  528. }
  529. }
  530. #if defined(USE_IPV6)
  531. #if ! USE_IPV6
  532. else
  533. SetLimited(NET_IPV6);
  534. #endif
  535. #endif
  536. CService addrProxy;
  537. bool fProxy = false;
  538. if (mapArgs.count("-proxy")) {
  539. addrProxy = CService(mapArgs["-proxy"], 9050);
  540. if (!addrProxy.IsValid())
  541. return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
  542. if (!IsLimited(NET_IPV4))
  543. SetProxy(NET_IPV4, addrProxy, nSocksVersion);
  544. if (nSocksVersion > 4) {
  545. #ifdef USE_IPV6
  546. if (!IsLimited(NET_IPV6))
  547. SetProxy(NET_IPV6, addrProxy, nSocksVersion);
  548. #endif
  549. SetNameProxy(addrProxy, nSocksVersion);
  550. }
  551. fProxy = true;
  552. }
  553. // -tor can override normal proxy, -notor disables tor entirely
  554. if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
  555. CService addrOnion;
  556. if (!mapArgs.count("-tor"))
  557. addrOnion = addrProxy;
  558. else
  559. addrOnion = CService(mapArgs["-tor"], 9050);
  560. if (!addrOnion.IsValid())
  561. return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
  562. SetProxy(NET_TOR, addrOnion, 5);
  563. SetReachable(NET_TOR);
  564. }
  565. // see Step 2: parameter interactions for more information about these
  566. fNoListen = !GetBoolArg("-listen", true);
  567. fDiscover = GetBoolArg("-discover", true);
  568. fNameLookup = GetBoolArg("-dns", true);
  569. bool fBound = false;
  570. if (!fNoListen) {
  571. if (mapArgs.count("-bind")) {
  572. BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
  573. CService addrBind;
  574. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  575. return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
  576. fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
  577. }
  578. }
  579. else {
  580. struct in_addr inaddr_any;
  581. inaddr_any.s_addr = INADDR_ANY;
  582. #ifdef USE_IPV6
  583. fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
  584. #endif
  585. fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
  586. }
  587. if (!fBound)
  588. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  589. }
  590. if (mapArgs.count("-externalip")) {
  591. BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
  592. CService addrLocal(strAddr, GetListenPort(), fNameLookup);
  593. if (!addrLocal.IsValid())
  594. return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
  595. AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
  596. }
  597. }
  598. BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
  599. AddOneShot(strDest);
  600. // ********************************************************* Step 7: load block chain
  601. fReindex = GetBoolArg("-reindex", false);
  602. // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
  603. filesystem::path blocksDir = GetDataDir() / "blocks";
  604. if (!filesystem::exists(blocksDir))
  605. {
  606. filesystem::create_directories(blocksDir);
  607. bool linked = false;
  608. for (unsigned int i = 1; i < 10000; i++) {
  609. filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
  610. if (!filesystem::exists(source)) break;
  611. filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
  612. try {
  613. filesystem::create_hard_link(source, dest);
  614. printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
  615. linked = true;
  616. } catch (filesystem::filesystem_error & e) {
  617. // Note: hardlink creation failing is not a disaster, it just means
  618. // blocks will get re-downloaded from peers.
  619. printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
  620. break;
  621. }
  622. }
  623. if (linked)
  624. {
  625. fReindex = true;
  626. }
  627. }
  628. // cache size calculations
  629. size_t nTotalCache = GetArg("-dbcache", 25) << 20;
  630. if (nTotalCache < (1 << 22))
  631. nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
  632. size_t nBlockTreeDBCache = nTotalCache / 8;
  633. if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
  634. nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
  635. nTotalCache -= nBlockTreeDBCache;
  636. size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
  637. nTotalCache -= nCoinDBCache;
  638. nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
  639. bool fLoaded = false;
  640. while (!fLoaded) {
  641. bool fReset = fReindex;
  642. std::string strLoadError;
  643. uiInterface.InitMessage(_("Loading block index..."));
  644. nStart = GetTimeMillis();
  645. do {
  646. try {
  647. UnloadBlockIndex();
  648. delete pcoinsTip;
  649. delete pcoinsdbview;
  650. delete pblocktree;
  651. pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
  652. pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
  653. pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
  654. if (fReindex)
  655. pblocktree->WriteReindexing(true);
  656. if (!LoadBlockIndex()) {
  657. strLoadError = _("Error loading block database");
  658. break;
  659. }
  660. // If the loaded chain has a wrong genesis, bail out immediately
  661. // (we're likely using a testnet datadir, or the other way around).
  662. if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
  663. return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
  664. // Check for changed -txindex state (only necessary if we are not reindexing anyway)
  665. if (!fReindex && fTxIndex != GetBoolArg("-txindex", false)) {
  666. strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
  667. break;
  668. }
  669. // Initialize the block index (no-op if non-empty database was already loaded)
  670. if (!InitBlockIndex()) {
  671. strLoadError = _("Error initializing block database");
  672. break;
  673. }
  674. uiInterface.InitMessage(_("Verifying blocks..."));
  675. if (!VerifyDB()) {
  676. strLoadError = _("Corrupted block database detected");
  677. break;
  678. }
  679. } catch(std::exception &e) {
  680. strLoadError = _("Error opening block database");
  681. break;
  682. }
  683. fLoaded = true;
  684. } while(false);
  685. if (!fLoaded) {
  686. // first suggest a reindex
  687. if (!fReset) {
  688. bool fRet = uiInterface.ThreadSafeMessageBox(
  689. strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
  690. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
  691. if (fRet) {
  692. fReindex = true;
  693. fRequestShutdown = false;
  694. } else {
  695. return false;
  696. }
  697. } else {
  698. return InitError(strLoadError);
  699. }
  700. }
  701. }
  702. // as LoadBlockIndex can take several minutes, it's possible the user
  703. // requested to kill bitcoin-qt during the last operation. If so, exit.
  704. // As the program has not fully started yet, Shutdown() is possibly overkill.
  705. if (fRequestShutdown)
  706. {
  707. printf("Shutdown requested. Exiting.\n");
  708. return false;
  709. }
  710. printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  711. if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false))
  712. {
  713. PrintBlockTree();
  714. return false;
  715. }
  716. if (mapArgs.count("-printblock"))
  717. {
  718. string strMatch = mapArgs["-printblock"];
  719. int nFound = 0;
  720. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  721. {
  722. uint256 hash = (*mi).first;
  723. if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
  724. {
  725. CBlockIndex* pindex = (*mi).second;
  726. CBlock block;
  727. block.ReadFromDisk(pindex);
  728. block.BuildMerkleTree();
  729. block.print();
  730. printf("\n");
  731. nFound++;
  732. }
  733. }
  734. if (nFound == 0)
  735. printf("No blocks matching %s were found\n", strMatch.c_str());
  736. return false;
  737. }
  738. // ********************************************************* Step 8: load wallet
  739. uiInterface.InitMessage(_("Loading wallet..."));
  740. nStart = GetTimeMillis();
  741. bool fFirstRun = true;
  742. pwalletMain = new CWallet("wallet.dat");
  743. DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
  744. if (nLoadWalletRet != DB_LOAD_OK)
  745. {
  746. if (nLoadWalletRet == DB_CORRUPT)
  747. strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
  748. else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
  749. {
  750. string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
  751. " or address book entries might be missing or incorrect."));
  752. InitWarning(msg);
  753. }
  754. else if (nLoadWalletRet == DB_TOO_NEW)
  755. strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
  756. else if (nLoadWalletRet == DB_NEED_REWRITE)
  757. {
  758. strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
  759. printf("%s", strErrors.str().c_str());
  760. return InitError(strErrors.str());
  761. }
  762. else
  763. strErrors << _("Error loading wallet.dat") << "\n";
  764. }
  765. if (GetBoolArg("-upgradewallet", fFirstRun))
  766. {
  767. int nMaxVersion = GetArg("-upgradewallet", 0);
  768. if (nMaxVersion == 0) // the -upgradewallet without argument case
  769. {
  770. printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
  771. nMaxVersion = CLIENT_VERSION;
  772. pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
  773. }
  774. else
  775. printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
  776. if (nMaxVersion < pwalletMain->GetVersion())
  777. strErrors << _("Cannot downgrade wallet") << "\n";
  778. pwalletMain->SetMaxVersion(nMaxVersion);
  779. }
  780. if (fFirstRun)
  781. {
  782. // Create new keyUser and set as default key
  783. RandAddSeedPerfmon();
  784. CPubKey newDefaultKey;
  785. if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
  786. pwalletMain->SetDefaultKey(newDefaultKey);
  787. if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
  788. strErrors << _("Cannot write default address") << "\n";
  789. }
  790. pwalletMain->SetBestChain(CBlockLocator(pindexBest));
  791. }
  792. printf("%s", strErrors.str().c_str());
  793. printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  794. RegisterWallet(pwalletMain);
  795. CBlockIndex *pindexRescan = pindexBest;
  796. if (GetBoolArg("-rescan", false))
  797. pindexRescan = pindexGenesisBlock;
  798. else
  799. {
  800. CWalletDB walletdb("wallet.dat");
  801. CBlockLocator locator;
  802. if (walletdb.ReadBestBlock(locator))
  803. pindexRescan = locator.GetBlockIndex();
  804. else
  805. pindexRescan = pindexGenesisBlock;
  806. }
  807. if (pindexBest && pindexBest != pindexRescan)
  808. {
  809. uiInterface.InitMessage(_("Rescanning..."));
  810. printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
  811. nStart = GetTimeMillis();
  812. pwalletMain->ScanForWalletTransactions(pindexRescan, true);
  813. printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  814. pwalletMain->SetBestChain(CBlockLocator(pindexBest));
  815. nWalletDBUpdated++;
  816. }
  817. // ********************************************************* Step 9: import blocks
  818. // scan for better chains in the block chain database, that are not yet connected in the active best chain
  819. CValidationState state;
  820. if (!ConnectBestBlock(state))
  821. strErrors << "Failed to connect best block";
  822. std::vector<boost::filesystem::path> vImportFiles;
  823. if (mapArgs.count("-loadblock"))
  824. {
  825. BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
  826. vImportFiles.push_back(strFile);
  827. }
  828. threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
  829. // ********************************************************* Step 10: load peers
  830. uiInterface.InitMessage(_("Loading addresses..."));
  831. nStart = GetTimeMillis();
  832. {
  833. CAddrDB adb;
  834. if (!adb.Read(addrman))
  835. printf("Invalid or missing peers.dat; recreating\n");
  836. }
  837. printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
  838. addrman.size(), GetTimeMillis() - nStart);
  839. // ********************************************************* Step 11: start node
  840. if (!CheckDiskSpace())
  841. return false;
  842. if (!strErrors.str().empty())
  843. return InitError(strErrors.str());
  844. RandAddSeedPerfmon();
  845. //// debug print
  846. printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
  847. printf("nBestHeight = %d\n", nBestHeight);
  848. printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
  849. printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
  850. printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
  851. StartNode(threadGroup);
  852. // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
  853. InitRPCMining();
  854. if (fServer)
  855. StartRPCThreads();
  856. // Generate coins in the background
  857. GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
  858. // ********************************************************* Step 12: finished
  859. uiInterface.InitMessage(_("Done loading"));
  860. // Add wallet transactions that aren't already in a block to mapTransactions
  861. pwalletMain->ReacceptWalletTransactions();
  862. // Run a thread to flush wallet periodically
  863. threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
  864. return !fRequestShutdown;
  865. }