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