1 // Copyright (c) 2011-2020 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 #if defined(HAVE_CONFIG_H)
6 #include <config/bitcoin-config.h>
7 #endif
8 
9 #include <qt/bitcoin.h>
10 #include <qt/bitcoingui.h>
11 
12 #include <chainparams.h>
13 #include <qt/clientmodel.h>
14 #include <qt/guiconstants.h>
15 #include <qt/guiutil.h>
16 #include <qt/intro.h>
17 #include <qt/networkstyle.h>
18 #include <qt/optionsmodel.h>
19 #include <qt/platformstyle.h>
20 #include <qt/splashscreen.h>
21 #include <qt/utilitydialog.h>
22 #include <qt/winshutdownmonitor.h>
23 #include <qt/styleSheet.h>
24 
25 #ifdef ENABLE_WALLET
26 #include <qt/paymentserver.h>
27 #include <qt/walletcontroller.h>
28 #include <qt/walletmodel.h>
29 #include <wallet/walletutil.h>
30 #endif // ENABLE_WALLET
31 
32 #include <interfaces/handler.h>
33 #include <interfaces/node.h>
34 #include <noui.h>
35 #include <init.h>
36 #include <ui_interface.h>
37 #include <uint256.h>
38 #include <util/system.h>
39 #include <util/threadnames.h>
40 #include <validation.h>
41 
42 #include <memory>
43 
44 #include <QApplication>
45 #include <QDebug>
46 #include <QLibraryInfo>
47 #include <QLocale>
48 #include <QMessageBox>
49 #include <QSettings>
50 #include <QThread>
51 #include <QTimer>
52 #include <QTranslator>
53 #include <QFile>
54 #include <QProcess>
55 #include <QFileInfo>
56 
57 #if defined(QT_STATICPLUGIN)
58 #include <QtPlugin>
59 #if defined(QT_QPA_PLATFORM_XCB)
60 Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
61 #elif defined(QT_QPA_PLATFORM_WINDOWS)
62 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
63 #elif defined(QT_QPA_PLATFORM_COCOA)
64 Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
65 #endif
66 #endif
67 
68 // Declare meta types used for QMetaObject::invokeMethod
69 Q_DECLARE_METATYPE(bool*)
Q_DECLARE_METATYPE(CAmount)70 Q_DECLARE_METATYPE(CAmount)
71 Q_DECLARE_METATYPE(uint256)
72 
73 static QString GetLangTerritory()
74 {
75     QSettings settings;
76     // Get desired locale (e.g. "de_DE")
77     // 1) System default language
78     QString lang_territory = QLocale::system().name();
79     // 2) Language from QSettings
80     QString lang_territory_qsettings = settings.value("language", "").toString();
81     if(!lang_territory_qsettings.isEmpty())
82         lang_territory = lang_territory_qsettings;
83     // 3) -lang command line argument
84     lang_territory = QString::fromStdString(gArgs.GetArg("-lang", lang_territory.toStdString()));
85     return lang_territory;
86 }
87 
88 /** Set up translations */
initTranslations(QTranslator & qtTranslatorBase,QTranslator & qtTranslator,QTranslator & translatorBase,QTranslator & translator)89 static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
90 {
91     // Remove old translators
92     QApplication::removeTranslator(&qtTranslatorBase);
93     QApplication::removeTranslator(&qtTranslator);
94     QApplication::removeTranslator(&translatorBase);
95     QApplication::removeTranslator(&translator);
96 
97     // Get desired locale (e.g. "de_DE")
98     // 1) System default language
99     QString lang_territory = GetLangTerritory();
100 
101     // Convert to "de" only by truncating "_DE"
102     QString lang = lang_territory;
103     lang.truncate(lang_territory.lastIndexOf('_'));
104 
105     // Load language files for configured locale:
106     // - First load the translator for the base language, without territory
107     // - Then load the more specific locale translator
108 
109     // Load e.g. qt_de.qm
110     if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
111         QApplication::installTranslator(&qtTranslatorBase);
112 
113     // Load e.g. qt_de_DE.qm
114     if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
115         QApplication::installTranslator(&qtTranslator);
116 
117     // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
118     if (translatorBase.load(lang, ":/translations/"))
119         QApplication::installTranslator(&translatorBase);
120 
121     // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
122     if (translator.load(lang_territory, ":/translations/"))
123         QApplication::installTranslator(&translator);
124 }
125 
126 /* qDebug() message handler --> debug.log */
DebugMessageHandler(QtMsgType type,const QMessageLogContext & context,const QString & msg)127 void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
128 {
129     Q_UNUSED(context);
130     if (type == QtDebugMsg) {
131         LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
132     } else {
133         LogPrintf("GUI: %s\n", msg.toStdString());
134     }
135 }
136 
removeParam(QStringList & list,const QString & param,bool startWith)137 void removeParam(QStringList& list, const QString& param, bool startWith)
138 {
139     for(int index = 0; index < list.size();)
140     {
141         QString item = list[index];
142         bool remove = false;
143         if(startWith)
144         {
145             remove = item.startsWith(param);
146         }
147         else
148         {
149             remove = item == param;
150         }
151 
152         if(remove)
153         {
154             list.removeAt(index);
155         }
156         else
157         {
158             index++;
159         }
160     }
161 }
162 
BitcoinCore(interfaces::Node & node)163 BitcoinCore::BitcoinCore(interfaces::Node& node) :
164     QObject(), m_node(node)
165 {
166 }
167 
handleRunawayException(const std::exception * e)168 void BitcoinCore::handleRunawayException(const std::exception *e)
169 {
170     PrintExceptionContinue(e, "Runaway exception");
171     Q_EMIT runawayException(QString::fromStdString(m_node.getWarnings()));
172 }
173 
initialize()174 void BitcoinCore::initialize()
175 {
176     try
177     {
178         qDebug() << __func__ << ": Running initialization in thread";
179         util::ThreadRename("qt-init");
180         bool rv = m_node.appInitMain();
181         Q_EMIT initializeResult(rv);
182     } catch (const std::exception& e) {
183         handleRunawayException(&e);
184     } catch (...) {
185         handleRunawayException(nullptr);
186     }
187 }
188 
shutdown()189 void BitcoinCore::shutdown()
190 {
191     try
192     {
193         qDebug() << __func__ << ": Running Shutdown in thread";
194         m_node.appShutdown();
195         qDebug() << __func__ << ": Shutdown finished";
196         Q_EMIT shutdownResult();
197     } catch (const std::exception& e) {
198         handleRunawayException(&e);
199     } catch (...) {
200         handleRunawayException(nullptr);
201     }
202 }
203 
204 static int qt_argc = 1;
205 static const char* qt_argv = "qtum-qt";
206 
BitcoinApplication(interfaces::Node & node)207 BitcoinApplication::BitcoinApplication(interfaces::Node& node):
208     QApplication(qt_argc, const_cast<char **>(&qt_argv)),
209     coreThread(nullptr),
210     m_node(node),
211     optionsModel(nullptr),
212     clientModel(nullptr),
213     window(nullptr),
214     pollShutdownTimer(nullptr),
215     returnValue(0),
216     platformStyle(nullptr),
217     restartApp(false)
218 {
219     setQuitOnLastWindowClosed(false);
220 }
221 
setupPlatformStyle()222 void BitcoinApplication::setupPlatformStyle()
223 {
224     // UI per-platform customization
225     // This must be done inside the BitcoinApplication constructor, or after it, because
226     // PlatformStyle::instantiate requires a QApplication
227     std::string platformName;
228     platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
229     platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName));
230     if (!platformStyle) // Fall back to "other" if specified name not found
231         platformStyle = PlatformStyle::instantiate("other");
232     assert(platformStyle);
233 }
234 
~BitcoinApplication()235 BitcoinApplication::~BitcoinApplication()
236 {
237     if(coreThread)
238     {
239         qDebug() << __func__ << ": Stopping thread";
240         coreThread->quit();
241         coreThread->wait();
242         qDebug() << __func__ << ": Stopped thread";
243     }
244 
245     delete window;
246     window = nullptr;
247     delete optionsModel;
248     optionsModel = nullptr;
249     delete platformStyle;
250     platformStyle = nullptr;
251 }
252 
253 #ifdef ENABLE_WALLET
createPaymentServer()254 void BitcoinApplication::createPaymentServer()
255 {
256     paymentServer = new PaymentServer(this);
257 }
258 #endif
259 
createOptionsModel(bool resetSettings)260 void BitcoinApplication::createOptionsModel(bool resetSettings)
261 {
262     optionsModel = new OptionsModel(m_node, nullptr, resetSettings);
263 }
264 
createWindow(const NetworkStyle * networkStyle)265 void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
266 {
267     window = new BitcoinGUI(m_node, platformStyle, networkStyle, nullptr);
268 
269     pollShutdownTimer = new QTimer(window);
270     connect(pollShutdownTimer, &QTimer::timeout, window, &BitcoinGUI::detectShutdown);
271 }
272 
createSplashScreen(const NetworkStyle * networkStyle)273 void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
274 {
275     SplashScreen *splash = new SplashScreen(m_node, nullptr, networkStyle);
276     // We don't hold a direct pointer to the splash screen after creation, but the splash
277     // screen will take care of deleting itself when finish() happens.
278     splash->show();
279     connect(this, &BitcoinApplication::splashFinished, splash, &SplashScreen::finish);
280     connect(this, &BitcoinApplication::requestedShutdown, splash, &QWidget::close);
281 }
282 
baseInitialize()283 bool BitcoinApplication::baseInitialize()
284 {
285     return m_node.baseInitialize();
286 }
287 
startThread()288 void BitcoinApplication::startThread()
289 {
290     if(coreThread)
291         return;
292     coreThread = new QThread(this);
293     BitcoinCore *executor = new BitcoinCore(m_node);
294     executor->moveToThread(coreThread);
295 
296     /*  communication to and from thread */
297     connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult);
298     connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult);
299     connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException);
300     connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize);
301     connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown);
302     /*  make sure executor object is deleted in its own thread */
303     connect(coreThread, &QThread::finished, executor, &QObject::deleteLater);
304 
305     coreThread->start();
306 }
307 
parameterSetup()308 void BitcoinApplication::parameterSetup()
309 {
310     // Default printtoconsole to false for the GUI. GUI programs should not
311     // print to the console unnecessarily.
312     gArgs.SoftSetBoolArg("-printtoconsole", false);
313 
314     m_node.initLogging();
315     m_node.initParameterInteraction();
316 }
317 
InitializePruneSetting(bool prune)318 void BitcoinApplication::InitializePruneSetting(bool prune)
319 {
320     // If prune is set, intentionally override existing prune size with
321     // the default size since this is called when choosing a new datadir.
322     optionsModel->SetPruneTargetGB(prune ? DEFAULT_PRUNE_TARGET_GB : 0, true);
323 }
324 
requestInitialize()325 void BitcoinApplication::requestInitialize()
326 {
327     qDebug() << __func__ << ": Requesting initialize";
328     startThread();
329     Q_EMIT requestedInitialize();
330 }
331 
requestShutdown()332 void BitcoinApplication::requestShutdown()
333 {
334     // Show a simple window indicating shutdown status
335     // Do this first as some of the steps may take some time below,
336     // for example the RPC console may still be executing a command.
337     shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window));
338 
339     qDebug() << __func__ << ": Requesting shutdown";
340     startThread();
341     window->hide();
342     // Must disconnect node signals otherwise current thread can deadlock since
343     // no event loop is running.
344     window->unsubscribeFromCoreSignals();
345 #ifdef ENABLE_WALLET
346     // Get restore wallet data
347     if(m_wallet_controller) m_wallet_controller->getRestoreData(restorePath, restoreParam, restoreName);
348 #endif
349     // Get restart wallet
350     if(optionsModel) restartApp = optionsModel->getRestartApp();
351     // Request node shutdown, which can interrupt long operations, like
352     // rescanning a wallet.
353     m_node.startShutdown();
354     // Unsetting the client model can cause the current thread to wait for node
355     // to complete an operation, like wait for a RPC execution to complete.
356     window->setClientModel(nullptr);
357     pollShutdownTimer->stop();
358 
359     delete clientModel;
360     clientModel = nullptr;
361 
362     // Request shutdown from core thread
363     Q_EMIT requestedShutdown();
364 }
365 
initializeResult(bool success)366 void BitcoinApplication::initializeResult(bool success)
367 {
368     qDebug() << __func__ << ": Initialization result: " << success;
369     // Set exit result.
370     returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE;
371     if(success)
372     {
373         LOCK(cs_main);
374         // Log this only after AppInitMain finishes, as then logging setup is guaranteed complete
375         qInfo() << "Platform customization:" << platformStyle->getName();
376         clientModel = new ClientModel(m_node, optionsModel);
377         window->setClientModel(clientModel);
378 #ifdef ENABLE_WALLET
379         if (WalletModel::isWalletEnabled()) {
380             m_wallet_controller = new WalletController(m_node, platformStyle, optionsModel, this);
381             window->setWalletController(m_wallet_controller);
382             if (paymentServer) {
383                 paymentServer->setOptionsModel(optionsModel);
384             }
385         }
386 #endif // ENABLE_WALLET
387 
388         // If -min option passed, start window minimized (iconified) or minimized to tray
389         if (!gArgs.GetBoolArg("-min", false)) {
390             window->show();
391         } else if (clientModel->getOptionsModel()->getMinimizeToTray() && window->hasTrayIcon()) {
392             // do nothing as the window is managed by the tray icon
393         } else {
394             window->showMinimized();
395         }
396         Q_EMIT splashFinished();
397 
398 #ifdef ENABLE_WALLET
399         // Now that initialization/startup is done, process any command-line
400         // bitcoin: URIs or payment requests:
401         if (paymentServer) {
402             connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &BitcoinGUI::handlePaymentRequest);
403             connect(window, &BitcoinGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile);
404             connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) {
405                 window->message(title, message, style);
406             });
407             QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady);
408         }
409 #endif
410         pollShutdownTimer->start(200);
411 
412         processEvents();
413     }
414 
415     if(success) {
416         Q_EMIT windowShown(window);
417     } else {
418         Q_EMIT splashFinished(); // Make sure splash screen doesn't stick around during shutdown
419         quit(); // Exit first main loop invocation
420     }
421 }
422 
shutdownResult()423 void BitcoinApplication::shutdownResult()
424 {
425     quit(); // Exit second main loop invocation after shutdown finished
426 }
427 
handleRunawayException(const QString & message)428 void BitcoinApplication::handleRunawayException(const QString &message)
429 {
430     QMessageBox::critical(nullptr, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Qtum can no longer continue safely and will quit.") + QString("\n\n") + message);
431     ::exit(EXIT_FAILURE);
432 }
433 
getMainWinId() const434 WId BitcoinApplication::getMainWinId() const
435 {
436     if (!window)
437         return 0;
438 
439     return window->winId();
440 }
441 
parseParameters(int argc,const char * const argv[])442 void BitcoinApplication::parseParameters(int argc, const char* const argv[])
443 {
444     for(int i = 0; i < argc; i++)
445     {
446         parameters.append(argv[i]);
447     }
448 }
449 
restart(const QString & commandLine)450 void BitcoinApplication::restart(const QString& commandLine)
451 {
452     // Unlock the data folder
453     UnlockDataDirectory();
454     QThread::currentThread()->sleep(2);
455 
456     // Create new process and start the wallet
457     QProcess::startDetached(commandLine);
458 }
459 
restartWallet()460 void BitcoinApplication::restartWallet()
461 {
462 #ifdef ENABLE_WALLET
463     // Restart the wallet if needed
464     if(!restorePath.isEmpty())
465     {
466         // Create command line
467         QString walletParam = "-wallet=" + restoreName;
468         QString commandLine;
469         QStringList arg = parameters;
470         removeParam(arg, "-reindex", false);
471         removeParam(arg, "-zapwallettxes=2", false);
472         removeParam(arg, "-deleteblockchaindata", false);
473         removeParam(arg, "-wallet", true);
474         if(!arg.contains(restoreParam))
475         {
476             arg.append(restoreParam);
477         }
478         arg.append(walletParam);
479         commandLine = arg.join(' ');
480 
481         // Copy the new wallet.dat to the data folder
482         fs::path path = GetWalletDir();
483         if(!restoreName.isEmpty())
484         {
485             path /= restoreName.toStdString();
486         }
487         path /= "wallet.dat";
488         QString pathWallet = QString::fromStdString(path.string());
489         bool ret = QFile::exists(restorePath) && QFile::exists(pathWallet);
490         if(ret && QFileInfo(restorePath) != QFileInfo(pathWallet))
491         {
492             ret &= QFile::remove(pathWallet);
493             ret &= QFile::copy(restorePath, pathWallet);
494         }
495 
496         // Restart wallet for restore
497         if(ret)
498         {
499             restart(commandLine);
500             restartApp = false;
501         }
502     }
503 #endif
504 
505     if(restartApp)
506     {
507         // Restart wallet for option
508         QString commandLine = parameters.join(' ');
509         restart(commandLine);
510     }
511 }
512 
SetupUIArgs()513 static void SetupUIArgs()
514 {
515     gArgs.AddArg("-choosedatadir", strprintf("Choose data directory on startup (default: %u)", DEFAULT_CHOOSE_DATADIR), ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
516     gArgs.AddArg("-lang=<lang>", "Set language, for example \"de_DE\" (default: system locale)", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
517     gArgs.AddArg("-min", "Start minimized", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
518     gArgs.AddArg("-resetguisettings", "Reset all settings changed in the GUI", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
519     gArgs.AddArg("-splash", strprintf("Show splash screen on startup (default: %u)", DEFAULT_SPLASHSCREEN), ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
520     gArgs.AddArg("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::GUI);
521 }
522 
GuiMain(int argc,char * argv[])523 int GuiMain(int argc, char* argv[])
524 {
525 #ifdef WIN32
526     util::WinCmdLineArgs winArgs;
527     std::tie(argc, argv) = winArgs.get();
528 #endif
529     SetupEnvironment();
530     util::ThreadSetInternalName("main");
531 
532     std::unique_ptr<interfaces::Node> node = interfaces::MakeNode();
533 
534     // Subscribe to global signals from core
535     std::unique_ptr<interfaces::Handler> handler_message_box = node->handleMessageBox(noui_ThreadSafeMessageBox);
536     std::unique_ptr<interfaces::Handler> handler_question = node->handleQuestion(noui_ThreadSafeQuestion);
537     std::unique_ptr<interfaces::Handler> handler_init_message = node->handleInitMessage(noui_InitMessage);
538 
539     // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
540 
541     /// 1. Basic Qt initialization (not dependent on parameters or configuration)
542     Q_INIT_RESOURCE(bitcoin);
543     Q_INIT_RESOURCE(bitcoin_locale);
544 
545     // Generate high-dpi pixmaps
546     QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
547 #if QT_VERSION >= 0x050600
548     QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
549 #endif
550 
551     BitcoinApplication app(*node);
552     app.parseParameters(argc, argv);
553 
554     // Register meta types used for QMetaObject::invokeMethod and Qt::QueuedConnection
555     qRegisterMetaType<bool*>();
556 #ifdef ENABLE_WALLET
557     qRegisterMetaType<WalletModel*>();
558 #endif
559     // Register typedefs (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
560     // IMPORTANT: if CAmount is no longer a typedef use the normal variant above (see https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType-1)
561     qRegisterMetaType<CAmount>("CAmount");
562     qRegisterMetaType<size_t>("size_t");
563 
564     qRegisterMetaType<std::function<void()>>("std::function<void()>");
565     qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon");
566 
567     /// 2. Parse command-line options. We do this after qt in order to show an error if there are problems parsing these
568     // Command-line options take precedence:
569     node->setupServerArgs();
570     SetupUIArgs();
571     std::string error;
572     if (!node->parseParameters(argc, argv, error)) {
573         node->initError(strprintf("Error parsing command line arguments: %s\n", error));
574         // Create a message box, because the gui has neither been created nor has subscribed to core signals
575         QMessageBox::critical(nullptr, PACKAGE_NAME,
576             // message can not be translated because translations have not been initialized
577             QString::fromStdString("Error parsing command line arguments: %1.").arg(QString::fromStdString(error)));
578         return EXIT_FAILURE;
579     }
580 
581     /// 3. Application identification
582     // must be set before OptionsModel is initialized or translations are loaded,
583     // as it is used to locate QSettings
584     QApplication::setOrganizationName(QAPP_ORG_NAME);
585     QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
586     QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
587 
588     /// 4. Initialization of translations, so that intro dialog is in user's language
589     // Now that QSettings are accessible, initialize translations
590     QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
591     initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
592 
593     // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
594     // but before showing splash screen.
595     if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
596         HelpMessageDialog help(*node, nullptr, gArgs.IsArgSet("-version"));
597         help.showOrPrint();
598         return EXIT_SUCCESS;
599     }
600 
601     /// 5. Now that settings and translations are available, ask user for data directory
602     // User language is set up: pick a data directory
603     bool did_show_intro = false;
604     bool prune = false; // Intro dialog prune check box
605     // Gracefully exit if the user cancels
606     if (!Intro::showIfNeeded(*node, did_show_intro, prune)) return EXIT_SUCCESS;
607 
608     /// 6. Determine availability of data directory and parse bitcoin.conf
609     /// - Do not call GetDataDir(true) before this step finishes
610     if (!CheckDataDirOption()) {
611         node->initError(strprintf("Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "")));
612         QMessageBox::critical(nullptr, PACKAGE_NAME,
613             QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(gArgs.GetArg("-datadir", ""))));
614         return EXIT_FAILURE;
615     }
616     if (!node->readConfigFiles(error)) {
617         node->initError(strprintf("Error reading configuration file: %s\n", error));
618         QMessageBox::critical(nullptr, PACKAGE_NAME,
619             QObject::tr("Error: Cannot parse configuration file: %1.").arg(QString::fromStdString(error)));
620         return EXIT_FAILURE;
621     }
622 
623     /// 7. Determine network (and switch to network specific options)
624     // - Do not call Params() before this step
625     // - Do this after parsing the configuration file, as the network can be switched there
626     // - QSettings() will use the new application name after this, resulting in network-specific settings
627     // - Needs to be done before createOptionsModel
628 
629     // Check for -chain, -testnet or -regtest parameter (Params() calls are only valid after this clause)
630     try {
631         node->selectParams(gArgs.GetChainName());
632     } catch(std::exception &e) {
633         node->initError(strprintf("%s\n", e.what()));
634         QMessageBox::critical(nullptr, PACKAGE_NAME, QObject::tr("Error: %1").arg(e.what()));
635         return EXIT_FAILURE;
636     }
637 #ifdef ENABLE_WALLET
638     // Parse URIs on command line -- this can affect Params()
639     PaymentServer::ipcParseCommandLine(*node, argc, argv);
640 #endif
641 
642     QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(Params().NetworkIDString()));
643     assert(!networkStyle.isNull());
644     // Allow for separate UI settings for testnets
645     QApplication::setApplicationName(networkStyle->getAppName());
646     // Now that the QApplication is setup and we have parsed our parameters, we can set the platform style
647     app.setupPlatformStyle();
648     // Re-initialize translations after changing application name (language in network-specific settings can be different)
649     initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
650 
651 #ifdef ENABLE_WALLET
652     /// 8. URI IPC sending
653     // - Do this early as we don't want to bother initializing if we are just calling IPC
654     // - Do this *after* setting up the data directory, as the data directory hash is used in the name
655     // of the server.
656     // - Do this after creating app and setting up translations, so errors are
657     // translated properly.
658     if (PaymentServer::ipcSendCommandLine())
659         exit(EXIT_SUCCESS);
660 
661     // Start up the payment server early, too, so impatient users that click on
662     // bitcoin: links repeatedly have their payment requests routed to this process:
663     if (WalletModel::isWalletEnabled()) {
664         app.createPaymentServer();
665     }
666 #endif // ENABLE_WALLET
667 
668     /// 9. Main GUI initialization
669     // Install global event filter that makes sure that long tooltips can be word-wrapped
670     app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
671 #if defined(Q_OS_WIN)
672     // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
673     qApp->installNativeEventFilter(new WinShutdownMonitor());
674 #endif
675     // Install qDebug() message handler to route to debug.log
676     qInstallMessageHandler(DebugMessageHandler);
677     // Allow parameter interaction before we create the options model
678     app.parameterSetup();
679     GUIUtil::LogQtInfo();
680     // Load GUI settings from QSettings
681     app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
682 
683     if (did_show_intro) {
684         // Store intro dialog settings other than datadir (network specific)
685         app.InitializePruneSetting(prune);
686     }
687 
688     if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false))
689         app.createSplashScreen(networkStyle.data());
690 
691     int rv = EXIT_SUCCESS;
692     try
693     {
694         SetObjectStyleSheet(&app, StyleSheetNames::App);
695 
696         app.createWindow(networkStyle.data());
697         // Perform base initialization before spinning up initialization/shutdown thread
698         // This is acceptable because this function only contains steps that are quick to execute,
699         // so the GUI thread won't be held up.
700         if (app.baseInitialize()) {
701             app.requestInitialize();
702 #if defined(Q_OS_WIN)
703             WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(PACKAGE_NAME), (HWND)app.getMainWinId());
704 #endif
705             app.exec();
706             app.requestShutdown();
707             app.exec();
708             rv = app.getReturnValue();
709         } else {
710             // A dialog with detailed error will have been shown by InitError()
711             rv = EXIT_FAILURE;
712         }
713     } catch (const std::exception& e) {
714         PrintExceptionContinue(&e, "Runaway exception");
715         app.handleRunawayException(QString::fromStdString(node->getWarnings()));
716     } catch (...) {
717         PrintExceptionContinue(nullptr, "Runaway exception");
718         app.handleRunawayException(QString::fromStdString(node->getWarnings()));
719     }
720     app.restartWallet();
721     return rv;
722 }
723