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