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