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

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