You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bitcoin.cpp 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // Copyright (c) 2011-2014 The Bitcoin developers
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #if defined(HAVE_CONFIG_H)
  5. #include "bitcoin-config.h"
  6. #endif
  7. #include "bitcoingui.h"
  8. #include "clientmodel.h"
  9. #include "guiconstants.h"
  10. #include "guiutil.h"
  11. #include "intro.h"
  12. #include "optionsmodel.h"
  13. #include "splashscreen.h"
  14. #include "utilitydialog.h"
  15. #ifdef ENABLE_WALLET
  16. #include "paymentserver.h"
  17. #include "walletmodel.h"
  18. #endif
  19. #include "init.h"
  20. #include "main.h"
  21. #include "rpcserver.h"
  22. #include "ui_interface.h"
  23. #include "util.h"
  24. #include "wallet.h"
  25. #include <stdint.h>
  26. #include <boost/filesystem/operations.hpp>
  27. #include <QApplication>
  28. #include <QLibraryInfo>
  29. #include <QLocale>
  30. #include <QMessageBox>
  31. #include <QSettings>
  32. #include <QTimer>
  33. #include <QTranslator>
  34. #include <QThread>
  35. #if defined(QT_STATICPLUGIN)
  36. #include <QtPlugin>
  37. #if QT_VERSION < 0x050000
  38. Q_IMPORT_PLUGIN(qcncodecs)
  39. Q_IMPORT_PLUGIN(qjpcodecs)
  40. Q_IMPORT_PLUGIN(qtwcodecs)
  41. Q_IMPORT_PLUGIN(qkrcodecs)
  42. Q_IMPORT_PLUGIN(qtaccessiblewidgets)
  43. #else
  44. Q_IMPORT_PLUGIN(AccessibleFactory)
  45. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  46. #endif
  47. #endif
  48. #if QT_VERSION < 0x050000
  49. #include <QTextCodec>
  50. #endif
  51. // Declare meta types used for QMetaObject::invokeMethod
  52. Q_DECLARE_METATYPE(bool*)
  53. static void InitMessage(const std::string &message)
  54. {
  55. LogPrintf("init message: %s\n", message);
  56. }
  57. /*
  58. Translate string to current locale using Qt.
  59. */
  60. static std::string Translate(const char* psz)
  61. {
  62. return QCoreApplication::translate("bitcoin-core", psz).toStdString();
  63. }
  64. /** Set up translations */
  65. static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
  66. {
  67. QSettings settings;
  68. // Remove old translators
  69. QApplication::removeTranslator(&qtTranslatorBase);
  70. QApplication::removeTranslator(&qtTranslator);
  71. QApplication::removeTranslator(&translatorBase);
  72. QApplication::removeTranslator(&translator);
  73. // Get desired locale (e.g. "de_DE")
  74. // 1) System default language
  75. QString lang_territory = QLocale::system().name();
  76. // 2) Language from QSettings
  77. QString lang_territory_qsettings = settings.value("language", "").toString();
  78. if(!lang_territory_qsettings.isEmpty())
  79. lang_territory = lang_territory_qsettings;
  80. // 3) -lang command line argument
  81. lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString()));
  82. // Convert to "de" only by truncating "_DE"
  83. QString lang = lang_territory;
  84. lang.truncate(lang_territory.lastIndexOf('_'));
  85. // Load language files for configured locale:
  86. // - First load the translator for the base language, without territory
  87. // - Then load the more specific locale translator
  88. // Load e.g. qt_de.qm
  89. if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
  90. QApplication::installTranslator(&qtTranslatorBase);
  91. // Load e.g. qt_de_DE.qm
  92. if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
  93. QApplication::installTranslator(&qtTranslator);
  94. // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
  95. if (translatorBase.load(lang, ":/translations/"))
  96. QApplication::installTranslator(&translatorBase);
  97. // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
  98. if (translator.load(lang_territory, ":/translations/"))
  99. QApplication::installTranslator(&translator);
  100. }
  101. /* qDebug() message handler --> debug.log */
  102. #if QT_VERSION < 0x050000
  103. void DebugMessageHandler(QtMsgType type, const char *msg)
  104. {
  105. Q_UNUSED(type);
  106. LogPrint("qt", "GUI: %s\n", msg);
  107. }
  108. #else
  109. void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
  110. {
  111. Q_UNUSED(type);
  112. Q_UNUSED(context);
  113. LogPrint("qt", "GUI: %s\n", qPrintable(msg));
  114. }
  115. #endif
  116. /** Class encapsulating Bitcoin Core startup and shutdown.
  117. * Allows running startup and shutdown in a different thread from the UI thread.
  118. */
  119. class BitcoinCore: public QObject
  120. {
  121. Q_OBJECT
  122. public:
  123. explicit BitcoinCore();
  124. public slots:
  125. void initialize();
  126. void shutdown();
  127. signals:
  128. void initializeResult(int retval);
  129. void shutdownResult(int retval);
  130. void runawayException(const QString &message);
  131. private:
  132. boost::thread_group threadGroup;
  133. /// Pass fatal exception message to UI thread
  134. void handleRunawayException(std::exception *e);
  135. };
  136. /** Main Bitcoin application object */
  137. class BitcoinApplication: public QApplication
  138. {
  139. Q_OBJECT
  140. public:
  141. explicit BitcoinApplication(int &argc, char **argv);
  142. ~BitcoinApplication();
  143. #ifdef ENABLE_WALLET
  144. /// Create payment server
  145. void createPaymentServer();
  146. #endif
  147. /// Create options model
  148. void createOptionsModel();
  149. /// Create main window
  150. void createWindow(bool isaTestNet);
  151. /// Create splash screen
  152. void createSplashScreen(bool isaTestNet);
  153. /// Request core initialization
  154. void requestInitialize();
  155. /// Request core shutdown
  156. void requestShutdown();
  157. /// Get process return value
  158. int getReturnValue() { return returnValue; }
  159. public slots:
  160. void initializeResult(int retval);
  161. void shutdownResult(int retval);
  162. /// Handle runaway exceptions. Shows a message box with the problem and quits the program.
  163. void handleRunawayException(const QString &message);
  164. signals:
  165. void requestedInitialize();
  166. void requestedShutdown();
  167. void stopThread();
  168. void splashFinished(QWidget *window);
  169. private:
  170. QThread *coreThread;
  171. OptionsModel *optionsModel;
  172. ClientModel *clientModel;
  173. BitcoinGUI *window;
  174. QTimer *pollShutdownTimer;
  175. #ifdef ENABLE_WALLET
  176. PaymentServer* paymentServer;
  177. WalletModel *walletModel;
  178. #endif
  179. int returnValue;
  180. void startThread();
  181. };
  182. #include "bitcoin.moc"
  183. BitcoinCore::BitcoinCore():
  184. QObject()
  185. {
  186. }
  187. void BitcoinCore::handleRunawayException(std::exception *e)
  188. {
  189. PrintExceptionContinue(e, "Runaway exception");
  190. emit runawayException(QString::fromStdString(strMiscWarning));
  191. }
  192. void BitcoinCore::initialize()
  193. {
  194. try
  195. {
  196. LogPrintf("Running AppInit2 in thread\n");
  197. int rv = AppInit2(threadGroup);
  198. if(rv)
  199. {
  200. /* Start a dummy RPC thread if no RPC thread is active yet
  201. * to handle timeouts.
  202. */
  203. StartDummyRPCThread();
  204. }
  205. emit initializeResult(rv);
  206. } catch (std::exception& e) {
  207. handleRunawayException(&e);
  208. } catch (...) {
  209. handleRunawayException(NULL);
  210. }
  211. }
  212. void BitcoinCore::shutdown()
  213. {
  214. try
  215. {
  216. LogPrintf("Running Shutdown in thread\n");
  217. threadGroup.interrupt_all();
  218. threadGroup.join_all();
  219. Shutdown();
  220. LogPrintf("Shutdown finished\n");
  221. emit shutdownResult(1);
  222. } catch (std::exception& e) {
  223. handleRunawayException(&e);
  224. } catch (...) {
  225. handleRunawayException(NULL);
  226. }
  227. }
  228. BitcoinApplication::BitcoinApplication(int &argc, char **argv):
  229. QApplication(argc, argv),
  230. coreThread(0),
  231. optionsModel(0),
  232. clientModel(0),
  233. window(0),
  234. pollShutdownTimer(0),
  235. #ifdef ENABLE_WALLET
  236. paymentServer(0),
  237. walletModel(0),
  238. #endif
  239. returnValue(0)
  240. {
  241. setQuitOnLastWindowClosed(false);
  242. startThread();
  243. }
  244. BitcoinApplication::~BitcoinApplication()
  245. {
  246. LogPrintf("Stopping thread\n");
  247. emit stopThread();
  248. coreThread->wait();
  249. LogPrintf("Stopped thread\n");
  250. delete window;
  251. window = 0;
  252. #ifdef ENABLE_WALLET
  253. delete paymentServer;
  254. paymentServer = 0;
  255. #endif
  256. delete optionsModel;
  257. optionsModel = 0;
  258. }
  259. #ifdef ENABLE_WALLET
  260. void BitcoinApplication::createPaymentServer()
  261. {
  262. paymentServer = new PaymentServer(this);
  263. }
  264. #endif
  265. void BitcoinApplication::createOptionsModel()
  266. {
  267. optionsModel = new OptionsModel();
  268. }
  269. void BitcoinApplication::createWindow(bool isaTestNet)
  270. {
  271. window = new BitcoinGUI(isaTestNet, 0);
  272. pollShutdownTimer = new QTimer(window);
  273. connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
  274. pollShutdownTimer->start(200);
  275. }
  276. void BitcoinApplication::createSplashScreen(bool isaTestNet)
  277. {
  278. SplashScreen *splash = new SplashScreen(QPixmap(), 0, isaTestNet);
  279. splash->setAttribute(Qt::WA_DeleteOnClose);
  280. splash->show();
  281. connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*)));
  282. }
  283. void BitcoinApplication::startThread()
  284. {
  285. coreThread = new QThread(this);
  286. BitcoinCore *executor = new BitcoinCore();
  287. executor->moveToThread(coreThread);
  288. /* communication to and from thread */
  289. connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int)));
  290. connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int)));
  291. connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString)));
  292. connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize()));
  293. connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown()));
  294. /* make sure executor object is deleted in its own thread */
  295. connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
  296. connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit()));
  297. coreThread->start();
  298. }
  299. void BitcoinApplication::requestInitialize()
  300. {
  301. LogPrintf("Requesting initialize\n");
  302. emit requestedInitialize();
  303. }
  304. void BitcoinApplication::requestShutdown()
  305. {
  306. LogPrintf("Requesting shutdown\n");
  307. window->hide();
  308. window->setClientModel(0);
  309. pollShutdownTimer->stop();
  310. #ifdef ENABLE_WALLET
  311. window->removeAllWallets();
  312. delete walletModel;
  313. walletModel = 0;
  314. #endif
  315. delete clientModel;
  316. clientModel = 0;
  317. // Show a simple window indicating shutdown status
  318. ShutdownWindow::showShutdownWindow(window);
  319. // Request shutdown from core thread
  320. emit requestedShutdown();
  321. }
  322. void BitcoinApplication::initializeResult(int retval)
  323. {
  324. LogPrintf("Initialization result: %i\n", retval);
  325. // Set exit result: 0 if successful, 1 if failure
  326. returnValue = retval ? 0 : 1;
  327. if(retval)
  328. {
  329. #ifdef ENABLE_WALLET
  330. PaymentServer::LoadRootCAs();
  331. paymentServer->setOptionsModel(optionsModel);
  332. #endif
  333. emit splashFinished(window);
  334. clientModel = new ClientModel(optionsModel);
  335. window->setClientModel(clientModel);
  336. #ifdef ENABLE_WALLET
  337. if(pwalletMain)
  338. {
  339. walletModel = new WalletModel(pwalletMain, optionsModel);
  340. window->addWallet("~Default", walletModel);
  341. window->setCurrentWallet("~Default");
  342. connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
  343. paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
  344. }
  345. #endif
  346. // If -min option passed, start window minimized.
  347. if(GetBoolArg("-min", false))
  348. {
  349. window->showMinimized();
  350. }
  351. else
  352. {
  353. window->show();
  354. }
  355. #ifdef ENABLE_WALLET
  356. // Now that initialization/startup is done, process any command-line
  357. // bitcoin: URIs or payment requests:
  358. connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
  359. window, SLOT(handlePaymentRequest(SendCoinsRecipient)));
  360. connect(window, SIGNAL(receivedURI(QString)),
  361. paymentServer, SLOT(handleURIOrFile(QString)));
  362. connect(paymentServer, SIGNAL(message(QString,QString,unsigned int)),
  363. window, SLOT(message(QString,QString,unsigned int)));
  364. QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
  365. #endif
  366. } else {
  367. quit(); // Exit main loop
  368. }
  369. }
  370. void BitcoinApplication::shutdownResult(int retval)
  371. {
  372. LogPrintf("Shutdown result: %i\n", retval);
  373. quit(); // Exit main loop after shutdown finished
  374. }
  375. void BitcoinApplication::handleRunawayException(const QString &message)
  376. {
  377. QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + message);
  378. ::exit(1);
  379. }
  380. #ifndef BITCOIN_QT_TEST
  381. int main(int argc, char *argv[])
  382. {
  383. /// 1. Parse command-line options. These take precedence over anything else.
  384. // Command-line options take precedence:
  385. ParseParameters(argc, argv);
  386. // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
  387. /// 2. Basic Qt initialization (not dependent on parameters or configuration)
  388. #if QT_VERSION < 0x050000
  389. // Internal string conversion is all UTF-8
  390. QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
  391. QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
  392. #endif
  393. Q_INIT_RESOURCE(bitcoin);
  394. BitcoinApplication app(argc, argv);
  395. #if QT_VERSION > 0x050100
  396. // Generate high-dpi pixmaps
  397. QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  398. #endif
  399. #ifdef Q_OS_MAC
  400. QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
  401. #endif
  402. // Register meta types used for QMetaObject::invokeMethod
  403. qRegisterMetaType< bool* >();
  404. /// 3. Application identification
  405. // must be set before OptionsModel is initialized or translations are loaded,
  406. // as it is used to locate QSettings
  407. QApplication::setOrganizationName(QAPP_ORG_NAME);
  408. QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
  409. QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
  410. /// 4. Initialization of translations, so that intro dialog is in user's language
  411. // Now that QSettings are accessible, initialize translations
  412. QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
  413. initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
  414. uiInterface.Translate.connect(Translate);
  415. // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
  416. // but before showing splash screen.
  417. if (mapArgs.count("-?") || mapArgs.count("--help"))
  418. {
  419. HelpMessageDialog help(NULL);
  420. help.showOrPrint();
  421. return 1;
  422. }
  423. /// 5. Now that settings and translations are available, ask user for data directory
  424. // User language is set up: pick a data directory
  425. Intro::pickDataDirectory();
  426. /// 6. Determine availability of data directory and parse bitcoin.conf
  427. /// - Do not call GetDataDir(true) before this step finishes
  428. if (!boost::filesystem::is_directory(GetDataDir(false)))
  429. {
  430. QMessageBox::critical(0, QObject::tr("Bitcoin"),
  431. QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
  432. return 1;
  433. }
  434. ReadConfigFile(mapArgs, mapMultiArgs);
  435. /// 7. Determine network (and switch to network specific options)
  436. // - Do not call Params() before this step
  437. // - Do this after parsing the configuration file, as the network can be switched there
  438. // - QSettings() will use the new application name after this, resulting in network-specific settings
  439. // - Needs to be done before createOptionsModel
  440. // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
  441. if (!SelectParamsFromCommandLine()) {
  442. QMessageBox::critical(0, QObject::tr("Bitcoin"), QObject::tr("Error: Invalid combination of -regtest and -testnet."));
  443. return 1;
  444. }
  445. #ifdef ENABLE_WALLET
  446. // Parse URIs on command line -- this can affect Params()
  447. if (!PaymentServer::ipcParseCommandLine(argc, argv))
  448. exit(0);
  449. #endif
  450. bool isaTestNet = Params().NetworkID() != CChainParams::MAIN;
  451. // Allow for separate UI settings for testnets
  452. if (isaTestNet)
  453. QApplication::setApplicationName(QAPP_APP_NAME_TESTNET);
  454. else
  455. QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
  456. // Re-initialize translations after changing application name (language in network-specific settings can be different)
  457. initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
  458. #ifdef ENABLE_WALLET
  459. /// 8. URI IPC sending
  460. // - Do this early as we don't want to bother initializing if we are just calling IPC
  461. // - Do this *after* setting up the data directory, as the data directory hash is used in the name
  462. // of the server.
  463. // - Do this after creating app and setting up translations, so errors are
  464. // translated properly.
  465. if (PaymentServer::ipcSendCommandLine())
  466. exit(0);
  467. // Start up the payment server early, too, so impatient users that click on
  468. // bitcoin: links repeatedly have their payment requests routed to this process:
  469. app.createPaymentServer();
  470. #endif
  471. /// 9. Main GUI initialization
  472. // Install global event filter that makes sure that long tooltips can be word-wrapped
  473. app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
  474. // Install qDebug() message handler to route to debug.log
  475. #if QT_VERSION < 0x050000
  476. qInstallMsgHandler(DebugMessageHandler);
  477. #else
  478. qInstallMessageHandler(DebugMessageHandler);
  479. #endif
  480. // Load GUI settings from QSettings
  481. app.createOptionsModel();
  482. // Subscribe to global signals from core
  483. uiInterface.InitMessage.connect(InitMessage);
  484. if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
  485. app.createSplashScreen(isaTestNet);
  486. try
  487. {
  488. app.createWindow(isaTestNet);
  489. app.requestInitialize();
  490. app.exec();
  491. app.requestShutdown();
  492. app.exec();
  493. } catch (std::exception& e) {
  494. PrintExceptionContinue(&e, "Runaway exception");
  495. app.handleRunawayException(QString::fromStdString(strMiscWarning));
  496. } catch (...) {
  497. PrintExceptionContinue(NULL, "Runaway exception");
  498. app.handleRunawayException(QString::fromStdString(strMiscWarning));
  499. }
  500. return app.getReturnValue();
  501. }
  502. #endif // BITCOIN_QT_TEST