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