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

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