Bitcoin ABC 0.32.12
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 <common/args.h>
9#include <common/init.h>
10#include <config.h>
11#include <httprpc.h>
12#include <init.h>
13#include <interfaces/handler.h>
14#include <interfaces/node.h>
15#include <node/context.h>
16#include <node/ui_interface.h>
17#include <noui.h>
18#include <qt/bitcoingui.h>
19#include <qt/clientmodel.h>
20#include <qt/guiconstants.h>
21#include <qt/guiutil.h>
22#include <qt/intro.h>
23#include <qt/networkstyle.h>
24#include <qt/optionsmodel.h>
25#include <qt/platformstyle.h>
26#include <qt/splashscreen.h>
27#include <qt/utilitydialog.h>
29#include <rpc/server.h>
30#include <uint256.h>
31#include <util/exception.h>
32#include <util/string.h>
33#include <util/threadnames.h>
34#include <util/translation.h>
35#include <validation.h>
36
37#ifdef ENABLE_WALLET
38#include <qt/paymentserver.h>
39#include <qt/walletcontroller.h>
40#include <qt/walletmodel.h>
41#endif // ENABLE_WALLET
42
43#include <QDebug>
44#include <QLibraryInfo>
45#include <QLocale>
46#include <QMessageBox>
47#include <QSettings>
48#include <QThread>
49#include <QTimer>
50#include <QTranslator>
51#include <QWindow>
52
53#include <boost/signals2/connection.hpp>
54
55#include <any>
56
57#if defined(QT_STATICPLUGIN)
58#include <QtPlugin>
59#if defined(QT_QPA_PLATFORM_XCB)
60Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
61#elif defined(QT_QPA_PLATFORM_WINDOWS)
62Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
63#elif defined(QT_QPA_PLATFORM_COCOA)
64Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
65Q_IMPORT_PLUGIN(QMacStylePlugin);
66#endif
67#endif
68
69// Declare meta types used for QMetaObject::invokeMethod
70Q_DECLARE_METATYPE(bool *)
71Q_DECLARE_METATYPE(Amount)
72Q_DECLARE_METATYPE(HTTPRPCRequestProcessor *)
73Q_DECLARE_METATYPE(RPCServer *)
74Q_DECLARE_METATYPE(SynchronizationState)
75Q_DECLARE_METATYPE(SyncType)
76Q_DECLARE_METATYPE(uint256)
77
78// Config is non-copyable so we can only register pointers to it
79Q_DECLARE_METATYPE(Config *)
80
82
84
85static void RegisterMetaTypes() {
86 // Register meta types used for QMetaObject::invokeMethod and
87 // Qt::QueuedConnection
88 qRegisterMetaType<bool *>();
89 qRegisterMetaType<SynchronizationState>();
90 qRegisterMetaType<SyncType>();
91#ifdef ENABLE_WALLET
92 qRegisterMetaType<WalletModel *>();
93#endif
94 qRegisterMetaType<Amount>();
95 // Register typedefs (see
96 // http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
97 qRegisterMetaType<size_t>("size_t");
98
99 qRegisterMetaType<std::function<void()>>("std::function<void()>");
100 qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon");
101 qRegisterMetaType<interfaces::BlockAndHeaderTipInfo>(
102 "interfaces::BlockAndHeaderTipInfo");
103
104 // Need to register any types Qt doesn't know about if you intend
105 // to use them with the signal/slot mechanism Qt provides. Even pointers.
106 // Note that class Config is noncopyable and so we can't register a
107 // non-pointer version of it with Qt, because Qt expects to be able to
108 // copy-construct non-pointers to objects for invoking slots
109 // behind-the-scenes in the 'Queued' connection case.
110 qRegisterMetaType<Config *>();
111 qRegisterMetaType<RPCServer *>();
112 qRegisterMetaType<HTTPRPCRequestProcessor *>();
113
114 // TODO: apply core-gui#623 if we ever backport core-gui#556
115}
116
117static QString GetLangTerritory() {
118 QSettings settings;
119 // Get desired locale (e.g. "de_DE")
120 // 1) System default language
121 QString lang_territory = QLocale::system().name();
122 // 2) Language from QSettings
123 QString lang_territory_qsettings =
124 settings.value("language", "").toString();
125 if (!lang_territory_qsettings.isEmpty()) {
126 lang_territory = lang_territory_qsettings;
127 }
128 // 3) -lang command line argument
129 lang_territory = QString::fromStdString(
130 gArgs.GetArg("-lang", lang_territory.toStdString()));
131 return lang_territory;
132}
133
135static void initTranslations(QTranslator &qtTranslatorBase,
136 QTranslator &qtTranslator,
137 QTranslator &translatorBase,
138 QTranslator &translator) {
139 // Remove old translators
140 QApplication::removeTranslator(&qtTranslatorBase);
141 QApplication::removeTranslator(&qtTranslator);
142 QApplication::removeTranslator(&translatorBase);
143 QApplication::removeTranslator(&translator);
144
145 // Get desired locale (e.g. "de_DE")
146 // 1) System default language
147 QString lang_territory = GetLangTerritory();
148
149 // Convert to "de" only by truncating "_DE"
150 QString lang = lang_territory;
151 lang.truncate(lang_territory.lastIndexOf('_'));
152
153 // Load language files for configured locale:
154 // - First load the translator for the base language, without territory
155 // - Then load the more specific locale translator
156
157#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
158 const QString translation_path{
159 QLibraryInfo::location(QLibraryInfo::TranslationsPath)};
160#else
161 const QString translation_path{
162 QLibraryInfo::path(QLibraryInfo::TranslationsPath)};
163#endif
164 // Load e.g. qt_de.qm
165 if (qtTranslatorBase.load("qt_" + lang, translation_path)) {
166 QApplication::installTranslator(&qtTranslatorBase);
167 }
168
169 // Load e.g. qt_de_DE.qm
170 if (qtTranslator.load("qt_" + lang_territory, translation_path)) {
171 QApplication::installTranslator(&qtTranslator);
172 }
173
174 // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in
175 // bitcoin.qrc)
176 if (translatorBase.load(lang, ":/translations/")) {
177 QApplication::installTranslator(&translatorBase);
178 }
179
180 // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in
181 // bitcoin.qrc)
182 if (translator.load(lang_territory, ":/translations/")) {
183 QApplication::installTranslator(&translator);
184 }
185}
186
187static bool ErrorSettingsRead(const bilingual_str &error,
188 const std::vector<std::string> &details) {
189 QMessageBox messagebox(
190 QMessageBox::Critical, PACKAGE_NAME,
191 QString::fromStdString(strprintf("%s.", error.translated)),
192 QMessageBox::Reset | QMessageBox::Abort);
193 // Explanatory text shown on startup when the settings file cannot
194 // be read. Prompts user to make a choice between resetting or aborting.
195 messagebox.setInformativeText(
196 QObject::tr("Do you want to reset settings to default values, or to "
197 "abort without making changes?"));
198 messagebox.setDetailedText(
199 QString::fromStdString(MakeUnorderedList(details)));
200 messagebox.setTextFormat(Qt::PlainText);
201 messagebox.setDefaultButton(QMessageBox::Reset);
202 switch (messagebox.exec()) {
203 case QMessageBox::Reset:
204 return false;
205 case QMessageBox::Abort:
206 return true;
207 default:
208 assert(false);
209 }
210}
211
212static void ErrorSettingsWrite(const bilingual_str &error,
213 const std::vector<std::string> &details) {
214 QMessageBox messagebox(
215 QMessageBox::Critical, PACKAGE_NAME,
216 QString::fromStdString(strprintf("%s.", error.translated)),
217 QMessageBox::Ok);
218 // Explanatory text shown on startup when the settings file could
219 // not be written. Prompts user to check that we have the ability to
220 // write to the file. Explains that the user has the option of running
221 // without a settings file.
222 messagebox.setInformativeText(
223 QObject::tr("A fatal error occurred. Check that settings file is "
224 "writable, or try running with -nosettings."));
225 messagebox.setDetailedText(
226 QString::fromStdString(MakeUnorderedList(details)));
227 messagebox.setTextFormat(Qt::PlainText);
228 messagebox.setDefaultButton(QMessageBox::Ok);
229 messagebox.exec();
230}
231
232/* qDebug() message handler --> debug.log */
233void DebugMessageHandler(QtMsgType type, const QMessageLogContext &context,
234 const QString &msg) {
235 Q_UNUSED(context);
236 if (type == QtDebugMsg) {
237 LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
238 } else {
239 LogPrintf("GUI: %s\n", msg.toStdString());
240 }
241}
242
244
245void BitcoinABC::handleRunawayException(const std::exception *e) {
246 PrintExceptionContinue(e, "Runaway exception");
247 Q_EMIT runawayException(
248 QString::fromStdString(m_node.getWarnings().translated));
249}
250
251void BitcoinABC::initialize(Config *config, RPCServer *rpcServer,
252 HTTPRPCRequestProcessor *httpRPCRequestProcessor) {
253 try {
254 util::ThreadRename("qt-init");
255 qDebug() << __func__ << ": Running initialization in thread";
257 bool rv = m_node.appInitMain(*config, *rpcServer,
258 *httpRPCRequestProcessor, &tip_info);
259 Q_EMIT initializeResult(rv, tip_info);
260 } catch (const std::exception &e) {
262 } catch (...) {
263 handleRunawayException(nullptr);
264 }
265}
266
268 try {
269 qDebug() << __func__ << ": Running Shutdown in thread";
271 qDebug() << __func__ << ": Shutdown finished";
272 Q_EMIT shutdownResult();
273 } catch (const std::exception &e) {
275 } catch (...) {
276 handleRunawayException(nullptr);
277 }
278}
279
280static int qt_argc = 1;
281static const char *qt_argv = "bitcoin-qt";
282
284 : QApplication(qt_argc, const_cast<char **>(&qt_argv)), coreThread(nullptr),
285 optionsModel(nullptr), clientModel(nullptr), window(nullptr),
286 pollShutdownTimer(nullptr), platformStyle(nullptr) {
287 // Qt runs setlocale(LC_ALL, "") on initialization.
289 setQuitOnLastWindowClosed(false);
290}
291
293 // UI per-platform customization
294 // This must be done inside the BitcoinApplication constructor, or after it,
295 // because PlatformStyle::instantiate requires a QApplication.
296 std::string platformName;
297 platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
299 PlatformStyle::instantiate(QString::fromStdString(platformName));
300 // Fall back to "other" if specified name not found.
301 if (!platformStyle) {
303 }
305}
306
308 if (coreThread) {
309 qDebug() << __func__ << ": Stopping thread";
310 coreThread->quit();
311 coreThread->wait();
312 qDebug() << __func__ << ": Stopped thread";
313 }
314
315 delete window;
316 window = nullptr;
317 delete platformStyle;
318 platformStyle = nullptr;
319}
320
321#ifdef ENABLE_WALLET
322void BitcoinApplication::createPaymentServer() {
323 paymentServer = new PaymentServer(this);
324}
325#endif
326
328 optionsModel = new OptionsModel(this, resetSettings);
329}
330
332 const NetworkStyle *networkStyle) {
333 window =
334 new BitcoinGUI(node(), config, platformStyle, networkStyle, nullptr);
335 connect(window, &BitcoinGUI::quitRequested, this,
337
338 pollShutdownTimer = new QTimer(window);
339 connect(pollShutdownTimer, &QTimer::timeout, [this] {
340 if (!QApplication::activeModalWidget()) {
342 }
343 });
344}
345
348 m_splash = new SplashScreen(networkStyle);
349 // We don't hold a direct pointer to the splash screen after creation, but
350 // the splash screen will take care of deleting itself when finish()
351 // happens.
352 m_splash->show();
358 &QWidget::close);
359}
360
362 assert(!m_node);
363 m_node = &node;
364 if (optionsModel) {
366 }
367 if (m_splash) {
369 }
370}
371
373 return node().baseInitialize(config);
374}
375
377 if (coreThread) {
378 return;
379 }
380 coreThread = new QThread(this);
381 BitcoinABC *executor = new BitcoinABC(node());
382 executor->moveToThread(coreThread);
383
384 /* communication to and from thread */
385 connect(executor, &BitcoinABC::initializeResult, this,
387 connect(executor, &BitcoinABC::shutdownResult, this,
388 [] { QCoreApplication::exit(0); });
389 connect(executor, &BitcoinABC::runawayException, this,
391
392 // Note on how Qt works: it tries to directly invoke methods if the signal
393 // is emitted on the same thread that the target object 'lives' on.
394 // But if the target object 'lives' on another thread (executor here does)
395 // the SLOT will be invoked asynchronously at a later time in the thread
396 // of the target object. So.. we pass a pointer around. If you pass
397 // a reference around (even if it's non-const) you'll get Qt generating
398 // code to copy-construct the parameter in question (Q_DECLARE_METATYPE
399 // and qRegisterMetaType generate this code). For the Config class,
400 // which is noncopyable, we can't do this. So.. we have to pass
401 // pointers to Config around. Make sure Config &/Config * isn't a
402 // temporary (eg it lives somewhere aside from the stack) or this will
403 // crash because initialize() gets executed in another thread at some
404 // unspecified time (after) requestedInitialize() is emitted!
405 connect(this, &BitcoinApplication::requestedInitialize, executor,
407
408 connect(this, &BitcoinApplication::requestedShutdown, executor,
410 /* make sure executor object is deleted in its own thread */
411 connect(coreThread, &QThread::finished, executor, &QObject::deleteLater);
412
413 coreThread->start();
414}
415
417 // Default printtoconsole to false for the GUI. GUI programs should not
418 // print to the console unnecessarily.
419 gArgs.SoftSetBoolArg("-printtoconsole", false);
420
423}
424
426 // If prune is set, intentionally override existing prune size with
427 // the default size since this is called when choosing a new datadir.
429}
430
432 Config &config, RPCServer &rpcServer,
433 HTTPRPCRequestProcessor &httpRPCRequestProcessor) {
434 qDebug() << __func__ << ": Requesting initialize";
435 startThread();
436 // IMPORTANT: config must NOT be a reference to a temporary because below
437 // signal may be connected to a slot that will be executed as a queued
438 // connection in another thread!
439 Q_EMIT requestedInitialize(&config, &rpcServer, &httpRPCRequestProcessor);
440}
441
443 for (const auto w : QGuiApplication::topLevelWindows()) {
444 w->hide();
445 }
446
447 // Show a simple window indicating shutdown status. Do this first as some of
448 // the steps may take some time below, for example the RPC console may still
449 // be executing a command.
451
452 qDebug() << __func__ << ": Requesting shutdown";
453 startThread();
454
455 // Must disconnect node signals otherwise current thread can deadlock since
456 // no event loop is running.
458 // Request node shutdown, which can interrupt long operations, like
459 // rescanning a wallet.
461 // Prior to unsetting the client model, stop listening backend signals
462 if (clientModel) {
463 clientModel->stop();
464 }
465
466 // Unsetting the client model can cause the current thread to wait for node
467 // to complete an operation, like wait for a RPC execution to complete.
468 window->setClientModel(nullptr);
469 pollShutdownTimer->stop();
470
471#ifdef ENABLE_WALLET
472 // Delete wallet controller here manually, instead of relying on Qt object
473 // tracking (https://doc.qt.io/qt-5/objecttrees.html). This makes sure
474 // walletmodel m_handle_* notification handlers are deleted before wallets
475 // are unloaded, which can simplify wallet implementations. It also avoids
476 // these notifications having to be handled while GUI objects are being
477 // destroyed, making GUI code less fragile as well.
478 delete m_wallet_controller;
479 m_wallet_controller = nullptr;
480#endif // ENABLE_WALLET
481
482 delete clientModel;
483 clientModel = nullptr;
484
485 // Request shutdown from core thread
486 Q_EMIT requestedShutdown();
487}
488
490 bool success, interfaces::BlockAndHeaderTipInfo tip_info) {
491 qDebug() << __func__ << ": Initialization result: " << success;
492 if (!success) {
493 // Make sure splash screen doesn't stick around during shutdown.
494 Q_EMIT splashFinished();
496 return;
497 }
498 // Log this only after AppInitMain finishes, as then logging setup is
499 // guaranteed complete.
500 qInfo() << "Platform customization:" << platformStyle->getName();
502 window->setClientModel(clientModel, &tip_info);
503#ifdef ENABLE_WALLET
505 m_wallet_controller =
507 window->setWalletController(m_wallet_controller);
508 if (paymentServer) {
509 paymentServer->setOptionsModel(optionsModel);
510#ifdef ENABLE_BIP70
511 PaymentServer::LoadRootCAs();
512 connect(m_wallet_controller, &WalletController::coinsSent,
513 paymentServer, &PaymentServer::fetchPaymentACK);
514#endif
515 }
516 }
517#endif // ENABLE_WALLET
518
519 // If -min option passed, start window minimized(iconified)
520 // or minimized to tray
521 if (!gArgs.GetBoolArg("-min", false)) {
522 window->show();
524 window->hasTrayIcon()) {
525 // do nothing as the window is managed by the tray icon
526 } else {
527 window->showMinimized();
528 }
529 Q_EMIT splashFinished();
530 Q_EMIT windowShown(window);
531
532#ifdef ENABLE_WALLET
533 // Now that initialization/startup is done, process any command-line
534 // bitcoincash: URIs or payment requests:
535 if (paymentServer) {
536 connect(paymentServer, &PaymentServer::receivedPaymentRequest, window,
537 &BitcoinGUI::handlePaymentRequest);
538 connect(window, &BitcoinGUI::receivedURI, paymentServer,
540 connect(paymentServer, &PaymentServer::message,
541 [this](const QString &title, const QString &message,
542 unsigned int style) {
543 window->message(title, message, style);
544 });
545 QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady);
546 }
547#endif
548
549 pollShutdownTimer->start(200);
550}
551
552void BitcoinApplication::handleRunawayException(const QString &message) {
553 QMessageBox::critical(
554 nullptr, "Runaway exception",
555 BitcoinGUI::tr("A fatal error occurred. %1 can no longer continue "
556 "safely and will quit.")
557 .arg(PACKAGE_NAME) +
558 QString("<br><br>") + message);
559 ::exit(EXIT_FAILURE);
560}
561
563 if (!window) {
564 return 0;
565 }
566
567 return window->winId();
568}
569
571 if (e->type() == QEvent::Quit) {
573 return true;
574 }
575
576 return QApplication::event(e);
577}
578
579static void SetupUIArgs(ArgsManager &argsman) {
580#if defined(ENABLE_WALLET) && defined(ENABLE_BIP70)
581 argsman.AddArg(
582 "-allowselfsignedrootcertificates",
583 strprintf("Allow self signed root certificates (default: %d)",
586#endif
587 argsman.AddArg("-choosedatadir",
588 strprintf("Choose data directory on startup (default: %d)",
591 argsman.AddArg(
592 "-lang=<lang>",
593 "Set language, for example \"de_DE\" (default: system locale)",
595 argsman.AddArg("-min", "Start minimized", ArgsManager::ALLOW_ANY,
597 argsman.AddArg(
598 "-rootcertificates=<file>",
599 "Set SSL root certificates for payment request (default: -system-)",
601 argsman.AddArg("-splash",
602 strprintf("Show splash screen on startup (default: %d)",
605 argsman.AddArg("-resetguisettings", "Reset all settings changed in the GUI",
607 argsman.AddArg("-uiplatform",
608 strprintf("Select platform to customize UI for (one of "
609 "windows, macosx, other; default: %s)",
613}
614
615int GuiMain(int argc, char *argv[]) {
616#ifdef WIN32
617 common::WinCmdLineArgs winArgs;
618 std::tie(argc, argv) = winArgs.get();
619#endif
622
623 NodeContext node_context;
624 std::unique_ptr<interfaces::Node> node =
625 interfaces::MakeNode(&node_context);
626
627 // Subscribe to global signals from core
628 boost::signals2::scoped_connection handler_message_box =
629 ::uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
630 boost::signals2::scoped_connection handler_question =
631 ::uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion);
632 boost::signals2::scoped_connection handler_init_message =
633 ::uiInterface.InitMessage_connect(noui_InitMessage);
634
635 // Do not refer to data directory yet, this can be overridden by
636 // Intro::pickDataDirectory
637
640 Q_INIT_RESOURCE(bitcoin);
641 Q_INIT_RESOURCE(bitcoin_locale);
642
643#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
644 // Generate high-dpi pixmaps
645 QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
646 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
647#endif
648
650
653 // Command-line options take precedence:
654 SetupServerArgs(node_context);
656 std::string error;
657 if (!gArgs.ParseParameters(argc, argv, error)) {
659 Untranslated("Error parsing command line arguments: %s"), error));
660 // Create a message box, because the gui has neither been created nor
661 // has subscribed to core signals
662 QMessageBox::critical(
663 nullptr, PACKAGE_NAME,
664 // message can not be translated because translations have not been
665 // initialized
666 QString::fromStdString("Error parsing command line arguments: %1.")
667 .arg(QString::fromStdString(error)));
668 return EXIT_FAILURE;
669 }
670
671 // Now that the QApplication is setup and we have parsed our parameters, we
672 // can set the platform style
673 app.setupPlatformStyle();
674
676 // must be set before OptionsModel is initialized or translations are
677 // loaded, as it is used to locate QSettings.
678 QApplication::setOrganizationName(QAPP_ORG_NAME);
679 QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
680 QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
681
684 QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
685 initTranslations(qtTranslatorBase, qtTranslator, translatorBase,
686 translator);
687
688 // Show help message immediately after parsing command-line options (for
689 // "-lang") and setting locale, but before showing splash screen.
690 if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
691 HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version"));
692 help.showOrPrint();
693 return EXIT_SUCCESS;
694 }
695
696 // Install global event filter that makes sure that long tooltips can be
697 // word-wrapped
698 app.installEventFilter(
700
703 bool did_show_intro = false;
704 // Intro dialog prune check box
705 bool prune = false;
706 // Gracefully exit if the user cancels
707 if (!Intro::showIfNeeded(did_show_intro, prune)) {
708 return EXIT_SUCCESS;
709 }
710
713 // - Do not call gArgs.GetDataDirNet() before this step finishes
714 // - Do not call Params() before this step
715 // - QSettings() will use the new application name after this, resulting in
716 // network-specific settings
717 // - Needs to be done before createOptionsModel
718 if (auto err = common::InitConfig(gArgs, ErrorSettingsRead)) {
719 InitError(err->message, err->details);
720 if (err->status == common::ConfigStatus::FAILED_WRITE) {
721 // Show a custom error message to provide more information in the
722 // case of a datadir write error.
723 ErrorSettingsWrite(err->message, err->details);
724 } else if (err->status != common::ConfigStatus::ABORTED) {
725 // Show a generic message in other cases, and no additional error
726 // message in the case of a read error if the user decided to abort.
727 QMessageBox::critical(
728 nullptr, PACKAGE_NAME,
729 QObject::tr("Error: %1")
730 .arg(QString::fromStdString(err->message.translated)));
731 }
732 return EXIT_FAILURE;
733 }
734#ifdef ENABLE_WALLET
735 // Parse URIs on command line -- this can affect Params()
737#endif
738
739 QScopedPointer<const NetworkStyle> networkStyle(
740 NetworkStyle::instantiate(Params().GetChainType()));
741 assert(!networkStyle.isNull());
742 // Allow for separate UI settings for testnets
743 QApplication::setApplicationName(networkStyle->getAppName());
744 // Re-initialize translations after changing application name (language in
745 // network-specific settings can be different)
746 initTranslations(qtTranslatorBase, qtTranslator, translatorBase,
747 translator);
748
749#ifdef ENABLE_WALLET
751 // - Do this early as we don't want to bother initializing if we are just
752 // calling IPC
753 // - Do this *after* setting up the data directory, as the data directory
754 // hash is used in the name
755 // of the server.
756 // - Do this after creating app and setting up translations, so errors are
757 // translated properly.
759 exit(EXIT_SUCCESS);
760 }
761
762 // Start up the payment server early, too, so impatient users that click on
763 // bitcoincash: links repeatedly have their payment requests routed to this
764 // process:
766 app.createPaymentServer();
767 }
768#endif // ENABLE_WALLET
769
771 // Install global event filter that makes sure that out-of-focus labels do
772 // not contain text cursor.
773 app.installEventFilter(new GUIUtil::LabelOutOfFocusEventFilter(&app));
774#if defined(Q_OS_WIN)
775 // Install global event filter for processing Windows session related
776 // Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
777 qApp->installNativeEventFilter(new WinShutdownMonitor());
778#endif
779 // Install qDebug() message handler to route to debug.log
780 qInstallMessageHandler(DebugMessageHandler);
781 // Allow parameter interaction before we create the options model
782 app.parameterSetup();
784 // Load GUI settings from QSettings
785 app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
786
787 if (did_show_intro) {
788 // Store intro dialog settings other than datadir (network specific)
789 app.InitializePruneSetting(prune);
790 }
791
792 // Get global config
793 Config &config = const_cast<Config &>(GetConfig());
794
795 if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) &&
796 !gArgs.GetBoolArg("-min", false)) {
797 app.createSplashScreen(networkStyle.data());
798 }
799
800 app.setNode(*node);
801
802 RPCServer rpcServer;
803 std::any context{&node_context};
804 HTTPRPCRequestProcessor httpRPCRequestProcessor(config, rpcServer, context);
805
806 try {
807 app.createWindow(config, networkStyle.data());
808 // Perform base initialization before spinning up
809 // initialization/shutdown thread. This is acceptable because this
810 // function only contains steps that are quick to execute, so the GUI
811 // thread won't be held up.
812 if (!app.baseInitialize(config)) {
813 // A dialog with detailed error will have been shown by InitError()
814 return EXIT_FAILURE;
815 }
816 app.requestInitialize(config, rpcServer, httpRPCRequestProcessor);
817#if defined(Q_OS_WIN)
818 WinShutdownMonitor::registerShutdownBlockReason(
819 QObject::tr("%1 didn't yet exit safely...").arg(PACKAGE_NAME),
820 (HWND)app.getMainWinId());
821#endif
822 app.exec();
823 } catch (const std::exception &e) {
824 PrintExceptionContinue(&e, "Runaway exception");
826 QString::fromStdString(app.node().getWarnings().translated));
827 } catch (...) {
828 PrintExceptionContinue(nullptr, "Runaway exception");
830 QString::fromStdString(app.node().getWarnings().translated));
831 }
832 return app.node().getExitStatus();
833}
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:700
ArgsManager gArgs
Definition: args.cpp:39
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
@ ALLOW_ANY
disable validation
Definition: args.h:114
@ DEBUG_ONLY
Definition: args.h:128
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:210
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:371
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:462
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: args.cpp:557
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:524
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:588
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:245
void shutdown()
Definition: bitcoin.cpp:267
void runawayException(const QString &message)
void shutdownResult()
BitcoinABC(interfaces::Node &node)
Definition: bitcoin.cpp:243
void initialize(Config *config, RPCServer *rpcServer, HTTPRPCRequestProcessor *httpRPCRequestProcessor)
Definition: bitcoin.cpp:251
Main Bitcoin application object.
Definition: bitcoin.h:60
void createWindow(const Config &, const NetworkStyle *networkStyle)
Create main window.
Definition: bitcoin.cpp:331
ClientModel * clientModel
Definition: bitcoin.h:122
bool baseInitialize(Config &config)
Basic initialization, before starting initialization/shutdown thread.
Definition: bitcoin.cpp:372
void createSplashScreen(const NetworkStyle *networkStyle)
Create splash screen.
Definition: bitcoin.cpp:346
void requestShutdown()
Request core shutdown.
Definition: bitcoin.cpp:442
SplashScreen * m_splash
Definition: bitcoin.h:131
void windowShown(BitcoinGUI *window)
void initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info)
Definition: bitcoin.cpp:489
QThread * coreThread
Definition: bitcoin.h:120
void setNode(interfaces::Node &node)
Definition: bitcoin.cpp:361
interfaces::Node & node() const
Definition: bitcoin.h:94
QTimer * pollShutdownTimer
Definition: bitcoin.h:124
BitcoinGUI * window
Definition: bitcoin.h:123
void InitializePruneSetting(bool prune)
Initialize prune setting.
Definition: bitcoin.cpp:425
interfaces::Node * m_node
Definition: bitcoin.h:132
const PlatformStyle * platformStyle
Definition: bitcoin.h:129
void parameterSetup()
parameter interaction/setup based on rules
Definition: bitcoin.cpp:416
void handleRunawayException(const QString &message)
Handle runaway exceptions.
Definition: bitcoin.cpp:552
OptionsModel * optionsModel
Definition: bitcoin.h:121
bool event(QEvent *e) override
Definition: bitcoin.cpp:570
void createOptionsModel(bool resetSettings)
Create options model.
Definition: bitcoin.cpp:327
void requestInitialize(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Request core initialization.
Definition: bitcoin.cpp:431
void setupPlatformStyle()
Setup platform style.
Definition: bitcoin.cpp:292
void requestedInitialize(Config *config, RPCServer *rpcServer, HTTPRPCRequestProcessor *httpRPCRequestProcessor)
std::unique_ptr< QWidget > shutdownWindow
Definition: bitcoin.h:130
WId getMainWinId() const
Get window identifier of QMainWindow (BitcoinGUI)
Definition: bitcoin.cpp:562
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:637
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.
void quitRequested()
Model for Bitcoin network client.
Definition: clientmodel.h:43
OptionsModel * getOptionsModel()
Definition: config.h:19
Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and resets their ‘textInt...
Definition: guiutil.h:218
Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text repre...
Definition: guiutil.h:198
"Help message" dialog box
Definition: utilitydialog.h:20
static bool showIfNeeded(bool &did_show_intro, bool &prune)
Determine data directory.
Definition: intro.cpp:180
static const NetworkStyle * instantiate(const ChainType 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:40
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:59
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 int getExitStatus()=0
Get exit status.
virtual bool baseInitialize(Config &config)=0
Initialize app dependencies.
256-bit opaque blob.
Definition: uint256.h:129
SyncType
Definition: clientmodel.h:40
const Config & GetConfig()
Definition: config.cpp:40
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: exception.cpp:38
static constexpr int DEFAULT_PRUNE_TARGET_GB
Definition: guiconstants.h:56
static const int TOOLTIP_WRAP_THRESHOLD
Definition: guiconstants.h:41
#define QAPP_ORG_NAME
Definition: guiconstants.h:46
static const bool DEFAULT_SPLASHSCREEN
Definition: guiconstants.h:22
#define QAPP_APP_NAME_DEFAULT
Definition: guiconstants.h:48
#define QAPP_ORG_DOMAIN
Definition: guiconstants.h:47
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1779
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:433
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1645
static const bool DEFAULT_CHOOSE_DATADIR
Definition: intro.h:12
#define LogPrint(category,...)
Definition: logging.h:452
#define LogPrintf(...)
Definition: logging.h:424
@ QT
Definition: logging.h:88
void LogQtInfo()
Writes to debug.log short info about the used Qt and the host system.
Definition: guiutil.cpp:970
std::optional< ConfigError > InitConfig(ArgsManager &args, SettingsAbortFn settings_abort_fn)
Read config files, and create datadir and settings.json if they don't exist.
Definition: init.cpp:19
@ ABORTED
Aborted by user.
@ FAILED_WRITE
Failed to write settings.json.
std::unique_ptr< Node > MakeNode(node::NodeContext *context)
Return implementation of Node interface.
Definition: interfaces.cpp:830
Definition: messages.h:12
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:53
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
Definition: string.h:132
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:823
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 bool ErrorSettingsRead(const bilingual_str &error, const std::vector< std::string > &details)
Definition: bitcoin.cpp:187
static void RegisterMetaTypes()
Definition: bitcoin.cpp:85
static int qt_argc
Definition: bitcoin.cpp:280
static QString GetLangTerritory()
Definition: bitcoin.cpp:117
int GuiMain(int argc, char *argv[])
Definition: bitcoin.cpp:615
static void ErrorSettingsWrite(const bilingual_str &error, const std::vector< std::string > &details)
Definition: bitcoin.cpp:212
static void SetupUIArgs(ArgsManager &argsman)
Definition: bitcoin.cpp:579
static const char * qt_argv
Definition: bitcoin.cpp:281
static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
Set up translations.
Definition: bitcoin.cpp:135
void DebugMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
Definition: bitcoin.cpp:233
static RPCHelpMan help()
Definition: server.cpp:185
Definition: amount.h:21
Bilingual messages:
Definition: translation.h:17
std::string translated
Definition: translation.h:19
Block and header tip information.
Definition: node.h:50
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
void SetupEnvironment()
Definition: system.cpp:73
#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:118