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 57KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 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. #if defined(HAVE_CONFIG_H)
  6. #include "config/bitcoin-config.h"
  7. #endif
  8. #include "init.h"
  9. #include "addrman.h"
  10. #include "checkpoints.h"
  11. #include "compat/sanity.h"
  12. #include "key.h"
  13. #include "main.h"
  14. #include "miner.h"
  15. #include "net.h"
  16. #include "rpcserver.h"
  17. #include "txdb.h"
  18. #include "ui_interface.h"
  19. #include "util.h"
  20. #include "utilmoneystr.h"
  21. #ifdef ENABLE_WALLET
  22. #include "db.h"
  23. #include "wallet.h"
  24. #include "walletdb.h"
  25. #endif
  26. #include <stdint.h>
  27. #include <stdio.h>
  28. #ifndef WIN32
  29. #include <signal.h>
  30. #endif
  31. #include <boost/algorithm/string/predicate.hpp>
  32. #include <boost/algorithm/string/replace.hpp>
  33. #include <boost/filesystem.hpp>
  34. #include <boost/interprocess/sync/file_lock.hpp>
  35. #include <boost/thread.hpp>
  36. #include <openssl/crypto.h>
  37. using namespace boost;
  38. using namespace std;
  39. #ifdef ENABLE_WALLET
  40. CWallet* pwalletMain = NULL;
  41. #endif
  42. #ifdef WIN32
  43. // Win32 LevelDB doesn't use filedescriptors, and the ones used for
  44. // accessing block files, don't count towards to fd_set size limit
  45. // anyway.
  46. #define MIN_CORE_FILEDESCRIPTORS 0
  47. #else
  48. #define MIN_CORE_FILEDESCRIPTORS 150
  49. #endif
  50. // Used to pass flags to the Bind() function
  51. enum BindFlags {
  52. BF_NONE = 0,
  53. BF_EXPLICIT = (1U << 0),
  54. BF_REPORT_ERROR = (1U << 1),
  55. BF_WHITELIST = (1U << 2),
  56. };
  57. static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
  58. CClientUIInterface uiInterface;
  59. //////////////////////////////////////////////////////////////////////////////
  60. //
  61. // Shutdown
  62. //
  63. //
  64. // Thread management and startup/shutdown:
  65. //
  66. // The network-processing threads are all part of a thread group
  67. // created by AppInit() or the Qt main() function.
  68. //
  69. // A clean exit happens when StartShutdown() or the SIGTERM
  70. // signal handler sets fRequestShutdown, which triggers
  71. // the DetectShutdownThread(), which interrupts the main thread group.
  72. // DetectShutdownThread() then exits, which causes AppInit() to
  73. // continue (it .joins the shutdown thread).
  74. // Shutdown() is then
  75. // called to clean up database connections, and stop other
  76. // threads that should only be stopped after the main network-processing
  77. // threads have exited.
  78. //
  79. // Note that if running -daemon the parent process returns from AppInit2
  80. // before adding any threads to the threadGroup, so .join_all() returns
  81. // immediately and the parent exits from main().
  82. //
  83. // Shutdown for Qt is very similar, only it uses a QTimer to detect
  84. // fRequestShutdown getting set, and then does the normal Qt
  85. // shutdown thing.
  86. //
  87. volatile bool fRequestShutdown = false;
  88. void StartShutdown()
  89. {
  90. fRequestShutdown = true;
  91. }
  92. bool ShutdownRequested()
  93. {
  94. return fRequestShutdown;
  95. }
  96. static CCoinsViewDB *pcoinsdbview = NULL;
  97. void Shutdown()
  98. {
  99. LogPrintf("%s: In progress...\n", __func__);
  100. static CCriticalSection cs_Shutdown;
  101. TRY_LOCK(cs_Shutdown, lockShutdown);
  102. if (!lockShutdown)
  103. return;
  104. RenameThread("bitcoin-shutoff");
  105. mempool.AddTransactionsUpdated(1);
  106. StopRPCThreads();
  107. #ifdef ENABLE_WALLET
  108. if (pwalletMain)
  109. bitdb.Flush(false);
  110. GenerateBitcoins(false, NULL, 0);
  111. #endif
  112. StopNode();
  113. UnregisterNodeSignals(GetNodeSignals());
  114. {
  115. boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
  116. CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
  117. if (est_fileout)
  118. mempool.WriteFeeEstimates(est_fileout);
  119. else
  120. LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
  121. }
  122. {
  123. LOCK(cs_main);
  124. #ifdef ENABLE_WALLET
  125. if (pwalletMain)
  126. pwalletMain->SetBestChain(chainActive.GetLocator());
  127. #endif
  128. if (pblocktree)
  129. pblocktree->Flush();
  130. if (pcoinsTip)
  131. pcoinsTip->Flush();
  132. delete pcoinsTip;
  133. pcoinsTip = NULL;
  134. delete pcoinsdbview;
  135. pcoinsdbview = NULL;
  136. delete pblocktree;
  137. pblocktree = NULL;
  138. }
  139. #ifdef ENABLE_WALLET
  140. if (pwalletMain)
  141. bitdb.Flush(true);
  142. #endif
  143. #ifndef WIN32
  144. boost::filesystem::remove(GetPidFile());
  145. #endif
  146. UnregisterAllWallets();
  147. #ifdef ENABLE_WALLET
  148. delete pwalletMain;
  149. pwalletMain = NULL;
  150. #endif
  151. LogPrintf("%s: done\n", __func__);
  152. }
  153. //
  154. // Signal handlers are very limited in what they are allowed to do, so:
  155. //
  156. void HandleSIGTERM(int)
  157. {
  158. fRequestShutdown = true;
  159. }
  160. void HandleSIGHUP(int)
  161. {
  162. fReopenDebugLog = true;
  163. }
  164. bool static InitError(const std::string &str)
  165. {
  166. uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
  167. return false;
  168. }
  169. bool static InitWarning(const std::string &str)
  170. {
  171. uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
  172. return true;
  173. }
  174. bool static Bind(const CService &addr, unsigned int flags) {
  175. if (!(flags & BF_EXPLICIT) && IsLimited(addr))
  176. return false;
  177. std::string strError;
  178. if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
  179. if (flags & BF_REPORT_ERROR)
  180. return InitError(strError);
  181. return false;
  182. }
  183. return true;
  184. }
  185. std::string HelpMessage(HelpMessageMode mode)
  186. {
  187. // When adding new options to the categories, please keep and ensure alphabetical ordering.
  188. string strUsage = _("Options:") + "\n";
  189. strUsage += " -? " + _("This help message") + "\n";
  190. strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)") + "\n";
  191. strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n";
  192. strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n";
  193. strUsage += " -checklevel=<n> " + _("How thorough the block verification of -checkblocks is (0-4, default: 3)") + "\n";
  194. strUsage += " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n";
  195. if (mode == HMM_BITCOIND)
  196. {
  197. #if !defined(WIN32)
  198. strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n";
  199. #endif
  200. }
  201. strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n";
  202. strUsage += " -dbcache=<n> " + strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache) + "\n";
  203. strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + " " + _("on startup") + "\n";
  204. strUsage += " -maxorphanblocks=<n> " + strprintf(_("Keep at most <n> unconnectable blocks in memory (default: %u)"), DEFAULT_MAX_ORPHAN_BLOCKS) + "\n";
  205. strUsage += " -maxorphantx=<n> " + strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS) + "\n";
  206. strUsage += " -par=<n> " + strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS) + "\n";
  207. #ifndef WIN32
  208. strUsage += " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n";
  209. #endif
  210. strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup") + "\n";
  211. #if !defined(WIN32)
  212. strUsage += " -sysperms " + _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)") + "\n";
  213. #endif
  214. strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n";
  215. strUsage += "\n" + _("Connection options:") + "\n";
  216. strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n";
  217. strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n";
  218. strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n";
  219. strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n";
  220. strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n";
  221. strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n";
  222. strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)") + "\n";
  223. strUsage += " -dnsseed " + _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)") + "\n";
  224. strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n";
  225. strUsage += " -forcednsseed " + _("Always query for peer addresses via DNS lookup (default: 0)") + "\n";
  226. strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n";
  227. strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n";
  228. strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n";
  229. strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n";
  230. strUsage += " -onion=<ip:port> " + _("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)") + "\n";
  231. strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)") + "\n";
  232. strUsage += " -permitbaremultisig " + _("Relay non-P2SH multisig (default: 1)") + "\n";
  233. strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n";
  234. strUsage += " -proxy=<ip:port> " + _("Connect through SOCKS5 proxy") + "\n";
  235. strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n";
  236. strUsage += " -timeout=<n> " + strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT) + "\n";
  237. #ifdef USE_UPNP
  238. #if USE_UPNP
  239. strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n";
  240. #else
  241. strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n";
  242. #endif
  243. #endif
  244. strUsage += " -whitebind=<addr> " + _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6") + "\n";
  245. strUsage += " -whitelist=<netmask> " + _("Whitelist peers connecting from the given netmask or ip. Can be specified multiple times.") + "\n";
  246. strUsage += " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway") + "\n";
  247. #ifdef ENABLE_WALLET
  248. strUsage += "\n" + _("Wallet options:") + "\n";
  249. strUsage += " -disablewallet " + _("Do not load the wallet and disable wallet RPC calls") + "\n";
  250. strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n";
  251. if (GetBoolArg("-help-debug", false))
  252. strUsage += " -mintxfee=<amt> " + strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for transaction creation (default: %s)"), FormatMoney(CWallet::minTxFee.GetFeePerK())) + "\n";
  253. strUsage += " -paytxfee=<amt> " + strprintf(_("Fee (in BTC/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK())) + "\n";
  254. strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + " " + _("on startup") + "\n";
  255. strUsage += " -respendnotify=<cmd> " + _("Execute command when a network tx respends wallet tx input (%s=respend TxID, %t=wallet TxID)") + "\n";
  256. strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup") + "\n";
  257. strUsage += " -spendzeroconfchange " + _("Spend unconfirmed change when sending transactions (default: 1)") + "\n";
  258. strUsage += " -txconfirmtarget=<n> " + _("If paytxfee is not set, include enough fee so transactions are confirmed on average within n blocks (default: 1)") + "\n";
  259. strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + " " + _("on startup") + "\n";
  260. strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + " " + _("(default: wallet.dat)") + "\n";
  261. strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n";
  262. strUsage += " -zapwallettxes=<mode> " + _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") + "\n";
  263. strUsage += " " + _("(default: 1, 1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)") + "\n";
  264. #endif
  265. strUsage += "\n" + _("Debugging/Testing options:") + "\n";
  266. if (GetBoolArg("-help-debug", false))
  267. {
  268. strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n";
  269. strUsage += " -dblogsize=<n> " + _("Flush database activity from memory pool to disk log every <n> megabytes (default: 100)") + "\n";
  270. strUsage += " -disablesafemode " + _("Disable safemode, override a real safe mode event (default: 0)") + "\n";
  271. strUsage += " -testsafemode " + _("Force safe mode (default: 0)") + "\n";
  272. strUsage += " -dropmessagestest=<n> " + _("Randomly drop 1 of every <n> network messages") + "\n";
  273. strUsage += " -fuzzmessagestest=<n> " + _("Randomly fuzz 1 of every <n> network messages") + "\n";
  274. strUsage += " -flushwallet " + _("Run a thread to flush wallet periodically (default: 1)") + "\n";
  275. strUsage += " -stopafterblockimport " + _("Stop running after importing blocks from disk (default: 0)") + "\n";
  276. }
  277. strUsage += " -debug=<category> " + _("Output debugging information (default: 0, supplying <category> is optional)") + "\n";
  278. strUsage += " " + _("If <category> is not supplied, output all debugging information.") + "\n";
  279. strUsage += " " + _("<category> can be:");
  280. strUsage += " addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, net"; // Don't translate these and qt below
  281. if (mode == HMM_BITCOIN_QT)
  282. strUsage += ", qt";
  283. strUsage += ".\n";
  284. #ifdef ENABLE_WALLET
  285. strUsage += " -gen " + _("Generate coins (default: 0)") + "\n";
  286. strUsage += " -genproclimit=<n> " + _("Set the processor limit for when generation is on (-1 = unlimited, default: -1)") + "\n";
  287. #endif
  288. strUsage += " -help-debug " + _("Show all debugging options (usage: --help -help-debug)") + "\n";
  289. strUsage += " -logips " + _("Include IP addresses in debug output (default: 0)") + "\n";
  290. strUsage += " -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n";
  291. if (GetBoolArg("-help-debug", false))
  292. {
  293. strUsage += " -limitfreerelay=<n> " + _("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:15)") + "\n";
  294. strUsage += " -maxsigcachesize=<n> " + _("Limit size of signature cache to <n> entries (default: 50000)") + "\n";
  295. }
  296. strUsage += " -minrelaytxfee=<amt> " + strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for relaying (default: %s)"), FormatMoney(::minRelayTxFee.GetFeePerK())) + "\n";
  297. strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n";
  298. if (GetBoolArg("-help-debug", false))
  299. {
  300. strUsage += " -printblock=<hash> " + _("Print block on startup, if found in block index") + "\n";
  301. strUsage += " -printblocktree " + _("Print block tree on startup (default: 0)") + "\n";
  302. strUsage += " -printpriority " + _("Log transaction priority and fee per kB when mining blocks (default: 0)") + "\n";
  303. strUsage += " -privdb " + _("Sets the DB_PRIVATE flag in the wallet db environment (default: 1)") + "\n";
  304. strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + "\n";
  305. strUsage += " " + _("This is intended for regression testing tools and app development.") + "\n";
  306. strUsage += " " + _("In this mode -genproclimit controls how many blocks are generated immediately.") + "\n";
  307. }
  308. strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n";
  309. strUsage += " -testnet " + _("Use the test network") + "\n";
  310. strUsage += "\n" + _("Node relay options:") + "\n";
  311. strUsage += " -datacarrier " + _("Relay and mine data carrier transactions (default: 1)") + "\n";
  312. strUsage += "\n" + _("Block creation options:") + "\n";
  313. strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n";
  314. strUsage += " -blockmaxsize=<n> " + strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE) + "\n";
  315. strUsage += " -blockprioritysize=<n> " + strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE) + "\n";
  316. strUsage += "\n" + _("RPC server options:") + "\n";
  317. strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n";
  318. strUsage += " -rpcbind=<addr> " + _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)") + "\n";
  319. strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n";
  320. strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n";
  321. strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n";
  322. strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times") + "\n";
  323. strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n";
  324. strUsage += "\n" + _("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
  325. strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
  326. strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n";
  327. strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n";
  328. strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n";
  329. return strUsage;
  330. }
  331. std::string LicenseInfo()
  332. {
  333. return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
  334. "\n" +
  335. FormatParagraph(_("This is experimental software.")) + "\n" +
  336. "\n" +
  337. FormatParagraph(_("Distributed under the MIT/X11 software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
  338. "\n" +
  339. FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) +
  340. "\n";
  341. }
  342. static void BlockNotifyCallback(const uint256& hashNewTip)
  343. {
  344. std::string strCmd = GetArg("-blocknotify", "");
  345. boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
  346. boost::thread t(runCommand, strCmd); // thread runs free
  347. }
  348. struct CImportingNow
  349. {
  350. CImportingNow() {
  351. assert(fImporting == false);
  352. fImporting = true;
  353. }
  354. ~CImportingNow() {
  355. assert(fImporting == true);
  356. fImporting = false;
  357. }
  358. };
  359. void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
  360. {
  361. RenameThread("bitcoin-loadblk");
  362. // -reindex
  363. if (fReindex) {
  364. CImportingNow imp;
  365. int nFile = 0;
  366. while (true) {
  367. CDiskBlockPos pos(nFile, 0);
  368. if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
  369. break; // No block files left to reindex
  370. FILE *file = OpenBlockFile(pos, true);
  371. if (!file)
  372. break; // This error is logged in OpenBlockFile
  373. LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
  374. LoadExternalBlockFile(file, &pos);
  375. nFile++;
  376. }
  377. pblocktree->WriteReindexing(false);
  378. fReindex = false;
  379. LogPrintf("Reindexing finished\n");
  380. // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
  381. InitBlockIndex();
  382. }
  383. // hardcoded $DATADIR/bootstrap.dat
  384. filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
  385. if (filesystem::exists(pathBootstrap)) {
  386. FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
  387. if (file) {
  388. CImportingNow imp;
  389. filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
  390. LogPrintf("Importing bootstrap.dat...\n");
  391. LoadExternalBlockFile(file);
  392. RenameOver(pathBootstrap, pathBootstrapOld);
  393. } else {
  394. LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
  395. }
  396. }
  397. // -loadblock=
  398. BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
  399. FILE *file = fopen(path.string().c_str(), "rb");
  400. if (file) {
  401. CImportingNow imp;
  402. LogPrintf("Importing blocks file %s...\n", path.string());
  403. LoadExternalBlockFile(file);
  404. } else {
  405. LogPrintf("Warning: Could not open blocks file %s\n", path.string());
  406. }
  407. }
  408. if (GetBoolArg("-stopafterblockimport", false)) {
  409. LogPrintf("Stopping after block import\n");
  410. StartShutdown();
  411. }
  412. }
  413. /** Sanity checks
  414. * Ensure that Bitcoin is running in a usable environment with all
  415. * necessary library support.
  416. */
  417. bool InitSanityCheck(void)
  418. {
  419. if(!ECC_InitSanityCheck()) {
  420. InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
  421. "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
  422. return false;
  423. }
  424. if (!glibc_sanity_test() || !glibcxx_sanity_test())
  425. return false;
  426. return true;
  427. }
  428. /** Initialize bitcoin.
  429. * @pre Parameters should be parsed and config file should be read.
  430. */
  431. bool AppInit2(boost::thread_group& threadGroup)
  432. {
  433. // ********************************************************* Step 1: setup
  434. #ifdef _MSC_VER
  435. // Turn off Microsoft heap dump noise
  436. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  437. _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  438. #endif
  439. #if _MSC_VER >= 1400
  440. // Disable confusing "helpful" text message on abort, Ctrl-C
  441. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  442. #endif
  443. #ifdef WIN32
  444. // Enable Data Execution Prevention (DEP)
  445. // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
  446. // A failure is non-critical and needs no further attention!
  447. #ifndef PROCESS_DEP_ENABLE
  448. // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
  449. // which is not correct. Can be removed, when GCCs winbase.h is fixed!
  450. #define PROCESS_DEP_ENABLE 0x00000001
  451. #endif
  452. typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
  453. PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
  454. if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
  455. // Initialize Windows Sockets
  456. WSADATA wsadata;
  457. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  458. if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
  459. {
  460. return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
  461. }
  462. #endif
  463. #ifndef WIN32
  464. if (GetBoolArg("-sysperms", false)) {
  465. #ifdef ENABLE_WALLET
  466. if (!GetBoolArg("-disablewallet", false))
  467. return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
  468. #endif
  469. } else {
  470. umask(077);
  471. }
  472. // Clean shutdown on SIGTERM
  473. struct sigaction sa;
  474. sa.sa_handler = HandleSIGTERM;
  475. sigemptyset(&sa.sa_mask);
  476. sa.sa_flags = 0;
  477. sigaction(SIGTERM, &sa, NULL);
  478. sigaction(SIGINT, &sa, NULL);
  479. // Reopen debug.log on SIGHUP
  480. struct sigaction sa_hup;
  481. sa_hup.sa_handler = HandleSIGHUP;
  482. sigemptyset(&sa_hup.sa_mask);
  483. sa_hup.sa_flags = 0;
  484. sigaction(SIGHUP, &sa_hup, NULL);
  485. #if defined (__SVR4) && defined (__sun)
  486. // ignore SIGPIPE on Solaris
  487. signal(SIGPIPE, SIG_IGN);
  488. #endif
  489. #endif
  490. // ********************************************************* Step 2: parameter interactions
  491. if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
  492. // when specifying an explicit binding address, you want to listen on it
  493. // even when -connect or -proxy is specified
  494. if (SoftSetBoolArg("-listen", true))
  495. LogPrintf("AppInit2 : parameter interaction: -bind or -whitebind set -> setting -listen=1\n");
  496. }
  497. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
  498. // when only connecting to trusted nodes, do not seed via DNS, or listen by default
  499. if (SoftSetBoolArg("-dnsseed", false))
  500. LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n");
  501. if (SoftSetBoolArg("-listen", false))
  502. LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n");
  503. }
  504. if (mapArgs.count("-proxy")) {
  505. // to protect privacy, do not listen by default if a default proxy server is specified
  506. if (SoftSetBoolArg("-listen", false))
  507. LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -listen=0\n");
  508. }
  509. if (!GetBoolArg("-listen", true)) {
  510. // do not map ports or try to retrieve public IP when not listening (pointless)
  511. if (SoftSetBoolArg("-upnp", false))
  512. LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n");
  513. if (SoftSetBoolArg("-discover", false))
  514. LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n");
  515. }
  516. if (mapArgs.count("-externalip")) {
  517. // if an explicit public IP is specified, do not try to find others
  518. if (SoftSetBoolArg("-discover", false))
  519. LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n");
  520. }
  521. if (GetBoolArg("-salvagewallet", false)) {
  522. // Rewrite just private keys: rescan to find transactions
  523. if (SoftSetBoolArg("-rescan", true))
  524. LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n");
  525. }
  526. // -zapwallettx implies a rescan
  527. if (GetBoolArg("-zapwallettxes", false)) {
  528. if (SoftSetBoolArg("-rescan", true))
  529. LogPrintf("AppInit2 : parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n");
  530. }
  531. // Make sure enough file descriptors are available
  532. int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
  533. nMaxConnections = GetArg("-maxconnections", 125);
  534. nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
  535. int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
  536. if (nFD < MIN_CORE_FILEDESCRIPTORS)
  537. return InitError(_("Not enough file descriptors available."));
  538. if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
  539. nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
  540. // ********************************************************* Step 3: parameter-to-internal-flags
  541. fDebug = !mapMultiArgs["-debug"].empty();
  542. // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
  543. const vector<string>& categories = mapMultiArgs["-debug"];
  544. if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
  545. fDebug = false;
  546. // Check for -debugnet
  547. if (GetBoolArg("-debugnet", false))
  548. InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
  549. // Check for -socks - as this is a privacy risk to continue, exit here
  550. if (mapArgs.count("-socks"))
  551. return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
  552. // Check for -tor - as this is a privacy risk to continue, exit here
  553. if (GetBoolArg("-tor", false))
  554. return InitError(_("Error: Unsupported argument -tor found, use -onion."));
  555. if (GetBoolArg("-benchmark", false))
  556. InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
  557. // Checkmempool defaults to true in regtest mode
  558. mempool.setSanityCheck(GetBoolArg("-checkmempool", Params().DefaultCheckMemPool()));
  559. Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
  560. // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
  561. nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
  562. if (nScriptCheckThreads <= 0)
  563. nScriptCheckThreads += boost::thread::hardware_concurrency();
  564. if (nScriptCheckThreads <= 1)
  565. nScriptCheckThreads = 0;
  566. else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
  567. nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
  568. fServer = GetBoolArg("-server", false);
  569. fPrintToConsole = GetBoolArg("-printtoconsole", false);
  570. fLogTimestamps = GetBoolArg("-logtimestamps", true);
  571. fLogIPs = GetBoolArg("-logips", false);
  572. #ifdef ENABLE_WALLET
  573. bool fDisableWallet = GetBoolArg("-disablewallet", false);
  574. #endif
  575. nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
  576. if (nConnectTimeout <= 0)
  577. nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
  578. // Continue to put "/P2SH/" in the coinbase to monitor
  579. // BIP16 support.
  580. // This can be removed eventually...
  581. const char* pszP2SH = "/P2SH/";
  582. COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
  583. // Fee-per-kilobyte amount considered the same as "free"
  584. // If you are mining, be careful setting this:
  585. // if you set it to zero then
  586. // a transaction spammer can cheaply fill blocks using
  587. // 1-satoshi-fee transactions. It should be set above the real
  588. // cost to you of processing a transaction.
  589. if (mapArgs.count("-minrelaytxfee"))
  590. {
  591. CAmount n = 0;
  592. if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
  593. ::minRelayTxFee = CFeeRate(n);
  594. else
  595. return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
  596. }
  597. #ifdef ENABLE_WALLET
  598. if (mapArgs.count("-mintxfee"))
  599. {
  600. CAmount n = 0;
  601. if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
  602. CWallet::minTxFee = CFeeRate(n);
  603. else
  604. return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
  605. }
  606. if (mapArgs.count("-paytxfee"))
  607. {
  608. CAmount nFeePerK = 0;
  609. if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
  610. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
  611. if (nFeePerK > nHighTransactionFeeWarning)
  612. InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
  613. payTxFee = CFeeRate(nFeePerK, 1000);
  614. if (payTxFee < ::minRelayTxFee)
  615. {
  616. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
  617. mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
  618. }
  619. }
  620. nTxConfirmTarget = GetArg("-txconfirmtarget", 1);
  621. bSpendZeroConfChange = GetArg("-spendzeroconfchange", true);
  622. std::string strWalletFile = GetArg("-wallet", "wallet.dat");
  623. #endif // ENABLE_WALLET
  624. fIsBareMultisigStd = GetArg("-permitbaremultisig", true) != 0;
  625. // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
  626. // Sanity check
  627. if (!InitSanityCheck())
  628. return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
  629. std::string strDataDir = GetDataDir().string();
  630. #ifdef ENABLE_WALLET
  631. // Wallet file must be a plain filename without a directory
  632. if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
  633. return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
  634. #endif
  635. // Make sure only a single Bitcoin process is using the data directory.
  636. boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
  637. FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
  638. if (file) fclose(file);
  639. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  640. if (!lock.try_lock())
  641. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
  642. #ifndef WIN32
  643. CreatePidFile(GetPidFile(), getpid());
  644. #endif
  645. if (GetBoolArg("-shrinkdebugfile", !fDebug))
  646. ShrinkDebugFile();
  647. LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  648. LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
  649. LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
  650. #ifdef ENABLE_WALLET
  651. LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
  652. #endif
  653. if (!fLogTimestamps)
  654. LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
  655. LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
  656. LogPrintf("Using data directory %s\n", strDataDir);
  657. LogPrintf("Using config file %s\n", GetConfigFile().string());
  658. LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
  659. std::ostringstream strErrors;
  660. if (nScriptCheckThreads) {
  661. LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
  662. for (int i=0; i<nScriptCheckThreads-1; i++)
  663. threadGroup.create_thread(&ThreadScriptCheck);
  664. }
  665. int64_t nStart;
  666. // ********************************************************* Step 5: verify wallet database integrity
  667. #ifdef ENABLE_WALLET
  668. if (!fDisableWallet) {
  669. LogPrintf("Using wallet %s\n", strWalletFile);
  670. uiInterface.InitMessage(_("Verifying wallet..."));
  671. if (!bitdb.Open(GetDataDir()))
  672. {
  673. // try moving the database env out of the way
  674. boost::filesystem::path pathDatabase = GetDataDir() / "database";
  675. boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
  676. try {
  677. boost::filesystem::rename(pathDatabase, pathDatabaseBak);
  678. LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
  679. } catch(boost::filesystem::filesystem_error &error) {
  680. // failure is ok (well, not really, but it's not worse than what we started with)
  681. }
  682. // try again
  683. if (!bitdb.Open(GetDataDir())) {
  684. // if it still fails, it probably means we can't even create the database env
  685. string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir);
  686. return InitError(msg);
  687. }
  688. }
  689. if (GetBoolArg("-salvagewallet", false))
  690. {
  691. // Recover readable keypairs:
  692. if (!CWalletDB::Recover(bitdb, strWalletFile, true))
  693. return false;
  694. }
  695. if (filesystem::exists(GetDataDir() / strWalletFile))
  696. {
  697. CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover);
  698. if (r == CDBEnv::RECOVER_OK)
  699. {
  700. string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
  701. " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
  702. " your balance or transactions are incorrect you should"
  703. " restore from a backup."), strDataDir);
  704. InitWarning(msg);
  705. }
  706. if (r == CDBEnv::RECOVER_FAIL)
  707. return InitError(_("wallet.dat corrupt, salvage failed"));
  708. }
  709. } // (!fDisableWallet)
  710. #endif // ENABLE_WALLET
  711. // ********************************************************* Step 6: network initialization
  712. RegisterNodeSignals(GetNodeSignals());
  713. if (mapArgs.count("-onlynet")) {
  714. std::set<enum Network> nets;
  715. BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
  716. enum Network net = ParseNetwork(snet);
  717. if (net == NET_UNROUTABLE)
  718. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
  719. nets.insert(net);
  720. }
  721. for (int n = 0; n < NET_MAX; n++) {
  722. enum Network net = (enum Network)n;
  723. if (!nets.count(net))
  724. SetLimited(net);
  725. }
  726. }
  727. if (mapArgs.count("-whitelist")) {
  728. BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
  729. CSubNet subnet(net);
  730. if (!subnet.IsValid())
  731. return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
  732. CNode::AddWhitelistedRange(subnet);
  733. }
  734. }
  735. CService addrProxy;
  736. bool fProxy = false;
  737. if (mapArgs.count("-proxy")) {
  738. addrProxy = CService(mapArgs["-proxy"], 9050);
  739. if (!addrProxy.IsValid())
  740. return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"]));
  741. if (!IsLimited(NET_IPV4))
  742. SetProxy(NET_IPV4, addrProxy);
  743. if (!IsLimited(NET_IPV6))
  744. SetProxy(NET_IPV6, addrProxy);
  745. SetNameProxy(addrProxy);
  746. fProxy = true;
  747. }
  748. // -onion can override normal proxy, -noonion disables tor entirely
  749. if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") &&
  750. (fProxy || mapArgs.count("-onion"))) {
  751. CService addrOnion;
  752. if (!mapArgs.count("-onion"))
  753. addrOnion = addrProxy;
  754. else
  755. addrOnion = CService(mapArgs["-onion"], 9050);
  756. if (!addrOnion.IsValid())
  757. return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs["-onion"]));
  758. SetProxy(NET_TOR, addrOnion);
  759. SetReachable(NET_TOR);
  760. }
  761. // see Step 2: parameter interactions for more information about these
  762. fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
  763. fDiscover = GetBoolArg("-discover", true);
  764. fNameLookup = GetBoolArg("-dns", true);
  765. bool fBound = false;
  766. if (fListen) {
  767. if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
  768. BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
  769. CService addrBind;
  770. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  771. return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
  772. fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
  773. }
  774. BOOST_FOREACH(std::string strBind, mapMultiArgs["-whitebind"]) {
  775. CService addrBind;
  776. if (!Lookup(strBind.c_str(), addrBind, 0, false))
  777. return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
  778. if (addrBind.GetPort() == 0)
  779. return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
  780. fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
  781. }
  782. }
  783. else {
  784. struct in_addr inaddr_any;
  785. inaddr_any.s_addr = INADDR_ANY;
  786. fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
  787. fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
  788. }
  789. if (!fBound)
  790. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  791. }
  792. if (mapArgs.count("-externalip")) {
  793. BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
  794. CService addrLocal(strAddr, GetListenPort(), fNameLookup);
  795. if (!addrLocal.IsValid())
  796. return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
  797. AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
  798. }
  799. }
  800. BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
  801. AddOneShot(strDest);
  802. // ********************************************************* Step 7: load block chain
  803. fReindex = GetBoolArg("-reindex", false);
  804. // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
  805. filesystem::path blocksDir = GetDataDir() / "blocks";
  806. if (!filesystem::exists(blocksDir))
  807. {
  808. filesystem::create_directories(blocksDir);
  809. bool linked = false;
  810. for (unsigned int i = 1; i < 10000; i++) {
  811. filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
  812. if (!filesystem::exists(source)) break;
  813. filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
  814. try {
  815. filesystem::create_hard_link(source, dest);
  816. LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
  817. linked = true;
  818. } catch (filesystem::filesystem_error & e) {
  819. // Note: hardlink creation failing is not a disaster, it just means
  820. // blocks will get re-downloaded from peers.
  821. LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
  822. break;
  823. }
  824. }
  825. if (linked)
  826. {
  827. fReindex = true;
  828. }
  829. }
  830. // cache size calculations
  831. size_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
  832. if (nTotalCache < (nMinDbCache << 20))
  833. nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache
  834. else if (nTotalCache > (nMaxDbCache << 20))
  835. nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache
  836. size_t nBlockTreeDBCache = nTotalCache / 8;
  837. if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
  838. nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
  839. nTotalCache -= nBlockTreeDBCache;
  840. size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
  841. nTotalCache -= nCoinDBCache;
  842. nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
  843. bool fLoaded = false;
  844. while (!fLoaded) {
  845. bool fReset = fReindex;
  846. std::string strLoadError;
  847. uiInterface.InitMessage(_("Loading block index..."));
  848. nStart = GetTimeMillis();
  849. do {
  850. try {
  851. UnloadBlockIndex();
  852. delete pcoinsTip;
  853. delete pcoinsdbview;
  854. delete pblocktree;
  855. pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
  856. pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
  857. pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
  858. if (fReindex)
  859. pblocktree->WriteReindexing(true);
  860. if (!LoadBlockIndex()) {
  861. strLoadError = _("Error loading block database");
  862. break;
  863. }
  864. // If the loaded chain has a wrong genesis, bail out immediately
  865. // (we're likely using a testnet datadir, or the other way around).
  866. if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL)
  867. return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
  868. // Initialize the block index (no-op if non-empty database was already loaded)
  869. if (!InitBlockIndex()) {
  870. strLoadError = _("Error initializing block database");
  871. break;
  872. }
  873. // Check for changed -txindex state
  874. if (fTxIndex != GetBoolArg("-txindex", false)) {
  875. strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
  876. break;
  877. }
  878. uiInterface.InitMessage(_("Verifying blocks..."));
  879. if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
  880. GetArg("-checkblocks", 288))) {
  881. strLoadError = _("Corrupted block database detected");
  882. break;
  883. }
  884. } catch(std::exception &e) {
  885. if (fDebug) LogPrintf("%s\n", e.what());
  886. strLoadError = _("Error opening block database");
  887. break;
  888. }
  889. fLoaded = true;
  890. } while(false);
  891. if (!fLoaded) {
  892. // first suggest a reindex
  893. if (!fReset) {
  894. bool fRet = uiInterface.ThreadSafeMessageBox(
  895. strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
  896. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
  897. if (fRet) {
  898. fReindex = true;
  899. fRequestShutdown = false;
  900. } else {
  901. LogPrintf("Aborted block database rebuild. Exiting.\n");
  902. return false;
  903. }
  904. } else {
  905. return InitError(strLoadError);
  906. }
  907. }
  908. }
  909. // As LoadBlockIndex can take several minutes, it's possible the user
  910. // requested to kill the GUI during the last operation. If so, exit.
  911. // As the program has not fully started yet, Shutdown() is possibly overkill.
  912. if (fRequestShutdown)
  913. {
  914. LogPrintf("Shutdown requested. Exiting.\n");
  915. return false;
  916. }
  917. LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
  918. if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false))
  919. {
  920. PrintBlockTree();
  921. return false;
  922. }
  923. if (mapArgs.count("-printblock"))
  924. {
  925. string strMatch = mapArgs["-printblock"];
  926. int nFound = 0;
  927. for (BlockMap::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  928. {
  929. uint256 hash = (*mi).first;
  930. if (boost::algorithm::starts_with(hash.ToString(), strMatch))
  931. {
  932. CBlockIndex* pindex = (*mi).second;
  933. CBlock block;
  934. ReadBlockFromDisk(block, pindex);
  935. block.BuildMerkleTree();
  936. LogPrintf("%s\n", block.ToString());
  937. nFound++;
  938. }
  939. }
  940. if (nFound == 0)
  941. LogPrintf("No blocks matching %s were found\n", strMatch);
  942. return false;
  943. }
  944. boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
  945. CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
  946. // Allowed to fail as this file IS missing on first startup.
  947. if (est_filein)
  948. mempool.ReadFeeEstimates(est_filein);
  949. // ********************************************************* Step 8: load wallet
  950. #ifdef ENABLE_WALLET
  951. if (fDisableWallet) {
  952. pwalletMain = NULL;
  953. LogPrintf("Wallet disabled!\n");
  954. } else {
  955. // needed to restore wallet transaction meta data after -zapwallettxes
  956. std::vector<CWalletTx> vWtx;
  957. if (GetBoolArg("-zapwallettxes", false)) {
  958. uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
  959. pwalletMain = new CWallet(strWalletFile);
  960. DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
  961. if (nZapWalletRet != DB_LOAD_OK) {
  962. uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
  963. return false;
  964. }
  965. delete pwalletMain;
  966. pwalletMain = NULL;
  967. }
  968. uiInterface.InitMessage(_("Loading wallet..."));
  969. nStart = GetTimeMillis();
  970. bool fFirstRun = true;
  971. pwalletMain = new CWallet(strWalletFile);
  972. DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
  973. if (nLoadWalletRet != DB_LOAD_OK)
  974. {
  975. if (nLoadWalletRet == DB_CORRUPT)
  976. strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
  977. else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
  978. {
  979. string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
  980. " or address book entries might be missing or incorrect."));
  981. InitWarning(msg);
  982. }
  983. else if (nLoadWalletRet == DB_TOO_NEW)
  984. strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
  985. else if (nLoadWalletRet == DB_NEED_REWRITE)
  986. {
  987. strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
  988. LogPrintf("%s", strErrors.str());
  989. return InitError(strErrors.str());
  990. }
  991. else
  992. strErrors << _("Error loading wallet.dat") << "\n";
  993. }
  994. if (GetBoolArg("-upgradewallet", fFirstRun))
  995. {
  996. int nMaxVersion = GetArg("-upgradewallet", 0);
  997. if (nMaxVersion == 0) // the -upgradewallet without argument case
  998. {
  999. LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
  1000. nMaxVersion = CLIENT_VERSION;
  1001. pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
  1002. }
  1003. else
  1004. LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
  1005. if (nMaxVersion < pwalletMain->GetVersion())
  1006. strErrors << _("Cannot downgrade wallet") << "\n";
  1007. pwalletMain->SetMaxVersion(nMaxVersion);
  1008. }
  1009. if (fFirstRun)
  1010. {
  1011. // Create new keyUser and set as default key
  1012. RandAddSeedPerfmon();
  1013. CPubKey newDefaultKey;
  1014. if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
  1015. pwalletMain->SetDefaultKey(newDefaultKey);
  1016. if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
  1017. strErrors << _("Cannot write default address") << "\n";
  1018. }
  1019. pwalletMain->SetBestChain(chainActive.GetLocator());
  1020. }
  1021. LogPrintf("%s", strErrors.str());
  1022. LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
  1023. RegisterWallet(pwalletMain);
  1024. CBlockIndex *pindexRescan = chainActive.Tip();
  1025. if (GetBoolArg("-rescan", false))
  1026. pindexRescan = chainActive.Genesis();
  1027. else
  1028. {
  1029. CWalletDB walletdb(strWalletFile);
  1030. CBlockLocator locator;
  1031. if (walletdb.ReadBestBlock(locator))
  1032. pindexRescan = FindForkInGlobalIndex(chainActive, locator);
  1033. else
  1034. pindexRescan = chainActive.Genesis();
  1035. }
  1036. if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
  1037. {
  1038. uiInterface.InitMessage(_("Rescanning..."));
  1039. LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
  1040. nStart = GetTimeMillis();
  1041. pwalletMain->ScanForWalletTransactions(pindexRescan, true);
  1042. LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
  1043. pwalletMain->SetBestChain(chainActive.GetLocator());
  1044. nWalletDBUpdated++;
  1045. // Restore wallet transaction metadata after -zapwallettxes=1
  1046. if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
  1047. {
  1048. BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
  1049. {
  1050. uint256 hash = wtxOld.GetHash();
  1051. std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
  1052. if (mi != pwalletMain->mapWallet.end())
  1053. {
  1054. const CWalletTx* copyFrom = &wtxOld;
  1055. CWalletTx* copyTo = &mi->second;
  1056. copyTo->mapValue = copyFrom->mapValue;
  1057. copyTo->vOrderForm = copyFrom->vOrderForm;
  1058. copyTo->nTimeReceived = copyFrom->nTimeReceived;
  1059. copyTo->nTimeSmart = copyFrom->nTimeSmart;
  1060. copyTo->fFromMe = copyFrom->fFromMe;
  1061. copyTo->strFromAccount = copyFrom->strFromAccount;
  1062. copyTo->nOrderPos = copyFrom->nOrderPos;
  1063. copyTo->WriteToDisk();
  1064. }
  1065. }
  1066. }
  1067. }
  1068. } // (!fDisableWallet)
  1069. #else // ENABLE_WALLET
  1070. LogPrintf("No wallet compiled in!\n");
  1071. #endif // !ENABLE_WALLET
  1072. // ********************************************************* Step 9: import blocks
  1073. if (mapArgs.count("-blocknotify"))
  1074. uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
  1075. // scan for better chains in the block chain database, that are not yet connected in the active best chain
  1076. CValidationState state;
  1077. if (!ActivateBestChain(state))
  1078. strErrors << "Failed to connect best block";
  1079. std::vector<boost::filesystem::path> vImportFiles;
  1080. if (mapArgs.count("-loadblock"))
  1081. {
  1082. BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
  1083. vImportFiles.push_back(strFile);
  1084. }
  1085. threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
  1086. // ********************************************************* Step 10: load peers
  1087. uiInterface.InitMessage(_("Loading addresses..."));
  1088. nStart = GetTimeMillis();
  1089. {
  1090. CAddrDB adb;
  1091. if (!adb.Read(addrman))
  1092. LogPrintf("Invalid or missing peers.dat; recreating\n");
  1093. }
  1094. LogPrintf("Loaded %i addresses from peers.dat %dms\n",
  1095. addrman.size(), GetTimeMillis() - nStart);
  1096. // ********************************************************* Step 11: start node
  1097. if (!CheckDiskSpace())
  1098. return false;
  1099. if (!strErrors.str().empty())
  1100. return InitError(strErrors.str());
  1101. RandAddSeedPerfmon();
  1102. //// debug print
  1103. LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
  1104. LogPrintf("nBestHeight = %d\n", chainActive.Height());
  1105. #ifdef ENABLE_WALLET
  1106. LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
  1107. LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
  1108. LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
  1109. #endif
  1110. StartNode(threadGroup);
  1111. if (fServer)
  1112. StartRPCThreads();
  1113. #ifdef ENABLE_WALLET
  1114. // Generate coins in the background
  1115. if (pwalletMain)
  1116. GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", -1));
  1117. #endif
  1118. // ********************************************************* Step 12: finished
  1119. uiInterface.InitMessage(_("Done loading"));
  1120. #ifdef ENABLE_WALLET
  1121. if (pwalletMain) {
  1122. // Add wallet transactions that aren't already in a block to mapTransactions
  1123. pwalletMain->ReacceptWalletTransactions();
  1124. // Run a thread to flush wallet periodically
  1125. threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
  1126. }
  1127. #endif
  1128. return !fRequestShutdown;
  1129. }