Projects : bitcoin : bitcoin_help_tuneups

bitcoin/src/init.cpp

Dir - Raw

1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2012 The Bitcoin developers
3// Distributed under the MIT/X11 software license, see the accompanying
4// file license.txt or http://www.opensource.org/licenses/mit-license.php.
5#include "headers.h"
6#include "db.h"
7#include "bitcoinrpc.h"
8#include "net.h"
9#include "init.h"
10#include "strlcpy.h"
11#include <boost/filesystem.hpp>
12#include <boost/filesystem/fstream.hpp>
13#include <boost/interprocess/sync/file_lock.hpp>
14
15// v0.5.4 RELEASE (keccak)
16
17using namespace std;
18using namespace boost;
19
20CWallet* pwalletMain;
21
22//////////////////////////////////////////////////////////////////////////////
23//
24// Shutdown
25//
26
27void ExitTimeout(void* parg)
28{
29}
30
31void Shutdown(void* parg)
32{
33 static CCriticalSection cs_Shutdown;
34 static bool fTaken;
35 bool fFirstThread = false;
36 TRY_CRITICAL_BLOCK(cs_Shutdown)
37 {
38 fFirstThread = !fTaken;
39 fTaken = true;
40 }
41 static bool fExit;
42 if (fFirstThread)
43 {
44 fShutdown = true;
45 nTransactionsUpdated++;
46 DBFlush(false);
47 StopNode();
48 DBFlush(true);
49 boost::filesystem::remove(GetPidFile());
50 UnregisterWallet(pwalletMain);
51 delete pwalletMain;
52 CreateThread(ExitTimeout, NULL);
53 Sleep(50);
54 printf("Bitcoin exiting\n\n");
55 fExit = true;
56 exit(0);
57 }
58 else
59 {
60 while (!fExit)
61 Sleep(500);
62 Sleep(100);
63 ExitThread(0);
64 }
65}
66
67void HandleSIGTERM(int)
68{
69 fRequestShutdown = true;
70}
71
72
73
74
75
76
77//////////////////////////////////////////////////////////////////////////////
78//
79// Start
80//
81
82int main(int argc, char* argv[])
83{
84 bool fRet = false;
85 fRet = AppInit(argc, argv);
86
87 if (fRet && fDaemon)
88 return 0;
89
90 return 1;
91}
92
93
94bool AppInit(int argc, char* argv[])
95{
96 bool fRet = false;
97 try
98 {
99 fRet = AppInit2(argc, argv);
100 }
101 catch (std::exception& e) {
102 PrintException(&e, "AppInit()");
103 } catch (...) {
104 PrintException(NULL, "AppInit()");
105 }
106 if (!fRet)
107 Shutdown(NULL);
108 return fRet;
109}
110
111bool AppInit2(int argc, char* argv[])
112{
113 umask(077);
114
115 // Clean shutdown on SIGTERM
116 struct sigaction sa;
117 sa.sa_handler = HandleSIGTERM;
118 sigemptyset(&sa.sa_mask);
119 sa.sa_flags = 0;
120 sigaction(SIGTERM, &sa, NULL);
121 sigaction(SIGINT, &sa, NULL);
122 sigaction(SIGHUP, &sa, NULL);
123
124 //
125 // Parameters
126 //
127 ParseParameters(argc, argv);
128
129 if (mapArgs.count("-datadir"))
130 {
131 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
132 {
133 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
134 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
135 }
136 else
137 {
138 fprintf(stderr, "Error: Specified directory does not exist\n");
139 Shutdown(NULL);
140 }
141 }
142
143
144 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
145
146 if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("--help"))
147 {
148 string strUsage = string() +
149 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
150 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
151 " bitcoind [options] \t " + "\n" +
152 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
153 " bitcoind [options] help \t\t " + _("List commands\n") +
154 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
155 _("Options:\n") +
156 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
157 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
158 " -gen \t\t " + _("Generate coins\n") +
159 " -gen=0 \t\t " + _("Don't generate coins\n") +
160 " -min \t\t " + _("Start minimized\n") +
161 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
162 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
163 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
164 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333)\n") +
165 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
166 " -myip=<ip> \t " + _("Set this node's external IP address.\n") +
167 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
168 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
169 " -nolisten \t " + _("Don't accept connections from outside\n") +
170 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
171 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
172 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
173 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
174 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
175 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
176 " -debug \t\t " + _("Output extra debugging information\n") +
177 " -caneat Permit the use of 'eatblock'\n" +
178 " -verifyall Forbid the skipping of ECDSA signature verification between checkpoints\n" +
179 " -setverstring Set a custom version string\n" +
180 " -setvernum Set a custom version number\n" +
181 " -highs Normalize ECDSA S-values to 'high' when signing\n" +
182 " -lows Normalize ECDSA S-values to 'low' when signing (may be necessary as some implementations refuse to relay transactions with high-S signatures)\n" +
183 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
184 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
185 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
186 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
187 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
188 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
189 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
190 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
191 " -rescan Rescan the block chain for missing wallet transactions\n" +
192 " -disablesafemode Don't lock certain commands when hazards are detected such as DB corruption or network fork\n" +
193 " -? This help message\n";
194
195 // Remove tabs
196 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
197 fprintf(stderr, "%s", strUsage.c_str());
198 return false;
199 }
200
201 fDebug = GetBoolArg("-debug");
202 fDaemon = GetBoolArg("-daemon");
203 fCanEat = GetBoolArg("-caneat");
204 fVerifyAll = GetBoolArg("-verifyall");
205 fHighS = GetBoolArg("-highs");
206 fLowS = GetBoolArg("-lows");
207 fTestSafeMode = GetBoolArg("-testsafemode"); /* undocumented */
208 fDisableSafeMode = GetBoolArg("-disablesafemode");
209
210 if (fHighS && fLowS)
211 {
212 printf("Error: '-highs' and '-lows' can not be set at the same time.\n");
213 return false;
214 }
215
216 if (mapArgs.count("-setverstring"))
217 {
218 CLIENT_NAME = mapArgs["-setverstring"];
219 }
220
221 if (mapArgs.count("-setvernum"))
222 {
223 VERSION = atoi(mapArgs["-setvernum"]);
224 }
225
226 if (fDaemon)
227 fServer = true;
228 else
229 fServer = GetBoolArg("-server");
230
231 /* force fServer when running without GUI */
232 fServer = true;
233 fPrintToConsole = GetBoolArg("-printtoconsole");
234 fPrintToDebugger = GetBoolArg("-printtodebugger");
235 fLogTimestamps = GetBoolArg("-logtimestamps");
236
237 for (int i = 1; i < argc; i++)
238 if (!IsSwitchChar(argv[i][0]))
239 fCommandLine = true;
240
241 if (fCommandLine)
242 {
243 int ret = CommandLineRPC(argc, argv);
244 exit(ret);
245 }
246
247 if (fDaemon)
248 {
249 // Daemonize
250 pid_t pid = fork();
251 if (pid < 0)
252 {
253 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
254 return false;
255 }
256 if (pid > 0)
257 {
258 CreatePidFile(GetPidFile(), pid);
259 return true;
260 }
261
262 pid_t sid = setsid();
263 if (sid < 0)
264 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
265 }
266
267 if (!fDebug && !pszSetDataDir[0])
268 ShrinkDebugFile();
269 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
270 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
271 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
272
273 if (GetBoolArg("-loadblockindextest"))
274 {
275 CTxDB txdb("r");
276 txdb.LoadBlockIndex();
277 PrintBlockTree();
278 return false;
279 }
280
281 // Make sure only a single bitcoin process is using the data directory.
282 string strLockFile = GetDataDir() + "/.lock";
283 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
284 if (file) fclose(file);
285 static boost::interprocess::file_lock lock(strLockFile.c_str());
286 if (!lock.try_lock())
287 {
288 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
289 return false;
290 }
291
292 string strErrors;
293
294 //
295 // Load data files
296 //
297 if (fDaemon)
298 fprintf(stdout, "bitcoin server starting\n");
299 strErrors = "";
300 int64 nStart;
301
302 InitMessage(_("Loading addresses..."));
303 printf("Loading addresses...\n");
304 nStart = GetTimeMillis();
305 if (!LoadAddresses())
306 strErrors += _("Error loading addr.dat \n");
307 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
308
309 InitMessage(_("Loading block index..."));
310 printf("Loading block index...\n");
311 nStart = GetTimeMillis();
312 if (!LoadBlockIndex())
313 strErrors += _("Error loading blkindex.dat \n");
314 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
315
316 InitMessage(_("Loading wallet..."));
317 printf("Loading wallet...\n");
318 nStart = GetTimeMillis();
319 bool fFirstRun;
320 pwalletMain = new CWallet("wallet.dat");
321 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
322 if (nLoadWalletRet != DB_LOAD_OK)
323 {
324 if (nLoadWalletRet == DB_CORRUPT)
325 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
326 else if (nLoadWalletRet == DB_TOO_NEW)
327 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
328 else if (nLoadWalletRet == DB_NEED_REWRITE)
329 {
330 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
331 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
332 return false;
333 }
334 else
335 strErrors += _("Error loading wallet.dat \n");
336 }
337 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
338
339 RegisterWallet(pwalletMain);
340
341 CBlockIndex *pindexRescan = pindexBest;
342 if (GetBoolArg("-rescan"))
343 pindexRescan = pindexGenesisBlock;
344 else
345 {
346 CWalletDB walletdb("wallet.dat");
347 CBlockLocator locator;
348 if (walletdb.ReadBestBlock(locator))
349 pindexRescan = locator.GetBlockIndex();
350 }
351 if (pindexBest != pindexRescan)
352 {
353 InitMessage(_("Rescanning..."));
354 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
355 nStart = GetTimeMillis();
356 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
357 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
358 }
359
360 InitMessage(_("Done loading"));
361 printf("Done loading\n");
362
363 //// debug print
364 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
365 printf("nBestHeight = %d\n", nBestHeight);
366 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
367 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
368 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
369
370 if (!strErrors.empty())
371 {
372 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
373 return false;
374 }
375
376 // Add wallet transactions that aren't already in a block to mapTransactions
377 pwalletMain->ReacceptWalletTransactions();
378
379 // Note: Bitcoin-QT stores several settings in the wallet, so we want
380 // to load the wallet BEFORE parsing command-line arguments, so
381 // the command-line/bitcoin.conf settings override GUI setting.
382
383 //
384 // Parameters
385 //
386 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
387 {
388 PrintBlockTree();
389 return false;
390 }
391
392 if (mapArgs.count("-timeout"))
393 {
394 int nNewTimeout = GetArg("-timeout", 5000);
395 if (nNewTimeout > 0 && nNewTimeout < 600000)
396 nConnectTimeout = nNewTimeout;
397 }
398
399 if (mapArgs.count("-printblock"))
400 {
401 string strMatch = mapArgs["-printblock"];
402 int nFound = 0;
403 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
404 {
405 uint256 hash = (*mi).first;
406 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
407 {
408 CBlockIndex* pindex = (*mi).second;
409 CBlock block;
410 block.ReadFromDisk(pindex);
411 block.BuildMerkleTree();
412 block.print();
413 printf("\n");
414 nFound++;
415 }
416 }
417 if (nFound == 0)
418 printf("No blocks matching %s were found\n", strMatch.c_str());
419 return false;
420 }
421
422 fGenerateBitcoins = GetBoolArg("-gen");
423
424 if (mapArgs.count("-proxy"))
425 {
426 fUseProxy = true;
427 addrProxy = CAddress(mapArgs["-proxy"]);
428 if (!addrProxy.IsValid())
429 {
430 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
431 return false;
432 }
433 }
434
435 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
436 if (fTor)
437 {
438 // Use SoftSetArg here so user can override any of these if they wish.
439 // Note: the GetBoolArg() calls for all of these must happen later.
440 SoftSetArg("-nolisten", true);
441 }
442
443 fNoListen = GetBoolArg("-nolisten");
444
445 // Command-line args override in-wallet settings:
446
447 if (!fNoListen)
448 {
449 if (!BindListenPort(strErrors))
450 {
451 wxMessageBox(strErrors, "Bitcoin");
452 return false;
453 }
454 }
455
456 if (mapArgs.count("-addnode"))
457 {
458 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
459 {
460 CAddress addr(strAddr);
461 addr.nTime = 0; // so it won't relay unless successfully connected
462 if (addr.IsValid())
463 AddAddress(addr);
464 }
465 }
466
467 if (mapArgs.count("-paytxfee"))
468 {
469 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
470 {
471 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
472 return false;
473 }
474 if (nTransactionFee > 0.25 * COIN)
475 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
476 }
477
478 //
479 // Start the node
480 //
481 if (!CheckDiskSpace())
482 return false;
483
484 RandAddSeedPerfmon();
485
486 if (!CreateThread(StartNode, NULL))
487 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
488
489 if (fServer)
490 CreateThread(ThreadRPCServer, NULL);
491
492 while (1)
493 Sleep(5000);
494
495 return true;
496}