]>
Commit | Line | Data |
---|---|---|
69d605f4 | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
f914f1a7 | 2 | // Copyright (c) 2009-2014 The Bitcoin Core developers |
c5b390b6 | 3 | // Distributed under the MIT software license, see the accompanying |
3a25a2b9 | 4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5350ea41 | 5 | |
35b8af92 | 6 | #if defined(HAVE_CONFIG_H) |
f3967bcc | 7 | #include "config/bitcoin-config.h" |
35b8af92 CF |
8 | #endif |
9 | ||
663224c2 | 10 | #include "init.h" |
2902ac7c | 11 | #include "crypto/common.h" |
51ed9ec9 | 12 | #include "addrman.h" |
eda37330 | 13 | #include "amount.h" |
8e8b6d70 JG |
14 | #ifdef ENABLE_MINING |
15 | #include "base58.h" | |
16 | #endif | |
51ed9ec9 | 17 | #include "checkpoints.h" |
611116d4 | 18 | #include "compat/sanity.h" |
da29ecbc | 19 | #include "consensus/validation.h" |
4a09e1df | 20 | #include "key.h" |
a9a37c8b | 21 | #include "main.h" |
a6df7ab5 | 22 | #include "metrics.h" |
d247a5d1 | 23 | #include "miner.h" |
51ed9ec9 | 24 | #include "net.h" |
a9a37c8b | 25 | #include "rpcserver.h" |
2aa63292 | 26 | #include "script/standard.h" |
ddd0acd3 | 27 | #include "scheduler.h" |
51ed9ec9 | 28 | #include "txdb.h" |
ed6d0b5f | 29 | #include "ui_interface.h" |
51ed9ec9 | 30 | #include "util.h" |
ad49c256 | 31 | #include "utilmoneystr.h" |
cbb2cf55 | 32 | #include "validationinterface.h" |
48ba56cd | 33 | #ifdef ENABLE_WALLET |
50c72f23 JS |
34 | #include "wallet/wallet.h" |
35 | #include "wallet/walletdb.h" | |
48ba56cd | 36 | #endif |
51ed9ec9 | 37 | #include <stdint.h> |
283e405c | 38 | #include <stdio.h> |
69d605f4 | 39 | |
ed6d0b5f PW |
40 | #ifndef WIN32 |
41 | #include <signal.h> | |
52d3a481 | 42 | #endif |
5f2e76b8 | 43 | |
51ed9ec9 | 44 | #include <boost/algorithm/string/predicate.hpp> |
e9dd83f0 | 45 | #include <boost/algorithm/string/replace.hpp> |
36cba8f1 | 46 | #include <boost/bind.hpp> |
51ed9ec9 | 47 | #include <boost/filesystem.hpp> |
36cba8f1 | 48 | #include <boost/function.hpp> |
51ed9ec9 | 49 | #include <boost/interprocess/sync/file_lock.hpp> |
ad49c256 | 50 | #include <boost/thread.hpp> |
51ed9ec9 BD |
51 | #include <openssl/crypto.h> |
52 | ||
d66877af SB |
53 | #include "libsnark/common/profiling.hpp" |
54 | ||
f200002c JG |
55 | #if ENABLE_ZMQ |
56 | #include "zmq/zmqnotificationinterface.h" | |
57 | #endif | |
58 | ||
00d1980b | 59 | using namespace std; |
69d605f4 | 60 | |
b39e1bdb S |
61 | extern void ThreadSendAlert(); |
62 | ||
2dc35992 | 63 | ZCJoinSplit* pzcashParams = NULL; |
4f1c3798 | 64 | |
48ba56cd | 65 | #ifdef ENABLE_WALLET |
20a11ffa | 66 | CWallet* pwalletMain = NULL; |
48ba56cd | 67 | #endif |
94064710 | 68 | bool fFeeEstimatesInitialized = false; |
e8ef3da7 | 69 | |
f200002c JG |
70 | #if ENABLE_ZMQ |
71 | static CZMQNotificationInterface* pzmqNotificationInterface = NULL; | |
72 | #endif | |
73 | ||
ba29a559 | 74 | #ifdef WIN32 |
df22af00 | 75 | // Win32 LevelDB doesn't use file descriptors, and the ones used for |
7e6d23b1 | 76 | // accessing block files don't count towards the fd_set size limit |
ba29a559 PW |
77 | // anyway. |
78 | #define MIN_CORE_FILEDESCRIPTORS 0 | |
79 | #else | |
80 | #define MIN_CORE_FILEDESCRIPTORS 150 | |
81 | #endif | |
82 | ||
c5b390b6 | 83 | /** Used to pass flags to the Bind() function */ |
c73323ee | 84 | enum BindFlags { |
29e214aa PK |
85 | BF_NONE = 0, |
86 | BF_EXPLICIT = (1U << 0), | |
dc942e6f PW |
87 | BF_REPORT_ERROR = (1U << 1), |
88 | BF_WHITELIST = (1U << 2), | |
c73323ee PK |
89 | }; |
90 | ||
171ca774 | 91 | static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat"; |
b74dcb3b | 92 | CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h |
4751d07e | 93 | |
69d605f4 WL |
94 | ////////////////////////////////////////////////////////////////////////////// |
95 | // | |
96 | // Shutdown | |
97 | // | |
98 | ||
b31499ec GA |
99 | // |
100 | // Thread management and startup/shutdown: | |
101 | // | |
102 | // The network-processing threads are all part of a thread group | |
103 | // created by AppInit() or the Qt main() function. | |
104 | // | |
105 | // A clean exit happens when StartShutdown() or the SIGTERM | |
106 | // signal handler sets fRequestShutdown, which triggers | |
107 | // the DetectShutdownThread(), which interrupts the main thread group. | |
108 | // DetectShutdownThread() then exits, which causes AppInit() to | |
109 | // continue (it .joins the shutdown thread). | |
110 | // Shutdown() is then | |
111 | // called to clean up database connections, and stop other | |
112 | // threads that should only be stopped after the main network-processing | |
113 | // threads have exited. | |
114 | // | |
115 | // Note that if running -daemon the parent process returns from AppInit2 | |
116 | // before adding any threads to the threadGroup, so .join_all() returns | |
117 | // immediately and the parent exits from main(). | |
118 | // | |
119 | // Shutdown for Qt is very similar, only it uses a QTimer to detect | |
723035bb GA |
120 | // fRequestShutdown getting set, and then does the normal Qt |
121 | // shutdown thing. | |
b31499ec GA |
122 | // |
123 | ||
bf673640 | 124 | std::atomic<bool> fRequestShutdown(false); |
69d605f4 | 125 | |
9247134e PK |
126 | void StartShutdown() |
127 | { | |
b31499ec | 128 | fRequestShutdown = true; |
9247134e | 129 | } |
723035bb GA |
130 | bool ShutdownRequested() |
131 | { | |
132 | return fRequestShutdown; | |
133 | } | |
9247134e | 134 | |
13cdce43 PW |
135 | class CCoinsViewErrorCatcher : public CCoinsViewBacked |
136 | { | |
137 | public: | |
138 | CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} | |
139 | bool GetCoins(const uint256 &txid, CCoins &coins) const { | |
140 | try { | |
141 | return CCoinsViewBacked::GetCoins(txid, coins); | |
142 | } catch(const std::runtime_error& e) { | |
143 | uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); | |
144 | LogPrintf("Error reading from database: %s\n", e.what()); | |
145 | // Starting the shutdown sequence and returning false to the caller would be | |
146 | // interpreted as 'entry not found' (as opposed to unable to read data), and | |
c0692346 | 147 | // could lead to invalid interpretation. Just exit immediately, as we can't |
13cdce43 PW |
148 | // continue anyway, and all writes should be atomic. |
149 | abort(); | |
150 | } | |
151 | } | |
152 | // Writes do not need similar protection, as failure to write is handled by the caller. | |
153 | }; | |
154 | ||
20a11ffa | 155 | static CCoinsViewDB *pcoinsdbview = NULL; |
13cdce43 | 156 | static CCoinsViewErrorCatcher *pcoinscatcher = NULL; |
ae8bfd12 | 157 | |
b31499ec | 158 | void Shutdown() |
69d605f4 | 159 | { |
00d1980b | 160 | LogPrintf("%s: In progress...\n", __func__); |
69d605f4 | 161 | static CCriticalSection cs_Shutdown; |
b31499ec | 162 | TRY_LOCK(cs_Shutdown, lockShutdown); |
00d1980b PK |
163 | if (!lockShutdown) |
164 | return; | |
96931d6f | 165 | |
94064710 WL |
166 | /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way, |
167 | /// for example if the data directory was found to be locked. | |
168 | /// Be sure that anything that writes files or flushes caches only does this if the respective | |
169 | /// module was initialized. | |
7662d72b | 170 | RenameThread("zcash-shutoff"); |
319b1160 | 171 | mempool.AddTransactionsUpdated(1); |
21eb5ada | 172 | StopRPCThreads(); |
4a85e067 | 173 | #ifdef ENABLE_WALLET |
b0730874 | 174 | if (pwalletMain) |
2bb1c877 | 175 | pwalletMain->Flush(false); |
8e8b6d70 JG |
176 | #endif |
177 | #ifdef ENABLE_MINING | |
178 | #ifdef ENABLE_WALLET | |
c8b74258 | 179 | GenerateBitcoins(false, NULL, 0); |
8e8b6d70 JG |
180 | #else |
181 | GenerateBitcoins(false, 0); | |
2cc0a252 | 182 | #endif |
48ba56cd | 183 | #endif |
21eb5ada | 184 | StopNode(); |
b2864d2f | 185 | UnregisterNodeSignals(GetNodeSignals()); |
171ca774 | 186 | |
94064710 | 187 | if (fFeeEstimatesInitialized) |
09c744c2 PW |
188 | { |
189 | boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; | |
190 | CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); | |
a8738238 | 191 | if (!est_fileout.IsNull()) |
09c744c2 PW |
192 | mempool.WriteFeeEstimates(est_fileout); |
193 | else | |
194 | LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); | |
94064710 | 195 | fFeeEstimatesInitialized = false; |
09c744c2 | 196 | } |
171ca774 | 197 | |
69d605f4 | 198 | { |
b31499ec | 199 | LOCK(cs_main); |
51ce901a PW |
200 | if (pcoinsTip != NULL) { |
201 | FlushStateToDisk(); | |
202 | } | |
00d1980b PK |
203 | delete pcoinsTip; |
204 | pcoinsTip = NULL; | |
13cdce43 PW |
205 | delete pcoinscatcher; |
206 | pcoinscatcher = NULL; | |
00d1980b PK |
207 | delete pcoinsdbview; |
208 | pcoinsdbview = NULL; | |
209 | delete pblocktree; | |
210 | pblocktree = NULL; | |
69d605f4 | 211 | } |
48ba56cd | 212 | #ifdef ENABLE_WALLET |
b0730874 | 213 | if (pwalletMain) |
2bb1c877 | 214 | pwalletMain->Flush(true); |
48ba56cd | 215 | #endif |
f200002c JG |
216 | |
217 | #if ENABLE_ZMQ | |
218 | if (pzmqNotificationInterface) { | |
219 | UnregisterValidationInterface(pzmqNotificationInterface); | |
f200002c JG |
220 | delete pzmqNotificationInterface; |
221 | pzmqNotificationInterface = NULL; | |
222 | } | |
223 | #endif | |
224 | ||
d6712db3 | 225 | #ifndef WIN32 |
ffdda4e8 AW |
226 | try { |
227 | boost::filesystem::remove(GetPidFile()); | |
228 | } catch (const boost::filesystem::filesystem_error& e) { | |
229 | LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what()); | |
230 | } | |
d6712db3 | 231 | #endif |
a96d1139 | 232 | UnregisterAllValidationInterfaces(); |
48ba56cd | 233 | #ifdef ENABLE_WALLET |
20a11ffa PK |
234 | delete pwalletMain; |
235 | pwalletMain = NULL; | |
48ba56cd | 236 | #endif |
7ee82c43 SB |
237 | delete pzcashParams; |
238 | pzcashParams = NULL; | |
a56054be | 239 | ECC_Stop(); |
00d1980b | 240 | LogPrintf("%s: done\n", __func__); |
69d605f4 WL |
241 | } |
242 | ||
c5b390b6 MF |
243 | /** |
244 | * Signal handlers are very limited in what they are allowed to do, so: | |
245 | */ | |
69d605f4 WL |
246 | void HandleSIGTERM(int) |
247 | { | |
248 | fRequestShutdown = true; | |
249 | } | |
250 | ||
9af080c3 MH |
251 | void HandleSIGHUP(int) |
252 | { | |
253 | fReopenDebugLog = true; | |
254 | } | |
69d605f4 | 255 | |
ac7c7ab9 PW |
256 | bool static InitError(const std::string &str) |
257 | { | |
49d57125 | 258 | uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); |
ac7c7ab9 | 259 | return false; |
ac7c7ab9 PW |
260 | } |
261 | ||
262 | bool static InitWarning(const std::string &str) | |
263 | { | |
49d57125 | 264 | uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); |
ac7c7ab9 PW |
265 | return true; |
266 | } | |
267 | ||
29e214aa | 268 | bool static Bind(const CService &addr, unsigned int flags) { |
c73323ee | 269 | if (!(flags & BF_EXPLICIT) && IsLimited(addr)) |
8f10a288 PW |
270 | return false; |
271 | std::string strError; | |
8d657a65 | 272 | if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { |
c73323ee | 273 | if (flags & BF_REPORT_ERROR) |
587f929c PW |
274 | return InitError(strError); |
275 | return false; | |
276 | } | |
8f10a288 PW |
277 | return true; |
278 | } | |
279 | ||
4401b2d7 EL |
280 | void OnRPCStopped() |
281 | { | |
282 | cvBlockChange.notify_all(); | |
283 | LogPrint("rpc", "RPC stopped.\n"); | |
284 | } | |
285 | ||
286 | void OnRPCPreCommand(const CRPCCommand& cmd) | |
287 | { | |
4401b2d7 EL |
288 | // Observe safe mode |
289 | string strWarning = GetWarnings("rpc"); | |
290 | if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && | |
291 | !cmd.okSafeMode) | |
292 | throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); | |
293 | } | |
294 | ||
1020f599 | 295 | std::string HelpMessage(HelpMessageMode mode) |
9f5b11e6 | 296 | { |
94cd7051 | 297 | const bool showDebug = GetBoolArg("-help-debug", false); |
1fdb9fa3 | 298 | |
1020f599 | 299 | // When adding new options to the categories, please keep and ensure alphabetical ordering. |
94cd7051 WL |
300 | // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators |
301 | ||
1fdb9fa3 LV |
302 | string strUsage = HelpMessageGroup(_("Options:")); |
303 | strUsage += HelpMessageOpt("-?", _("This help message")); | |
4d9c7fe6 | 304 | strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS)); |
1fdb9fa3 LV |
305 | 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)")); |
306 | strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)")); | |
307 | strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288)); | |
308 | strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3)); | |
aaf64959 | 309 | strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "zcash.conf")); |
1020f599 | 310 | if (mode == HMM_BITCOIND) |
7398f4a7 CL |
311 | { |
312 | #if !defined(WIN32) | |
1fdb9fa3 | 313 | strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands")); |
7398f4a7 CL |
314 | #endif |
315 | } | |
1fdb9fa3 | 316 | strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); |
9064d73b | 317 | strUsage += HelpMessageOpt("-exportdir=<dir>", _("Specify directory to be used when exporting data")); |
1fdb9fa3 LV |
318 | strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache)); |
319 | strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup")); | |
320 | strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS)); | |
321 | 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)"), | |
322 | -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS)); | |
d6712db3 | 323 | #ifndef WIN32 |
aaf64959 | 324 | strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "zcashd.pid")); |
d6712db3 | 325 | #endif |
fc44231c WL |
326 | strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode disables wallet support and is incompatible with -txindex. " |
327 | "Warning: Reverting this setting requires re-downloading the entire blockchain. " | |
328 | "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); | |
a1d0ec44 | 329 | strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup")); |
bdd5b587 | 330 | #if !defined(WIN32) |
1fdb9fa3 | 331 | strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)")); |
bdd5b587 | 332 | #endif |
1fdb9fa3 LV |
333 | strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0)); |
334 | ||
335 | strUsage += HelpMessageGroup(_("Connection options:")); | |
336 | strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open")); | |
337 | strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100)); | |
338 | strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400)); | |
339 | strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6")); | |
340 | strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)")); | |
341 | strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)")); | |
342 | strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)")); | |
343 | strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)")); | |
344 | strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address")); | |
345 | strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0)); | |
346 | strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)")); | |
347 | strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), 125)); | |
348 | strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000)); | |
349 | strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000)); | |
350 | strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy")); | |
351 | strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)")); | |
352 | strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1)); | |
3985a40d | 353 | strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8233, 18233)); |
1fdb9fa3 | 354 | strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy")); |
67a79493 | 355 | strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1)); |
1fdb9fa3 LV |
356 | strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect")); |
357 | strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT)); | |
9f5b11e6 WL |
358 | #ifdef USE_UPNP |
359 | #if USE_UPNP | |
1fdb9fa3 | 360 | strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening)")); |
9f5b11e6 | 361 | #else |
1fdb9fa3 | 362 | strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0)); |
2a03a390 | 363 | #endif |
9f5b11e6 | 364 | #endif |
1fdb9fa3 LV |
365 | strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6")); |
366 | strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") + | |
367 | " " + _("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")); | |
7398f4a7 CL |
368 | |
369 | #ifdef ENABLE_WALLET | |
1fdb9fa3 LV |
370 | strUsage += HelpMessageGroup(_("Wallet options:")); |
371 | strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls")); | |
372 | strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100)); | |
94cd7051 WL |
373 | if (showDebug) |
374 | strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in BTC/Kb) smaller than this are considered zero fee for transaction creation (default: %s)", | |
1fdb9fa3 LV |
375 | FormatMoney(CWallet::minTxFee.GetFeePerK()))); |
376 | strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in BTC/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK()))); | |
df22af00 | 377 | strUsage += HelpMessageOpt("-rescan", _("Rescan the blockchain for missing wallet transactions") + " " + _("on startup")); |
1fdb9fa3 LV |
378 | strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup")); |
379 | strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0)); | |
380 | strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1)); | |
77ed59df | 381 | strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET)); |
7e6d23b1 | 382 | strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)"), |
1fdb9fa3 LV |
383 | FormatMoney(maxTxFee))); |
384 | strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup")); | |
385 | strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat")); | |
6f252627 | 386 | strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true)); |
1fdb9fa3 LV |
387 | strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)")); |
388 | strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") + | |
389 | " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)")); | |
390 | ||
7398f4a7 CL |
391 | #endif |
392 | ||
f200002c JG |
393 | #if ENABLE_ZMQ |
394 | strUsage += HelpMessageGroup(_("ZeroMQ notification options:")); | |
395 | strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>")); | |
57c6ef01 | 396 | strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>")); |
f200002c | 397 | strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>")); |
57c6ef01 | 398 | strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>")); |
f200002c JG |
399 | #endif |
400 | ||
1fdb9fa3 | 401 | strUsage += HelpMessageGroup(_("Debugging/Testing options:")); |
94cd7051 | 402 | if (showDebug) |
7398f4a7 | 403 | { |
94cd7051 WL |
404 | strUsage += HelpMessageOpt("-checkpoints", strprintf("Only accept block chain matching built-in checkpoints (default: %u)", 1)); |
405 | strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100)); | |
406 | strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0)); | |
407 | strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0)); | |
408 | strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages"); | |
409 | strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages"); | |
410 | strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1)); | |
411 | strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0)); | |
7398f4a7 | 412 | } |
53e9a6a0 | 413 | string debugCategories = "addrman, alert, bench, coindb, db, estimatefee, lock, mempool, net, partitioncheck, pow, proxy, prune, " |
6550e972 | 414 | "rand, reindex, rpc, selectcoins, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these and qt below |
1020f599 | 415 | if (mode == HMM_BITCOIN_QT) |
1fdb9fa3 LV |
416 | debugCategories += ", qt"; |
417 | strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " + | |
53e9a6a0 | 418 | _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + debugCategories + "."); |
1f015f6a | 419 | strUsage += HelpMessageOpt("-experimentalfeatures", _("Enable use of experimental features")); |
1fdb9fa3 LV |
420 | strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)")); |
421 | strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0)); | |
422 | strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1)); | |
94cd7051 | 423 | if (showDebug) |
3b570559 | 424 | { |
94cd7051 | 425 | strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15)); |
a5150a15 | 426 | strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 0)); |
94cd7051 | 427 | strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000)); |
3b570559 | 428 | } |
1fdb9fa3 LV |
429 | strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for relaying (default: %s)"), FormatMoney(::minRelayTxFee.GetFeePerK()))); |
430 | strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file")); | |
94cd7051 | 431 | if (showDebug) |
3b570559 | 432 | { |
94cd7051 WL |
433 | strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0)); |
434 | strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1)); | |
435 | strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. " | |
436 | "This is intended for regression testing tools and app development."); | |
3b570559 | 437 | } |
1fdb9fa3 LV |
438 | strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)")); |
439 | strUsage += HelpMessageOpt("-testnet", _("Use the test network")); | |
440 | ||
441 | strUsage += HelpMessageGroup(_("Node relay options:")); | |
442 | strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1)); | |
443 | strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY)); | |
444 | ||
445 | strUsage += HelpMessageGroup(_("Block creation options:")); | |
446 | strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0)); | |
447 | strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE)); | |
448 | strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE)); | |
449 | ||
78ba3472 JG |
450 | #ifdef ENABLE_MINING |
451 | strUsage += HelpMessageGroup(_("Mining options:")); | |
452 | strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0)); | |
453 | strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1)); | |
454 | strUsage += HelpMessageOpt("-equihashsolver=<name>", _("Specify the Equihash solver to be used if enabled (default: \"default\")")); | |
455 | strUsage += HelpMessageOpt("-mineraddress=<addr>", _("Send mined coins to a specific single address")); | |
f49bcdf9 JG |
456 | strUsage += HelpMessageOpt("-minetolocalwallet", strprintf( |
457 | _("Require that mined blocks use a coinbase address in the local wallet (default: %u)"), | |
458 | #ifdef ENABLE_WALLET | |
459 | 1 | |
460 | #else | |
461 | 0 | |
462 | #endif | |
463 | )); | |
78ba3472 JG |
464 | #endif |
465 | ||
1fdb9fa3 LV |
466 | strUsage += HelpMessageGroup(_("RPC server options:")); |
467 | strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands")); | |
468 | strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0)); | |
469 | 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)")); | |
470 | strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); | |
471 | strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); | |
3985a40d | 472 | strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8232, 18232)); |
1fdb9fa3 LV |
473 | 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")); |
474 | strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), 4)); | |
f4404d7b S |
475 | |
476 | // TODO #1856: Re-enable support for persistent connections. | |
477 | // Disabled to avoid rpc deadlock #1680, until we backport upstream changes which replace boost::asio with libevent, or another solution is implemented. | |
478 | //strUsage += HelpMessageOpt("-rpckeepalive", strprintf(_("RPC support for HTTP persistent connections (default: %d)"), 1)); | |
008fccfa S |
479 | |
480 | // Disabled until we can lock notes and also tune performance of libsnark which by default uses multiple threads | |
481 | //strUsage += HelpMessageOpt("-rpcasyncthreads=<n>", strprintf(_("Set the number of threads to service Async RPC calls (default: %d)"), 1)); | |
1fdb9fa3 LV |
482 | |
483 | strUsage += HelpMessageGroup(_("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)")); | |
484 | strUsage += HelpMessageOpt("-rpcssl", _("Use OpenSSL (https) for JSON-RPC connections")); | |
485 | strUsage += HelpMessageOpt("-rpcsslcertificatechainfile=<file.cert>", strprintf(_("Server certificate file (default: %s)"), "server.cert")); | |
486 | strUsage += HelpMessageOpt("-rpcsslprivatekeyfile=<file.pem>", strprintf(_("Server private key (default: %s)"), "server.pem")); | |
487 | strUsage += HelpMessageOpt("-rpcsslciphers=<ciphers>", strprintf(_("Acceptable ciphers (default: %s)"), "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH")); | |
9f5b11e6 | 488 | |
f7547079 LV |
489 | if (mode == HMM_BITCOIN_QT) |
490 | { | |
491 | strUsage += HelpMessageGroup(_("UI Options:")); | |
94cd7051 WL |
492 | if (showDebug) { |
493 | strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", "Allow self signed root certificates (default: 0)"); | |
f7547079 LV |
494 | } |
495 | strUsage += HelpMessageOpt("-choosedatadir", _("Choose data directory on startup (default: 0)")); | |
496 | strUsage += HelpMessageOpt("-lang=<lang>", _("Set language, for example \"de_DE\" (default: system locale)")); | |
497 | strUsage += HelpMessageOpt("-min", _("Start minimized")); | |
498 | strUsage += HelpMessageOpt("-rootcertificates=<file>", _("Set SSL root certificates for payment request (default: -system-)")); | |
499 | strUsage += HelpMessageOpt("-splash", _("Show splash screen on startup (default: 1)")); | |
18f656d2 JG |
500 | } else if (mode == HMM_BITCOIND) { |
501 | strUsage += HelpMessageGroup(_("Metrics Options (only if -daemon and -printtoconsole are not set):")); | |
0076a80a JG |
502 | strUsage += HelpMessageOpt("-showmetrics", _("Show metrics on stdout (default: 1 if running in a console, 0 otherwise)")); |
503 | strUsage += HelpMessageOpt("-metricsui", _("Set to 1 for a persistent metrics screen, 0 for sequential metrics output (default: 1 if running in a console, 0 otherwise)")); | |
504 | strUsage += HelpMessageOpt("-metricsrefreshtime", strprintf(_("Number of seconds between metrics refreshes (default: %u if running in a console, %u otherwise)"), 1, 600)); | |
f7547079 LV |
505 | } |
506 | ||
9f5b11e6 WL |
507 | return strUsage; |
508 | } | |
509 | ||
c7b6117d JG |
510 | static void BlockNotifyCallback(const uint256& hashNewTip) |
511 | { | |
512 | std::string strCmd = GetArg("-blocknotify", ""); | |
513 | ||
514 | boost::replace_all(strCmd, "%s", hashNewTip.GetHex()); | |
515 | boost::thread t(runCommand, strCmd); // thread runs free | |
516 | } | |
517 | ||
7a5b7535 PW |
518 | struct CImportingNow |
519 | { | |
520 | CImportingNow() { | |
521 | assert(fImporting == false); | |
522 | fImporting = true; | |
523 | } | |
524 | ||
525 | ~CImportingNow() { | |
526 | assert(fImporting == true); | |
527 | fImporting = false; | |
528 | } | |
529 | }; | |
530 | ||
f9ec3f0f | 531 | |
532 | // If we're using -prune with -reindex, then delete block files that will be ignored by the | |
533 | // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile | |
6cb70ca4 AW |
534 | // is missing, do the same here to delete any later block files after a gap. Also delete all |
535 | // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile | |
536 | // is in sync with what's actually on disk by the time we start downloading, so that pruning | |
537 | // works correctly. | |
538 | void CleanupBlockRevFiles() | |
f9ec3f0f | 539 | { |
6cb70ca4 AW |
540 | using namespace boost::filesystem; |
541 | map<string, path> mapBlockFiles; | |
542 | ||
543 | // Glob all blk?????.dat and rev?????.dat files from the blocks directory. | |
544 | // Remove the rev files immediately and insert the blk file paths into an | |
545 | // ordered map keyed by block file index. | |
546 | LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n"); | |
547 | path blocksdir = GetDataDir() / "blocks"; | |
548 | for (directory_iterator it(blocksdir); it != directory_iterator(); it++) { | |
549 | if (is_regular_file(*it) && | |
550 | it->path().filename().string().length() == 12 && | |
551 | it->path().filename().string().substr(8,4) == ".dat") | |
552 | { | |
553 | if (it->path().filename().string().substr(0,3) == "blk") | |
554 | mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path(); | |
555 | else if (it->path().filename().string().substr(0,3) == "rev") | |
556 | remove(it->path()); | |
557 | } | |
558 | } | |
f9ec3f0f | 559 | |
6cb70ca4 AW |
560 | // Remove all block files that aren't part of a contiguous set starting at |
561 | // zero by walking the ordered map (keys are block file indices) by | |
562 | // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist) | |
563 | // start removing block files. | |
564 | int nContigCounter = 0; | |
565 | BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) { | |
566 | if (atoi(item.first) == nContigCounter) { | |
567 | nContigCounter++; | |
568 | continue; | |
f9ec3f0f | 569 | } |
6cb70ca4 | 570 | remove(item.second); |
f9ec3f0f | 571 | } |
572 | } | |
573 | ||
21eb5ada GA |
574 | void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) |
575 | { | |
7662d72b | 576 | RenameThread("zcash-loadblk"); |
7fea4846 PW |
577 | // -reindex |
578 | if (fReindex) { | |
579 | CImportingNow imp; | |
580 | int nFile = 0; | |
21eb5ada | 581 | while (true) { |
a8a4b967 | 582 | CDiskBlockPos pos(nFile, 0); |
ec7eb0fa SD |
583 | if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk"))) |
584 | break; // No block files left to reindex | |
7fea4846 PW |
585 | FILE *file = OpenBlockFile(pos, true); |
586 | if (!file) | |
ec7eb0fa | 587 | break; // This error is logged in OpenBlockFile |
881a85a2 | 588 | LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); |
7fea4846 PW |
589 | LoadExternalBlockFile(file, &pos); |
590 | nFile++; | |
591 | } | |
21eb5ada GA |
592 | pblocktree->WriteReindexing(false); |
593 | fReindex = false; | |
881a85a2 | 594 | LogPrintf("Reindexing finished\n"); |
21eb5ada GA |
595 | // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): |
596 | InitBlockIndex(); | |
7a5b7535 PW |
597 | } |
598 | ||
599 | // hardcoded $DATADIR/bootstrap.dat | |
a3241998 CF |
600 | boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; |
601 | if (boost::filesystem::exists(pathBootstrap)) { | |
7a5b7535 PW |
602 | FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); |
603 | if (file) { | |
7fea4846 | 604 | CImportingNow imp; |
a3241998 | 605 | boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; |
881a85a2 | 606 | LogPrintf("Importing bootstrap.dat...\n"); |
7a5b7535 PW |
607 | LoadExternalBlockFile(file); |
608 | RenameOver(pathBootstrap, pathBootstrapOld); | |
d54e819f WL |
609 | } else { |
610 | LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string()); | |
7a5b7535 PW |
611 | } |
612 | } | |
613 | ||
7fea4846 | 614 | // -loadblock= |
db954a65 | 615 | BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) { |
7fea4846 PW |
616 | FILE *file = fopen(path.string().c_str(), "rb"); |
617 | if (file) { | |
618 | CImportingNow imp; | |
d54e819f | 619 | LogPrintf("Importing blocks file %s...\n", path.string()); |
7fea4846 | 620 | LoadExternalBlockFile(file); |
d54e819f WL |
621 | } else { |
622 | LogPrintf("Warning: Could not open blocks file %s\n", path.string()); | |
7fea4846 PW |
623 | } |
624 | } | |
1569353b WL |
625 | |
626 | if (GetBoolArg("-stopafterblockimport", false)) { | |
627 | LogPrintf("Stopping after block import\n"); | |
628 | StartShutdown(); | |
629 | } | |
7a5b7535 PW |
630 | } |
631 | ||
4a09e1df AP |
632 | /** Sanity checks |
633 | * Ensure that Bitcoin is running in a usable environment with all | |
634 | * necessary library support. | |
635 | */ | |
636 | bool InitSanityCheck(void) | |
637 | { | |
638 | if(!ECC_InitSanityCheck()) { | |
639 | InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more " | |
640 | "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries"); | |
641 | return false; | |
642 | } | |
92a62207 CF |
643 | if (!glibc_sanity_test() || !glibcxx_sanity_test()) |
644 | return false; | |
4a09e1df AP |
645 | |
646 | return true; | |
647 | } | |
648 | ||
4f1c3798 SB |
649 | |
650 | static void ZC_LoadParams() | |
651 | { | |
652 | struct timeval tv_start, tv_end; | |
653 | float elapsed; | |
654 | ||
27e3f362 SB |
655 | boost::filesystem::path pk_path = ZC_GetParamsDir() / "sprout-proving.key"; |
656 | boost::filesystem::path vk_path = ZC_GetParamsDir() / "sprout-verifying.key"; | |
4f1c3798 | 657 | |
bddf4079 JG |
658 | if (!(boost::filesystem::exists(pk_path) && boost::filesystem::exists(vk_path))) { |
659 | uiInterface.ThreadSafeMessageBox(strprintf( | |
660 | _("Cannot find the Zcash network parameters in the following directory:\n" | |
661 | "%s\n" | |
0b0a48c8 | 662 | "Please run 'zcash-fetch-params' or './zcutil/fetch-params.sh' and then restart."), |
bddf4079 JG |
663 | ZC_GetParamsDir()), |
664 | "", CClientUIInterface::MSG_ERROR); | |
665 | StartShutdown(); | |
666 | return; | |
667 | } | |
668 | ||
2dc35992 | 669 | pzcashParams = ZCJoinSplit::Unopened(); |
4f1c3798 | 670 | |
f4091941 | 671 | LogPrintf("Loading verifying key from %s\n", vk_path.string().c_str()); |
4f1c3798 | 672 | gettimeofday(&tv_start, 0); |
2dc35992 SB |
673 | |
674 | pzcashParams->loadVerifyingKey(vk_path.string()); | |
675 | ||
4f1c3798 SB |
676 | gettimeofday(&tv_end, 0); |
677 | elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000); | |
f4091941 | 678 | LogPrintf("Loaded verifying key in %fs seconds.\n", elapsed); |
4f1c3798 | 679 | |
2dc35992 | 680 | pzcashParams->setProvingKeyPath(pk_path.string()); |
4f1c3798 SB |
681 | } |
682 | ||
9f5b11e6 WL |
683 | /** Initialize bitcoin. |
684 | * @pre Parameters should be parsed and config file should be read. | |
685 | */ | |
ddd0acd3 | 686 | bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) |
69d605f4 | 687 | { |
7d80d2e3 | 688 | // ********************************************************* Step 1: setup |
69d605f4 | 689 | #ifdef _MSC_VER |
814efd6f | 690 | // Turn off Microsoft heap dump noise |
69d605f4 WL |
691 | _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); |
692 | _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); | |
693 | #endif | |
694 | #if _MSC_VER >= 1400 | |
814efd6f | 695 | // Disable confusing "helpful" text message on abort, Ctrl-C |
69d605f4 WL |
696 | _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); |
697 | #endif | |
3d88c9b4 PK |
698 | #ifdef WIN32 |
699 | // Enable Data Execution Prevention (DEP) | |
700 | // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 | |
701 | // A failure is non-critical and needs no further attention! | |
702 | #ifndef PROCESS_DEP_ENABLE | |
f65dddc7 PK |
703 | // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), |
704 | // which is not correct. Can be removed, when GCCs winbase.h is fixed! | |
3d88c9b4 PK |
705 | #define PROCESS_DEP_ENABLE 0x00000001 |
706 | #endif | |
707 | typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); | |
708 | PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); | |
709 | if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); | |
d23fa49c WL |
710 | |
711 | // Initialize Windows Sockets | |
712 | WSADATA wsadata; | |
713 | int ret = WSAStartup(MAKEWORD(2,2), &wsadata); | |
110257a6 | 714 | if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) |
d23fa49c | 715 | { |
110257a6 | 716 | return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret)); |
d23fa49c | 717 | } |
69d605f4 | 718 | #endif |
6853e627 | 719 | #ifndef WIN32 |
bdd5b587 RS |
720 | |
721 | if (GetBoolArg("-sysperms", false)) { | |
722 | #ifdef ENABLE_WALLET | |
723 | if (!GetBoolArg("-disablewallet", false)) | |
724 | return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality"); | |
725 | #endif | |
726 | } else { | |
727 | umask(077); | |
728 | } | |
3d88c9b4 | 729 | |
69d605f4 WL |
730 | // Clean shutdown on SIGTERM |
731 | struct sigaction sa; | |
732 | sa.sa_handler = HandleSIGTERM; | |
733 | sigemptyset(&sa.sa_mask); | |
734 | sa.sa_flags = 0; | |
735 | sigaction(SIGTERM, &sa, NULL); | |
736 | sigaction(SIGINT, &sa, NULL); | |
9af080c3 MH |
737 | |
738 | // Reopen debug.log on SIGHUP | |
739 | struct sigaction sa_hup; | |
740 | sa_hup.sa_handler = HandleSIGHUP; | |
741 | sigemptyset(&sa_hup.sa_mask); | |
742 | sa_hup.sa_flags = 0; | |
743 | sigaction(SIGHUP, &sa_hup, NULL); | |
b34255b7 | 744 | |
745 | #if defined (__SVR4) && defined (__sun) | |
746 | // ignore SIGPIPE on Solaris | |
747 | signal(SIGPIPE, SIG_IGN); | |
748 | #endif | |
69d605f4 WL |
749 | #endif |
750 | ||
7d80d2e3 | 751 | // ********************************************************* Step 2: parameter interactions |
4e382177 | 752 | const CChainParams& chainparams = Params(); |
13f90318 | 753 | |
1f015f6a JG |
754 | // Set this early so that experimental features are correctly enabled/disabled |
755 | fExperimentalMode = GetBoolArg("-experimentalfeatures", false); | |
756 | ||
b8eb3775 JG |
757 | // Fail early if user has set experimental options without the global flag |
758 | if (!fExperimentalMode) { | |
759 | if (mapArgs.count("-developerencryptwallet")) { | |
760 | return InitError(_("Wallet encryption requires -experimentalfeatures.")); | |
761 | } | |
762 | } | |
763 | ||
eadcd0c8 MC |
764 | // Set this early so that parameter interactions go to console |
765 | fPrintToConsole = GetBoolArg("-printtoconsole", false); | |
766 | fLogTimestamps = GetBoolArg("-logtimestamps", true); | |
767 | fLogIPs = GetBoolArg("-logips", false); | |
7d80d2e3 | 768 | |
13f90318 PK |
769 | // when specifying an explicit binding address, you want to listen on it |
770 | // even when -connect or -proxy is specified | |
771 | if (mapArgs.count("-bind")) { | |
772 | if (SoftSetBoolArg("-listen", true)) | |
773 | LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); | |
774 | } | |
775 | if (mapArgs.count("-whitebind")) { | |
df966d1b | 776 | if (SoftSetBoolArg("-listen", true)) |
13f90318 | 777 | LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); |
587f929c | 778 | } |
7d80d2e3 | 779 | |
f161a2c2 | 780 | if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { |
587f929c | 781 | // when only connecting to trusted nodes, do not seed via DNS, or listen by default |
df966d1b | 782 | if (SoftSetBoolArg("-dnsseed", false)) |
13f90318 | 783 | LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); |
df966d1b | 784 | if (SoftSetBoolArg("-listen", false)) |
13f90318 | 785 | LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__); |
587f929c PW |
786 | } |
787 | ||
788 | if (mapArgs.count("-proxy")) { | |
df966d1b PK |
789 | // to protect privacy, do not listen by default if a default proxy server is specified |
790 | if (SoftSetBoolArg("-listen", false)) | |
13f90318 | 791 | LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); |
8c35b6f3 WL |
792 | // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 |
793 | // to listen locally, so don't rely on this happening through -listen below. | |
794 | if (SoftSetBoolArg("-upnp", false)) | |
795 | LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); | |
845c86d1 GM |
796 | // to protect privacy, do not discover addresses by default |
797 | if (SoftSetBoolArg("-discover", false)) | |
13f90318 | 798 | LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__); |
587f929c PW |
799 | } |
800 | ||
13f90318 | 801 | if (!GetBoolArg("-listen", DEFAULT_LISTEN)) { |
587f929c | 802 | // do not map ports or try to retrieve public IP when not listening (pointless) |
df966d1b | 803 | if (SoftSetBoolArg("-upnp", false)) |
13f90318 | 804 | LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__); |
df966d1b | 805 | if (SoftSetBoolArg("-discover", false)) |
13f90318 | 806 | LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__); |
7d80d2e3 PW |
807 | } |
808 | ||
587f929c PW |
809 | if (mapArgs.count("-externalip")) { |
810 | // if an explicit public IP is specified, do not try to find others | |
df966d1b | 811 | if (SoftSetBoolArg("-discover", false)) |
13f90318 | 812 | LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); |
587f929c PW |
813 | } |
814 | ||
3260b4c0 | 815 | if (GetBoolArg("-salvagewallet", false)) { |
eed1785f | 816 | // Rewrite just private keys: rescan to find transactions |
df966d1b | 817 | if (SoftSetBoolArg("-rescan", true)) |
13f90318 | 818 | LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); |
eed1785f GA |
819 | } |
820 | ||
518f3bda JG |
821 | // -zapwallettx implies a rescan |
822 | if (GetBoolArg("-zapwallettxes", false)) { | |
823 | if (SoftSetBoolArg("-rescan", true)) | |
13f90318 | 824 | LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__); |
518f3bda JG |
825 | } |
826 | ||
ba29a559 | 827 | // Make sure enough file descriptors are available |
dc942e6f | 828 | int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1); |
ba29a559 | 829 | nMaxConnections = GetArg("-maxconnections", 125); |
03f49808 | 830 | nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); |
ba29a559 PW |
831 | int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); |
832 | if (nFD < MIN_CORE_FILEDESCRIPTORS) | |
833 | return InitError(_("Not enough file descriptors available.")); | |
834 | if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) | |
835 | nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; | |
836 | ||
f9ec3f0f | 837 | // if using block pruning, then disable txindex |
838 | // also disable the wallet (for now, until SPV support is implemented in wallet) | |
839 | if (GetArg("-prune", 0)) { | |
840 | if (GetBoolArg("-txindex", false)) | |
841 | return InitError(_("Prune mode is incompatible with -txindex.")); | |
842 | #ifdef ENABLE_WALLET | |
843 | if (!GetBoolArg("-disablewallet", false)) { | |
844 | if (SoftSetBoolArg("-disablewallet", true)) | |
845 | LogPrintf("%s : parameter interaction: -prune -> setting -disablewallet=1\n", __func__); | |
846 | else | |
847 | return InitError(_("Can't run with a wallet in prune mode.")); | |
848 | } | |
849 | #endif | |
850 | } | |
851 | ||
7d80d2e3 PW |
852 | // ********************************************************* Step 3: parameter-to-internal-flags |
853 | ||
3b570559 PK |
854 | fDebug = !mapMultiArgs["-debug"].empty(); |
855 | // Special-case: if -debug=0/-nodebug is set, turn off debugging messages | |
856 | const vector<string>& categories = mapMultiArgs["-debug"]; | |
857 | if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) | |
858 | fDebug = false; | |
859 | ||
3307124a S |
860 | // Special case: if debug=zrpcunsafe, implies debug=zrpc, so add it to debug categories |
861 | if (find(categories.begin(), categories.end(), string("zrpcunsafe")) != categories.end()) { | |
862 | if (find(categories.begin(), categories.end(), string("zrpc")) == categories.end()) { | |
43b67537 | 863 | LogPrintf("%s: parameter interaction: setting -debug=zrpcunsafe -> -debug=zrpc\n", __func__); |
3307124a S |
864 | vector<string>& v = mapMultiArgs["-debug"]; |
865 | v.push_back("zrpc"); | |
866 | } | |
867 | } | |
868 | ||
00d1980b | 869 | // Check for -debugnet |
3b570559 | 870 | if (GetBoolArg("-debugnet", false)) |
00d1980b | 871 | InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net.")); |
a339a37b PK |
872 | // Check for -socks - as this is a privacy risk to continue, exit here |
873 | if (mapArgs.count("-socks")) | |
874 | return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); | |
1c750dbd PK |
875 | // Check for -tor - as this is a privacy risk to continue, exit here |
876 | if (GetBoolArg("-tor", false)) | |
877 | return InitError(_("Error: Unsupported argument -tor found, use -onion.")); | |
3b570559 | 878 | |
d70bc52e PW |
879 | if (GetBoolArg("-benchmark", false)) |
880 | InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench.")); | |
881 | ||
3fcfbc8a | 882 | // Checkmempool and checkblockindex default to true in regtest mode |
4e382177 JT |
883 | mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks())); |
884 | fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); | |
a8cdaf5c | 885 | fCheckpointsEnabled = GetBoolArg("-checkpoints", true); |
d07eaba1 | 886 | |
f9cae832 | 887 | // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency |
5409404d | 888 | nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); |
ebd7e8bf DS |
889 | if (nScriptCheckThreads <= 0) |
890 | nScriptCheckThreads += boost::thread::hardware_concurrency(); | |
69e07747 | 891 | if (nScriptCheckThreads <= 1) |
f9cae832 PW |
892 | nScriptCheckThreads = 0; |
893 | else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) | |
894 | nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; | |
895 | ||
8b9adca4 | 896 | fServer = GetBoolArg("-server", false); |
f9ec3f0f | 897 | |
898 | // block pruning; get the amount of disk space (in MB) to allot for block & undo files | |
899 | int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024; | |
900 | if (nSignedPruneTarget < 0) { | |
901 | return InitError(_("Prune cannot be configured with a negative value.")); | |
902 | } | |
903 | nPruneTarget = (uint64_t) nSignedPruneTarget; | |
904 | if (nPruneTarget) { | |
905 | if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) { | |
906 | return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); | |
907 | } | |
908 | LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024); | |
909 | fPruneMode = true; | |
910 | } | |
911 | ||
48ba56cd | 912 | #ifdef ENABLE_WALLET |
e6b7e3dc | 913 | bool fDisableWallet = GetBoolArg("-disablewallet", false); |
48ba56cd | 914 | #endif |
69d605f4 | 915 | |
de10efd1 PK |
916 | nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); |
917 | if (nConnectTimeout <= 0) | |
918 | nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; | |
7d80d2e3 | 919 | |
000dc551 GA |
920 | // Fee-per-kilobyte amount considered the same as "free" |
921 | // If you are mining, be careful setting this: | |
922 | // if you set it to zero then | |
923 | // a transaction spammer can cheaply fill blocks using | |
924 | // 1-satoshi-fee transactions. It should be set above the real | |
925 | // cost to you of processing a transaction. | |
000dc551 GA |
926 | if (mapArgs.count("-minrelaytxfee")) |
927 | { | |
a372168e | 928 | CAmount n = 0; |
000dc551 | 929 | if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0) |
13fc83c7 | 930 | ::minRelayTxFee = CFeeRate(n); |
000dc551 | 931 | else |
7d9d134b | 932 | return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"])); |
000dc551 | 933 | } |
7d80d2e3 | 934 | |
cd7fa8bb | 935 | #ifdef ENABLE_WALLET |
13fc83c7 GA |
936 | if (mapArgs.count("-mintxfee")) |
937 | { | |
a372168e | 938 | CAmount n = 0; |
13fc83c7 GA |
939 | if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0) |
940 | CWallet::minTxFee = CFeeRate(n); | |
941 | else | |
942 | return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"])); | |
943 | } | |
7d80d2e3 PW |
944 | if (mapArgs.count("-paytxfee")) |
945 | { | |
a372168e | 946 | CAmount nFeePerK = 0; |
c6cb21d1 | 947 | if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK)) |
7d9d134b | 948 | return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"])); |
c6cb21d1 | 949 | if (nFeePerK > nHighTransactionFeeWarning) |
e6bc9c35 | 950 | InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); |
c6cb21d1 | 951 | payTxFee = CFeeRate(nFeePerK, 1000); |
13fc83c7 | 952 | if (payTxFee < ::minRelayTxFee) |
b33d1f5e GA |
953 | { |
954 | return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), | |
13fc83c7 | 955 | mapArgs["-paytxfee"], ::minRelayTxFee.ToString())); |
b33d1f5e | 956 | } |
7d80d2e3 | 957 | } |
aa279d61 GM |
958 | if (mapArgs.count("-maxtxfee")) |
959 | { | |
960 | CAmount nMaxFee = 0; | |
961 | if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee)) | |
962 | return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"])); | |
963 | if (nMaxFee > nHighTransactionMaxFeeWarning) | |
964 | InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction.")); | |
965 | maxTxFee = nMaxFee; | |
966 | if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) | |
967 | { | |
968 | return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"), | |
969 | mapArgs["-maxtxfee"], ::minRelayTxFee.ToString())); | |
970 | } | |
971 | } | |
77ed59df | 972 | nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET); |
472b4c5d AM |
973 | bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true); |
974 | fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false); | |
7d80d2e3 | 975 | |
7d4dda76 | 976 | std::string strWalletFile = GetArg("-wallet", "wallet.dat"); |
3da434a2 JG |
977 | #endif // ENABLE_WALLET |
978 | ||
472b4c5d | 979 | fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true); |
2aa63292 | 980 | nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes); |
3da434a2 | 981 | |
4d9c7fe6 WL |
982 | fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS); |
983 | ||
8e8b6d70 JG |
984 | #ifdef ENABLE_MINING |
985 | if (mapArgs.count("-mineraddress")) { | |
986 | CBitcoinAddress addr; | |
987 | if (!addr.SetString(mapArgs["-mineraddress"])) { | |
988 | return InitError(strprintf( | |
989 | _("Invalid address for -mineraddress=<addr>: '%s' (must be a transparent address)"), | |
990 | mapArgs["-mineraddress"])); | |
991 | } | |
992 | } | |
993 | #endif | |
994 | ||
7d80d2e3 | 995 | // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log |
20a11ffa | 996 | |
f4091941 | 997 | // Initialize libsodium |
2902ac7c | 998 | if (init_and_check_sodium() == -1) { |
f4091941 SB |
999 | return false; |
1000 | } | |
1001 | ||
a56054be PW |
1002 | // Initialize elliptic curve code |
1003 | ECC_Start(); | |
1004 | ||
4a09e1df AP |
1005 | // Sanity check |
1006 | if (!InitSanityCheck()) | |
7662d72b | 1007 | return InitError(_("Initialization sanity check failed. Zcash is shutting down.")); |
7d80d2e3 | 1008 | |
22bb0490 | 1009 | std::string strDataDir = GetDataDir().string(); |
48ba56cd | 1010 | #ifdef ENABLE_WALLET |
674cb304 NS |
1011 | // Wallet file must be a plain filename without a directory |
1012 | if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) | |
7d9d134b | 1013 | return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir)); |
48ba56cd | 1014 | #endif |
7d80d2e3 PW |
1015 | // Make sure only a single Bitcoin process is using the data directory. |
1016 | boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; | |
1017 | FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. | |
1018 | if (file) fclose(file); | |
ffdda4e8 AW |
1019 | |
1020 | try { | |
1021 | static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); | |
1022 | if (!lock.try_lock()) | |
7662d72b | 1023 | return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Zcash is probably already running."), strDataDir)); |
ffdda4e8 | 1024 | } catch(const boost::interprocess::interprocess_exception& e) { |
7662d72b | 1025 | return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Zcash is probably already running.") + " %s.", strDataDir, e.what())); |
ffdda4e8 AW |
1026 | } |
1027 | ||
d6712db3 WL |
1028 | #ifndef WIN32 |
1029 | CreatePidFile(GetPidFile(), getpid()); | |
1030 | #endif | |
7f1de3fe | 1031 | if (GetBoolArg("-shrinkdebugfile", !fDebug)) |
69d605f4 | 1032 | ShrinkDebugFile(); |
881a85a2 | 1033 | LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); |
7662d72b | 1034 | LogPrintf("Zcash version %s (%s)\n", FormatFullVersion(), CLIENT_DATE); |
881a85a2 | 1035 | LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); |
d0a2e2eb WL |
1036 | #ifdef ENABLE_WALLET |
1037 | LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0)); | |
1038 | #endif | |
dcb14198 | 1039 | if (!fLogTimestamps) |
7d9d134b WL |
1040 | LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime())); |
1041 | LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); | |
1042 | LogPrintf("Using data directory %s\n", strDataDir); | |
5bd02cf7 | 1043 | LogPrintf("Using config file %s\n", GetConfigFile().string()); |
881a85a2 | 1044 | LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); |
7d80d2e3 | 1045 | std::ostringstream strErrors; |
69d605f4 | 1046 | |
9bdec760 | 1047 | LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); |
f9cae832 | 1048 | if (nScriptCheckThreads) { |
f9cae832 | 1049 | for (int i=0; i<nScriptCheckThreads-1; i++) |
21eb5ada | 1050 | threadGroup.create_thread(&ThreadScriptCheck); |
f9cae832 PW |
1051 | } |
1052 | ||
ddd0acd3 GA |
1053 | // Start the lightweight task scheduler thread |
1054 | CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler); | |
1055 | threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop)); | |
1056 | ||
000499ae JG |
1057 | // Count uptime |
1058 | MarkStartTime(); | |
1059 | ||
d35172fb | 1060 | if ((chainparams.NetworkIDString() != "regtest") && |
57724029 | 1061 | GetBoolArg("-showmetrics", isatty(STDOUT_FILENO)) && |
d35172fb | 1062 | !fPrintToConsole && !GetBoolArg("-daemon", false)) { |
a6df7ab5 | 1063 | // Start the persistent metrics interface |
4ace963c | 1064 | ConnectMetricsScreen(); |
a6df7ab5 JG |
1065 | threadGroup.create_thread(&ThreadShowMetricsScreen); |
1066 | } | |
1067 | ||
f4091941 SB |
1068 | // These must be disabled for now, they are buggy and we probably don't |
1069 | // want any of libsnark's profiling in production anyway. | |
1070 | libsnark::inhibit_profiling_info = true; | |
1071 | libsnark::inhibit_profiling_counters = true; | |
1072 | ||
226a6b32 SB |
1073 | // Initialize Zcash circuit parameters |
1074 | ZC_LoadParams(); | |
1075 | ||
af82884a DK |
1076 | /* Start the RPC server already. It will be started in "warmup" mode |
1077 | * and not really process calls already (but it will signify connections | |
1078 | * that the server is there and will be ready later). Warmup mode will | |
1079 | * be disabled when initialisation is finished. | |
1080 | */ | |
1081 | if (fServer) | |
1082 | { | |
1083 | uiInterface.InitMessage.connect(SetRPCWarmupStatus); | |
4401b2d7 EL |
1084 | RPCServer::OnStopped(&OnRPCStopped); |
1085 | RPCServer::OnPreCommand(&OnRPCPreCommand); | |
af82884a DK |
1086 | StartRPCThreads(); |
1087 | } | |
1088 | ||
51ed9ec9 | 1089 | int64_t nStart; |
7d80d2e3 | 1090 | |
06494cab | 1091 | // ********************************************************* Step 5: verify wallet database integrity |
48ba56cd | 1092 | #ifdef ENABLE_WALLET |
e6b7e3dc | 1093 | if (!fDisableWallet) { |
8a6894ca | 1094 | LogPrintf("Using wallet %s\n", strWalletFile); |
f9ee7a03 | 1095 | uiInterface.InitMessage(_("Verifying wallet...")); |
eed1785f | 1096 | |
2bb1c877 JS |
1097 | std::string warningString; |
1098 | std::string errorString; | |
db954a65 | 1099 | |
2bb1c877 JS |
1100 | if (!CWallet::Verify(strWalletFile, warningString, errorString)) |
1101 | return false; | |
db954a65 | 1102 | |
2bb1c877 JS |
1103 | if (!warningString.empty()) |
1104 | InitWarning(warningString); | |
1105 | if (!errorString.empty()) | |
1106 | return InitError(warningString); | |
db954a65 | 1107 | |
e6b7e3dc | 1108 | } // (!fDisableWallet) |
48ba56cd | 1109 | #endif // ENABLE_WALLET |
eed1785f | 1110 | // ********************************************************* Step 6: network initialization |
7d80d2e3 | 1111 | |
501da250 | 1112 | RegisterNodeSignals(GetNodeSignals()); |
0e4b3175 | 1113 | |
7d80d2e3 PW |
1114 | if (mapArgs.count("-onlynet")) { |
1115 | std::set<enum Network> nets; | |
db954a65 | 1116 | BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) { |
7d80d2e3 PW |
1117 | enum Network net = ParseNetwork(snet); |
1118 | if (net == NET_UNROUTABLE) | |
7d9d134b | 1119 | return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); |
7d80d2e3 PW |
1120 | nets.insert(net); |
1121 | } | |
1122 | for (int n = 0; n < NET_MAX; n++) { | |
1123 | enum Network net = (enum Network)n; | |
1124 | if (!nets.count(net)) | |
1125 | SetLimited(net); | |
1126 | } | |
1127 | } | |
1128 | ||
dc942e6f PW |
1129 | if (mapArgs.count("-whitelist")) { |
1130 | BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) { | |
1131 | CSubNet subnet(net); | |
1132 | if (!subnet.IsValid()) | |
1133 | return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net)); | |
1134 | CNode::AddWhitelistedRange(subnet); | |
1135 | } | |
1136 | } | |
1137 | ||
67a79493 | 1138 | proxyType addrProxy; |
54ce3bad | 1139 | bool fProxy = false; |
587f929c | 1140 | if (mapArgs.count("-proxy")) { |
472b4c5d | 1141 | addrProxy = proxyType(CService(mapArgs["-proxy"], 9050), GetBoolArg("-proxyrandomize", true)); |
587f929c | 1142 | if (!addrProxy.IsValid()) |
7d9d134b | 1143 | return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"])); |
587f929c | 1144 | |
3c777141 GM |
1145 | SetProxy(NET_IPV4, addrProxy); |
1146 | SetProxy(NET_IPV6, addrProxy); | |
0127a9be | 1147 | SetNameProxy(addrProxy); |
54ce3bad PW |
1148 | fProxy = true; |
1149 | } | |
1150 | ||
67a79493 | 1151 | // -onion can override normal proxy, -noonion disables connecting to .onion entirely |
102518fd | 1152 | if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") && |
1c750dbd | 1153 | (fProxy || mapArgs.count("-onion"))) { |
67a79493 | 1154 | proxyType addrOnion; |
1c750dbd | 1155 | if (!mapArgs.count("-onion")) |
54ce3bad PW |
1156 | addrOnion = addrProxy; |
1157 | else | |
472b4c5d | 1158 | addrOnion = proxyType(CService(mapArgs["-onion"], 9050), GetBoolArg("-proxyrandomize", true)); |
54ce3bad | 1159 | if (!addrOnion.IsValid()) |
1c750dbd | 1160 | return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs["-onion"])); |
0127a9be | 1161 | SetProxy(NET_TOR, addrOnion); |
54ce3bad | 1162 | SetReachable(NET_TOR); |
587f929c PW |
1163 | } |
1164 | ||
1165 | // see Step 2: parameter interactions for more information about these | |
56b07d2d | 1166 | fListen = GetBoolArg("-listen", DEFAULT_LISTEN); |
587f929c PW |
1167 | fDiscover = GetBoolArg("-discover", true); |
1168 | fNameLookup = GetBoolArg("-dns", true); | |
928d3a01 | 1169 | |
7d80d2e3 | 1170 | bool fBound = false; |
53a08815 | 1171 | if (fListen) { |
dc942e6f | 1172 | if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { |
db954a65 | 1173 | BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) { |
7d80d2e3 PW |
1174 | CService addrBind; |
1175 | if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) | |
7d9d134b | 1176 | return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind)); |
c73323ee | 1177 | fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); |
7d80d2e3 | 1178 | } |
db954a65 | 1179 | BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) { |
dc942e6f PW |
1180 | CService addrBind; |
1181 | if (!Lookup(strBind.c_str(), addrBind, 0, false)) | |
1182 | return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind)); | |
1183 | if (addrBind.GetPort() == 0) | |
1184 | return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind)); | |
1185 | fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); | |
1186 | } | |
c73323ee PK |
1187 | } |
1188 | else { | |
7d80d2e3 PW |
1189 | struct in_addr inaddr_any; |
1190 | inaddr_any.s_addr = INADDR_ANY; | |
c73323ee | 1191 | fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); |
c73323ee | 1192 | fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); |
7d80d2e3 PW |
1193 | } |
1194 | if (!fBound) | |
587f929c | 1195 | return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); |
928d3a01 JG |
1196 | } |
1197 | ||
c73323ee | 1198 | if (mapArgs.count("-externalip")) { |
db954a65 | 1199 | BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) { |
7d80d2e3 PW |
1200 | CService addrLocal(strAddr, GetListenPort(), fNameLookup); |
1201 | if (!addrLocal.IsValid()) | |
7d9d134b | 1202 | return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr)); |
7d80d2e3 PW |
1203 | AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); |
1204 | } | |
1205 | } | |
1206 | ||
db954a65 | 1207 | BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"]) |
587f929c PW |
1208 | AddOneShot(strDest); |
1209 | ||
f200002c JG |
1210 | #if ENABLE_ZMQ |
1211 | pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs); | |
1212 | ||
1213 | if (pzmqNotificationInterface) { | |
f200002c JG |
1214 | RegisterValidationInterface(pzmqNotificationInterface); |
1215 | } | |
1216 | #endif | |
1217 | ||
729b1806 | 1218 | // ********************************************************* Step 7: load block chain |
7d80d2e3 | 1219 | |
3260b4c0 | 1220 | fReindex = GetBoolArg("-reindex", false); |
7fea4846 | 1221 | |
f4445f99 | 1222 | // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ |
a3241998 CF |
1223 | boost::filesystem::path blocksDir = GetDataDir() / "blocks"; |
1224 | if (!boost::filesystem::exists(blocksDir)) | |
f4445f99 | 1225 | { |
a3241998 | 1226 | boost::filesystem::create_directories(blocksDir); |
f4445f99 GA |
1227 | bool linked = false; |
1228 | for (unsigned int i = 1; i < 10000; i++) { | |
a3241998 CF |
1229 | boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); |
1230 | if (!boost::filesystem::exists(source)) break; | |
1231 | boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); | |
f4445f99 | 1232 | try { |
a3241998 | 1233 | boost::filesystem::create_hard_link(source, dest); |
7d9d134b | 1234 | LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string()); |
f4445f99 | 1235 | linked = true; |
a3241998 | 1236 | } catch (const boost::filesystem::filesystem_error& e) { |
f4445f99 GA |
1237 | // Note: hardlink creation failing is not a disaster, it just means |
1238 | // blocks will get re-downloaded from peers. | |
5262fde0 | 1239 | LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what()); |
f4445f99 GA |
1240 | break; |
1241 | } | |
1242 | } | |
1243 | if (linked) | |
1244 | { | |
1245 | fReindex = true; | |
1246 | } | |
1247 | } | |
1248 | ||
1c83b0a3 | 1249 | // cache size calculations |
b3ed4236 PW |
1250 | int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20); |
1251 | nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache | |
1252 | nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache | |
1253 | int64_t nBlockTreeDBCache = nTotalCache / 8; | |
2d1fa42e | 1254 | if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) |
1c83b0a3 PW |
1255 | nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB |
1256 | nTotalCache -= nBlockTreeDBCache; | |
b3ed4236 | 1257 | int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache |
1c83b0a3 | 1258 | nTotalCache -= nCoinDBCache; |
b3ed4236 PW |
1259 | nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache |
1260 | LogPrintf("Cache configuration:\n"); | |
1261 | LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024)); | |
1262 | LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024)); | |
1263 | LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024)); | |
1c83b0a3 | 1264 | |
f7f3a96b PW |
1265 | bool fLoaded = false; |
1266 | while (!fLoaded) { | |
1267 | bool fReset = fReindex; | |
1268 | std::string strLoadError; | |
bb41a87d | 1269 | |
f7f3a96b | 1270 | uiInterface.InitMessage(_("Loading block index...")); |
ae8bfd12 | 1271 | |
f7f3a96b PW |
1272 | nStart = GetTimeMillis(); |
1273 | do { | |
1274 | try { | |
1275 | UnloadBlockIndex(); | |
1276 | delete pcoinsTip; | |
1277 | delete pcoinsdbview; | |
13cdce43 | 1278 | delete pcoinscatcher; |
f7f3a96b PW |
1279 | delete pblocktree; |
1280 | ||
1281 | pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex); | |
1282 | pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); | |
13cdce43 PW |
1283 | pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview); |
1284 | pcoinsTip = new CCoinsViewCache(pcoinscatcher); | |
f7f3a96b | 1285 | |
f9ec3f0f | 1286 | if (fReindex) { |
f7f3a96b | 1287 | pblocktree->WriteReindexing(true); |
6cb70ca4 | 1288 | //If we're reindexing in prune mode, wipe away unusable block files and all undo data files |
f9ec3f0f | 1289 | if (fPruneMode) |
6cb70ca4 | 1290 | CleanupBlockRevFiles(); |
f9ec3f0f | 1291 | } |
f7f3a96b PW |
1292 | |
1293 | if (!LoadBlockIndex()) { | |
1294 | strLoadError = _("Error loading block database"); | |
1295 | break; | |
1296 | } | |
1297 | ||
5d274c99 PW |
1298 | // If the loaded chain has a wrong genesis, bail out immediately |
1299 | // (we're likely using a testnet datadir, or the other way around). | |
4e382177 | 1300 | if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0) |
5d274c99 PW |
1301 | return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); |
1302 | ||
f7f3a96b PW |
1303 | // Initialize the block index (no-op if non-empty database was already loaded) |
1304 | if (!InitBlockIndex()) { | |
1305 | strLoadError = _("Error initializing block database"); | |
1306 | break; | |
1307 | } | |
1308 | ||
067a6092 PW |
1309 | // Check for changed -txindex state |
1310 | if (fTxIndex != GetBoolArg("-txindex", false)) { | |
1311 | strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); | |
1312 | break; | |
1313 | } | |
1314 | ||
f9ec3f0f | 1315 | // Check for changed -prune state. What we are concerned about is a user who has pruned blocks |
1316 | // in the past, but is now trying to run unpruned. | |
1317 | if (fHavePruned && !fPruneMode) { | |
1318 | strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain"); | |
1319 | break; | |
1320 | } | |
1321 | ||
e1ca89df | 1322 | uiInterface.InitMessage(_("Verifying blocks...")); |
f9ec3f0f | 1323 | if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) { |
1324 | LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n", | |
1325 | MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288)); | |
1326 | } | |
2e280311 | 1327 | if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3), |
d78900cc | 1328 | GetArg("-checkblocks", 288))) { |
f7f3a96b PW |
1329 | strLoadError = _("Corrupted block database detected"); |
1330 | break; | |
1331 | } | |
27df4123 | 1332 | } catch (const std::exception& e) { |
881a85a2 | 1333 | if (fDebug) LogPrintf("%s\n", e.what()); |
f7f3a96b PW |
1334 | strLoadError = _("Error opening block database"); |
1335 | break; | |
1336 | } | |
1f355b66 | 1337 | |
f7f3a96b PW |
1338 | fLoaded = true; |
1339 | } while(false); | |
1340 | ||
1341 | if (!fLoaded) { | |
1342 | // first suggest a reindex | |
1343 | if (!fReset) { | |
5d66d0a1 | 1344 | bool fRet = uiInterface.ThreadSafeQuestion( |
0206e38d | 1345 | strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), |
f42cde3c | 1346 | strLoadError + ".\nPlease restart with -reindex to recover.", |
f7f3a96b PW |
1347 | "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); |
1348 | if (fRet) { | |
1349 | fReindex = true; | |
1350 | fRequestShutdown = false; | |
1351 | } else { | |
881a85a2 | 1352 | LogPrintf("Aborted block database rebuild. Exiting.\n"); |
f7f3a96b PW |
1353 | return false; |
1354 | } | |
1355 | } else { | |
1356 | return InitError(strLoadError); | |
1357 | } | |
1358 | } | |
1359 | } | |
871c3557 | 1360 | |
46469d0f PK |
1361 | // As LoadBlockIndex can take several minutes, it's possible the user |
1362 | // requested to kill the GUI during the last operation. If so, exit. | |
871c3557 B |
1363 | // As the program has not fully started yet, Shutdown() is possibly overkill. |
1364 | if (fRequestShutdown) | |
1365 | { | |
881a85a2 | 1366 | LogPrintf("Shutdown requested. Exiting.\n"); |
871c3557 B |
1367 | return false; |
1368 | } | |
f48742c2 | 1369 | LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); |
69d605f4 | 1370 | |
171ca774 | 1371 | boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; |
eee030f6 | 1372 | CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION); |
00d1980b | 1373 | // Allowed to fail as this file IS missing on first startup. |
a8738238 | 1374 | if (!est_filein.IsNull()) |
171ca774 | 1375 | mempool.ReadFeeEstimates(est_filein); |
94064710 | 1376 | fFeeEstimatesInitialized = true; |
171ca774 | 1377 | |
d66877af | 1378 | |
eed1785f | 1379 | // ********************************************************* Step 8: load wallet |
48ba56cd | 1380 | #ifdef ENABLE_WALLET |
e6b7e3dc JG |
1381 | if (fDisableWallet) { |
1382 | pwalletMain = NULL; | |
1383 | LogPrintf("Wallet disabled!\n"); | |
1384 | } else { | |
77cbd462 CL |
1385 | |
1386 | // needed to restore wallet transaction meta data after -zapwallettxes | |
1387 | std::vector<CWalletTx> vWtx; | |
1388 | ||
518f3bda JG |
1389 | if (GetBoolArg("-zapwallettxes", false)) { |
1390 | uiInterface.InitMessage(_("Zapping all transactions from wallet...")); | |
1391 | ||
1392 | pwalletMain = new CWallet(strWalletFile); | |
77cbd462 | 1393 | DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx); |
518f3bda JG |
1394 | if (nZapWalletRet != DB_LOAD_OK) { |
1395 | uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted")); | |
1396 | return false; | |
1397 | } | |
1398 | ||
1399 | delete pwalletMain; | |
1400 | pwalletMain = NULL; | |
1401 | } | |
1402 | ||
f9ee7a03 | 1403 | uiInterface.InitMessage(_("Loading wallet...")); |
bb41a87d | 1404 | |
f9ee7a03 JG |
1405 | nStart = GetTimeMillis(); |
1406 | bool fFirstRun = true; | |
1407 | pwalletMain = new CWallet(strWalletFile); | |
1408 | DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); | |
1409 | if (nLoadWalletRet != DB_LOAD_OK) | |
eed1785f | 1410 | { |
f9ee7a03 JG |
1411 | if (nLoadWalletRet == DB_CORRUPT) |
1412 | strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; | |
1413 | else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) | |
1414 | { | |
1415 | string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" | |
1416 | " or address book entries might be missing or incorrect.")); | |
1417 | InitWarning(msg); | |
1418 | } | |
1419 | else if (nLoadWalletRet == DB_TOO_NEW) | |
2b410c2f | 1420 | strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n"; |
f9ee7a03 JG |
1421 | else if (nLoadWalletRet == DB_NEED_REWRITE) |
1422 | { | |
2b410c2f | 1423 | strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n"; |
7d9d134b | 1424 | LogPrintf("%s", strErrors.str()); |
f9ee7a03 JG |
1425 | return InitError(strErrors.str()); |
1426 | } | |
1427 | else | |
1428 | strErrors << _("Error loading wallet.dat") << "\n"; | |
eed1785f | 1429 | } |
f9ee7a03 JG |
1430 | |
1431 | if (GetBoolArg("-upgradewallet", fFirstRun)) | |
d764d916 | 1432 | { |
f9ee7a03 JG |
1433 | int nMaxVersion = GetArg("-upgradewallet", 0); |
1434 | if (nMaxVersion == 0) // the -upgradewallet without argument case | |
1435 | { | |
1436 | LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST); | |
1437 | nMaxVersion = CLIENT_VERSION; | |
1438 | pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately | |
1439 | } | |
1440 | else | |
1441 | LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion); | |
1442 | if (nMaxVersion < pwalletMain->GetVersion()) | |
1443 | strErrors << _("Cannot downgrade wallet") << "\n"; | |
1444 | pwalletMain->SetMaxVersion(nMaxVersion); | |
d764d916 | 1445 | } |
439e1497 | 1446 | |
f9ee7a03 | 1447 | if (fFirstRun) |
439e1497 | 1448 | { |
f9ee7a03 | 1449 | // Create new keyUser and set as default key |
f9ee7a03 JG |
1450 | CPubKey newDefaultKey; |
1451 | if (pwalletMain->GetKeyFromPool(newDefaultKey)) { | |
1452 | pwalletMain->SetDefaultKey(newDefaultKey); | |
1453 | if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive")) | |
1454 | strErrors << _("Cannot write default address") << "\n"; | |
1455 | } | |
439e1497 | 1456 | |
f9ee7a03 | 1457 | pwalletMain->SetBestChain(chainActive.GetLocator()); |
360cfe14 | 1458 | } |
95c7db3d | 1459 | |
7d9d134b | 1460 | LogPrintf("%s", strErrors.str()); |
f48742c2 | 1461 | LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart); |
69d605f4 | 1462 | |
a96d1139 | 1463 | RegisterValidationInterface(pwalletMain); |
e8ef3da7 | 1464 | |
f9ee7a03 JG |
1465 | CBlockIndex *pindexRescan = chainActive.Tip(); |
1466 | if (GetBoolArg("-rescan", false)) | |
03f83b9b JG |
1467 | { |
1468 | pwalletMain->ClearNoteWitnessCache(); | |
4c6d41b8 | 1469 | pindexRescan = chainActive.Genesis(); |
03f83b9b | 1470 | } |
f9ee7a03 JG |
1471 | else |
1472 | { | |
1473 | CWalletDB walletdb(strWalletFile); | |
1474 | CBlockLocator locator; | |
1475 | if (walletdb.ReadBestBlock(locator)) | |
6db83db3 | 1476 | pindexRescan = FindForkInGlobalIndex(chainActive, locator); |
f9ee7a03 JG |
1477 | else |
1478 | pindexRescan = chainActive.Genesis(); | |
1479 | } | |
1480 | if (chainActive.Tip() && chainActive.Tip() != pindexRescan) | |
1481 | { | |
1482 | uiInterface.InitMessage(_("Rescanning...")); | |
1483 | LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); | |
1484 | nStart = GetTimeMillis(); | |
1485 | pwalletMain->ScanForWalletTransactions(pindexRescan, true); | |
f48742c2 | 1486 | LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); |
f9ee7a03 JG |
1487 | pwalletMain->SetBestChain(chainActive.GetLocator()); |
1488 | nWalletDBUpdated++; | |
77cbd462 CL |
1489 | |
1490 | // Restore wallet transaction metadata after -zapwallettxes=1 | |
1491 | if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2") | |
1492 | { | |
44bc988e CL |
1493 | CWalletDB walletdb(strWalletFile); |
1494 | ||
77cbd462 CL |
1495 | BOOST_FOREACH(const CWalletTx& wtxOld, vWtx) |
1496 | { | |
805344dc | 1497 | uint256 hash = wtxOld.GetHash(); |
77cbd462 CL |
1498 | std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash); |
1499 | if (mi != pwalletMain->mapWallet.end()) | |
1500 | { | |
1501 | const CWalletTx* copyFrom = &wtxOld; | |
1502 | CWalletTx* copyTo = &mi->second; | |
1503 | copyTo->mapValue = copyFrom->mapValue; | |
1504 | copyTo->vOrderForm = copyFrom->vOrderForm; | |
1505 | copyTo->nTimeReceived = copyFrom->nTimeReceived; | |
1506 | copyTo->nTimeSmart = copyFrom->nTimeSmart; | |
1507 | copyTo->fFromMe = copyFrom->fFromMe; | |
1508 | copyTo->strFromAccount = copyFrom->strFromAccount; | |
1509 | copyTo->nOrderPos = copyFrom->nOrderPos; | |
44bc988e | 1510 | copyTo->WriteToDisk(&walletdb); |
77cbd462 CL |
1511 | } |
1512 | } | |
1513 | } | |
f9ee7a03 | 1514 | } |
6f252627 | 1515 | pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true)); |
e6b7e3dc | 1516 | } // (!fDisableWallet) |
48ba56cd | 1517 | #else // ENABLE_WALLET |
a60bfd81 | 1518 | LogPrintf("No wallet support compiled in!\n"); |
48ba56cd | 1519 | #endif // !ENABLE_WALLET |
e6adac7b | 1520 | |
f49bcdf9 | 1521 | #ifdef ENABLE_MINING |
9bba9b37 | 1522 | #ifndef ENABLE_WALLET |
3df7c4c8 | 1523 | if (GetBoolArg("-minetolocalwallet", false)) { |
9bba9b37 DH |
1524 | return InitError(_("Zcash was not built with wallet support. Set -minetolocalwallet=0 to use -mineraddress, or rebuild Zcash with wallet support.")); |
1525 | } | |
3df7c4c8 | 1526 | if (GetArg("-mineraddress", "").empty() && GetBoolArg("-gen", false)) { |
9bba9b37 DH |
1527 | return InitError(_("Zcash was not built with wallet support. Set -mineraddress, or rebuild Zcash with wallet support.")); |
1528 | } | |
1529 | #endif // !ENABLE_WALLET | |
1530 | ||
f49bcdf9 | 1531 | if (mapArgs.count("-mineraddress")) { |
9bba9b37 | 1532 | #ifdef ENABLE_WALLET |
f49bcdf9 JG |
1533 | bool minerAddressInLocalWallet = false; |
1534 | if (pwalletMain) { | |
1535 | // Address has alreday been validated | |
1536 | CBitcoinAddress addr(mapArgs["-mineraddress"]); | |
1537 | CKeyID keyID; | |
1538 | addr.GetKeyID(keyID); | |
1539 | minerAddressInLocalWallet = pwalletMain->HaveKey(keyID); | |
1540 | } | |
3df7c4c8 | 1541 | if (GetBoolArg("-minetolocalwallet", true) && !minerAddressInLocalWallet) { |
f49bcdf9 JG |
1542 | return InitError(_("-mineraddress is not in the local wallet. Either use a local address, or set -minetolocalwallet=0")); |
1543 | } | |
9bba9b37 | 1544 | #endif // ENABLE_WALLET |
f49bcdf9 JG |
1545 | } |
1546 | #endif // ENABLE_MINING | |
1547 | ||
e6adac7b AW |
1548 | // ********************************************************* Step 9: data directory maintenance |
1549 | ||
1550 | // if pruning, unset the service bit and perform the initial blockstore prune | |
1551 | // after any wallet rescanning has taken place. | |
1552 | if (fPruneMode) { | |
e6adac7b AW |
1553 | LogPrintf("Unsetting NODE_NETWORK on prune mode\n"); |
1554 | nLocalServices &= ~NODE_NETWORK; | |
1555 | if (!fReindex) { | |
dfe55bdc | 1556 | uiInterface.InitMessage(_("Pruning blockstore...")); |
e6adac7b AW |
1557 | PruneAndFlush(); |
1558 | } | |
1559 | } | |
1560 | ||
1561 | // ********************************************************* Step 10: import blocks | |
0fcf91ea | 1562 | |
c7b6117d JG |
1563 | if (mapArgs.count("-blocknotify")) |
1564 | uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); | |
1565 | ||
04140457 | 1566 | uiInterface.InitMessage(_("Activating best chain...")); |
4fea06db | 1567 | // scan for better chains in the block chain database, that are not yet connected in the active best chain |
ef3988ca | 1568 | CValidationState state; |
75f51f2a | 1569 | if (!ActivateBestChain(state)) |
857c61df | 1570 | strErrors << "Failed to connect best block"; |
4fea06db | 1571 | |
21eb5ada | 1572 | std::vector<boost::filesystem::path> vImportFiles; |
7d80d2e3 | 1573 | if (mapArgs.count("-loadblock")) |
69d605f4 | 1574 | { |
db954a65 | 1575 | BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"]) |
21eb5ada | 1576 | vImportFiles.push_back(strFile); |
52c90a2b | 1577 | } |
21eb5ada | 1578 | threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); |
ff09e31a MC |
1579 | if (chainActive.Tip() == NULL) { |
1580 | LogPrintf("Waiting for genesis block to be imported...\n"); | |
1581 | while (!fRequestShutdown && chainActive.Tip() == NULL) | |
1582 | MilliSleep(10); | |
1583 | } | |
52c90a2b | 1584 | |
e6adac7b | 1585 | // ********************************************************* Step 11: start node |
69d605f4 | 1586 | |
69d605f4 WL |
1587 | if (!CheckDiskSpace()) |
1588 | return false; | |
1589 | ||
d605bc4c GA |
1590 | if (!strErrors.str().empty()) |
1591 | return InitError(strErrors.str()); | |
1592 | ||
7d80d2e3 | 1593 | //// debug print |
783b182c | 1594 | LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); |
4c6d41b8 | 1595 | LogPrintf("nBestHeight = %d\n", chainActive.Height()); |
48ba56cd | 1596 | #ifdef ENABLE_WALLET |
783b182c WL |
1597 | LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); |
1598 | LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); | |
1599 | LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0); | |
48ba56cd | 1600 | #endif |
7d80d2e3 | 1601 | |
9a1dcea2 | 1602 | StartNode(threadGroup, scheduler); |
e6334f4a | 1603 | |
36cba8f1 GA |
1604 | // Monitor the chain, and alert if we get blocks much quicker or slower than expected |
1605 | int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing; | |
1606 | CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload, | |
fce474c9 | 1607 | boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing); |
36cba8f1 | 1608 | scheduler.scheduleEvery(f, nPowTargetSpacing); |
e6334f4a | 1609 | |
8e8b6d70 | 1610 | #ifdef ENABLE_MINING |
a0cafb79 | 1611 | // Generate coins in the background |
8e8b6d70 JG |
1612 | #ifdef ENABLE_WALLET |
1613 | if (pwalletMain || !GetArg("-mineraddress", "").empty()) | |
f654f004 | 1614 | GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1)); |
8e8b6d70 JG |
1615 | #else |
1616 | GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1)); | |
1617 | #endif | |
48ba56cd | 1618 | #endif |
a0cafb79 | 1619 | |
94064710 | 1620 | // ********************************************************* Step 11: finished |
7d80d2e3 | 1621 | |
af82884a | 1622 | SetRPCWarmupFinished(); |
7d80d2e3 | 1623 | uiInterface.InitMessage(_("Done loading")); |
7d80d2e3 | 1624 | |
48ba56cd | 1625 | #ifdef ENABLE_WALLET |
b0730874 JG |
1626 | if (pwalletMain) { |
1627 | // Add wallet transactions that aren't already in a block to mapTransactions | |
1628 | pwalletMain->ReacceptWalletTransactions(); | |
7d80d2e3 | 1629 | |
b0730874 JG |
1630 | // Run a thread to flush wallet periodically |
1631 | threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); | |
1632 | } | |
48ba56cd | 1633 | #endif |
69d605f4 | 1634 | |
b39e1bdb S |
1635 | // SENDALERT |
1636 | threadGroup.create_thread(boost::bind(ThreadSendAlert)); | |
1637 | ||
b31499ec | 1638 | return !fRequestShutdown; |
69d605f4 | 1639 | } |