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