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

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