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