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