Bitcoin Core  0.20.99
P2P Digital Currency
walletcontroller.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-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 #include <qt/walletcontroller.h>
6 
8 #include <qt/clientmodel.h>
10 #include <qt/guiconstants.h>
11 #include <qt/guiutil.h>
12 #include <qt/walletmodel.h>
13 
14 #include <interfaces/handler.h>
15 #include <interfaces/node.h>
16 #include <util/string.h>
17 #include <util/translation.h>
18 #include <wallet/wallet.h>
19 
20 #include <algorithm>
21 
22 #include <QApplication>
23 #include <QMessageBox>
24 #include <QMutexLocker>
25 #include <QThread>
26 #include <QTimer>
27 #include <QWindow>
28 
29 WalletController::WalletController(ClientModel& client_model, const PlatformStyle* platform_style, QObject* parent)
30  : QObject(parent)
31  , m_activity_thread(new QThread(this))
32  , m_activity_worker(new QObject)
33  , m_client_model(client_model)
34  , m_node(client_model.node())
35  , m_platform_style(platform_style)
36  , m_options_model(client_model.getOptionsModel())
37 {
38  m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) {
39  getOrCreateWallet(std::move(wallet));
40  });
41 
42  for (std::unique_ptr<interfaces::Wallet>& wallet : m_node.getWallets()) {
43  getOrCreateWallet(std::move(wallet));
44  }
45 
46  m_activity_worker->moveToThread(m_activity_thread);
47  m_activity_thread->start();
48 }
49 
50 // Not using the default destructor because not all member types definitions are
51 // available in the header, just forward declared.
53 {
54  m_activity_thread->quit();
55  m_activity_thread->wait();
56  delete m_activity_worker;
57 }
58 
59 std::vector<WalletModel*> WalletController::getOpenWallets() const
60 {
61  QMutexLocker locker(&m_mutex);
62  return m_wallets;
63 }
64 
65 std::map<std::string, bool> WalletController::listWalletDir() const
66 {
67  QMutexLocker locker(&m_mutex);
68  std::map<std::string, bool> wallets;
69  for (const std::string& name : m_node.listWalletDir()) {
70  wallets[name] = false;
71  }
72  for (WalletModel* wallet_model : m_wallets) {
73  auto it = wallets.find(wallet_model->wallet().getWalletName());
74  if (it != wallets.end()) it->second = true;
75  }
76  return wallets;
77 }
78 
79 void WalletController::closeWallet(WalletModel* wallet_model, QWidget* parent)
80 {
81  QMessageBox box(parent);
82  box.setWindowTitle(tr("Close wallet"));
83  box.setText(tr("Are you sure you wish to close the wallet <i>%1</i>?").arg(GUIUtil::HtmlEscape(wallet_model->getDisplayName())));
84  box.setInformativeText(tr("Closing the wallet for too long can result in having to resync the entire chain if pruning is enabled."));
85  box.setStandardButtons(QMessageBox::Yes|QMessageBox::Cancel);
86  box.setDefaultButton(QMessageBox::Yes);
87  if (box.exec() != QMessageBox::Yes) return;
88 
89  // First remove wallet from node.
90  wallet_model->wallet().remove();
91  // Now release the model.
92  removeAndDeleteWallet(wallet_model);
93 }
94 
95 void WalletController::closeAllWallets(QWidget* parent)
96 {
97  QMessageBox::StandardButton button = QMessageBox::question(parent, tr("Close all wallets"),
98  tr("Are you sure you wish to close all wallets?"),
99  QMessageBox::Yes|QMessageBox::Cancel,
100  QMessageBox::Yes);
101  if (button != QMessageBox::Yes) return;
102 
103  QMutexLocker locker(&m_mutex);
104  for (WalletModel* wallet_model : m_wallets) {
105  wallet_model->wallet().remove();
106  Q_EMIT walletRemoved(wallet_model);
107  delete wallet_model;
108  }
109  m_wallets.clear();
110 }
111 
112 WalletModel* WalletController::getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet)
113 {
114  QMutexLocker locker(&m_mutex);
115 
116  // Return model instance if exists.
117  if (!m_wallets.empty()) {
118  std::string name = wallet->getWalletName();
119  for (WalletModel* wallet_model : m_wallets) {
120  if (wallet_model->wallet().getWalletName() == name) {
121  return wallet_model;
122  }
123  }
124  }
125 
126  // Instantiate model and register it.
127  WalletModel* wallet_model = new WalletModel(std::move(wallet), m_client_model, m_platform_style, nullptr);
128  // Handler callback runs in a different thread so fix wallet model thread affinity.
129  wallet_model->moveToThread(thread());
130  wallet_model->setParent(this);
131  m_wallets.push_back(wallet_model);
132 
133  // WalletModel::startPollBalance needs to be called in a thread managed by
134  // Qt because of startTimer. Considering the current thread can be a RPC
135  // thread, better delegate the calling to Qt with Qt::AutoConnection.
136  const bool called = QMetaObject::invokeMethod(wallet_model, "startPollBalance");
137  assert(called);
138 
139  connect(wallet_model, &WalletModel::unload, this, [this, wallet_model] {
140  // Defer removeAndDeleteWallet when no modal widget is active.
141  // TODO: remove this workaround by removing usage of QDiallog::exec.
142  if (QApplication::activeModalWidget()) {
143  connect(qApp, &QApplication::focusWindowChanged, wallet_model, [this, wallet_model]() {
144  if (!QApplication::activeModalWidget()) {
145  removeAndDeleteWallet(wallet_model);
146  }
147  }, Qt::QueuedConnection);
148  } else {
149  removeAndDeleteWallet(wallet_model);
150  }
151  }, Qt::QueuedConnection);
152 
153  // Re-emit coinsSent signal from wallet model.
154  connect(wallet_model, &WalletModel::coinsSent, this, &WalletController::coinsSent);
155 
156  // Notify walletAdded signal on the GUI thread.
157  Q_EMIT walletAdded(wallet_model);
158 
159  return wallet_model;
160 }
161 
163 {
164  // Unregister wallet model.
165  {
166  QMutexLocker locker(&m_mutex);
167  m_wallets.erase(std::remove(m_wallets.begin(), m_wallets.end(), wallet_model));
168  }
169  Q_EMIT walletRemoved(wallet_model);
170  // Currently this can trigger the unload since the model can hold the last
171  // CWallet shared pointer.
172  delete wallet_model;
173 }
174 
175 WalletControllerActivity::WalletControllerActivity(WalletController* wallet_controller, QWidget* parent_widget)
176  : QObject(wallet_controller)
177  , m_wallet_controller(wallet_controller)
178  , m_parent_widget(parent_widget)
179 {
180 }
181 
183 {
184  delete m_progress_dialog;
185 }
186 
187 void WalletControllerActivity::showProgressDialog(const QString& label_text)
188 {
189  assert(!m_progress_dialog);
190  m_progress_dialog = new QProgressDialog(m_parent_widget);
191 
192  m_progress_dialog->setLabelText(label_text);
193  m_progress_dialog->setRange(0, 0);
194  m_progress_dialog->setCancelButton(nullptr);
195  m_progress_dialog->setWindowModality(Qt::ApplicationModal);
197 }
198 
200 {
201  assert(m_progress_dialog);
202  delete m_progress_dialog;
203  m_progress_dialog = nullptr;
204 }
205 
206 CreateWalletActivity::CreateWalletActivity(WalletController* wallet_controller, QWidget* parent_widget)
207  : WalletControllerActivity(wallet_controller, parent_widget)
208 {
210 }
211 
213 {
214  delete m_create_wallet_dialog;
215  delete m_passphrase_dialog;
216 }
217 
219 {
221  m_passphrase_dialog->setWindowModality(Qt::ApplicationModal);
222  m_passphrase_dialog->show();
223 
224  connect(m_passphrase_dialog, &QObject::destroyed, [this] {
225  m_passphrase_dialog = nullptr;
226  });
227  connect(m_passphrase_dialog, &QDialog::accepted, [this] {
228  createWallet();
229  });
230  connect(m_passphrase_dialog, &QDialog::rejected, [this] {
231  Q_EMIT finished();
232  });
233 }
234 
236 {
237  showProgressDialog(tr("Creating Wallet <b>%1</b>...").arg(m_create_wallet_dialog->walletName().toHtmlEscaped()));
238 
239  std::string name = m_create_wallet_dialog->walletName().toStdString();
240  uint64_t flags = 0;
243  }
245  flags |= WALLET_FLAG_BLANK_WALLET;
246  }
248  flags |= WALLET_FLAG_DESCRIPTORS;
249  }
250 
251  QTimer::singleShot(500, worker(), [this, name, flags] {
252  WalletCreationStatus status;
253  std::unique_ptr<interfaces::Wallet> wallet = node().createWallet(m_passphrase, flags, name, m_error_message, m_warning_message, status);
254 
256 
257  QTimer::singleShot(500, this, &CreateWalletActivity::finish);
258  });
259 }
260 
262 {
264 
265  if (!m_error_message.empty()) {
266  QMessageBox::critical(m_parent_widget, tr("Create wallet failed"), QString::fromStdString(m_error_message.translated));
267  } else if (!m_warning_message.empty()) {
268  QMessageBox::warning(m_parent_widget, tr("Create wallet warning"), QString::fromStdString(Join(m_warning_message, Untranslated("\n")).translated));
269  }
270 
272 
273  Q_EMIT finished();
274 }
275 
277 {
279  m_create_wallet_dialog->setWindowModality(Qt::ApplicationModal);
280  m_create_wallet_dialog->show();
281 
282  connect(m_create_wallet_dialog, &QObject::destroyed, [this] {
283  m_create_wallet_dialog = nullptr;
284  });
285  connect(m_create_wallet_dialog, &QDialog::rejected, [this] {
286  Q_EMIT finished();
287  });
288  connect(m_create_wallet_dialog, &QDialog::accepted, [this] {
290  askPassphrase();
291  } else {
292  createWallet();
293  }
294  });
295 }
296 
297 OpenWalletActivity::OpenWalletActivity(WalletController* wallet_controller, QWidget* parent_widget)
298  : WalletControllerActivity(wallet_controller, parent_widget)
299 {
300 }
301 
303 {
305 
306  if (!m_error_message.empty()) {
307  QMessageBox::critical(m_parent_widget, tr("Open wallet failed"), QString::fromStdString(m_error_message.translated));
308  } else if (!m_warning_message.empty()) {
309  QMessageBox::warning(m_parent_widget, tr("Open wallet warning"), QString::fromStdString(Join(m_warning_message, Untranslated("\n")).translated));
310  }
311 
312  if (m_wallet_model) Q_EMIT opened(m_wallet_model);
313 
314  Q_EMIT finished();
315 }
316 
317 void OpenWalletActivity::open(const std::string& path)
318 {
319  QString name = path.empty() ? QString("["+tr("default wallet")+"]") : QString::fromStdString(path);
320 
321  showProgressDialog(tr("Opening Wallet <b>%1</b>...").arg(name.toHtmlEscaped()));
322 
323  QTimer::singleShot(0, worker(), [this, path] {
324  std::unique_ptr<interfaces::Wallet> wallet = node().loadWallet(path, m_error_message, m_warning_message);
325 
326  if (wallet) m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(wallet));
327 
328  QTimer::singleShot(0, this, &OpenWalletActivity::finish);
329  });
330 }
std::vector< WalletModel * > m_wallets
static const int MAX_PASSPHRASE_SIZE
Definition: guiconstants.h:14
interfaces::Wallet & wallet() const
Definition: walletmodel.h:146
bool isDescriptorWalletChecked() const
void coinsSent(WalletModel *wallet, SendCoinsRecipient recipient, QByteArray transaction)
interfaces::Node & node() const
bool isEncryptWalletChecked() const
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:34
bool empty() const
Definition: translation.h:27
CreateWalletDialog * m_create_wallet_dialog
NodeContext & m_node
Definition: chain.cpp:382
void closeAllWallets(QWidget *parent=nullptr)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
void opened(WalletModel *wallet_model)
const PlatformStyle *const m_platform_style
CreateWalletActivity(WalletController *wallet_controller, QWidget *parent_widget)
virtual std::vector< std::string > listWalletDir()=0
Return available wallets in wallet directory.
void unload()
void showProgressDialog(const QString &label_text)
Ask passphrase twice and encrypt.
QString walletName() const
OpenWalletActivity(WalletController *wallet_controller, QWidget *parent_widget)
Controller between interfaces::Node, WalletModel instances and the GUI.
QProgressDialog * m_progress_dialog
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:220
std::string translated
Definition: translation.h:18
virtual std::unique_ptr< Wallet > loadWallet(const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings)=0
Attempts to load a wallet from file or directory.
bool isDisablePrivateKeysChecked() const
virtual std::vector< std::unique_ptr< Wallet > > getWallets()=0
Return interfaces for accessing wallets (if any).
WalletCreationStatus
Definition: wallet.h:59
QObject *const m_activity_worker
void coinsSent(WalletModel *wallet_model, SendCoinsRecipient recipient, QByteArray transaction)
std::map< std::string, bool > listWalletDir() const
Returns all wallet names in the wallet dir mapped to whether the wallet is loaded.
bool isMakeBlankWalletChecked() const
void created(WalletModel *wallet_model)
virtual std::unique_ptr< Wallet > createWallet(const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings, WalletCreationStatus &status)=0
Create a wallet from file.
void closeWallet(WalletModel *wallet_model, QWidget *parent=nullptr)
const char * name
Definition: rest.cpp:41
virtual void remove()=0
QWidget *const m_parent_widget
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:58
void open(const std::string &path)
std::vector< bilingual_str > m_warning_message
ClientModel & m_client_model
interfaces::Node & m_node
void walletAdded(WalletModel *wallet_model)
void PolishProgressDialog(QProgressDialog *dialog)
Definition: guiutil.cpp:859
Model for Bitcoin network client.
Definition: clientmodel.h:46
AskPassphraseDialog * m_passphrase_dialog
int flags
Definition: bitcoin-tx.cpp:509
virtual std::unique_ptr< Handler > handleLoadWallet(LoadWalletFn fn)=0
std::vector< WalletModel * > getOpenWallets() const
Returns wallet models currently open.
Interface to Bitcoin wallet from Qt view code.
Definition: walletmodel.h:51
Multifunctional dialog to ask for passphrases.
Dialog for creating wallets.
WalletModel * getOrCreateWallet(std::unique_ptr< interfaces::Wallet > wallet)
void walletRemoved(WalletModel *wallet_model)
QObject * worker() const
WalletControllerActivity(WalletController *wallet_controller, QWidget *parent_widget)
QString getDisplayName() const
QThread *const m_activity_thread
WalletController(ClientModel &client_model, const PlatformStyle *platform_style, QObject *parent)
std::unique_ptr< interfaces::Handler > m_handler_load_wallet
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:61
auto it
Definition: validation.cpp:384
void removeAndDeleteWallet(WalletModel *wallet_model)
WalletController *const m_wallet_controller