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