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

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