Bitcoin ABC  0.26.3
P2P Digital Currency
bitcoin.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2019 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <qt/bitcoin.h>
6 
7 #include <chainparams.h>
8 #include <config.h>
9 #include <httprpc.h>
10 #include <init.h>
11 #include <interfaces/handler.h>
12 #include <interfaces/node.h>
13 #include <node/context.h>
14 #include <node/ui_interface.h>
15 #include <noui.h>
16 #include <qt/bitcoingui.h>
17 #include <qt/clientmodel.h>
18 #include <qt/guiconstants.h>
19 #include <qt/guiutil.h>
20 #include <qt/intro.h>
21 #include <qt/networkstyle.h>
22 #include <qt/optionsmodel.h>
23 #include <qt/platformstyle.h>
24 #include <qt/splashscreen.h>
25 #include <qt/utilitydialog.h>
26 #include <qt/winshutdownmonitor.h>
27 #include <uint256.h>
28 #include <util/system.h>
29 #include <util/threadnames.h>
30 #include <util/translation.h>
31 #include <validation.h>
32 
33 #ifdef ENABLE_WALLET
34 #include <qt/paymentserver.h>
35 #include <qt/walletcontroller.h>
36 #include <qt/walletmodel.h>
37 #endif // ENABLE_WALLET
38 
39 #include <QDebug>
40 #include <QLibraryInfo>
41 #include <QLocale>
42 #include <QMessageBox>
43 #include <QSettings>
44 #include <QStringList>
45 #include <QThread>
46 #include <QTimer>
47 #include <QTranslator>
48 
49 #include <boost/signals2/connection.hpp>
50 
51 #include <any>
52 
53 #if defined(QT_STATICPLUGIN)
54 #include <QtPlugin>
55 #if defined(QT_QPA_PLATFORM_XCB)
56 Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
57 #elif defined(QT_QPA_PLATFORM_WINDOWS)
58 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
59 #elif defined(QT_QPA_PLATFORM_COCOA)
60 Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
61 #endif
62 #endif
63 
64 // Declare meta types used for QMetaObject::invokeMethod
65 Q_DECLARE_METATYPE(bool *)
66 Q_DECLARE_METATYPE(Amount)
67 Q_DECLARE_METATYPE(SynchronizationState)
68 Q_DECLARE_METATYPE(uint256)
69 
70 // Config is non-copyable so we can only register pointers to it
71 Q_DECLARE_METATYPE(Config *)
72 
73 static void RegisterMetaTypes() {
74  // Register meta types used for QMetaObject::invokeMethod and
75  // Qt::QueuedConnection
76  qRegisterMetaType<bool *>();
77  qRegisterMetaType<SynchronizationState>();
78 #ifdef ENABLE_WALLET
79  qRegisterMetaType<WalletModel *>();
80 #endif
81  qRegisterMetaType<Amount>();
82  // Register typedefs (see
83  // http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
84  qRegisterMetaType<size_t>("size_t");
85 
86  qRegisterMetaType<std::function<void()>>("std::function<void()>");
87  qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon");
88  qRegisterMetaType<interfaces::BlockAndHeaderTipInfo>(
89  "interfaces::BlockAndHeaderTipInfo");
90 
91  // Need to register any types Qt doesn't know about if you intend
92  // to use them with the signal/slot mechanism Qt provides. Even pointers.
93  // Note that class Config is noncopyable and so we can't register a
94  // non-pointer version of it with Qt, because Qt expects to be able to
95  // copy-construct non-pointers to objects for invoking slots
96  // behind-the-scenes in the 'Queued' connection case.
97  qRegisterMetaType<Config *>();
98 }
99 
100 static QString GetLangTerritory() {
101  QSettings settings;
102  // Get desired locale (e.g. "de_DE")
103  // 1) System default language
104  QString lang_territory = QLocale::system().name();
105  // 2) Language from QSettings
106  QString lang_territory_qsettings =
107  settings.value("language", "").toString();
108  if (!lang_territory_qsettings.isEmpty()) {
109  lang_territory = lang_territory_qsettings;
110  }
111  // 3) -lang command line argument
112  lang_territory = QString::fromStdString(
113  gArgs.GetArg("-lang", lang_territory.toStdString()));
114  return lang_territory;
115 }
116 
118 static void initTranslations(QTranslator &qtTranslatorBase,
119  QTranslator &qtTranslator,
120  QTranslator &translatorBase,
121  QTranslator &translator) {
122  // Remove old translators
123  QApplication::removeTranslator(&qtTranslatorBase);
124  QApplication::removeTranslator(&qtTranslator);
125  QApplication::removeTranslator(&translatorBase);
126  QApplication::removeTranslator(&translator);
127 
128  // Get desired locale (e.g. "de_DE")
129  // 1) System default language
130  QString lang_territory = GetLangTerritory();
131 
132  // Convert to "de" only by truncating "_DE"
133  QString lang = lang_territory;
134  lang.truncate(lang_territory.lastIndexOf('_'));
135 
136  // Load language files for configured locale:
137  // - First load the translator for the base language, without territory
138  // - Then load the more specific locale translator
139 
140  // Load e.g. qt_de.qm
141  if (qtTranslatorBase.load(
142  "qt_" + lang,
143  QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
144  QApplication::installTranslator(&qtTranslatorBase);
145  }
146 
147  // Load e.g. qt_de_DE.qm
148  if (qtTranslator.load(
149  "qt_" + lang_territory,
150  QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
151  QApplication::installTranslator(&qtTranslator);
152  }
153 
154  // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in
155  // bitcoin.qrc)
156  if (translatorBase.load(lang, ":/translations/")) {
157  QApplication::installTranslator(&translatorBase);
158  }
159 
160  // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in
161  // bitcoin.qrc)
162  if (translator.load(lang_territory, ":/translations/")) {
163  QApplication::installTranslator(&translator);
164  }
165 }
166 
167 /* qDebug() message handler --> debug.log */
168 void DebugMessageHandler(QtMsgType type, const QMessageLogContext &context,
169  const QString &msg) {
170  Q_UNUSED(context);
171  if (type == QtDebugMsg) {
172  LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
173  } else {
174  LogPrintf("GUI: %s\n", msg.toStdString());
175  }
176 }
177 
178 BitcoinABC::BitcoinABC(interfaces::Node &node) : QObject(), m_node(node) {}
179 
180 void BitcoinABC::handleRunawayException(const std::exception *e) {
181  PrintExceptionContinue(e, "Runaway exception");
182  Q_EMIT runawayException(
183  QString::fromStdString(m_node.getWarnings().translated));
184 }
185 
186 void BitcoinABC::initialize(Config *config, RPCServer *rpcServer,
187  HTTPRPCRequestProcessor *httpRPCRequestProcessor) {
188  try {
189  util::ThreadRename("qt-init");
190  qDebug() << __func__ << ": Running initialization in thread";
192  bool rv = m_node.appInitMain(*config, *rpcServer,
193  *httpRPCRequestProcessor, &tip_info);
194  Q_EMIT initializeResult(rv, tip_info);
195  } catch (const std::exception &e) {
197  } catch (...) {
198  handleRunawayException(nullptr);
199  }
200 }
201 
203  try {
204  qDebug() << __func__ << ": Running Shutdown in thread";
206  qDebug() << __func__ << ": Shutdown finished";
207  Q_EMIT shutdownResult();
208  } catch (const std::exception &e) {
210  } catch (...) {
211  handleRunawayException(nullptr);
212  }
213 }
214 
215 static int qt_argc = 1;
216 static const char *qt_argv = "bitcoin-qt";
217 
219  : QApplication(qt_argc, const_cast<char **>(&qt_argv)), coreThread(nullptr),
220  optionsModel(nullptr), clientModel(nullptr), window(nullptr),
221  pollShutdownTimer(nullptr), returnValue(0), platformStyle(nullptr) {
222  // Qt runs setlocale(LC_ALL, "") on initialization.
224  setQuitOnLastWindowClosed(false);
225 }
226 
228  // UI per-platform customization
229  // This must be done inside the BitcoinApplication constructor, or after it,
230  // because PlatformStyle::instantiate requires a QApplication.
231  std::string platformName;
232  platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
233  platformStyle =
234  PlatformStyle::instantiate(QString::fromStdString(platformName));
235  // Fall back to "other" if specified name not found.
236  if (!platformStyle) {
238  }
240 }
241 
243  if (coreThread) {
244  qDebug() << __func__ << ": Stopping thread";
245  coreThread->quit();
246  coreThread->wait();
247  qDebug() << __func__ << ": Stopped thread";
248  }
249 
250  delete window;
251  window = nullptr;
252  delete platformStyle;
253  platformStyle = nullptr;
254 }
255 
256 #ifdef ENABLE_WALLET
257 void BitcoinApplication::createPaymentServer() {
258  paymentServer = new PaymentServer(this);
259 }
260 #endif
261 
262 void BitcoinApplication::createOptionsModel(bool resetSettings) {
263  optionsModel = new OptionsModel(this, resetSettings);
264 }
265 
267  const NetworkStyle *networkStyle) {
268  window =
269  new BitcoinGUI(node(), config, platformStyle, networkStyle, nullptr);
270 
271  pollShutdownTimer = new QTimer(window);
272  connect(pollShutdownTimer, &QTimer::timeout, window,
274 }
275 
277  assert(!m_splash);
278  m_splash = new SplashScreen(networkStyle);
279  // We don't hold a direct pointer to the splash screen after creation, but
280  // the splash screen will take care of deleting itself when finish()
281  // happens.
282  m_splash->show();
288  &QWidget::close);
289 }
290 
292  assert(!m_node);
293  m_node = &node;
294  if (optionsModel) {
296  }
297  if (m_splash) {
299  }
300 }
301 
303  return node().baseInitialize(config);
304 }
305 
307  if (coreThread) {
308  return;
309  }
310  coreThread = new QThread(this);
311  BitcoinABC *executor = new BitcoinABC(node());
312  executor->moveToThread(coreThread);
313 
314  /* communication to and from thread */
315  connect(executor, &BitcoinABC::initializeResult, this,
317  connect(executor, &BitcoinABC::shutdownResult, this,
319  connect(executor, &BitcoinABC::runawayException, this,
321 
322  // Note on how Qt works: it tries to directly invoke methods if the signal
323  // is emitted on the same thread that the target object 'lives' on.
324  // But if the target object 'lives' on another thread (executor here does)
325  // the SLOT will be invoked asynchronously at a later time in the thread
326  // of the target object. So.. we pass a pointer around. If you pass
327  // a reference around (even if it's non-const) you'll get Qt generating
328  // code to copy-construct the parameter in question (Q_DECLARE_METATYPE
329  // and qRegisterMetaType generate this code). For the Config class,
330  // which is noncopyable, we can't do this. So.. we have to pass
331  // pointers to Config around. Make sure Config &/Config * isn't a
332  // temporary (eg it lives somewhere aside from the stack) or this will
333  // crash because initialize() gets executed in another thread at some
334  // unspecified time (after) requestedInitialize() is emitted!
335  connect(this, &BitcoinApplication::requestedInitialize, executor,
337 
338  connect(this, &BitcoinApplication::requestedShutdown, executor,
340  /* make sure executor object is deleted in its own thread */
341  connect(coreThread, &QThread::finished, executor, &QObject::deleteLater);
342 
343  coreThread->start();
344 }
345 
347  // Default printtoconsole to false for the GUI. GUI programs should not
348  // print to the console unnecessarily.
349  gArgs.SoftSetBoolArg("-printtoconsole", false);
350 
353 }
354 
356  // If prune is set, intentionally override existing prune size with
357  // the default size since this is called when choosing a new datadir.
359 }
360 
362  Config &config, RPCServer &rpcServer,
363  HTTPRPCRequestProcessor &httpRPCRequestProcessor) {
364  qDebug() << __func__ << ": Requesting initialize";
365  startThread();
366  // IMPORTANT: config must NOT be a reference to a temporary because below
367  // signal may be connected to a slot that will be executed as a queued
368  // connection in another thread!
369  Q_EMIT requestedInitialize(&config, &rpcServer, &httpRPCRequestProcessor);
370 }
371 
373  // Show a simple window indicating shutdown status. Do this first as some of
374  // the steps may take some time below, for example the RPC console may still
375  // be executing a command.
377 
378  qDebug() << __func__ << ": Requesting shutdown";
379  startThread();
380  window->hide();
381  // Must disconnect node signals otherwise current thread can deadlock since
382  // no event loop is running.
384  // Request node shutdown, which can interrupt long operations, like
385  // rescanning a wallet.
386  node().startShutdown();
387  // Unsetting the client model can cause the current thread to wait for node
388  // to complete an operation, like wait for a RPC execution to complete.
389  window->setClientModel(nullptr);
390  pollShutdownTimer->stop();
391 
392  delete clientModel;
393  clientModel = nullptr;
394 
395  // Request shutdown from core thread
396  Q_EMIT requestedShutdown();
397 }
398 
400  bool success, interfaces::BlockAndHeaderTipInfo tip_info) {
401  qDebug() << __func__ << ": Initialization result: " << success;
402  returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE;
403  if (!success) {
404  // Make sure splash screen doesn't stick around during shutdown.
405  Q_EMIT splashFinished();
406  // Exit first main loop invocation.
407  quit();
408  return;
409  }
410  // Log this only after AppInitMain finishes, as then logging setup is
411  // guaranteed complete.
412  qInfo() << "Platform customization:" << platformStyle->getName();
414  window->setClientModel(clientModel, &tip_info);
415 #ifdef ENABLE_WALLET
417  m_wallet_controller =
419  window->setWalletController(m_wallet_controller);
420  if (paymentServer) {
421  paymentServer->setOptionsModel(optionsModel);
422 #ifdef ENABLE_BIP70
423  PaymentServer::LoadRootCAs();
424  connect(m_wallet_controller, &WalletController::coinsSent,
425  paymentServer, &PaymentServer::fetchPaymentACK);
426 #endif
427  }
428  }
429 #endif // ENABLE_WALLET
430 
431  // If -min option passed, start window minimized(iconified)
432  // or minimized to tray
433  if (!gArgs.GetBoolArg("-min", false)) {
434  window->show();
435  } else if (clientModel->getOptionsModel()->getMinimizeToTray() &&
436  window->hasTrayIcon()) {
437  // do nothing as the window is managed by the tray icon
438  } else {
439  window->showMinimized();
440  }
441  Q_EMIT splashFinished();
442  Q_EMIT windowShown(window);
443 
444 #ifdef ENABLE_WALLET
445  // Now that initialization/startup is done, process any command-line
446  // bitcoincash: URIs or payment requests:
447  if (paymentServer) {
448  connect(paymentServer, &PaymentServer::receivedPaymentRequest, window,
449  &BitcoinGUI::handlePaymentRequest);
450  connect(window, &BitcoinGUI::receivedURI, paymentServer,
452  connect(paymentServer, &PaymentServer::message,
453  [this](const QString &title, const QString &message,
454  unsigned int style) {
455  window->message(title, message, style);
456  });
457  QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady);
458  }
459 #endif
460 
461  pollShutdownTimer->start(200);
462 }
463 
465  // Exit second main loop invocation after shutdown finished.
466  quit();
467 }
468 
469 void BitcoinApplication::handleRunawayException(const QString &message) {
470  QMessageBox::critical(
471  nullptr, "Runaway exception",
472  BitcoinGUI::tr("A fatal error occurred. %1 can no longer continue "
473  "safely and will quit.")
474  .arg(PACKAGE_NAME) +
475  QString("<br><br>") + message);
476  ::exit(EXIT_FAILURE);
477 }
478 
480  if (!window) {
481  return 0;
482  }
483 
484  return window->winId();
485 }
486 
487 static void SetupUIArgs(ArgsManager &argsman) {
488 #if defined(ENABLE_WALLET) && defined(ENABLE_BIP70)
489  argsman.AddArg(
490  "-allowselfsignedrootcertificates",
491  strprintf("Allow self signed root certificates (default: %d)",
494 #endif
495  argsman.AddArg("-choosedatadir",
496  strprintf("Choose data directory on startup (default: %d)",
499  argsman.AddArg(
500  "-lang=<lang>",
501  "Set language, for example \"de_DE\" (default: system locale)",
503  argsman.AddArg("-min", "Start minimized", ArgsManager::ALLOW_ANY,
505  argsman.AddArg(
506  "-rootcertificates=<file>",
507  "Set SSL root certificates for payment request (default: -system-)",
509  argsman.AddArg("-splash",
510  strprintf("Show splash screen on startup (default: %d)",
513  argsman.AddArg("-resetguisettings", "Reset all settings changed in the GUI",
515  argsman.AddArg("-uiplatform",
516  strprintf("Select platform to customize UI for (one of "
517  "windows, macosx, other; default: %s)",
521 }
522 
523 static void MigrateSettings() {
524  assert(!QApplication::applicationName().isEmpty());
525 
526  static const QString legacyAppName("Bitcoin-Qt"),
527 #ifdef Q_OS_DARWIN
528  // Macs and/or iOS et al use a domain-style name for Settings
529  // files. All other platforms use a simple orgname. This
530  // difference is documented in the QSettings class documentation.
531  legacyOrg("bitcoin.org");
532 #else
533  legacyOrg("Bitcoin");
534 #endif
535  QSettings
536  // below picks up settings file location based on orgname,appname
537  legacy(legacyOrg, legacyAppName),
538  // default c'tor below picks up settings file location based on
539  // QApplication::applicationName(), et al -- which was already set
540  // in main()
541  abc;
542 #ifdef Q_OS_DARWIN
543  // Disable bogus OSX keys from MacOS system-wide prefs that may cloud our
544  // judgement ;) (this behavior is also documented in QSettings docs)
545  legacy.setFallbacksEnabled(false);
546  abc.setFallbacksEnabled(false);
547 #endif
548  const QStringList legacyKeys(legacy.allKeys());
549 
550  // We only migrate settings if we have Core settings but no Bitcoin-ABC
551  // settings
552  if (!legacyKeys.isEmpty() && abc.allKeys().isEmpty()) {
553  for (const QString &key : legacyKeys) {
554  // now, copy settings over
555  abc.setValue(key, legacy.value(key));
556  }
557  }
558 }
559 
560 int GuiMain(int argc, char *argv[]) {
561 #ifdef WIN32
562  util::WinCmdLineArgs winArgs;
563  std::tie(argc, argv) = winArgs.get();
564 #endif
567 
568  NodeContext node_context;
569  std::unique_ptr<interfaces::Node> node =
570  interfaces::MakeNode(&node_context);
571 
572  // Subscribe to global signals from core
573  boost::signals2::scoped_connection handler_message_box =
574  ::uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
575  boost::signals2::scoped_connection handler_question =
576  ::uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion);
577  boost::signals2::scoped_connection handler_init_message =
578  ::uiInterface.InitMessage_connect(noui_InitMessage);
579 
580  // Do not refer to data directory yet, this can be overridden by
581  // Intro::pickDataDirectory
582 
585  Q_INIT_RESOURCE(bitcoin);
586  Q_INIT_RESOURCE(bitcoin_locale);
587 
588  // Generate high-dpi pixmaps
589  QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
590  QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
591 
592  BitcoinApplication app;
593 
596  // Command-line options take precedence:
597  SetupServerArgs(node_context);
599  std::string error;
600  if (!gArgs.ParseParameters(argc, argv, error)) {
602  Untranslated("Error parsing command line arguments: %s\n"), error));
603  // Create a message box, because the gui has neither been created nor
604  // has subscribed to core signals
605  QMessageBox::critical(
606  nullptr, PACKAGE_NAME,
607  // message can not be translated because translations have not been
608  // initialized
609  QString::fromStdString("Error parsing command line arguments: %1.")
610  .arg(QString::fromStdString(error)));
611  return EXIT_FAILURE;
612  }
613 
614  // Now that the QApplication is setup and we have parsed our parameters, we
615  // can set the platform style
616  app.setupPlatformStyle();
617 
619  // must be set before OptionsModel is initialized or translations are
620  // loaded, as it is used to locate QSettings.
621  // Note: If you move these calls somewhere else, be sure to bring
622  // MigrateSettings() below along for the ride.
623  QApplication::setOrganizationName(QAPP_ORG_NAME);
624  QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
625  QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
626  // Migrate settings from core's/our old GUI settings to Bitcoin ABC
627  // only if core's exist but Bitcoin ABC's doesn't.
628  // NOTE -- this function needs to be called *after* the above 3 lines
629  // that set the app orgname and app name! If you move the above 3 lines
630  // to elsewhere, take this call with you!
631  MigrateSettings();
632 
635  QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
636  initTranslations(qtTranslatorBase, qtTranslator, translatorBase,
637  translator);
638 
639  // Show help message immediately after parsing command-line options (for
640  // "-lang") and setting locale, but before showing splash screen.
641  if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
642  HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version"));
643  help.showOrPrint();
644  return EXIT_SUCCESS;
645  }
646 
647  // Install global event filter that makes sure that long tooltips can be
648  // word-wrapped
649  app.installEventFilter(
651 
654  bool did_show_intro = false;
655  // Intro dialog prune check box
656  bool prune = false;
657  // Gracefully exit if the user cancels
658  if (!Intro::showIfNeeded(did_show_intro, prune)) {
659  return EXIT_SUCCESS;
660  }
661 
665  if (!CheckDataDirOption()) {
667  Untranslated("Specified data directory \"%s\" does not exist.\n"),
668  gArgs.GetArg("-datadir", "")));
669  QMessageBox::critical(
670  nullptr, PACKAGE_NAME,
671  QObject::tr(
672  "Error: Specified data directory \"%1\" does not exist.")
673  .arg(QString::fromStdString(gArgs.GetArg("-datadir", ""))));
674  return EXIT_FAILURE;
675  }
676  if (!gArgs.ReadConfigFiles(error)) {
678  Untranslated("Error reading configuration file: %s\n"), error));
679  QMessageBox::critical(
680  nullptr, PACKAGE_NAME,
681  QObject::tr("Error: Cannot parse configuration file: %1.")
682  .arg(QString::fromStdString(error)));
683  return EXIT_FAILURE;
684  }
685 
687  // - Do not call Params() before this step.
688  // - Do this after parsing the configuration file, as the network can be
689  // switched there.
690  // - QSettings() will use the new application name after this, resulting in
691  // network-specific settings.
692  // - Needs to be done before createOptionsModel.
693 
694  // Check for -chain, -testnet or -regtest parameter (Params() calls are only
695  // valid after this clause)
696  try {
698  } catch (std::exception &e) {
699  InitError(Untranslated(strprintf("%s\n", e.what())));
700  QMessageBox::critical(nullptr, PACKAGE_NAME,
701  QObject::tr("Error: %1").arg(e.what()));
702  return EXIT_FAILURE;
703  }
704 #ifdef ENABLE_WALLET
705  // Parse URIs on command line -- this can affect Params()
707 #endif
708  if (!gArgs.InitSettings(error)) {
710  QMessageBox::critical(nullptr, PACKAGE_NAME,
711  QObject::tr("Error initializing settings: %1")
712  .arg(QString::fromStdString(error)));
713  return EXIT_FAILURE;
714  }
715 
716  QScopedPointer<const NetworkStyle> networkStyle(
717  NetworkStyle::instantiate(Params().NetworkIDString()));
718  assert(!networkStyle.isNull());
719  // Allow for separate UI settings for testnets
720  QApplication::setApplicationName(networkStyle->getAppName());
721  // Re-initialize translations after changing application name (language in
722  // network-specific settings can be different)
723  initTranslations(qtTranslatorBase, qtTranslator, translatorBase,
724  translator);
725 
726 #ifdef ENABLE_WALLET
728  // - Do this early as we don't want to bother initializing if we are just
729  // calling IPC
730  // - Do this *after* setting up the data directory, as the data directory
731  // hash is used in the name
732  // of the server.
733  // - Do this after creating app and setting up translations, so errors are
734  // translated properly.
736  exit(EXIT_SUCCESS);
737  }
738 
739  // Start up the payment server early, too, so impatient users that click on
740  // bitcoincash: links repeatedly have their payment requests routed to this
741  // process:
743  app.createPaymentServer();
744  }
745 #endif // ENABLE_WALLET
746 
748  // Install global event filter that makes sure that out-of-focus labels do
749  // not contain text cursor.
750  app.installEventFilter(new GUIUtil::LabelOutOfFocusEventFilter(&app));
751 #if defined(Q_OS_WIN)
752  // Install global event filter for processing Windows session related
753  // Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
754  qApp->installNativeEventFilter(new WinShutdownMonitor());
755 #endif
756  // Install qDebug() message handler to route to debug.log
757  qInstallMessageHandler(DebugMessageHandler);
758  // Allow parameter interaction before we create the options model
759  app.parameterSetup();
761  // Load GUI settings from QSettings
762  app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
763 
764  if (did_show_intro) {
765  // Store intro dialog settings other than datadir (network specific)
766  app.InitializePruneSetting(prune);
767  }
768 
769  // Get global config
770  Config &config = const_cast<Config &>(GetConfig());
771 
772  if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) &&
773  !gArgs.GetBoolArg("-min", false)) {
774  app.createSplashScreen(networkStyle.data());
775  }
776 
777  app.setNode(*node);
778 
779  RPCServer rpcServer;
780  std::any context{&node_context};
781  HTTPRPCRequestProcessor httpRPCRequestProcessor(config, rpcServer, context);
782 
783  try {
784  app.createWindow(&config, networkStyle.data());
785  // Perform base initialization before spinning up
786  // initialization/shutdown thread. This is acceptable because this
787  // function only contains steps that are quick to execute, so the GUI
788  // thread won't be held up.
789  if (!app.baseInitialize(config)) {
790  // A dialog with detailed error will have been shown by InitError()
791  return EXIT_FAILURE;
792  }
793  app.requestInitialize(config, rpcServer, httpRPCRequestProcessor);
794 #if defined(Q_OS_WIN)
795  WinShutdownMonitor::registerShutdownBlockReason(
796  QObject::tr("%1 didn't yet exit safely...").arg(PACKAGE_NAME),
797  (HWND)app.getMainWinId());
798 #endif
799  app.exec();
800  app.requestShutdown(config);
801  app.exec();
802  return app.getReturnValue();
803  } catch (const std::exception &e) {
804  PrintExceptionContinue(&e, "Runaway exception");
806  QString::fromStdString(app.node().getWarnings().translated));
807  } catch (...) {
808  PrintExceptionContinue(nullptr, "Runaway exception");
810  QString::fromStdString(app.node().getWarnings().translated));
811  }
812  return EXIT_FAILURE;
813 }
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given BIP70 chain name.
const CChainParams & Params()
Return the currently selected parameters.
@ ALLOW_ANY
Definition: system.h:150
@ DEBUG_ONLY
Definition: system.h:151
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:488
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:331
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:484
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:584
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:620
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:941
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:603
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:651
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1044
Class encapsulating Bitcoin ABC startup and shutdown.
Definition: bitcoin.h:36
interfaces::Node & m_node
Definition: bitcoin.h:56
void initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info)
void handleRunawayException(const std::exception *e)
Pass fatal exception message to UI thread.
Definition: bitcoin.cpp:180
void shutdown()
Definition: bitcoin.cpp:202
void runawayException(const QString &message)
void shutdownResult()
BitcoinABC(interfaces::Node &node)
Definition: bitcoin.cpp:178
void initialize(Config *config, RPCServer *rpcServer, HTTPRPCRequestProcessor *httpRPCRequestProcessor)
Definition: bitcoin.cpp:186
Main Bitcoin application object.
Definition: bitcoin.h:60
ClientModel * clientModel
Definition: bitcoin.h:123
bool baseInitialize(Config &config)
Basic initialization, before starting initialization/shutdown thread.
Definition: bitcoin.cpp:302
void createSplashScreen(const NetworkStyle *networkStyle)
Create splash screen.
Definition: bitcoin.cpp:276
SplashScreen * m_splash
Definition: bitcoin.h:133
void windowShown(BitcoinGUI *window)
void initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info)
Definition: bitcoin.cpp:399
QThread * coreThread
Definition: bitcoin.h:121
void setNode(interfaces::Node &node)
Definition: bitcoin.cpp:291
QTimer * pollShutdownTimer
Definition: bitcoin.h:125
BitcoinGUI * window
Definition: bitcoin.h:124
void InitializePruneSetting(bool prune)
Initialize prune setting.
Definition: bitcoin.cpp:355
interfaces::Node * m_node
Definition: bitcoin.h:134
const PlatformStyle * platformStyle
Definition: bitcoin.h:131
int getReturnValue() const
Get process return value.
Definition: bitcoin.h:91
void parameterSetup()
parameter interaction/setup based on rules
Definition: bitcoin.cpp:346
void handleRunawayException(const QString &message)
Handle runaway exceptions.
Definition: bitcoin.cpp:469
void createWindow(const Config *, const NetworkStyle *networkStyle)
Create main window.
Definition: bitcoin.cpp:266
OptionsModel * optionsModel
Definition: bitcoin.h:122
void createOptionsModel(bool resetSettings)
Create options model.
Definition: bitcoin.cpp:262
void requestInitialize(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Request core initialization.
Definition: bitcoin.cpp:361
void setupPlatformStyle()
Setup platform style.
Definition: bitcoin.cpp:227
void requestedInitialize(Config *config, RPCServer *rpcServer, HTTPRPCRequestProcessor *httpRPCRequestProcessor)
void shutdownResult()
Definition: bitcoin.cpp:464
std::unique_ptr< QWidget > shutdownWindow
Definition: bitcoin.h:132
void requestShutdown(Config &config)
Request core shutdown.
Definition: bitcoin.cpp:372
WId getMainWinId() const
Get window identifier of QMainWindow (BitcoinGUI)
Definition: bitcoin.cpp:479
interfaces::Node & node() const
Definition: bitcoin.h:99
Bitcoin GUI main class.
Definition: bitcoingui.h:68
static const std::string DEFAULT_UIPLATFORM
Definition: bitcoingui.h:72
void setClientModel(ClientModel *clientModel=nullptr, interfaces::BlockAndHeaderTipInfo *tip_info=nullptr)
Set the client model.
Definition: bitcoingui.cpp:655
void receivedURI(const QString &uri)
Signal raised when a URI was entered or dragged to the GUI.
void unsubscribeFromCoreSignals()
Disconnect core signals from GUI client.
bool hasTrayIcon() const
Get the tray icon status.
Definition: bitcoingui.h:113
void detectShutdown()
called by a timer to check if ShutdownRequested() has been set
void message(const QString &title, QString message, unsigned int style, bool *ret=nullptr, const QString &detailed_message=QString())
Notify the user of an event from the core network or transaction handling code.
Model for Bitcoin network client.
Definition: clientmodel.h:36
OptionsModel * getOptionsModel()
Definition: config.h:17
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:207
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:187
"Help message" dialog box
Definition: utilitydialog.h:20
static bool showIfNeeded(bool &did_show_intro, bool &prune)
Determine data directory.
Definition: intro.cpp:178
static const NetworkStyle * instantiate(const std::string &networkId)
Get style associated with provided BIP70 network id, or 0 if not known.
Interface from Qt to configuration data structure for Bitcoin client.
Definition: optionsmodel.h:48
void SetPruneTargetGB(int prune_target_gb, bool force=false)
bool getMinimizeToTray() const
Definition: optionsmodel.h:95
void setNode(interfaces::Node &node)
Definition: optionsmodel.h:117
static bool ipcSendCommandLine()
void message(const QString &title, const QString &message, unsigned int style)
static void ipcParseCommandLine(int argc, char *argv[])
void receivedPaymentRequest(SendCoinsRecipient)
void handleURIOrFile(const QString &s)
const QString & getName() const
Definition: platformstyle.h:18
static const PlatformStyle * instantiate(const QString &platformId)
Get style associated with provided platform name, or 0 if not known.
Class for registering and managing all RPC calls.
Definition: server.h:39
static QWidget * showShutdownWindow(QMainWindow *window)
Class for the splashscreen with information of the running client.
Definition: splashscreen.h:26
void finish()
Hide the splash screen window and schedule the splash screen object for deletion.
void handleLoadWallet()
Handle wallet load notifications.
void setNode(interfaces::Node &node)
Controller between interfaces::Node, WalletModel instances and the GUI.
void coinsSent(interfaces::Wallet &wallet, SendCoinsRecipient recipient, QByteArray transaction)
static bool isWalletEnabled()
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:55
virtual bilingual_str getWarnings()=0
Get warnings.
virtual void appShutdown()=0
Stop node.
virtual bool appInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, interfaces::BlockAndHeaderTipInfo *tip_info=nullptr)=0
Start node.
virtual void startShutdown()=0
Start shutdown.
virtual bool baseInitialize(Config &config)=0
Initialize app dependencies.
256-bit opaque blob.
Definition: uint256.h:127
const Config & GetConfig()
Definition: config.cpp:34
static constexpr int DEFAULT_PRUNE_TARGET_GB
Definition: guiconstants.h:55
static const int TOOLTIP_WRAP_THRESHOLD
Definition: guiconstants.h:40
#define QAPP_ORG_NAME
Definition: guiconstants.h:45
static const bool DEFAULT_SPLASHSCREEN
Definition: guiconstants.h:19
#define QAPP_APP_NAME_DEFAULT
Definition: guiconstants.h:47
#define QAPP_ORG_DOMAIN
Definition: guiconstants.h:46
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1586
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:387
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1452
NodeContext & m_node
Definition: chain.cpp:483
static const bool DEFAULT_CHOOSE_DATADIR
Definition: intro.h:12
#define LogPrint(category,...)
Definition: logging.h:208
#define LogPrintf(...)
Definition: logging.h:204
@ QT
Definition: logging.h:58
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:957
std::unique_ptr< Node > MakeNode(NodeContext *context)
Return implementation of Node interface.
Definition: node.cpp:312
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:53
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:48
bool noui_ThreadSafeQuestion(const bilingual_str &, const std::string &message, const std::string &caption, unsigned int style)
Non-GUI handler, which logs and prints questions.
Definition: noui.cpp:48
void noui_InitMessage(const std::string &message)
Non-GUI handler, which only logs a message.
Definition: noui.cpp:55
bool noui_ThreadSafeMessageBox(const bilingual_str &message, const std::string &caption, unsigned int style)
Non-GUI handler, which logs and prints messages.
Definition: noui.cpp:20
static const bool DEFAULT_SELFSIGNED_ROOTCERTS
static void RegisterMetaTypes()
Definition: bitcoin.cpp:73
static int qt_argc
Definition: bitcoin.cpp:215
static void MigrateSettings()
Definition: bitcoin.cpp:523
static QString GetLangTerritory()
Definition: bitcoin.cpp:100
int GuiMain(int argc, char *argv[])
Definition: bitcoin.cpp:560
static void SetupUIArgs(ArgsManager &argsman)
Definition: bitcoin.cpp:487
static const char * qt_argv
Definition: bitcoin.cpp:216
static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
Set up translations.
Definition: bitcoin.cpp:118
void DebugMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
Definition: bitcoin.cpp:168
static RPCHelpMan help()
Definition: server.cpp:177
Definition: amount.h:19
NodeContext struct containing references to chain state and connection state.
Definition: context.h:37
std::string translated
Definition: translation.h:19
Block and header tip information.
Definition: node.h:46
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:760
bool CheckDataDirOption()
Definition: system.cpp:836
ArgsManager gArgs
Definition: system.cpp:77
void SetupEnvironment()
Definition: system.cpp:1317
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:805
bool error(const char *fmt, const Args &...args)
Definition: system.h:46
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
CClientUIInterface uiInterface
bool InitError(const bilingual_str &str)
Show error message.
assert(!tx.IsCoinBase())
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:127