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 <QThread>
45 #include <QTimer>
46 #include <QTranslator>
47 
48 #include <boost/signals2/connection.hpp>
49 
50 #include <any>
51 
52 #if defined(QT_STATICPLUGIN)
53 #include <QtPlugin>
54 #if defined(QT_QPA_PLATFORM_XCB)
55 Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
56 #elif defined(QT_QPA_PLATFORM_WINDOWS)
57 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
58 #elif defined(QT_QPA_PLATFORM_COCOA)
59 Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
60 Q_IMPORT_PLUGIN(QMacStylePlugin);
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(SyncType)
69 Q_DECLARE_METATYPE(uint256)
70 
71 // Config is non-copyable so we can only register pointers to it
72 Q_DECLARE_METATYPE(Config *)
73 
74 using node::NodeContext;
75 
76 static void RegisterMetaTypes() {
77  // Register meta types used for QMetaObject::invokeMethod and
78  // Qt::QueuedConnection
79  qRegisterMetaType<bool *>();
80  qRegisterMetaType<SynchronizationState>();
81  qRegisterMetaType<SyncType>();
82 #ifdef ENABLE_WALLET
83  qRegisterMetaType<WalletModel *>();
84 #endif
85  qRegisterMetaType<Amount>();
86  // Register typedefs (see
87  // http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
88  qRegisterMetaType<size_t>("size_t");
89 
90  qRegisterMetaType<std::function<void()>>("std::function<void()>");
91  qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon");
92  qRegisterMetaType<interfaces::BlockAndHeaderTipInfo>(
93  "interfaces::BlockAndHeaderTipInfo");
94 
95  // Need to register any types Qt doesn't know about if you intend
96  // to use them with the signal/slot mechanism Qt provides. Even pointers.
97  // Note that class Config is noncopyable and so we can't register a
98  // non-pointer version of it with Qt, because Qt expects to be able to
99  // copy-construct non-pointers to objects for invoking slots
100  // behind-the-scenes in the 'Queued' connection case.
101  qRegisterMetaType<Config *>();
102 }
103 
104 static QString GetLangTerritory() {
105  QSettings settings;
106  // Get desired locale (e.g. "de_DE")
107  // 1) System default language
108  QString lang_territory = QLocale::system().name();
109  // 2) Language from QSettings
110  QString lang_territory_qsettings =
111  settings.value("language", "").toString();
112  if (!lang_territory_qsettings.isEmpty()) {
113  lang_territory = lang_territory_qsettings;
114  }
115  // 3) -lang command line argument
116  lang_territory = QString::fromStdString(
117  gArgs.GetArg("-lang", lang_territory.toStdString()));
118  return lang_territory;
119 }
120 
122 static void initTranslations(QTranslator &qtTranslatorBase,
123  QTranslator &qtTranslator,
124  QTranslator &translatorBase,
125  QTranslator &translator) {
126  // Remove old translators
127  QApplication::removeTranslator(&qtTranslatorBase);
128  QApplication::removeTranslator(&qtTranslator);
129  QApplication::removeTranslator(&translatorBase);
130  QApplication::removeTranslator(&translator);
131 
132  // Get desired locale (e.g. "de_DE")
133  // 1) System default language
134  QString lang_territory = GetLangTerritory();
135 
136  // Convert to "de" only by truncating "_DE"
137  QString lang = lang_territory;
138  lang.truncate(lang_territory.lastIndexOf('_'));
139 
140  // Load language files for configured locale:
141  // - First load the translator for the base language, without territory
142  // - Then load the more specific locale translator
143 
144  // Load e.g. qt_de.qm
145  if (qtTranslatorBase.load(
146  "qt_" + lang,
147  QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
148  QApplication::installTranslator(&qtTranslatorBase);
149  }
150 
151  // Load e.g. qt_de_DE.qm
152  if (qtTranslator.load(
153  "qt_" + lang_territory,
154  QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
155  QApplication::installTranslator(&qtTranslator);
156  }
157 
158  // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in
159  // bitcoin.qrc)
160  if (translatorBase.load(lang, ":/translations/")) {
161  QApplication::installTranslator(&translatorBase);
162  }
163 
164  // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in
165  // bitcoin.qrc)
166  if (translator.load(lang_territory, ":/translations/")) {
167  QApplication::installTranslator(&translator);
168  }
169 }
170 
171 /* qDebug() message handler --> debug.log */
172 void DebugMessageHandler(QtMsgType type, const QMessageLogContext &context,
173  const QString &msg) {
174  Q_UNUSED(context);
175  if (type == QtDebugMsg) {
176  LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
177  } else {
178  LogPrintf("GUI: %s\n", msg.toStdString());
179  }
180 }
181 
183 
184 void BitcoinABC::handleRunawayException(const std::exception *e) {
185  PrintExceptionContinue(e, "Runaway exception");
186  Q_EMIT runawayException(
187  QString::fromStdString(m_node.getWarnings().translated));
188 }
189 
190 void BitcoinABC::initialize(Config *config, RPCServer *rpcServer,
191  HTTPRPCRequestProcessor *httpRPCRequestProcessor) {
192  try {
193  util::ThreadRename("qt-init");
194  qDebug() << __func__ << ": Running initialization in thread";
196  bool rv = m_node.appInitMain(*config, *rpcServer,
197  *httpRPCRequestProcessor, &tip_info);
198  Q_EMIT initializeResult(rv, tip_info);
199  } catch (const std::exception &e) {
201  } catch (...) {
202  handleRunawayException(nullptr);
203  }
204 }
205 
207  try {
208  qDebug() << __func__ << ": Running Shutdown in thread";
210  qDebug() << __func__ << ": Shutdown finished";
211  Q_EMIT shutdownResult();
212  } catch (const std::exception &e) {
214  } catch (...) {
215  handleRunawayException(nullptr);
216  }
217 }
218 
219 static int qt_argc = 1;
220 static const char *qt_argv = "bitcoin-qt";
221 
223  : QApplication(qt_argc, const_cast<char **>(&qt_argv)), coreThread(nullptr),
224  optionsModel(nullptr), clientModel(nullptr), window(nullptr),
225  pollShutdownTimer(nullptr), returnValue(0), platformStyle(nullptr) {
226  // Qt runs setlocale(LC_ALL, "") on initialization.
228  setQuitOnLastWindowClosed(false);
229 }
230 
232  // UI per-platform customization
233  // This must be done inside the BitcoinApplication constructor, or after it,
234  // because PlatformStyle::instantiate requires a QApplication.
235  std::string platformName;
236  platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
237  platformStyle =
238  PlatformStyle::instantiate(QString::fromStdString(platformName));
239  // Fall back to "other" if specified name not found.
240  if (!platformStyle) {
242  }
244 }
245 
247  if (coreThread) {
248  qDebug() << __func__ << ": Stopping thread";
249  coreThread->quit();
250  coreThread->wait();
251  qDebug() << __func__ << ": Stopped thread";
252  }
253 
254  delete window;
255  window = nullptr;
256  delete platformStyle;
257  platformStyle = nullptr;
258 }
259 
260 #ifdef ENABLE_WALLET
261 void BitcoinApplication::createPaymentServer() {
262  paymentServer = new PaymentServer(this);
263 }
264 #endif
265 
266 void BitcoinApplication::createOptionsModel(bool resetSettings) {
267  optionsModel = new OptionsModel(this, resetSettings);
268 }
269 
271  const NetworkStyle *networkStyle) {
272  window =
273  new BitcoinGUI(node(), config, platformStyle, networkStyle, nullptr);
274 
275  pollShutdownTimer = new QTimer(window);
276  connect(pollShutdownTimer, &QTimer::timeout, window,
278 }
279 
281  assert(!m_splash);
282  m_splash = new SplashScreen(networkStyle);
283  // We don't hold a direct pointer to the splash screen after creation, but
284  // the splash screen will take care of deleting itself when finish()
285  // happens.
286  m_splash->show();
292  &QWidget::close);
293 }
294 
296  assert(!m_node);
297  m_node = &node;
298  if (optionsModel) {
300  }
301  if (m_splash) {
303  }
304 }
305 
307  return node().baseInitialize(config);
308 }
309 
311  if (coreThread) {
312  return;
313  }
314  coreThread = new QThread(this);
315  BitcoinABC *executor = new BitcoinABC(node());
316  executor->moveToThread(coreThread);
317 
318  /* communication to and from thread */
319  connect(executor, &BitcoinABC::initializeResult, this,
321  connect(executor, &BitcoinABC::shutdownResult, this,
323  connect(executor, &BitcoinABC::runawayException, this,
325 
326  // Note on how Qt works: it tries to directly invoke methods if the signal
327  // is emitted on the same thread that the target object 'lives' on.
328  // But if the target object 'lives' on another thread (executor here does)
329  // the SLOT will be invoked asynchronously at a later time in the thread
330  // of the target object. So.. we pass a pointer around. If you pass
331  // a reference around (even if it's non-const) you'll get Qt generating
332  // code to copy-construct the parameter in question (Q_DECLARE_METATYPE
333  // and qRegisterMetaType generate this code). For the Config class,
334  // which is noncopyable, we can't do this. So.. we have to pass
335  // pointers to Config around. Make sure Config &/Config * isn't a
336  // temporary (eg it lives somewhere aside from the stack) or this will
337  // crash because initialize() gets executed in another thread at some
338  // unspecified time (after) requestedInitialize() is emitted!
339  connect(this, &BitcoinApplication::requestedInitialize, executor,
341 
342  connect(this, &BitcoinApplication::requestedShutdown, executor,
344  /* make sure executor object is deleted in its own thread */
345  connect(coreThread, &QThread::finished, executor, &QObject::deleteLater);
346 
347  coreThread->start();
348 }
349 
351  // Default printtoconsole to false for the GUI. GUI programs should not
352  // print to the console unnecessarily.
353  gArgs.SoftSetBoolArg("-printtoconsole", false);
354 
357 }
358 
360  // If prune is set, intentionally override existing prune size with
361  // the default size since this is called when choosing a new datadir.
363 }
364 
366  Config &config, RPCServer &rpcServer,
367  HTTPRPCRequestProcessor &httpRPCRequestProcessor) {
368  qDebug() << __func__ << ": Requesting initialize";
369  startThread();
370  // IMPORTANT: config must NOT be a reference to a temporary because below
371  // signal may be connected to a slot that will be executed as a queued
372  // connection in another thread!
373  Q_EMIT requestedInitialize(&config, &rpcServer, &httpRPCRequestProcessor);
374 }
375 
377  // Show a simple window indicating shutdown status. Do this first as some of
378  // the steps may take some time below, for example the RPC console may still
379  // be executing a command.
381 
382  qDebug() << __func__ << ": Requesting shutdown";
383  startThread();
384  window->hide();
385  // Must disconnect node signals otherwise current thread can deadlock since
386  // no event loop is running.
388  // Request node shutdown, which can interrupt long operations, like
389  // rescanning a wallet.
390  node().startShutdown();
391  // Unsetting the client model can cause the current thread to wait for node
392  // to complete an operation, like wait for a RPC execution to complete.
393  window->setClientModel(nullptr);
394  pollShutdownTimer->stop();
395 
396  delete clientModel;
397  clientModel = nullptr;
398 
399  // Request shutdown from core thread
400  Q_EMIT requestedShutdown();
401 }
402 
404  bool success, interfaces::BlockAndHeaderTipInfo tip_info) {
405  qDebug() << __func__ << ": Initialization result: " << success;
406  returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE;
407  if (!success) {
408  // Make sure splash screen doesn't stick around during shutdown.
409  Q_EMIT splashFinished();
410  // Exit first main loop invocation.
411  quit();
412  return;
413  }
414  // Log this only after AppInitMain finishes, as then logging setup is
415  // guaranteed complete.
416  qInfo() << "Platform customization:" << platformStyle->getName();
418  window->setClientModel(clientModel, &tip_info);
419 #ifdef ENABLE_WALLET
421  m_wallet_controller =
423  window->setWalletController(m_wallet_controller);
424  if (paymentServer) {
425  paymentServer->setOptionsModel(optionsModel);
426 #ifdef ENABLE_BIP70
427  PaymentServer::LoadRootCAs();
428  connect(m_wallet_controller, &WalletController::coinsSent,
429  paymentServer, &PaymentServer::fetchPaymentACK);
430 #endif
431  }
432  }
433 #endif // ENABLE_WALLET
434 
435  // If -min option passed, start window minimized(iconified)
436  // or minimized to tray
437  if (!gArgs.GetBoolArg("-min", false)) {
438  window->show();
439  } else if (clientModel->getOptionsModel()->getMinimizeToTray() &&
440  window->hasTrayIcon()) {
441  // do nothing as the window is managed by the tray icon
442  } else {
443  window->showMinimized();
444  }
445  Q_EMIT splashFinished();
446  Q_EMIT windowShown(window);
447 
448 #ifdef ENABLE_WALLET
449  // Now that initialization/startup is done, process any command-line
450  // bitcoincash: URIs or payment requests:
451  if (paymentServer) {
452  connect(paymentServer, &PaymentServer::receivedPaymentRequest, window,
453  &BitcoinGUI::handlePaymentRequest);
454  connect(window, &BitcoinGUI::receivedURI, paymentServer,
456  connect(paymentServer, &PaymentServer::message,
457  [this](const QString &title, const QString &message,
458  unsigned int style) {
459  window->message(title, message, style);
460  });
461  QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady);
462  }
463 #endif
464 
465  pollShutdownTimer->start(200);
466 }
467 
469  // Exit second main loop invocation after shutdown finished.
470  quit();
471 }
472 
473 void BitcoinApplication::handleRunawayException(const QString &message) {
474  QMessageBox::critical(
475  nullptr, "Runaway exception",
476  BitcoinGUI::tr("A fatal error occurred. %1 can no longer continue "
477  "safely and will quit.")
478  .arg(PACKAGE_NAME) +
479  QString("<br><br>") + message);
480  ::exit(EXIT_FAILURE);
481 }
482 
484  if (!window) {
485  return 0;
486  }
487 
488  return window->winId();
489 }
490 
491 static void SetupUIArgs(ArgsManager &argsman) {
492 #if defined(ENABLE_WALLET) && defined(ENABLE_BIP70)
493  argsman.AddArg(
494  "-allowselfsignedrootcertificates",
495  strprintf("Allow self signed root certificates (default: %d)",
498 #endif
499  argsman.AddArg("-choosedatadir",
500  strprintf("Choose data directory on startup (default: %d)",
503  argsman.AddArg(
504  "-lang=<lang>",
505  "Set language, for example \"de_DE\" (default: system locale)",
507  argsman.AddArg("-min", "Start minimized", ArgsManager::ALLOW_ANY,
509  argsman.AddArg(
510  "-rootcertificates=<file>",
511  "Set SSL root certificates for payment request (default: -system-)",
513  argsman.AddArg("-splash",
514  strprintf("Show splash screen on startup (default: %d)",
517  argsman.AddArg("-resetguisettings", "Reset all settings changed in the GUI",
519  argsman.AddArg("-uiplatform",
520  strprintf("Select platform to customize UI for (one of "
521  "windows, macosx, other; default: %s)",
525 }
526 
527 int GuiMain(int argc, char *argv[]) {
528 #ifdef WIN32
529  util::WinCmdLineArgs winArgs;
530  std::tie(argc, argv) = winArgs.get();
531 #endif
534 
535  NodeContext node_context;
536  std::unique_ptr<interfaces::Node> node =
537  interfaces::MakeNode(&node_context);
538 
539  // Subscribe to global signals from core
540  boost::signals2::scoped_connection handler_message_box =
541  ::uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
542  boost::signals2::scoped_connection handler_question =
543  ::uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion);
544  boost::signals2::scoped_connection handler_init_message =
545  ::uiInterface.InitMessage_connect(noui_InitMessage);
546 
547  // Do not refer to data directory yet, this can be overridden by
548  // Intro::pickDataDirectory
549 
552  Q_INIT_RESOURCE(bitcoin);
553  Q_INIT_RESOURCE(bitcoin_locale);
554 
555  // Generate high-dpi pixmaps
556  QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
557  QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
558 
559  BitcoinApplication app;
560 
563  // Command-line options take precedence:
564  SetupServerArgs(node_context);
566  std::string error;
567  if (!gArgs.ParseParameters(argc, argv, error)) {
569  Untranslated("Error parsing command line arguments: %s\n"), error));
570  // Create a message box, because the gui has neither been created nor
571  // has subscribed to core signals
572  QMessageBox::critical(
573  nullptr, PACKAGE_NAME,
574  // message can not be translated because translations have not been
575  // initialized
576  QString::fromStdString("Error parsing command line arguments: %1.")
577  .arg(QString::fromStdString(error)));
578  return EXIT_FAILURE;
579  }
580 
581  // Now that the QApplication is setup and we have parsed our parameters, we
582  // can set the platform style
583  app.setupPlatformStyle();
584 
586  // must be set before OptionsModel is initialized or translations are
587  // loaded, as it is used to locate QSettings.
588  QApplication::setOrganizationName(QAPP_ORG_NAME);
589  QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
590  QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
591 
594  QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
595  initTranslations(qtTranslatorBase, qtTranslator, translatorBase,
596  translator);
597 
598  // Show help message immediately after parsing command-line options (for
599  // "-lang") and setting locale, but before showing splash screen.
600  if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
601  HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version"));
602  help.showOrPrint();
603  return EXIT_SUCCESS;
604  }
605 
606  // Install global event filter that makes sure that long tooltips can be
607  // word-wrapped
608  app.installEventFilter(
610 
613  bool did_show_intro = false;
614  // Intro dialog prune check box
615  bool prune = false;
616  // Gracefully exit if the user cancels
617  if (!Intro::showIfNeeded(did_show_intro, prune)) {
618  return EXIT_SUCCESS;
619  }
620 
624  if (!CheckDataDirOption()) {
626  Untranslated("Specified data directory \"%s\" does not exist.\n"),
627  gArgs.GetArg("-datadir", "")));
628  QMessageBox::critical(
629  nullptr, PACKAGE_NAME,
630  QObject::tr(
631  "Error: Specified data directory \"%1\" does not exist.")
632  .arg(QString::fromStdString(gArgs.GetArg("-datadir", ""))));
633  return EXIT_FAILURE;
634  }
635  if (!gArgs.ReadConfigFiles(error)) {
637  Untranslated("Error reading configuration file: %s\n"), error));
638  QMessageBox::critical(
639  nullptr, PACKAGE_NAME,
640  QObject::tr("Error: Cannot parse configuration file: %1.")
641  .arg(QString::fromStdString(error)));
642  return EXIT_FAILURE;
643  }
644 
646  // - Do not call Params() before this step.
647  // - Do this after parsing the configuration file, as the network can be
648  // switched there.
649  // - QSettings() will use the new application name after this, resulting in
650  // network-specific settings.
651  // - Needs to be done before createOptionsModel.
652 
653  // Check for -chain, -testnet or -regtest parameter (Params() calls are only
654  // valid after this clause)
655  try {
657  } catch (std::exception &e) {
658  InitError(Untranslated(strprintf("%s\n", e.what())));
659  QMessageBox::critical(nullptr, PACKAGE_NAME,
660  QObject::tr("Error: %1").arg(e.what()));
661  return EXIT_FAILURE;
662  }
663 #ifdef ENABLE_WALLET
664  // Parse URIs on command line -- this can affect Params()
666 #endif
667  if (!gArgs.InitSettings(error)) {
669  QMessageBox::critical(nullptr, PACKAGE_NAME,
670  QObject::tr("Error initializing settings: %1")
671  .arg(QString::fromStdString(error)));
672  return EXIT_FAILURE;
673  }
674 
675  QScopedPointer<const NetworkStyle> networkStyle(
676  NetworkStyle::instantiate(Params().NetworkIDString()));
677  assert(!networkStyle.isNull());
678  // Allow for separate UI settings for testnets
679  QApplication::setApplicationName(networkStyle->getAppName());
680  // Re-initialize translations after changing application name (language in
681  // network-specific settings can be different)
682  initTranslations(qtTranslatorBase, qtTranslator, translatorBase,
683  translator);
684 
685 #ifdef ENABLE_WALLET
687  // - Do this early as we don't want to bother initializing if we are just
688  // calling IPC
689  // - Do this *after* setting up the data directory, as the data directory
690  // hash is used in the name
691  // of the server.
692  // - Do this after creating app and setting up translations, so errors are
693  // translated properly.
695  exit(EXIT_SUCCESS);
696  }
697 
698  // Start up the payment server early, too, so impatient users that click on
699  // bitcoincash: links repeatedly have their payment requests routed to this
700  // process:
702  app.createPaymentServer();
703  }
704 #endif // ENABLE_WALLET
705 
707  // Install global event filter that makes sure that out-of-focus labels do
708  // not contain text cursor.
709  app.installEventFilter(new GUIUtil::LabelOutOfFocusEventFilter(&app));
710 #if defined(Q_OS_WIN)
711  // Install global event filter for processing Windows session related
712  // Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
713  qApp->installNativeEventFilter(new WinShutdownMonitor());
714 #endif
715  // Install qDebug() message handler to route to debug.log
716  qInstallMessageHandler(DebugMessageHandler);
717  // Allow parameter interaction before we create the options model
718  app.parameterSetup();
720  // Load GUI settings from QSettings
721  app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
722 
723  if (did_show_intro) {
724  // Store intro dialog settings other than datadir (network specific)
725  app.InitializePruneSetting(prune);
726  }
727 
728  // Get global config
729  Config &config = const_cast<Config &>(GetConfig());
730 
731  if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) &&
732  !gArgs.GetBoolArg("-min", false)) {
733  app.createSplashScreen(networkStyle.data());
734  }
735 
736  app.setNode(*node);
737 
738  RPCServer rpcServer;
739  std::any context{&node_context};
740  HTTPRPCRequestProcessor httpRPCRequestProcessor(config, rpcServer, context);
741 
742  try {
743  app.createWindow(&config, networkStyle.data());
744  // Perform base initialization before spinning up
745  // initialization/shutdown thread. This is acceptable because this
746  // function only contains steps that are quick to execute, so the GUI
747  // thread won't be held up.
748  if (!app.baseInitialize(config)) {
749  // A dialog with detailed error will have been shown by InitError()
750  return EXIT_FAILURE;
751  }
752  app.requestInitialize(config, rpcServer, httpRPCRequestProcessor);
753 #if defined(Q_OS_WIN)
754  WinShutdownMonitor::registerShutdownBlockReason(
755  QObject::tr("%1 didn't yet exit safely...").arg(PACKAGE_NAME),
756  (HWND)app.getMainWinId());
757 #endif
758  app.exec();
759  app.requestShutdown(config);
760  app.exec();
761  return app.getReturnValue();
762  } catch (const std::exception &e) {
763  PrintExceptionContinue(&e, "Runaway exception");
765  QString::fromStdString(app.node().getWarnings().translated));
766  } catch (...) {
767  PrintExceptionContinue(nullptr, "Runaway exception");
769  QString::fromStdString(app.node().getWarnings().translated));
770  }
771  return EXIT_FAILURE;
772 }
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:159
@ DEBUG_ONLY
Definition: system.h:160
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:494
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:322
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:490
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:603
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:698
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:1021
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:665
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:729
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1123
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:184
void shutdown()
Definition: bitcoin.cpp:206
void runawayException(const QString &message)
void shutdownResult()
BitcoinABC(interfaces::Node &node)
Definition: bitcoin.cpp:182
void initialize(Config *config, RPCServer *rpcServer, HTTPRPCRequestProcessor *httpRPCRequestProcessor)
Definition: bitcoin.cpp:190
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:306
void createSplashScreen(const NetworkStyle *networkStyle)
Create splash screen.
Definition: bitcoin.cpp:280
SplashScreen * m_splash
Definition: bitcoin.h:133
void windowShown(BitcoinGUI *window)
void initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info)
Definition: bitcoin.cpp:403
QThread * coreThread
Definition: bitcoin.h:121
void setNode(interfaces::Node &node)
Definition: bitcoin.cpp:295
QTimer * pollShutdownTimer
Definition: bitcoin.h:125
BitcoinGUI * window
Definition: bitcoin.h:124
void InitializePruneSetting(bool prune)
Initialize prune setting.
Definition: bitcoin.cpp:359
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:350
void handleRunawayException(const QString &message)
Handle runaway exceptions.
Definition: bitcoin.cpp:473
void createWindow(const Config *, const NetworkStyle *networkStyle)
Create main window.
Definition: bitcoin.cpp:270
OptionsModel * optionsModel
Definition: bitcoin.h:122
void createOptionsModel(bool resetSettings)
Create options model.
Definition: bitcoin.cpp:266
void requestInitialize(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Request core initialization.
Definition: bitcoin.cpp:365
void setupPlatformStyle()
Setup platform style.
Definition: bitcoin.cpp:231
void requestedInitialize(Config *config, RPCServer *rpcServer, HTTPRPCRequestProcessor *httpRPCRequestProcessor)
void shutdownResult()
Definition: bitcoin.cpp:468
std::unique_ptr< QWidget > shutdownWindow
Definition: bitcoin.h:132
void requestShutdown(Config &config)
Request core shutdown.
Definition: bitcoin.cpp:376
WId getMainWinId() const
Get window identifier of QMainWindow (BitcoinGUI)
Definition: bitcoin.cpp:483
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:39
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:58
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:129
SyncType
Definition: clientmodel.h:36
const Config & GetConfig()
Definition: config.cpp:34
static constexpr int DEFAULT_PRUNE_TARGET_GB
Definition: guiconstants.h:53
static const int TOOLTIP_WRAP_THRESHOLD
Definition: guiconstants.h:38
#define QAPP_ORG_NAME
Definition: guiconstants.h:43
static const bool DEFAULT_SPLASHSCREEN
Definition: guiconstants.h:19
#define QAPP_APP_NAME_DEFAULT
Definition: guiconstants.h:45
#define QAPP_ORG_DOMAIN
Definition: guiconstants.h:44
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1642
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:415
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1508
static const bool DEFAULT_CHOOSE_DATADIR
Definition: intro.h:12
#define LogPrint(category,...)
Definition: logging.h:210
#define LogPrintf(...)
Definition: logging.h:206
@ QT
Definition: logging.h:59
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:962
std::unique_ptr< Node > MakeNode(node::NodeContext *context)
Return implementation of Node interface.
Definition: interfaces.cpp:785
Definition: init.h:28
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
NodeContext & m_node
Definition: interfaces.cpp:778
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:76
static int qt_argc
Definition: bitcoin.cpp:219
static QString GetLangTerritory()
Definition: bitcoin.cpp:104
int GuiMain(int argc, char *argv[])
Definition: bitcoin.cpp:527
static void SetupUIArgs(ArgsManager &argsman)
Definition: bitcoin.cpp:491
static const char * qt_argv
Definition: bitcoin.cpp:220
static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
Set up translations.
Definition: bitcoin.cpp:122
void DebugMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
Definition: bitcoin.cpp:172
static RPCHelpMan help()
Definition: server.cpp:180
Definition: amount.h:19
std::string translated
Definition: translation.h:19
Block and header tip information.
Definition: node.h:49
NodeContext struct containing references to chain state and connection state.
Definition: context.h:38
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:841
bool CheckDataDirOption()
Definition: system.cpp:917
ArgsManager gArgs
Definition: system.cpp:80
void SetupEnvironment()
Definition: system.cpp:1398
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:886
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
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:113