Master Core  v0.0.9 - 2abfd2849db8ba7a83957c64eb976b406713c123
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
7 #include "bitcoin-config.h"
8 #endif
9 
10 #include "init.h"
11 
12 #include "addrman.h"
13 #include "checkpoints.h"
14 #include "key.h"
15 #include "main.h"
16 #include "miner.h"
17 #include "net.h"
18 #include "rpcserver.h"
19 #include "txdb.h"
20 #include "ui_interface.h"
21 #include "util.h"
22 #ifdef ENABLE_WALLET
23 #include "db.h"
24 #include "wallet.h"
25 #include "walletdb.h"
26 #endif
27 
28 #include <stdint.h>
29 #include <stdio.h>
30 
31 #ifndef WIN32
32 #include <signal.h>
33 #endif
34 
35 #include <boost/algorithm/string/predicate.hpp>
36 #include <boost/filesystem.hpp>
37 #include <boost/interprocess/sync/file_lock.hpp>
38 #include <openssl/crypto.h>
39 
40 using namespace std;
41 using namespace boost;
42 
43 #ifdef ENABLE_WALLET
44 std::string strWalletFile;
46 #endif
47 
48 #ifdef WIN32
49 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
50 // accessing block files, don't count towards to fd_set size limit
51 // anyway.
52 #define MIN_CORE_FILEDESCRIPTORS 0
53 #else
54 #define MIN_CORE_FILEDESCRIPTORS 150
55 #endif
56 
57 // Used to pass flags to the Bind() function
58 enum BindFlags {
59  BF_NONE = 0,
60  BF_EXPLICIT = (1U << 0),
61  BF_REPORT_ERROR = (1U << 1)
62 };
63 
64 int mastercore_init(void);
65 int mastercore_shutdown(void);
66 
68 //
69 // Shutdown
70 //
71 
72 //
73 // Thread management and startup/shutdown:
74 //
75 // The network-processing threads are all part of a thread group
76 // created by AppInit() or the Qt main() function.
77 //
78 // A clean exit happens when StartShutdown() or the SIGTERM
79 // signal handler sets fRequestShutdown, which triggers
80 // the DetectShutdownThread(), which interrupts the main thread group.
81 // DetectShutdownThread() then exits, which causes AppInit() to
82 // continue (it .joins the shutdown thread).
83 // Shutdown() is then
84 // called to clean up database connections, and stop other
85 // threads that should only be stopped after the main network-processing
86 // threads have exited.
87 //
88 // Note that if running -daemon the parent process returns from AppInit2
89 // before adding any threads to the threadGroup, so .join_all() returns
90 // immediately and the parent exits from main().
91 //
92 // Shutdown for Qt is very similar, only it uses a QTimer to detect
93 // fRequestShutdown getting set, and then does the normal Qt
94 // shutdown thing.
95 //
96 
97 volatile bool fRequestShutdown = false;
98 
100 {
101  fRequestShutdown = true;
102 }
104 {
105  return fRequestShutdown;
106 }
107 
109 
110 void Shutdown()
111 {
112  LogPrintf("Shutdown : In progress...\n");
113  static CCriticalSection cs_Shutdown;
114  TRY_LOCK(cs_Shutdown, lockShutdown);
115  if (!lockShutdown) return;
116 
117  RenameThread("bitcoin-shutoff");
119  StopRPCThreads();
121 #ifdef ENABLE_WALLET
122  if (pwalletMain)
123  bitdb.Flush(false);
124  GenerateBitcoins(false, NULL, 0);
125 #endif
126  StopNode();
128  {
129  LOCK(cs_main);
130 #ifdef ENABLE_WALLET
131  if (pwalletMain)
132  pwalletMain->SetBestChain(chainActive.GetLocator());
133 #endif
134  if (pblocktree)
135  pblocktree->Flush();
136  if (pcoinsTip)
137  pcoinsTip->Flush();
138  delete pcoinsTip; pcoinsTip = NULL;
139  (void) mastercore_shutdown();
140  delete pcoinsdbview; pcoinsdbview = NULL;
141  delete pblocktree; pblocktree = NULL;
142  }
143 #ifdef ENABLE_WALLET
144  if (pwalletMain)
145  bitdb.Flush(true);
146 #endif
147  boost::filesystem::remove(GetPidFile());
149 #ifdef ENABLE_WALLET
150  if (pwalletMain)
151  delete pwalletMain;
152 #endif
153  LogPrintf("Shutdown : done\n");
154 }
155 
156 //
157 // Signal handlers are very limited in what they are allowed to do, so:
158 //
159 void HandleSIGTERM(int)
160 {
161  fRequestShutdown = true;
162 }
163 
164 void HandleSIGHUP(int)
165 {
166  fReopenDebugLog = true;
167 }
168 
169 bool static InitError(const std::string &str)
170 {
172  return false;
173 }
174 
175 bool static InitWarning(const std::string &str)
176 {
178  return true;
179 }
180 
181 bool static Bind(const CService &addr, unsigned int flags) {
182  if (!(flags & BF_EXPLICIT) && IsLimited(addr))
183  return false;
184  std::string strError;
185  if (!BindListenPort(addr, strError)) {
186  if (flags & BF_REPORT_ERROR)
187  return InitError(strError);
188  return false;
189  }
190  return true;
191 }
192 
193 // Core-specific options shared between UI, daemon and RPC client
194 std::string HelpMessage(HelpMessageMode hmm)
195 {
196  string strUsage = _("Options:") + "\n";
197  strUsage += " -? " + _("This help message") + "\n";
198  strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)") + "\n";
199  strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n";
200  strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n";
201  strUsage += " -checklevel=<n> " + _("How thorough the block verification of -checkblocks is (0-4, default: 3)") + "\n";
202  strUsage += " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n";
203  if (hmm == HMM_BITCOIND)
204  {
205 #if !defined(WIN32)
206  strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n";
207 #endif
208  }
209  strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n";
210  strUsage += " -dbcache=<n> " + strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache) + "\n";
211  strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + " " + _("on startup") + "\n";
212  strUsage += " -maxorphanblocks=<n> " + strprintf(_("Keep at most <n> unconnectable blocks in memory (default: %u)"), DEFAULT_MAX_ORPHAN_BLOCKS) + "\n";
213  strUsage += " -maxorphantx=<n> " + strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS) + "\n";
214  strUsage += " -par=<n> " + strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS) + "\n";
215  strUsage += " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n";
216  strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup") + "\n";
217  strUsage += " -txindex " + _("Maintain a full transaction index (default: 1)") + "\n";
218 
219  strUsage += "\n" + _("Connection options:") + "\n";
220  strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n";
221  strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n";
222  strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n";
223  strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n";
224  strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n";
225  strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n";
226  strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)") + "\n";
227  strUsage += " -dnsseed " + _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)") + "\n";
228  strUsage += " -forcednsseed " + _("Always query for peer addresses via DNS lookup (default: 0)") + "\n";
229  strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n";
230  strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n";
231  strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n";
232  strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n";
233  strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n";
234  strUsage += " -onion=<ip:port> " + _("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)") + "\n";
235  strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n";
236  strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n";
237  strUsage += " -proxy=<ip:port> " + _("Connect through SOCKS proxy") + "\n";
238  strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n";
239  strUsage += " -socks=<n> " + _("Select SOCKS version for -proxy (4 or 5, default: 5)") + "\n";
240  strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n";
241 #ifdef USE_UPNP
242 #if USE_UPNP
243  strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n";
244 #else
245  strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n";
246 #endif
247 #endif
248 
249 #ifdef ENABLE_WALLET
250  strUsage += "\n" + _("Wallet options:") + "\n";
251  strUsage += " -disablewallet " + _("Do not load the wallet and disable wallet RPC calls") + "\n";
252  strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n";
253  strUsage += " -paytxfee=<amt> " + _("Fee per kB to add to transactions you send") + "\n";
254  strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + " " + _("on startup") + "\n";
255  strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup") + "\n";
256  strUsage += " -spendzeroconfchange " + _("Spend unconfirmed change when sending transactions (default: 1)") + "\n";
257  strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + " " + _("on startup") + "\n";
258  strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + " " + _("(default: wallet.dat)") + "\n";
259  strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n";
260  strUsage += " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n";
261 #endif
262 
263  strUsage += "\n" + _("Debugging/Testing options:") + "\n";
264  if (GetBoolArg("-help-debug", false))
265  {
266  strUsage += " -benchmark " + _("Show benchmark information (default: 0)") + "\n";
267  strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n";
268  strUsage += " -dblogsize=<n> " + _("Flush database activity from memory pool to disk log every <n> megabytes (default: 100)") + "\n";
269  strUsage += " -disablesafemode " + _("Disable safemode, override a real safe mode event (default: 0)") + "\n";
270  strUsage += " -testsafemode " + _("Force safe mode (default: 0)") + "\n";
271  strUsage += " -dropmessagestest=<n> " + _("Randomly drop 1 of every <n> network messages") + "\n";
272  strUsage += " -fuzzmessagestest=<n> " + _("Randomly fuzz 1 of every <n> network messages") + "\n";
273  strUsage += " -flushwallet " + _("Run a thread to flush wallet periodically (default: 1)") + "\n";
274  }
275  strUsage += " -debug=<category> " + _("Output debugging information (default: 0, supplying <category> is optional)") + "\n";
276  strUsage += " " + _("If <category> is not supplied, output all debugging information.") + "\n";
277  strUsage += " " + _("<category> can be:");
278  strUsage += " addrman, alert, coindb, db, lock, rand, rpc, selectcoins, mempool, net"; // Don't translate these and qt below
279  if (hmm == HMM_BITCOIN_QT)
280  strUsage += ", qt";
281  strUsage += ".\n";
282 #ifdef ENABLE_WALLET
283  strUsage += " -gen " + _("Generate coins (default: 0)") + "\n";
284  strUsage += " -genproclimit=<n> " + _("Set the processor limit for when generation is on (-1 = unlimited, default: -1)") + "\n";
285 #endif
286  strUsage += " -help-debug " + _("Show all debugging options (usage: --help -help-debug)") + "\n";
287  strUsage += " -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n";
288  if (GetBoolArg("-help-debug", false))
289  {
290  strUsage += " -limitfreerelay=<n> " + _("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:15)") + "\n";
291  strUsage += " -maxsigcachesize=<n> " + _("Limit size of signature cache to <n> entries (default: 50000)") + "\n";
292  }
293  strUsage += " -mintxfee=<amt> " + _("Fees smaller than this are considered zero fee (for transaction creation) (default:") + " " + FormatMoney(CTransaction::nMinTxFee) + ")" + "\n";
294  strUsage += " -minrelaytxfee=<amt> " + _("Fees smaller than this are considered zero fee (for relaying) (default:") + " " + FormatMoney(CTransaction::nMinRelayTxFee) + ")" + "\n";
295  strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n";
296  if (GetBoolArg("-help-debug", false))
297  {
298  strUsage += " -printblock=<hash> " + _("Print block on startup, if found in block index") + "\n";
299  strUsage += " -printblocktree " + _("Print block tree on startup (default: 0)") + "\n";
300  strUsage += " -printpriority " + _("Log transaction priority and fee per kB when mining blocks (default: 0)") + "\n";
301  strUsage += " -privdb " + _("Sets the DB_PRIVATE flag in the wallet db environment (default: 1)") + "\n";
302  strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + "\n";
303  strUsage += " " + _("This is intended for regression testing tools and app development.") + "\n";
304  strUsage += " " + _("In this mode -genproclimit controls how many blocks are generated immediately.") + "\n";
305  }
306  strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n";
307  strUsage += " -testnet " + _("Use the test network") + "\n";
308 
309  strUsage += "\n" + _("Block creation options:") + "\n";
310  strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n";
311  strUsage += " -blockmaxsize=<n> " + strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE) + "\n";
312  strUsage += " -blockprioritysize=<n> " + strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE) + "\n";
313 
314  strUsage += "\n" + _("RPC server options:") + "\n";
315  strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n";
316  strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n";
317  strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n";
318  strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n";
319  strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n";
320  strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n";
321 
322  strUsage += "\n" + _("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
323  strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
324  strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n";
325  strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n";
326  strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n";
327 
328  return strUsage;
329 }
330 
332 {
334  assert(fImporting == false);
335  fImporting = true;
336  }
337 
339  assert(fImporting == true);
340  fImporting = false;
341  }
342 };
343 
344 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
345 {
346  RenameThread("bitcoin-loadblk");
347 
348  // -reindex
349  if (fReindex) {
350  CImportingNow imp;
351  int nFile = 0;
352  while (true) {
353  CDiskBlockPos pos(nFile, 0);
354  FILE *file = OpenBlockFile(pos, true);
355  if (!file)
356  break;
357  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
358  LoadExternalBlockFile(file, &pos);
359  nFile++;
360  }
361  pblocktree->WriteReindexing(false);
362  fReindex = false;
363  LogPrintf("Reindexing finished\n");
364  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
365  InitBlockIndex();
366  }
367 
368  // hardcoded $DATADIR/bootstrap.dat
369  filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
370  if (filesystem::exists(pathBootstrap)) {
371  FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
372  if (file) {
373  CImportingNow imp;
374  filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
375  LogPrintf("Importing bootstrap.dat...\n");
376  LoadExternalBlockFile(file);
377  RenameOver(pathBootstrap, pathBootstrapOld);
378  } else {
379  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
380  }
381  }
382 
383  // -loadblock=
384  BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
385  FILE *file = fopen(path.string().c_str(), "rb");
386  if (file) {
387  CImportingNow imp;
388  LogPrintf("Importing blocks file %s...\n", path.string());
389  LoadExternalBlockFile(file);
390  } else {
391  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
392  }
393  }
394 }
395 
400 bool InitSanityCheck(void)
401 {
402  if(!ECC_InitSanityCheck()) {
403  InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
404  "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
405  return false;
406  }
407 
408  // TODO: remaining sanity checks, see #4081
409 
410  return true;
411 }
412 
416 bool AppInit2(boost::thread_group& threadGroup)
417 {
418  // ********************************************************* Step 1: setup
419 #ifdef _MSC_VER
420  // Turn off Microsoft heap dump noise
421  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
422  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
423 #endif
424 #if _MSC_VER >= 1400
425  // Disable confusing "helpful" text message on abort, Ctrl-C
426  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
427 #endif
428 #ifdef WIN32
429  // Enable Data Execution Prevention (DEP)
430  // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
431  // A failure is non-critical and needs no further attention!
432 #ifndef PROCESS_DEP_ENABLE
433  // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
434  // which is not correct. Can be removed, when GCCs winbase.h is fixed!
435 #define PROCESS_DEP_ENABLE 0x00000001
436 #endif
437  typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
438  PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
439  if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
440 
441  // Initialize Windows Sockets
442  WSADATA wsadata;
443  int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
444  if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
445  {
446  return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
447  }
448 #endif
449 #ifndef WIN32
450  umask(077);
451 
452  // Clean shutdown on SIGTERM
453  struct sigaction sa;
454  sa.sa_handler = HandleSIGTERM;
455  sigemptyset(&sa.sa_mask);
456  sa.sa_flags = 0;
457  sigaction(SIGTERM, &sa, NULL);
458  sigaction(SIGINT, &sa, NULL);
459 
460  // Reopen debug.log on SIGHUP
461  struct sigaction sa_hup;
462  sa_hup.sa_handler = HandleSIGHUP;
463  sigemptyset(&sa_hup.sa_mask);
464  sa_hup.sa_flags = 0;
465  sigaction(SIGHUP, &sa_hup, NULL);
466 
467 #if defined (__SVR4) && defined (__sun)
468  // ignore SIGPIPE on Solaris
469  signal(SIGPIPE, SIG_IGN);
470 #endif
471 #endif
472 
473  // ********************************************************* Step 2: parameter interactions
474 
475  if (mapArgs.count("-bind")) {
476  // when specifying an explicit binding address, you want to listen on it
477  // even when -connect or -proxy is specified
478  if (SoftSetBoolArg("-listen", true))
479  LogPrintf("AppInit2 : parameter interaction: -bind set -> setting -listen=1\n");
480  }
481 
482  if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
483  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
484  if (SoftSetBoolArg("-dnsseed", false))
485  LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n");
486  if (SoftSetBoolArg("-listen", false))
487  LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n");
488  }
489 
490  if (mapArgs.count("-proxy")) {
491  // to protect privacy, do not listen by default if a default proxy server is specified
492  if (SoftSetBoolArg("-listen", false))
493  LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -listen=0\n");
494  }
495 
496  if (!GetBoolArg("-listen", true)) {
497  // do not map ports or try to retrieve public IP when not listening (pointless)
498  if (SoftSetBoolArg("-upnp", false))
499  LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n");
500  if (SoftSetBoolArg("-discover", false))
501  LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n");
502  }
503 
504  if (mapArgs.count("-externalip")) {
505  // if an explicit public IP is specified, do not try to find others
506  if (SoftSetBoolArg("-discover", false))
507  LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n");
508  }
509 
510  if (GetBoolArg("-salvagewallet", false)) {
511  // Rewrite just private keys: rescan to find transactions
512  if (SoftSetBoolArg("-rescan", true))
513  LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n");
514  }
515 
516  // -zapwallettx implies a rescan
517  if (GetBoolArg("-zapwallettxes", false)) {
518  if (SoftSetBoolArg("-rescan", true))
519  LogPrintf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n");
520  }
521 
522  // Make sure enough file descriptors are available
523  int nBind = std::max((int)mapArgs.count("-bind"), 1);
524  nMaxConnections = GetArg("-maxconnections", 125);
525  nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
526  int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
527  if (nFD < MIN_CORE_FILEDESCRIPTORS)
528  return InitError(_("Not enough file descriptors available."));
529  if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
530  nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
531 
532  // ********************************************************* Step 3: parameter-to-internal-flags
533 
534  fDebug = !mapMultiArgs["-debug"].empty();
535  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
536  const vector<string>& categories = mapMultiArgs["-debug"];
537  if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
538  fDebug = false;
539 
540  // Check for -debugnet (deprecated)
541  if (GetBoolArg("-debugnet", false))
542  InitWarning(_("Warning: Deprecated argument -debugnet ignored, use -debug=net"));
543 
544  fBenchmark = GetBoolArg("-benchmark", false);
545  mempool.setSanityCheck(GetBoolArg("-checkmempool", RegTest()));
546  Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
547 
548  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
550  if (nScriptCheckThreads <= 0)
551  nScriptCheckThreads += boost::thread::hardware_concurrency();
552  if (nScriptCheckThreads <= 1)
556 
557  fServer = GetBoolArg("-server", false);
558  fPrintToConsole = GetBoolArg("-printtoconsole", false);
559  fLogTimestamps = GetBoolArg("-logtimestamps", true);
560  setvbuf(stdout, NULL, _IOLBF, 0);
561 #ifdef ENABLE_WALLET
562  bool fDisableWallet = GetBoolArg("-disablewallet", false);
563 #endif
564 
565  if (mapArgs.count("-timeout"))
566  {
567  int nNewTimeout = GetArg("-timeout", 5000);
568  if (nNewTimeout > 0 && nNewTimeout < 600000)
569  nConnectTimeout = nNewTimeout;
570  }
571 
572  // Continue to put "/P2SH/" in the coinbase to monitor
573  // BIP16 support.
574  // This can be removed eventually...
575  const char* pszP2SH = "/P2SH/";
576  COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
577 
578  // Fee-per-kilobyte amount considered the same as "free"
579  // If you are mining, be careful setting this:
580  // if you set it to zero then
581  // a transaction spammer can cheaply fill blocks using
582  // 1-satoshi-fee transactions. It should be set above the real
583  // cost to you of processing a transaction.
584  if (mapArgs.count("-mintxfee"))
585  {
586  int64_t n = 0;
587  if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
589  else
590  return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
591  }
592  if (mapArgs.count("-minrelaytxfee"))
593  {
594  int64_t n = 0;
595  if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
597  else
598  return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
599  }
600 
601 #ifdef ENABLE_WALLET
602  if (mapArgs.count("-paytxfee"))
603  {
604  if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
605  return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
607  InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
608  }
609  bSpendZeroConfChange = GetArg("-spendzeroconfchange", true);
610 
611  strWalletFile = GetArg("-wallet", "wallet.dat");
612 #endif
613  // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
614  // Sanity check
615  if (!InitSanityCheck())
616  return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
617 
618  std::string strDataDir = GetDataDir().string();
619 #ifdef ENABLE_WALLET
620  // Wallet file must be a plain filename without a directory
621  if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
622  return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
623 #endif
624  // Make sure only a single Bitcoin process is using the data directory.
625  boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
626  FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
627  if (file) fclose(file);
628  static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
629  if (!lock.try_lock())
630  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
631 
632  if (GetBoolArg("-shrinkdebugfile", !fDebug))
633  ShrinkDebugFile();
634  LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
635  LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
636  LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
637 #ifdef ENABLE_WALLET
638  LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
639 #endif
640  if (!fLogTimestamps)
641  LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
642  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
643  LogPrintf("Using data directory %s\n", strDataDir);
644  LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
645  std::ostringstream strErrors;
646 
647  if (nScriptCheckThreads) {
648  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
649  for (int i=0; i<nScriptCheckThreads-1; i++)
650  threadGroup.create_thread(&ThreadScriptCheck);
651  }
652 
653  int64_t nStart;
654 
655  // ********************************************************* Step 5: verify wallet database integrity
656 #ifdef ENABLE_WALLET
657  if (!fDisableWallet) {
658  LogPrintf("Using wallet %s\n", strWalletFile);
659  uiInterface.InitMessage(_("Verifying wallet..."));
660 
661  if (!bitdb.Open(GetDataDir()))
662  {
663  // try moving the database env out of the way
664  boost::filesystem::path pathDatabase = GetDataDir() / "database";
665  boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
666  try {
667  boost::filesystem::rename(pathDatabase, pathDatabaseBak);
668  LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
669  } catch(boost::filesystem::filesystem_error &error) {
670  // failure is ok (well, not really, but it's not worse than what we started with)
671  }
672 
673  // try again
674  if (!bitdb.Open(GetDataDir())) {
675  // if it still fails, it probably means we can't even create the database env
676  string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir);
677  return InitError(msg);
678  }
679  }
680 
681  if (GetBoolArg("-salvagewallet", false))
682  {
683  // Recover readable keypairs:
685  return false;
686  }
687 
688  if (filesystem::exists(GetDataDir() / strWalletFile))
689  {
691  if (r == CDBEnv::RECOVER_OK)
692  {
693  string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
694  " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
695  " your balance or transactions are incorrect you should"
696  " restore from a backup."), strDataDir);
697  InitWarning(msg);
698  }
699  if (r == CDBEnv::RECOVER_FAIL)
700  return InitError(_("wallet.dat corrupt, salvage failed"));
701  }
702  } // (!fDisableWallet)
703 #endif // ENABLE_WALLET
704  // ********************************************************* Step 6: network initialization
705 
707 
708  int nSocksVersion = GetArg("-socks", 5);
709  if (nSocksVersion != 4 && nSocksVersion != 5)
710  return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
711 
712  if (mapArgs.count("-onlynet")) {
713  std::set<enum Network> nets;
714  BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
715  enum Network net = ParseNetwork(snet);
716  if (net == NET_UNROUTABLE)
717  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
718  nets.insert(net);
719  }
720  for (int n = 0; n < NET_MAX; n++) {
721  enum Network net = (enum Network)n;
722  if (!nets.count(net))
723  SetLimited(net);
724  }
725  }
726 
727  CService addrProxy;
728  bool fProxy = false;
729  if (mapArgs.count("-proxy")) {
730  addrProxy = CService(mapArgs["-proxy"], 9050);
731  if (!addrProxy.IsValid())
732  return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"]));
733 
734  if (!IsLimited(NET_IPV4))
735  SetProxy(NET_IPV4, addrProxy, nSocksVersion);
736  if (nSocksVersion > 4) {
737  if (!IsLimited(NET_IPV6))
738  SetProxy(NET_IPV6, addrProxy, nSocksVersion);
739  SetNameProxy(addrProxy, nSocksVersion);
740  }
741  fProxy = true;
742  }
743 
744  // -onion can override normal proxy, -noonion disables tor entirely
745  // -tor here is a temporary backwards compatibility measure
746  if (mapArgs.count("-tor"))
747  printf("Notice: option -tor has been replaced with -onion and will be removed in a later version.\n");
748  if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") &&
749  !(mapArgs.count("-tor") && mapArgs["-tor"] == "0") &&
750  (fProxy || mapArgs.count("-onion") || mapArgs.count("-tor"))) {
751  CService addrOnion;
752  if (!mapArgs.count("-onion") && !mapArgs.count("-tor"))
753  addrOnion = addrProxy;
754  else
755  addrOnion = mapArgs.count("-onion")?CService(mapArgs["-onion"], 9050):CService(mapArgs["-tor"], 9050);
756  if (!addrOnion.IsValid())
757  return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs.count("-onion")?mapArgs["-onion"]:mapArgs["-tor"]));
758  SetProxy(NET_TOR, addrOnion, 5);
760  }
761 
762  // see Step 2: parameter interactions for more information about these
763  fNoListen = !GetBoolArg("-listen", true);
764  fDiscover = GetBoolArg("-discover", true);
765  fNameLookup = GetBoolArg("-dns", true);
766 
767  bool fBound = false;
768  if (!fNoListen) {
769  if (mapArgs.count("-bind")) {
770  BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
771  CService addrBind;
772  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
773  return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
774  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
775  }
776  }
777  else {
778  struct in_addr inaddr_any;
779  inaddr_any.s_addr = INADDR_ANY;
780  fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
781  fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
782  }
783  if (!fBound)
784  return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
785  }
786 
787  if (mapArgs.count("-externalip")) {
788  BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
789  CService addrLocal(strAddr, GetListenPort(), fNameLookup);
790  if (!addrLocal.IsValid())
791  return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
793  }
794  }
795 
796  BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
797  AddOneShot(strDest);
798 
799  // ********************************************************* Step 7: load block chain
800 
801  fReindex = GetBoolArg("-reindex", false);
802 
803  // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
804  filesystem::path blocksDir = GetDataDir() / "blocks";
805  if (!filesystem::exists(blocksDir))
806  {
807  filesystem::create_directories(blocksDir);
808  bool linked = false;
809  for (unsigned int i = 1; i < 10000; i++) {
810  filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
811  if (!filesystem::exists(source)) break;
812  filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
813  try {
814  filesystem::create_hard_link(source, dest);
815  LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
816  linked = true;
817  } catch (filesystem::filesystem_error & e) {
818  // Note: hardlink creation failing is not a disaster, it just means
819  // blocks will get re-downloaded from peers.
820  LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
821  break;
822  }
823  }
824  if (linked)
825  {
826  fReindex = true;
827  }
828  }
829 
830  // cache size calculations
831  size_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
832  if (nTotalCache < (nMinDbCache << 20))
833  nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache
834  else if (nTotalCache > (nMaxDbCache << 20))
835  nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache
836  size_t nBlockTreeDBCache = nTotalCache / 8;
837  if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", true))
838  nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
839  nTotalCache -= nBlockTreeDBCache;
840  size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
841  nTotalCache -= nCoinDBCache;
842  nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
843 
844  bool fLoaded = false;
845  while (!fLoaded) {
846  bool fReset = fReindex;
847  std::string strLoadError;
848 
849  uiInterface.InitMessage(_("Loading block index..."));
850 
851  nStart = GetTimeMillis();
852  do {
853  try {
855  delete pcoinsTip;
856  delete pcoinsdbview;
857  delete pblocktree;
858 
859  pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
860  pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
861  pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
862 
863  if (fReindex)
865 
866  if (!LoadBlockIndex()) {
867  strLoadError = _("Error loading block database");
868  break;
869  }
870 
871  // If the loaded chain has a wrong genesis, bail out immediately
872  // (we're likely using a testnet datadir, or the other way around).
873  if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL)
874  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
875 
876  // Initialize the block index (no-op if non-empty database was already loaded)
877  if (!InitBlockIndex()) {
878  strLoadError = _("Error initializing block database");
879  break;
880  }
881 
882  // Check for changed -txindex state
883  if (fTxIndex != GetBoolArg("-txindex", true)) {
884  strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
885  break;
886  }
887 
888  uiInterface.InitMessage(_("Verifying blocks..."));
889  if (!VerifyDB(GetArg("-checklevel", 3),
890  GetArg("-checkblocks", 288))) {
891  strLoadError = _("Corrupted block database detected");
892  break;
893  }
894  } catch(std::exception &e) {
895  if (fDebug) LogPrintf("%s\n", e.what());
896  strLoadError = _("Error opening block database");
897  break;
898  }
899 
900  fLoaded = true;
901  } while(false);
902 
903  if (!fLoaded) {
904  // first suggest a reindex
905  if (!fReset) {
906  bool fRet = uiInterface.ThreadSafeMessageBox(
907  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
909  if (fRet) {
910  fReindex = true;
911  fRequestShutdown = false;
912  } else {
913  LogPrintf("Aborted block database rebuild. Exiting.\n");
914  return false;
915  }
916  } else {
917  return InitError(strLoadError);
918  }
919  }
920  }
921 
922  // As LoadBlockIndex can take several minutes, it's possible the user
923  // requested to kill the GUI during the last operation. If so, exit.
924  // As the program has not fully started yet, Shutdown() is possibly overkill.
925  if (fRequestShutdown)
926  {
927  LogPrintf("Shutdown requested. Exiting.\n");
928  return false;
929  }
930  LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
931 
932  if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false))
933  {
934  PrintBlockTree();
935  return false;
936  }
937 
938  if (mapArgs.count("-printblock"))
939  {
940  string strMatch = mapArgs["-printblock"];
941  int nFound = 0;
942  for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
943  {
944  uint256 hash = (*mi).first;
945  if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
946  {
947  CBlockIndex* pindex = (*mi).second;
948  CBlock block;
949  ReadBlockFromDisk(block, pindex);
950  block.BuildMerkleTree();
951  block.print();
952  LogPrintf("\n");
953  nFound++;
954  }
955  }
956  if (nFound == 0)
957  LogPrintf("No blocks matching %s were found\n", strMatch);
958  return false;
959  }
960 
961  if (!fTxIndex) return InitError(_("Master Core: Please use -txindex option at the command line or add txindex=1 to bitcoin.conf file !!!\n")); // mastercore check
962  uiInterface.InitMessage(_("Parsing Master Protocol Transactions..."));
963  (void) mastercore_init();
964 
965  // ********************************************************* Step 8: load wallet
966 #ifdef ENABLE_WALLET
967  if (fDisableWallet) {
968  pwalletMain = NULL;
969  LogPrintf("Wallet disabled!\n");
970  } else {
971  if (GetBoolArg("-zapwallettxes", false)) {
972  uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
973 
974  pwalletMain = new CWallet(strWalletFile);
975  DBErrors nZapWalletRet = pwalletMain->ZapWalletTx();
976  if (nZapWalletRet != DB_LOAD_OK) {
977  uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
978  return false;
979  }
980 
981  delete pwalletMain;
982  pwalletMain = NULL;
983  }
984 
985  uiInterface.InitMessage(_("Loading wallet..."));
986 
987  nStart = GetTimeMillis();
988  bool fFirstRun = true;
989  pwalletMain = new CWallet(strWalletFile);
990  DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
991  if (nLoadWalletRet != DB_LOAD_OK)
992  {
993  if (nLoadWalletRet == DB_CORRUPT)
994  strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
995  else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
996  {
997  string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
998  " or address book entries might be missing or incorrect."));
999  InitWarning(msg);
1000  }
1001  else if (nLoadWalletRet == DB_TOO_NEW)
1002  strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
1003  else if (nLoadWalletRet == DB_NEED_REWRITE)
1004  {
1005  strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
1006  LogPrintf("%s", strErrors.str());
1007  return InitError(strErrors.str());
1008  }
1009  else
1010  strErrors << _("Error loading wallet.dat") << "\n";
1011  }
1012 
1013  if (GetBoolArg("-upgradewallet", fFirstRun))
1014  {
1015  int nMaxVersion = GetArg("-upgradewallet", 0);
1016  if (nMaxVersion == 0) // the -upgradewallet without argument case
1017  {
1018  LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1019  nMaxVersion = CLIENT_VERSION;
1020  pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1021  }
1022  else
1023  LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1024  if (nMaxVersion < pwalletMain->GetVersion())
1025  strErrors << _("Cannot downgrade wallet") << "\n";
1026  pwalletMain->SetMaxVersion(nMaxVersion);
1027  }
1028 
1029  if (fFirstRun)
1030  {
1031  // Create new keyUser and set as default key
1033 
1034  CPubKey newDefaultKey;
1035  if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1036  pwalletMain->SetDefaultKey(newDefaultKey);
1037  if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1038  strErrors << _("Cannot write default address") << "\n";
1039  }
1040 
1041  pwalletMain->SetBestChain(chainActive.GetLocator());
1042  }
1043 
1044  LogPrintf("%s", strErrors.str());
1045  LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1046 
1047  RegisterWallet(pwalletMain);
1048 
1049  CBlockIndex *pindexRescan = chainActive.Tip();
1050  if (GetBoolArg("-rescan", false))
1051  pindexRescan = chainActive.Genesis();
1052  else
1053  {
1054  CWalletDB walletdb(strWalletFile);
1055  CBlockLocator locator;
1056  if (walletdb.ReadBestBlock(locator))
1057  pindexRescan = chainActive.FindFork(locator);
1058  else
1059  pindexRescan = chainActive.Genesis();
1060  }
1061  if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1062  {
1063  uiInterface.InitMessage(_("Rescanning..."));
1064  LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1065  nStart = GetTimeMillis();
1066  pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1067  LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1068  pwalletMain->SetBestChain(chainActive.GetLocator());
1069  nWalletDBUpdated++;
1070  }
1071  } // (!fDisableWallet)
1072 #else // ENABLE_WALLET
1073  LogPrintf("No wallet compiled in!\n");
1074 #endif // !ENABLE_WALLET
1075  // ********************************************************* Step 9: import blocks
1076 
1077  // scan for better chains in the block chain database, that are not yet connected in the active best chain
1078  CValidationState state;
1079  if (!ActivateBestChain(state))
1080  strErrors << "Failed to connect best block";
1081 
1082  std::vector<boost::filesystem::path> vImportFiles;
1083  if (mapArgs.count("-loadblock"))
1084  {
1085  BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
1086  vImportFiles.push_back(strFile);
1087  }
1088  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1089 
1090  // ********************************************************* Step 10: load peers
1091 
1092  uiInterface.InitMessage(_("Loading addresses..."));
1093 
1094  nStart = GetTimeMillis();
1095 
1096  {
1097  CAddrDB adb;
1098  if (!adb.Read(addrman))
1099  LogPrintf("Invalid or missing peers.dat; recreating\n");
1100  }
1101 
1102  LogPrintf("Loaded %i addresses from peers.dat %dms\n",
1103  addrman.size(), GetTimeMillis() - nStart);
1104 
1105  // ********************************************************* Step 11: start node
1106 
1107  if (!CheckDiskSpace())
1108  return false;
1109 
1110  if (!strErrors.str().empty())
1111  return InitError(strErrors.str());
1112 
1114 
1116  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1117  LogPrintf("nBestHeight = %d\n", chainActive.Height());
1118 #ifdef ENABLE_WALLET
1119  LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1120  LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1121  LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1122 #endif
1123 
1124  StartNode(threadGroup);
1125  // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
1126  InitRPCMining();
1127  if (fServer)
1128  StartRPCThreads();
1129 
1130 #ifdef ENABLE_WALLET
1131  // Generate coins in the background
1132  if (pwalletMain)
1133  GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", -1));
1134 #endif
1135 
1136  // ********************************************************* Step 12: finished
1137 
1138  uiInterface.InitMessage(_("Done loading"));
1139 
1140 #ifdef ENABLE_WALLET
1141  if (pwalletMain) {
1142  // Add wallet transactions that aren't already in a block to mapTransactions
1143  pwalletMain->ReacceptWalletTransactions();
1144 
1145  // Run a thread to flush wallet periodically
1146  threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1147  }
1148 #endif
1149 
1150  return !fRequestShutdown;
1151 }
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:973
unsigned int nWalletDBUpdated
Definition: db.cpp:27
CClientUIInterface uiInterface
Definition: util.cpp:100
void SetReachable(enum Network net, bool fFlag)
Definition: net.cpp:207
CNodeSignals & GetNodeSignals()
Definition: net.cpp:86
std::set< int64_t > setKeyPool
Definition: wallet.h:137
Access to the (IP) address database (peers.dat)
Definition: net.h:721
void AddOneShot(string strDest)
Definition: net.cpp:88
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:1548
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
Definition: main.cpp:2840
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:216
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: core.h:459
#define TRY_LOCK(cs, name)
Definition: sync.h:158
bool fImporting
Definition: main.cpp:52
Definition: init.h:13
bool Flush()
Definition: coins.cpp:131
DBErrors ZapWalletTx()
Definition: wallet.cpp:1524
int mastercore_shutdown(void)
Definition: core.h:396
bool fDebug
Definition: util.cpp:91
void GenerateBitcoins(bool fGenerate, CWallet *pwallet, int nThreads)
Run the miner threads.
HelpMessageMode
Definition: init.h:26
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:173
bool ShutdownRequested()
Definition: init.cpp:103
BindFlags
Definition: init.cpp:58
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE
Default for -blockprioritysize, maximum space for zero/low-fee transactions.
Definition: main.h:42
static bool Bind(const CService &addr, unsigned int flags)
Definition: init.cpp:181
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: util.cpp:538
~CImportingNow()
Definition: init.cpp:338
bool bSpendZeroConfChange
Definition: wallet.cpp:20
boost::filesystem::path GetPidFile()
Definition: util.cpp:1045
CPubKey vchDefaultKey
Definition: wallet.h:175
void StartShutdown()
Definition: init.cpp:99
void ShutdownRPCMining()
Definition: rpcmining.cpp:49
static const int CLIENT_VERSION
Definition: version.h:15
void ThreadScriptCheck()
Run an instance of the script checking thread.
Definition: main.cpp:1753
void setSanityCheck(bool _fSanityCheck)
Definition: txmempool.h:74
std::string strWalletFile
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:251
CCriticalSection cs_main
Definition: main.cpp:43
int nMaxConnections
Definition: net.cpp:61
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
Definition: main.cpp:2923
void Flush(bool fShutdown)
Definition: db.cpp:435
bool fDiscover
Definition: net.cpp:50
#define strprintf
Definition: util.h:116
STL namespace.
unsigned short GetListenPort()
Definition: net.cpp:94
static const int64_t nMinDbCache
Definition: txdb.h:26
Don't bring GUI to foreground.
Definition: ui_interface.h:66
bool fReindex
Definition: main.cpp:53
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
Definition: util.cpp:1064
bool SetMaxVersion(int nVersion)
Definition: wallet.cpp:246
std::string HelpMessage(HelpMessageMode hmm)
Definition: init.cpp:194
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:29
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: util.cpp:1429
void RandAddSeedPerfmon()
Definition: util.cpp:159
static int64_t nMinTxFee
Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) ...
Definition: core.h:186
CAddrMan addrman
Definition: net.cpp:60
string FormatMoney(int64_t n, bool fPlus)
Definition: util.cpp:308
void ReacceptWalletTransactions()
Definition: wallet.cpp:887
bool RegTest()
Definition: chainparams.h:105
void RenameThread(const char *name)
Definition: util.cpp:1388
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:48
bool SetDefaultKey(const CPubKey &vchPubKey)
Definition: wallet.cpp:1593
static const unsigned int DEFAULT_BLOCK_MAX_SIZE
Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will cr...
Definition: main.h:39
int mastercore_init(void)
volatile bool fReopenDebugLog
Definition: util.cpp:99
bool fBenchmark
Definition: main.cpp:54
void PrintBlockTree()
Print the loaded block tree.
Definition: main.cpp:3049
void SetBestChain(const CBlockLocator &loc)
Definition: wallet.cpp:213
int RaiseFileDescriptorLimit(int nMinFD)
Definition: util.cpp:1119
CDBEnv bitdb
Definition: db.cpp:35
uint256 BuildMerkleTree() const
Definition: core.cpp:220
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: main.cpp:372
bool SetMinVersion(enum WalletFeature, CWalletDB *pwalletdbIn=NULL, bool fExplicit=false)
Definition: wallet.cpp:219
int nScriptCheckThreads
Definition: main.cpp:51
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: main.h:1012
VerifyResult
Definition: db.h:56
static bool InitWarning(const std::string &str)
Definition: init.cpp:175
int Height() const
Return the maximal height in the chain.
Definition: main.h:1043
const char * source
Definition: rpcconsole.cpp:36
static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS
Default for -maxorphanblocks, maximum number of orphan blocks kept in memory.
Definition: main.h:50
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:414
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:35
bool fNoListen
Definition: util.cpp:97
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:519
#define LogPrintf(...)
Definition: util.h:117
Access to the block database (blocks/index/)
Definition: txdb.h:46
int64_t nTransactionFee
Definition: wallet.cpp:19
volatile bool fRequestShutdown
Definition: init.cpp:97
bool IsValid() const
Definition: netbase.cpp:695
#define LOCK(cs)
Definition: sync.h:156
void UnloadBlockIndex()
Unload database information.
Definition: main.cpp:2997
bool fTxIndex
Definition: main.cpp:55
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
Definition: main.cpp:336
CImportingNow()
Definition: init.cpp:333
Definition: init.cpp:59
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netbase.h:94
static const int nHighTransactionFeeWarning
Definition: wallet.h:33
An encapsulated public key.
Definition: key.h:42
bool fServer
Definition: util.cpp:95
bool ActivateBestChain(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
Definition: main.cpp:2138
static bool error(const char *format)
Definition: util.h:148
bool AppInit2(boost::thread_group &threadGroup)
Initialize bitcoin.
Definition: init.cpp:416
void Shutdown()
Definition: init.cpp:110
bool LoadBlockIndex()
Load the block tree and coins database from disk.
Definition: main.cpp:3005
bool SetNameProxy(CService addrProxy, int nSocksVersion)
Definition: netbase.cpp:439
static const int64_t nDefaultDbCache
Definition: txdb.h:22
int64_t GetTimeMillis()
Definition: util.h:311
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:413
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:65
int64_t GetTime()
Definition: util.cpp:1215
int nConnectTimeout
Definition: netbase.cpp:30
void RegisterWallet(CWalletInterface *pwalletIn)
Register a wallet to receive updates from core.
Definition: main.cpp:160
static bool InitError(const std::string &str)
Definition: init.cpp:169
void print() const
Definition: core.cpp:270
CTxMemPool mempool
Definition: main.cpp:45
Access to the wallet database (wallet.dat)
Definition: walletdb.h:71
void ThreadImport(std::vector< boost::filesystem::path > vImportFiles)
Definition: init.cpp:344
void HandleSIGTERM(int)
Definition: init.cpp:159
bool fLogTimestamps
Definition: util.cpp:98
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: main.h:64
std::string strWalletFile
Definition: wallet.h:135
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:121
void StopRPCThreads()
Definition: rpcserver.cpp:664
Network
Definition: netbase.h:26
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: main.h:1007
int size()
Definition: addrman.h:394
Capture information about block/transaction validation.
Definition: main.h:938
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of script-checking threads allowed.
Definition: main.h:62
256-bit unsigned integer
Definition: uint256.h:531
bool BindListenPort(const CService &addrBind, string &strError)
Definition: net.cpp:1561
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
Definition: main.cpp:1145
bool fPrintToConsole
Definition: util.cpp:92
int ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate=false)
Definition: wallet.cpp:847
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:688
unsigned int nCoinCacheSize
Definition: main.cpp:56
void InitRPCMining()
Definition: rpcmining.cpp:46
std::string ToString() const
Definition: uint256.h:340
CCoinsView backed by the LevelDB coin database (chainstate/)
Definition: txdb.h:29
CBlockIndex * FindFork(const CBlockLocator &locator) const
Find the last common block between this chain and a locator.
Definition: main.cpp:399
string FormatFullVersion()
Definition: util.cpp:1325
static bool Recover(CDBEnv &dbenv, std::string filename, bool fOnlyKeys)
Definition: walletdb.cpp:868
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: ui_interface.h:105
bool StopNode()
Definition: net.cpp:1751
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:133
bool ParseMoney(const string &str, int64_t &nRet)
Definition: util.cpp:332
static const int64_t nMaxDbCache
Definition: txdb.h:24
void UnregisterAllWallets()
Unregister all wallets from core.
Definition: main.cpp:178
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:100
VerifyResult Verify(std::string strFile, bool(*recoverFunc)(CDBEnv &dbenv, std::string strFile))
Definition: db.cpp:143
bool InitSanityCheck(void)
Sanity checks Ensure that Bitcoin is running in a usable environment with all necessary library suppo...
Definition: init.cpp:400
bool WriteReindexing(bool fReindex)
Definition: txdb.cpp:94
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:168
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:75
static int64_t nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) ...
Definition: core.h:187
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:1496
void HandleSIGHUP(int)
Definition: init.cpp:164
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:505
bool GetKeyFromPool(CPubKey &key)
Definition: wallet.cpp:1726
int nHeight
Definition: main.h:698
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Definition: main.cpp:3118
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:620
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:308
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
Definition: main.cpp:2806
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:54
CKeyID GetID() const
Definition: key.h:131
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
Definition: main.cpp:3014
map< string, vector< string > > mapMultiArgs
Definition: util.cpp:90
bool Open(const boost::filesystem::path &path)
Definition: db.cpp:66
map< uint256, CBlockIndex * > mapBlockIndex
Definition: main.cpp:47
bool Read(CAddrMan &addr)
Definition: net.cpp:1952
bool fNameLookup
Definition: netbase.cpp:31
void ThreadFlushWalletDB(const std::string &strWalletFile)
Definition: walletdb.cpp:763
void ShrinkDebugFile()
Definition: util.cpp:1182
bool IsLimited(enum Network net)
Definition: net.cpp:259
const std::string CLIENT_DATE
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:78
void StartNode(boost::thread_group &threadGroup)
Definition: net.cpp:1708
CWallet * pwalletMain
map< string, string > mapArgs
Definition: util.cpp:89
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion)
Definition: netbase.cpp:419
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
Definition: main.h:48
boost::filesystem::path GetDefaultDataDir()
Definition: util.cpp:941
static CCoinsViewDB * pcoinsdbview
Definition: init.cpp:108
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
Definition: main.cpp:345
void StartRPCThreads()
Definition: rpcserver.cpp:531