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