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