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