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

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