Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

rpcconsole.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2015 The Bitcoin Core developers
2 // Copyright (c) 2014-2019 The Dash Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
7 #include <config/dash-config.h>
8 #endif
9 
10 #include <qt/rpcconsole.h>
11 #include <qt/forms/ui_debugwindow.h>
12 
13 #include <qt/bantablemodel.h>
14 #include <qt/clientmodel.h>
15 #include <chainparams.h>
16 #include <netbase.h>
17 #include <rpc/server.h>
18 #include <rpc/client.h>
19 #include <util.h>
20 
21 #include <openssl/crypto.h>
22 
23 #include <univalue.h>
24 
25 #ifdef ENABLE_WALLET
26 #include <db_cxx.h>
27 #include <wallet/wallet.h>
28 #endif
29 
30 #include <QDir>
31 #include <QDesktopWidget>
32 #include <QKeyEvent>
33 #include <QMenu>
34 #include <QMessageBox>
35 #include <QScrollBar>
36 #include <QSettings>
37 #include <QSignalMapper>
38 #include <QTime>
39 #include <QTimer>
40 #include <QStringList>
41 #include <QStyledItemDelegate>
42 
43 #if QT_VERSION < 0x050000
44 #include <QUrl>
45 #endif
46 
47 // TODO: add a scrollback limit, as there is currently none
48 // TODO: make it possible to filter out categories (esp debug messages when implemented)
49 // TODO: receive errors and debug messages through ClientModel
50 
51 const int CONSOLE_HISTORY = 50;
52 const QSize FONT_RANGE(4, 40);
53 const char fontSizeSettingsKey[] = "consoleFontSize";
54 
56 
57 // Repair parameters
58 const QString SALVAGEWALLET("-salvagewallet");
59 const QString RESCAN("-rescan");
60 const QString ZAPTXES1("-zapwallettxes=1 -persistmempool=0");
61 const QString ZAPTXES2("-zapwallettxes=2 -persistmempool=0");
62 const QString UPGRADEWALLET("-upgradewallet");
63 const QString REINDEX("-reindex");
64 
65 namespace {
66 
67 // don't add private key handling cmd's to the history
68 const QStringList historyFilter = QStringList()
69  << "importprivkey"
70  << "importmulti"
71  << "signmessagewithprivkey"
72  << "signrawtransaction"
73  << "walletpassphrase"
74  << "walletpassphrasechange"
75  << "encryptwallet";
76 
77 }
78 
79 /* Object for executing console RPC commands in a separate thread.
80 */
81 class RPCExecutor : public QObject
82 {
83  Q_OBJECT
84 
85 public Q_SLOTS:
86  void request(const QString &command);
87 
88 Q_SIGNALS:
89  void reply(int category, const QString &command);
90 };
91 
95 class QtRPCTimerBase: public QObject, public RPCTimerBase
96 {
97  Q_OBJECT
98 public:
99  QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis):
100  func(_func)
101  {
102  timer.setSingleShot(true);
103  connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
104  timer.start(millis);
105  }
107 private Q_SLOTS:
108  void timeout() { func(); }
109 private:
110  QTimer timer;
111  std::function<void(void)> func;
112 };
113 
115 {
116 public:
118  const char *Name() override { return "Qt"; }
119  RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) override
120  {
121  return new QtRPCTimerBase(func, millis);
122  }
123 };
124 
125 
126 #include <qt/rpcconsole.moc>
127 
147 bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut)
148 {
149  std::vector< std::vector<std::string> > stack;
150  stack.push_back(std::vector<std::string>());
151 
152  enum CmdParseState
153  {
154  STATE_EATING_SPACES,
155  STATE_EATING_SPACES_IN_ARG,
156  STATE_EATING_SPACES_IN_BRACKETS,
157  STATE_ARGUMENT,
158  STATE_SINGLEQUOTED,
159  STATE_DOUBLEQUOTED,
160  STATE_ESCAPE_OUTER,
161  STATE_ESCAPE_DOUBLEQUOTED,
162  STATE_COMMAND_EXECUTED,
163  STATE_COMMAND_EXECUTED_INNER
164  } state = STATE_EATING_SPACES;
165  std::string curarg;
166  UniValue lastResult;
167  unsigned nDepthInsideSensitive = 0;
168  size_t filter_begin_pos = 0, chpos;
169  std::vector<std::pair<size_t, size_t>> filter_ranges;
170 
171  auto add_to_current_stack = [&](const std::string& strArg) {
172  if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
173  nDepthInsideSensitive = 1;
174  filter_begin_pos = chpos;
175  }
176  // Make sure stack is not empty before adding something
177  if (stack.empty()) {
178  stack.push_back(std::vector<std::string>());
179  }
180  stack.back().push_back(strArg);
181  };
182 
183  auto close_out_params = [&]() {
184  if (nDepthInsideSensitive) {
185  if (!--nDepthInsideSensitive) {
186  assert(filter_begin_pos);
187  filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos));
188  filter_begin_pos = 0;
189  }
190  }
191  stack.pop_back();
192  };
193 
194  std::string strCommandTerminated = strCommand;
195  if (strCommandTerminated.back() != '\n')
196  strCommandTerminated += "\n";
197  for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
198  {
199  char ch = strCommandTerminated[chpos];
200  switch(state)
201  {
202  case STATE_COMMAND_EXECUTED_INNER:
203  case STATE_COMMAND_EXECUTED:
204  {
205  bool breakParsing = true;
206  switch(ch)
207  {
208  case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
209  default:
210  if (state == STATE_COMMAND_EXECUTED_INNER)
211  {
212  if (ch != ']')
213  {
214  // append char to the current argument (which is also used for the query command)
215  curarg += ch;
216  break;
217  }
218  if (curarg.size() && fExecute)
219  {
220  // if we have a value query, query arrays with index and objects with a string key
221  UniValue subelement;
222  if (lastResult.isArray())
223  {
224  for(char argch: curarg)
225  if (!std::isdigit(argch))
226  throw std::runtime_error("Invalid result query");
227  subelement = lastResult[atoi(curarg.c_str())];
228  }
229  else if (lastResult.isObject())
230  subelement = find_value(lastResult, curarg);
231  else
232  throw std::runtime_error("Invalid result query"); //no array or object: abort
233  lastResult = subelement;
234  }
235 
236  state = STATE_COMMAND_EXECUTED;
237  break;
238  }
239  // don't break parsing when the char is required for the next argument
240  breakParsing = false;
241 
242  // pop the stack and return the result to the current command arguments
243  close_out_params();
244 
245  // don't stringify the json in case of a string to avoid doublequotes
246  if (lastResult.isStr())
247  curarg = lastResult.get_str();
248  else
249  curarg = lastResult.write(2);
250 
251  // if we have a non empty result, use it as stack argument otherwise as general result
252  if (curarg.size())
253  {
254  if (stack.size())
255  add_to_current_stack(curarg);
256  else
257  strResult = curarg;
258  }
259  curarg.clear();
260  // assume eating space state
261  state = STATE_EATING_SPACES;
262  }
263  if (breakParsing)
264  break;
265  }
266  case STATE_ARGUMENT: // In or after argument
267  case STATE_EATING_SPACES_IN_ARG:
268  case STATE_EATING_SPACES_IN_BRACKETS:
269  case STATE_EATING_SPACES: // Handle runs of whitespace
270  switch(ch)
271  {
272  case '"': state = STATE_DOUBLEQUOTED; break;
273  case '\'': state = STATE_SINGLEQUOTED; break;
274  case '\\': state = STATE_ESCAPE_OUTER; break;
275  case '(': case ')': case '\n':
276  if (state == STATE_EATING_SPACES_IN_ARG)
277  throw std::runtime_error("Invalid Syntax");
278  if (state == STATE_ARGUMENT)
279  {
280  if (ch == '(' && stack.size() && stack.back().size() > 0)
281  {
282  if (nDepthInsideSensitive) {
283  ++nDepthInsideSensitive;
284  }
285  stack.push_back(std::vector<std::string>());
286  }
287 
288  // don't allow commands after executed commands on baselevel
289  if (!stack.size())
290  throw std::runtime_error("Invalid Syntax");
291 
292  add_to_current_stack(curarg);
293  curarg.clear();
294  state = STATE_EATING_SPACES_IN_BRACKETS;
295  }
296  if ((ch == ')' || ch == '\n') && stack.size() > 0)
297  {
298  if (fExecute) {
299  // Convert argument list to JSON objects in method-dependent way,
300  // and pass it along with the method name to the dispatcher.
301  JSONRPCRequest req;
302  req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
303  req.strMethod = stack.back()[0];
304 #ifdef ENABLE_WALLET
305  // TODO: Move this logic to WalletModel
306  if (HasWallets()) {
307  // in Qt, use always the wallet with index 0 when running with multiple wallets
308  QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(GetWallets()[0]->GetName()));
309  req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
310  }
311 #endif
312  lastResult = tableRPC.execute(req);
313  }
314 
315  state = STATE_COMMAND_EXECUTED;
316  curarg.clear();
317  }
318  break;
319  case ' ': case ',': case '\t':
320  if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
321  throw std::runtime_error("Invalid Syntax");
322 
323  else if(state == STATE_ARGUMENT) // Space ends argument
324  {
325  add_to_current_stack(curarg);
326  curarg.clear();
327  }
328  if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
329  {
330  state = STATE_EATING_SPACES_IN_ARG;
331  break;
332  }
333  state = STATE_EATING_SPACES;
334  break;
335  default: curarg += ch; state = STATE_ARGUMENT;
336  }
337  break;
338  case STATE_SINGLEQUOTED: // Single-quoted string
339  switch(ch)
340  {
341  case '\'': state = STATE_ARGUMENT; break;
342  default: curarg += ch;
343  }
344  break;
345  case STATE_DOUBLEQUOTED: // Double-quoted string
346  switch(ch)
347  {
348  case '"': state = STATE_ARGUMENT; break;
349  case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
350  default: curarg += ch;
351  }
352  break;
353  case STATE_ESCAPE_OUTER: // '\' outside quotes
354  curarg += ch; state = STATE_ARGUMENT;
355  break;
356  case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
357  if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
358  curarg += ch; state = STATE_DOUBLEQUOTED;
359  break;
360  }
361  }
362  if (pstrFilteredOut) {
363  if (STATE_COMMAND_EXECUTED == state) {
364  assert(!stack.empty());
365  close_out_params();
366  }
367  *pstrFilteredOut = strCommand;
368  for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
369  pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
370  }
371  }
372  switch(state) // final state
373  {
374  case STATE_COMMAND_EXECUTED:
375  if (lastResult.isStr())
376  strResult = lastResult.get_str();
377  else
378  strResult = lastResult.write(2);
379  case STATE_ARGUMENT:
380  case STATE_EATING_SPACES:
381  return true;
382  default: // ERROR to end in one of the other states
383  return false;
384  }
385 }
386 
387 void RPCExecutor::request(const QString &command)
388 {
389  try
390  {
391  std::string result;
392  std::string executableCommand = command.toStdString() + "\n";
393 
394  // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply.
395  if(executableCommand == "help-console\n")
396  {
397  Q_EMIT reply(RPCConsole::CMD_REPLY, QString(("\n"
398  "This console accepts RPC commands using the standard syntax.\n"
399  " example: getblockhash 0\n\n"
400 
401  "This console can also accept RPC commands using parenthesized syntax.\n"
402  " example: getblockhash(0)\n\n"
403 
404  "Commands may be nested when specified with the parenthesized syntax.\n"
405  " example: getblock(getblockhash(0) 1)\n\n"
406 
407  "A space or a comma can be used to delimit arguments for either syntax.\n"
408  " example: getblockhash 0\n"
409  " getblockhash,0\n\n"
410 
411  "Named results can be queried with a non-quoted key string in brackets.\n"
412  " example: getblock(getblockhash(0) true)[tx]\n\n"
413 
414  "Results without keys can be queried using an integer in brackets.\n"
415  " example: getblock(getblockhash(0),true)[tx][0]\n\n")));
416  return;
417  }
418  if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
419  {
420  Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
421  return;
422  }
423 
424  Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
425  }
426  catch (UniValue& objError)
427  {
428  try // Nice formatting for standard-format error
429  {
430  int code = find_value(objError, "code").get_int();
431  std::string message = find_value(objError, "message").get_str();
432  Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
433  }
434  catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
435  { // Show raw JSON object
436  Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
437  }
438  }
439  catch (const std::exception& e)
440  {
441  Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
442  }
443 }
444 
445 RPCConsole::RPCConsole(QWidget* parent) :
446  QWidget(parent, Qt::Window),
447  ui(new Ui::RPCConsole),
448  clientModel(0),
449  historyPtr(0),
450  peersTableContextMenu(0),
451  banTableContextMenu(0),
452  consoleFontSize(0)
453 {
454  ui->setupUi(this);
455 
456  GUIUtil::setFont({ui->label_9,
457  ui->labelNetwork,
458  ui->label_10,
459  ui->labelMempoolTitle,
460  ui->peerHeading,
461  ui->label_repair_header,
462  ui->banHeading
464 
466 
468 
469  QSettings settings;
470  if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) {
471  // Restore failed (perhaps missing setting), center the window
472  move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());
473  }
474 
475  ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
476 
477  setButtonIcons();
478 
479  // Install event filter for up and down arrow
480  ui->lineEdit->installEventFilter(this);
481  ui->messagesWidget->installEventFilter(this);
482 
483  connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
484  connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
485  connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
486  connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
487 
488  // Wallet Repair Buttons
489  // connect(ui->btn_salvagewallet, SIGNAL(clicked()), this, SLOT(walletSalvage()));
490  // Disable salvage option in GUI, it's way too powerful and can lead to funds loss
491  ui->btn_salvagewallet->setEnabled(false);
492  connect(ui->btn_rescan, SIGNAL(clicked()), this, SLOT(walletRescan()));
493  connect(ui->btn_zapwallettxes1, SIGNAL(clicked()), this, SLOT(walletZaptxes1()));
494  connect(ui->btn_zapwallettxes2, SIGNAL(clicked()), this, SLOT(walletZaptxes2()));
495  connect(ui->btn_upgradewallet, SIGNAL(clicked()), this, SLOT(walletUpgrade()));
496  connect(ui->btn_reindex, SIGNAL(clicked()), this, SLOT(walletReindex()));
497 
498  // set library version labels
499 #ifdef ENABLE_WALLET
500  ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
501  std::string walletPath = GetDataDir().string();
502  walletPath += QDir::separator().toLatin1() + gArgs.GetArg("-wallet", "wallet.dat");
503  ui->wallet_path->setText(QString::fromStdString(walletPath));
504 #else
505  ui->label_berkeleyDBVersion->hide();
506  ui->berkeleyDBVersion->hide();
507 #endif
508  // Register RPC timer interface
510  // avoid accidentally overwriting an existing, non QTThread
511  // based timer interface
513 
515 
516  ui->peerHeading->setText(tr("Select a peer to view detailed information."));
517 
518  consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(GUIUtil::getFontNormal()).pointSize()).toInt();
519 
520  pageButtons.addButton(ui->btnInfo, pageButtons.buttons().size());
521  pageButtons.addButton(ui->btnConsole, pageButtons.buttons().size());
522  pageButtons.addButton(ui->btnNetTraffic, pageButtons.buttons().size());
523  pageButtons.addButton(ui->btnPeers, pageButtons.buttons().size());
524  pageButtons.addButton(ui->btnRepair, pageButtons.buttons().size());
525  connect(&pageButtons, SIGNAL(buttonClicked(int)), this, SLOT(showPage(int)));
526 
527  clear();
528 }
529 
531 {
532  QSettings settings;
533  settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
535  delete rpcTimerInterface;
536  delete ui;
537 }
538 
539 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
540 {
541  if(event->type() == QEvent::KeyPress) // Special key handling
542  {
543  QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
544  int key = keyevt->key();
545  Qt::KeyboardModifiers mod = keyevt->modifiers();
546  switch(key)
547  {
548  case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
549  case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
550  case Qt::Key_PageUp: /* pass paging keys to messages widget */
551  case Qt::Key_PageDown:
552  if(obj == ui->lineEdit)
553  {
554  QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
555  return true;
556  }
557  break;
558  case Qt::Key_Return:
559  case Qt::Key_Enter:
560  // forward these events to lineEdit
561  if(obj == autoCompleter->popup()) {
562  autoCompleter->popup()->hide();
563  QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
564  return true;
565  }
566  break;
567  default:
568  // Typing in messages widget brings focus to line edit, and redirects key there
569  // Exclude most combinations and keys that emit no text, except paste shortcuts
570  if(obj == ui->messagesWidget && (
571  (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
572  ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
573  ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
574  {
575  ui->lineEdit->setFocus();
576  QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
577  return true;
578  }
579  }
580  }
581  return QWidget::eventFilter(obj, event);
582 }
583 
585 {
586  clientModel = model;
587  ui->trafficGraph->setClientModel(model);
589  // Keep up to date with client
591  connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
592 
593  setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getLastBlockHash(), model->getVerificationProgress(nullptr), false);
594  connect(model, SIGNAL(numBlocksChanged(int,QDateTime,QString,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,QString,double,bool)));
595 
597  connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
598 
599  connect(model, SIGNAL(masternodeListChanged()), this, SLOT(updateMasternodeCount()));
601 
602  connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
603  connect(model, SIGNAL(islockCountChanged(size_t)), this, SLOT(setInstantSendLockCount(size_t)));
604 
605  // set up peer table
606  ui->peerWidget->setModel(model->getPeerTableModel());
607  ui->peerWidget->verticalHeader()->hide();
608  ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
609  ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
610  ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
611  ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
612  ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
613  ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
614  ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
615  ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
616 
617  // create peer table context menu actions
618  QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
619  QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
620  QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
621  QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
622  QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
623 
624  // create peer table context menu
625  peersTableContextMenu = new QMenu(this);
626  peersTableContextMenu->addAction(disconnectAction);
627  peersTableContextMenu->addAction(banAction1h);
628  peersTableContextMenu->addAction(banAction24h);
629  peersTableContextMenu->addAction(banAction7d);
630  peersTableContextMenu->addAction(banAction365d);
631 
632  // Add a signal mapping to allow dynamic context menu arguments.
633  // We need to use int (instead of int64_t), because signal mapper only supports
634  // int or objects, which is okay because max bantime (1 year) is < int_max.
635  QSignalMapper* signalMapper = new QSignalMapper(this);
636  signalMapper->setMapping(banAction1h, 60*60);
637  signalMapper->setMapping(banAction24h, 60*60*24);
638  signalMapper->setMapping(banAction7d, 60*60*24*7);
639  signalMapper->setMapping(banAction365d, 60*60*24*365);
640  connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
641  connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
642  connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
643  connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
644  connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
645 
646  // peer table context menu signals
647  connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
648  connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
649 
650  // peer table signal handling - update peer details when selecting new node
651  connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
652  this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
653  // peer table signal handling - update peer details when new nodes are added to the model
654  connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
655  // peer table signal handling - cache selected node ids
656  connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
657 
658  // set up ban table
659  ui->banlistWidget->setModel(model->getBanTableModel());
660  ui->banlistWidget->verticalHeader()->hide();
661  ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
662  ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
663  ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
664  ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
665  ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
666  ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
667  ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
668 
669  // create ban table context menu action
670  QAction* unbanAction = new QAction(tr("&Unban"), this);
671 
672  // create ban table context menu
673  banTableContextMenu = new QMenu(this);
674  banTableContextMenu->addAction(unbanAction);
675 
676  // ban table context menu signals
677  connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
678  connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
679 
680  // ban table signal handling - clear peer details when clicking a peer in the ban table
681  connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
682  // ban table signal handling - ensure ban table is shown or hidden (if empty)
683  connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
685 
686  // Provide initial values
687  ui->clientVersion->setText(model->formatFullVersion());
688  ui->clientUserAgent->setText(model->formatSubVersion());
689  ui->dataDir->setText(model->dataDir());
690  ui->startupTime->setText(model->formatClientStartupTime());
691  ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
692 
693  //Setup autocomplete and attach it
694  QStringList wordList;
695  std::vector<std::string> commandList = tableRPC.listCommands();
696  for (size_t i = 0; i < commandList.size(); ++i)
697  {
698  wordList << commandList[i].c_str();
699  wordList << ("help " + commandList[i]).c_str();
700  }
701 
702  wordList << "help-console";
703  wordList.sort();
704  autoCompleter = new QCompleter(wordList, this);
705  autoCompleter->popup()->setItemDelegate(new QStyledItemDelegate(this));
706  autoCompleter->popup()->setObjectName("rpcAutoCompleter");
708  autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
709  ui->lineEdit->setCompleter(autoCompleter);
710  autoCompleter->popup()->installEventFilter(this);
711  // Start thread to execute RPC commands.
712  startExecutor();
713  }
714  if (!model) {
715  // Client model is being set to 0, this means shutdown() is about to be called.
716  // Make sure we clean up the executor thread
717  Q_EMIT stopExecutor();
718  thread.wait();
719  }
720 }
721 
722 static QString categoryClass(int category)
723 {
724  switch(category)
725  {
726  case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
727  case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
728  case RPCConsole::CMD_ERROR: return "cmd-error"; break;
729  default: return "misc";
730  }
731 }
732 
734 {
736 }
737 
739 {
741 }
742 
743 void RPCConsole::setFontSize(int newSize)
744 {
745  QSettings settings;
746 
747  //don't allow an insane font size
748  if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
749  return;
750 
751  // temp. store the console content
752  QString str = ui->messagesWidget->toHtml();
753 
754  // replace font tags size in current content
755  str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
756 
757  // store the new font size
758  consoleFontSize = newSize;
759  settings.setValue(fontSizeSettingsKey, consoleFontSize);
760 
761  // clear console (reset icon sizes, default stylesheet) and re-add the content
762  float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
763  clear(false);
764  ui->messagesWidget->setHtml(str);
765  ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
766 }
767 
770 {
772 }
773 
776 {
778 }
779 
782 {
784 }
785 
788 {
790 }
791 
794 {
796 }
797 
800 {
802 }
803 
806 {
807  // Get command-line arguments and remove the application name
808  QStringList args = QApplication::arguments();
809  args.removeFirst();
810 
811  // Remove existing repair-options
812  args.removeAll(SALVAGEWALLET);
813  args.removeAll(RESCAN);
814  args.removeAll(ZAPTXES1);
815  args.removeAll(ZAPTXES2);
816  args.removeAll(UPGRADEWALLET);
817  args.removeAll(REINDEX);
818 
819  // Append repair parameter to command line.
820  args.append(arg);
821 
822  // Send command-line arguments to BitcoinGUI::handleRestart()
823  Q_EMIT handleRestart(args);
824 }
825 
826 void RPCConsole::clear(bool clearHistory)
827 {
828  ui->messagesWidget->clear();
829  if(clearHistory)
830  {
831  history.clear();
832  historyPtr = 0;
833  }
834  ui->lineEdit->clear();
835  ui->lineEdit->setFocus();
836 
837  // Set default style sheet
838  QFontInfo fixedFontInfo(GUIUtil::getFontNormal());
839  ui->messagesWidget->document()->setDefaultStyleSheet(
840  QString(
841  "table { }"
842  "td.time { " + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_SECONDARY) + " font-size: %2; } "
843  "td.message { " + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_PRIMARY) + " font-family: %1; font-size: %2; white-space:pre-wrap; } "
844  "td.cmd-request, b { " + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_COMMAND) + " } "
845  "td.cmd-error, .secwarning { " + GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_ERROR) + " }"
846  ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
847  );
848 
849 #ifdef Q_OS_MAC
850  QString clsKey = "(⌘)-L";
851 #else
852  QString clsKey = "Ctrl-L";
853 #endif
854 
855  message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
856  tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
857  tr("Type %1 for an overview of available commands.").arg("<b>help</b>") + "<br>" +
858  tr("For more information on using this console type %1.").arg("<b>help-console</b>") +
859  "<br><span class=\"secwarning\"><br>" +
860  tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
861  "</span>"),
862  true);
863 }
864 
865 void RPCConsole::keyPressEvent(QKeyEvent *event)
866 {
867  if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
868  {
869  close();
870  }
871 }
872 
873 void RPCConsole::message(int category, const QString &message, bool html)
874 {
875  QTime time = QTime::currentTime();
876  QString timeString = time.toString();
877  QString out;
878  out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
879  out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
880  if(html)
881  out += message;
882  else
883  out += GUIUtil::HtmlEscape(message, false);
884  out += "</td></tr></table>";
885  ui->messagesWidget->append(out);
886 }
887 
889 {
890  QString connections = QString::number(clientModel->getNumConnections()) + " (";
891  connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
892  connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
893 
894  if(!clientModel->getNetworkActive()) {
895  connections += " (" + tr("Network activity disabled") + ")";
896  }
897 
898  ui->numberOfConnections->setText(connections);
899 }
900 
902 {
903  if (!clientModel)
904  return;
905 
907 }
908 
909 void RPCConsole::setNetworkActive(bool networkActive)
910 {
912 }
913 
914 void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, const QString& blockHash, double nVerificationProgress, bool headers)
915 {
916  if (!headers) {
917  ui->numberOfBlocks->setText(QString::number(count));
918  ui->lastBlockTime->setText(blockDate.toString());
919  ui->lastBlockHash->setText(blockHash);
920  }
921 }
922 
924 {
925  if (!clientModel) {
926  return;
927  }
928  auto mnList = clientModel->getMasternodeList();
929  QString strMasternodeCount = tr("Total: %1 (Enabled: %2)")
930  .arg(QString::number(mnList.GetAllMNsCount()))
931  .arg(QString::number(mnList.GetValidMNsCount()));
932  ui->masternodeCount->setText(strMasternodeCount);
933 }
934 
935 void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
936 {
937  ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
938 
939  if (dynUsage < 1000000)
940  ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
941  else
942  ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
943 }
944 
946 {
947  ui->instantSendLockCount->setText(QString::number(count));
948 }
949 
950 void RPCConsole::showPage(int index)
951 {
952  std::vector<QWidget*> vecNormal;
953  QAbstractButton* btnActive = pageButtons.button(index);
954  for (QAbstractButton* button : pageButtons.buttons()) {
955  if (button != btnActive) {
956  vecNormal.push_back(button);
957  }
958  }
959 
963 
964  ui->stackedWidgetRPC->setCurrentIndex(index);
965  btnActive->setChecked(true);
966 }
967 
969 {
970  QString cmd = ui->lineEdit->text();
971 
972  if(!cmd.isEmpty())
973  {
974  std::string strFilteredCmd;
975  try {
976  std::string dummy;
977  if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
978  // Failed to parse command, so we cannot even filter it for the history
979  throw std::runtime_error("Invalid command line");
980  }
981  } catch (const std::exception& e) {
982  QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
983  return;
984  }
985 
986  ui->lineEdit->clear();
987 
988  cmdBeforeBrowsing = QString();
989 
990  message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
991  Q_EMIT cmdRequest(cmd);
992 
993  cmd = QString::fromStdString(strFilteredCmd);
994 
995  // Remove command, if already in history
996  history.removeOne(cmd);
997  // Append command to history
998  history.append(cmd);
999  // Enforce maximum history size
1000  while(history.size() > CONSOLE_HISTORY)
1001  history.removeFirst();
1002  // Set pointer to end of history
1003  historyPtr = history.size();
1004 
1005  // Scroll console view to end
1006  scrollToEnd();
1007  }
1008 }
1009 
1011 {
1012  // store current text when start browsing through the history
1013  if (historyPtr == history.size()) {
1014  cmdBeforeBrowsing = ui->lineEdit->text();
1015  }
1016 
1017  historyPtr += offset;
1018  if(historyPtr < 0)
1019  historyPtr = 0;
1020  if(historyPtr > history.size())
1021  historyPtr = history.size();
1022  QString cmd;
1023  if(historyPtr < history.size())
1024  cmd = history.at(historyPtr);
1025  else if (!cmdBeforeBrowsing.isNull()) {
1026  cmd = cmdBeforeBrowsing;
1027  }
1028  ui->lineEdit->setText(cmd);
1029 }
1030 
1032 {
1033  RPCExecutor *executor = new RPCExecutor();
1034  executor->moveToThread(&thread);
1035 
1036  // Replies from executor object must go to this object
1037  connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
1038  // Requests from this object must go to executor
1039  connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
1040 
1041  // On stopExecutor signal
1042  // - quit the Qt event loop in the execution thread
1043  connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit()));
1044  // - queue executor for deletion (in execution thread)
1045  connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection);
1046 
1047  // Default implementation of QThread::run() simply spins up an event loop in the thread,
1048  // which is what we want.
1049  thread.start();
1050 }
1051 
1053 {
1054  if (ui->stackedWidgetRPC->widget(index) == ui->pageConsole)
1055  ui->lineEdit->setFocus();
1056  else if (ui->stackedWidgetRPC->widget(index) != ui->pagePeers)
1058 }
1059 
1061 {
1063 }
1064 
1066 {
1067  QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
1068  scrollbar->setValue(scrollbar->maximum());
1069 }
1070 
1072 {
1073  setTrafficGraphRange(static_cast<TrafficGraphData::GraphRange>(value));
1074 }
1075 
1077 {
1078  ui->trafficGraph->setGraphRangeMins(range);
1079  ui->lblGraphRange->setText(GUIUtil::formatDurationStr(TrafficGraphData::RangeMinutes[range] * 60));
1080 }
1081 
1082 void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
1083 {
1084  Q_UNUSED(deselected);
1085 
1086  if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
1087  return;
1088 
1089  const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
1090  if (stats)
1091  updateNodeDetail(stats);
1092 }
1093 
1095 {
1096  QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
1097  cachedNodeids.clear();
1098  for(int i = 0; i < selected.size(); i++)
1099  {
1100  const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
1101  cachedNodeids.append(stats->nodeStats.nodeid);
1102  }
1103 }
1104 
1106 {
1108  return;
1109 
1110  const CNodeCombinedStats *stats = nullptr;
1111  bool fUnselect = false;
1112  bool fReselect = false;
1113 
1114  if (cachedNodeids.empty()) // no node selected yet
1115  return;
1116 
1117  // find the currently selected row
1118  int selectedRow = -1;
1119  QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
1120  if (!selectedModelIndex.isEmpty()) {
1121  selectedRow = selectedModelIndex.first().row();
1122  }
1123 
1124  // check if our detail node has a row in the table (it may not necessarily
1125  // be at selectedRow since its position can change after a layout change)
1126  int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
1127 
1128  if (detailNodeRow < 0)
1129  {
1130  // detail node disappeared from table (node disconnected)
1131  fUnselect = true;
1132  }
1133  else
1134  {
1135  if (detailNodeRow != selectedRow)
1136  {
1137  // detail node moved position
1138  fUnselect = true;
1139  fReselect = true;
1140  }
1141 
1142  // get fresh stats on the detail node.
1143  stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1144  }
1145 
1146  if (fUnselect && selectedRow >= 0) {
1148  }
1149 
1150  if (fReselect)
1151  {
1152  for(int i = 0; i < cachedNodeids.size(); i++)
1153  {
1154  ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
1155  }
1156  }
1157 
1158  if (stats)
1159  updateNodeDetail(stats);
1160 }
1161 
1163 {
1164  // update the detail ui with latest node information
1165  QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
1166  peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
1167  if (!stats->nodeStats.addrLocal.empty())
1168  peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
1169  ui->peerHeading->setText(peerAddrDetails);
1170  ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
1171  ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
1172  ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
1173  ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes));
1174  ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes));
1175  ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
1176  ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
1177  ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
1178  ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
1179  ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
1180  ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
1181  ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
1182  ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
1183  ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
1184  ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
1185 
1186  // This check fails for example if the lock was busy and
1187  // nodeStateStats couldn't be fetched.
1188  if (stats->fNodeStateStatsAvailable) {
1189  // Ban score is init to 0
1190  ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
1191 
1192  // Sync height is init to -1
1193  if (stats->nodeStateStats.nSyncHeight > -1)
1194  ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
1195  else
1196  ui->peerSyncHeight->setText(tr("Unknown"));
1197 
1198  // Common height is init to -1
1199  if (stats->nodeStateStats.nCommonHeight > -1)
1200  ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
1201  else
1202  ui->peerCommonHeight->setText(tr("Unknown"));
1203  }
1204 
1205  ui->detailWidget->show();
1206 }
1207 
1209 {
1210  const QSize consoleButtonsSize(BUTTON_ICONSIZE * 0.8, BUTTON_ICONSIZE * 0.8);
1211  GUIUtil::setIcon(ui->clearButton, "remove", GUIUtil::ThemedColor::RED, consoleButtonsSize);
1212  GUIUtil::setIcon(ui->fontBiggerButton, "fontbigger", GUIUtil::ThemedColor::BLUE, consoleButtonsSize);
1213  GUIUtil::setIcon(ui->fontSmallerButton, "fontsmaller", GUIUtil::ThemedColor::BLUE, consoleButtonsSize);
1214 }
1215 
1216 void RPCConsole::resizeEvent(QResizeEvent *event)
1217 {
1218  QWidget::resizeEvent(event);
1219 }
1220 
1221 void RPCConsole::showEvent(QShowEvent *event)
1222 {
1223  QWidget::showEvent(event);
1224 
1226  return;
1227 
1228  // start PeerTableModel auto refresh
1230 }
1231 
1232 void RPCConsole::hideEvent(QHideEvent *event)
1233 {
1234  QWidget::hideEvent(event);
1235 
1237  return;
1238 
1239  // stop PeerTableModel auto refresh
1241 }
1242 
1244 {
1245  if (e->type() == QEvent::StyleChange) {
1246  clear();
1247  ui->promptIcon->setHidden(GUIUtil::dashThemeActive());
1248  // Adjust button icon colors on theme changes
1249  setButtonIcons();
1250  }
1251 
1252  QWidget::changeEvent(e);
1253 }
1254 
1255 void RPCConsole::showPeersTableContextMenu(const QPoint& point)
1256 {
1257  QModelIndex index = ui->peerWidget->indexAt(point);
1258  if (index.isValid())
1259  peersTableContextMenu->exec(QCursor::pos());
1260 }
1261 
1262 void RPCConsole::showBanTableContextMenu(const QPoint& point)
1263 {
1264  QModelIndex index = ui->banlistWidget->indexAt(point);
1265  if (index.isValid())
1266  banTableContextMenu->exec(QCursor::pos());
1267 }
1268 
1270 {
1271  if(!g_connman)
1272  return;
1273 
1274  // Get selected peer addresses
1275  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1276  for(int i = 0; i < nodes.count(); i++)
1277  {
1278  // Get currently selected peer address
1279  NodeId id = nodes.at(i).data().toLongLong();
1280  // Find the node, disconnect it and clear the selected node
1281  if(g_connman->DisconnectNode(id))
1283  }
1284 }
1285 
1287 {
1288  if (!clientModel || !g_connman)
1289  return;
1290 
1291  // Get selected peer addresses
1292  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1293  for(int i = 0; i < nodes.count(); i++)
1294  {
1295  // Get currently selected peer address
1296  NodeId id = nodes.at(i).data().toLongLong();
1297 
1298  // Get currently selected peer address
1299  int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
1300  if(detailNodeRow < 0)
1301  return;
1302 
1303  // Find possible nodes, ban it and clear the selected node
1304  const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1305  if(stats) {
1306  g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
1307  }
1308  }
1311 }
1312 
1314 {
1315  if (!clientModel)
1316  return;
1317 
1318  // Get selected ban addresses
1319  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
1320  for(int i = 0; i < nodes.count(); i++)
1321  {
1322  // Get currently selected ban address
1323  QString strNode = nodes.at(i).data().toString();
1324  CSubNet possibleSubnet;
1325 
1326  LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
1327  if (possibleSubnet.IsValid() && g_connman)
1328  {
1329  g_connman->Unban(possibleSubnet);
1331  }
1332  }
1333 }
1334 
1336 {
1337  ui->peerWidget->selectionModel()->clearSelection();
1338  cachedNodeids.clear();
1339  ui->detailWidget->hide();
1340  ui->peerHeading->setText(tr("Select a peer to view detailed information."));
1341 }
1342 
1344 {
1345  if (!clientModel)
1346  return;
1347 
1348  bool visible = clientModel->getBanTableModel()->shouldShow();
1349  ui->banlistWidget->setVisible(visible);
1350  ui->banHeading->setVisible(visible);
1351 }
1352 
1354 {
1355  showPage(tabType);
1356 }
void walletUpgrade()
Restart wallet with "-upgradewallet".
Definition: rpcconsole.cpp:793
void openDebugLogfile()
Definition: guiutil.cpp:652
QString formatClientStartupTime() const
int getRowByNodeId(NodeId nodeid)
bool isObject() const
Definition: univalue.h:85
int nStartingHeight
Definition: net.h:732
QString formatSubVersion() const
Local Bitcoin RPC console.
Definition: rpcconsole.h:32
RPC timer "driver".
Definition: server.h:98
void keyPressEvent(QKeyEvent *)
Definition: rpcconsole.cpp:865
QString cmdBeforeBrowsing
Definition: rpcconsole.h:168
CNodeStateStats nodeStateStats
bool getNetworkActive() const
Return true if network activity in core is enabled.
const QString SALVAGEWALLET("-salvagewallet")
QList< QModelIndex > getEntryData(QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:514
int64_t nTimeOffset
Definition: net.h:726
void showEvent(QShowEvent *event)
void on_lineEdit_returnPressed()
Definition: rpcconsole.cpp:968
void setFont(const std::vector< QWidget *> &vecWidgets, FontWeight weight, int nPointSize, bool fItalic)
Workaround to set correct font styles in all themes since there is a bug in macOS which leads to issu...
Definition: guiutil.cpp:1552
void message(int category, const QString &message, bool html=false)
Append the message to the message widget.
Definition: rpcconsole.cpp:873
static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string *const pstrFilteredOut=nullptr)
Definition: rpcconsole.h:41
void showPeersTableContextMenu(const QPoint &point)
Show custom context menu on Peers tab.
void walletSalvage()
Wallet repair options.
Definition: rpcconsole.cpp:769
bool dashThemeActive()
Check if a dash specific theme is activated (light/dark).
Definition: guiutil.cpp:1775
QStringList history
Definition: rpcconsole.h:166
void setInstantSendLockCount(size_t count)
Set number of InstantSend locks.
Definition: rpcconsole.cpp:945
QThread thread
Definition: rpcconsole.h:175
QFont getFontNormal()
Get the default normal QFont.
Definition: guiutil.cpp:1735
ServiceFlags nServices
Definition: net.h:721
void setNetworkActive(bool networkActive)
Set network state shown in the UI.
Definition: rpcconsole.cpp:909
void scrollToEnd()
Scroll console view to end.
const QString REINDEX("-reindex")
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:1935
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:1893
std::string cleanSubVer
Definition: net.h:729
static QString categoryClass(int category)
Definition: rpcconsole.cpp:722
void clearSelectedNode()
clear the selected node
const std::string & get_str() const
int64_t nTimeConnected
Definition: net.h:725
bool isStr() const
Definition: univalue.h:82
const QString UPGRADEWALLET("-upgradewallet")
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:481
void fontSmaller()
Definition: rpcconsole.cpp:738
PeerTableModel * getPeerTableModel()
void handleRestart(QStringList args)
Get restart command-line parameters and handle restart.
void disconnectSelectedNode()
Disconnect a selected node on the Peers tab.
CNodeStats nodeStats
const QString ZAPTXES2("-zapwallettxes=2 -persistmempool=0")
void updateNodeDetail(const CNodeCombinedStats *stats)
show detailed information on ui about selected node
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:601
void setNumBlocks(int count, const QDateTime &blockDate, const QString &blockHash, double nVerificationProgress, bool headers)
Set number of blocks, last block date and last block hash shown in the UI.
Definition: rpcconsole.cpp:914
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
Definition: client.cpp:230
void setClientModel(ClientModel *model)
Definition: rpcconsole.cpp:584
void resizeEvent(QResizeEvent *event)
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:536
std::string strMethod
Definition: server.h:41
std::vector< CWallet * > GetWallets()
Definition: wallet.cpp:79
void reply(int category, const QString &command)
void walletRescan()
Restart wallet with "-rescan".
Definition: rpcconsole.cpp:775
const QString ZAPTXES1("-zapwallettxes=1 -persistmempool=0")
void updateFonts()
Update the font of all widgets where a custom font has been set with GUIUtil::setFont.
Definition: guiutil.cpp:1563
QMenu * peersTableContextMenu
Definition: rpcconsole.h:171
CRPCTable tableRPC
Definition: server.cpp:616
int nVersion
Definition: net.h:728
const TrafficGraphData::GraphRange INITIAL_TRAFFIC_GRAPH_SETTING
Definition: rpcconsole.cpp:55
void browseHistory(int offset)
Go forward or back in history.
RPCTimerBase * NewTimer(std::function< void(void)> &func, int64_t millis) override
Factory function for timers.
Definition: rpcconsole.cpp:119
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
void updateMasternodeCount()
Update number of masternodes shown in the UI.
Definition: rpcconsole.cpp:923
int getNumConnections(unsigned int flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:62
double getVerificationProgress(const CBlockIndex *tip) const
int64_t GetSystemTimeInSeconds()
Returns the system time (not mockable)
Definition: utiltime.cpp:70
Class for handling RPC timers (used for e.g.
Definition: rpcconsole.cpp:95
QString formatDurationStr(int secs)
Definition: guiutil.cpp:1833
UniValue params
Definition: server.h:42
std::function< void(void)> func
Definition: rpcconsole.cpp:111
const int CONSOLE_HISTORY
Definition: rpcconsole.cpp:51
const QString RESCAN("-rescan")
void buildParameterlist(QString arg)
Build parameter list for restart.
Definition: rpcconsole.cpp:805
void walletReindex()
Restart wallet with "-reindex".
Definition: rpcconsole.cpp:799
QtRPCTimerBase(std::function< void(void)> &_func, int64_t millis)
Definition: rpcconsole.cpp:99
void setTabFocus(enum TabTypes tabType)
set which tab has the focus (is visible)
void request(const QString &command)
Definition: rpcconsole.cpp:387
QString getLastBlockHash() const
void showPage(int index)
custom tab buttons clicked
Definition: rpcconsole.cpp:950
bool fInbound
Definition: net.h:730
BanTableModel * getBanTableModel()
uint64_t nRecvBytes
Definition: net.h:735
int historyPtr
Definition: rpcconsole.h:167
void walletZaptxes2()
Restart wallet with "-zapwallettxes=2".
Definition: rpcconsole.cpp:787
void peerLayoutChanged()
Handle updated peer information.
RPCTimerInterface * rpcTimerInterface
Definition: rpcconsole.h:170
double dPingTime
Definition: net.h:738
std::string addrName
Definition: net.h:727
static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string *const pstrFilteredOut=nullptr)
Split shell command line into a list of arguments and optionally execute the command(s).
Definition: rpcconsole.cpp:147
void updateNetworkState()
Update UI with latest network info from model.
Definition: rpcconsole.cpp:888
int64_t NodeId
Definition: net.h:109
const CNodeCombinedStats * getNodeStats(int idx)
int get_int() const
CDeterministicMNList getMasternodeList() const
Definition: clientmodel.cpp:88
void setTrafficGraphRange(TrafficGraphData::GraphRange range)
uint64_t nSendBytes
Definition: net.h:733
void on_openDebugLogfileButton_clicked()
open the debug.log from the current datadir
const char * Name() override
Implementation name.
Definition: rpcconsole.cpp:118
void refreshMasternodeList()
Definition: clientmodel.cpp:94
void on_stackedWidgetRPC_currentChanged(int index)
Model for Dash network client.
Definition: clientmodel.h:42
void unbanSelectedNode()
Unban a selected node on the Bans tab.
void hideEvent(QHideEvent *event)
ClientModel * clientModel
Definition: rpcconsole.h:165
QString formatPingTime(double dPingTime)
Definition: guiutil.cpp:1888
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:590
void disableMacFocusRect(const QWidget *w)
Disable the OS default focus rect for macOS because we have custom focus rects set in the css files...
Definition: guiutil.cpp:1789
virtual bool eventFilter(QObject *obj, QEvent *event)
Definition: rpcconsole.cpp:539
QMenu * banTableContextMenu
Definition: rpcconsole.h:172
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:618
void clear(bool clearHistory=true)
Definition: rpcconsole.cpp:826
QDateTime getLastBlockDate() const
void showOrHideBanTableIfRequired()
Hides ban table if no bans are present.
void fontBigger()
Definition: rpcconsole.cpp:733
RPCConsole(QWidget *parent)
Definition: rpcconsole.cpp:445
bool IsValid() const
Definition: netaddress.cpp:711
QButtonGroup pageButtons
Definition: rpcconsole.h:164
ArgsManager gArgs
Definition: util.cpp:108
QList< NodeId > cachedNodeids
Definition: rpcconsole.h:169
void walletZaptxes1()
Restart wallet with "-zapwallettxes=1".
Definition: rpcconsole.cpp:781
void setMempoolSize(long numberOfTxs, size_t dynUsage)
Set size (number of transactions and memory usage) of the mempool in the UI.
Definition: rpcconsole.cpp:935
void setFontSize(int newSize)
Definition: rpcconsole.cpp:743
void setButtonIcons()
Set required icons for buttons inside the dialog.
void changeEvent(QEvent *e)
void setNumConnections(int count)
Set number of connections shown in the UI.
Definition: rpcconsole.cpp:901
void startExecutor()
const CChainParams & Params()
Return the currently selected parameters.
void peerLayoutAboutToChange()
Handle selection caching before update.
QString formatServicesStr(quint64 mask)
Definition: guiutil.cpp:1853
std::string addrLocal
Definition: net.h:742
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
void on_sldGraphRange_valueChanged(int value)
change the time range of the network traffic graph
std::string URI
Definition: server.h:44
void banSelectedNode(int bantime)
Ban a selected node on the Peers tab.
QString getThemedStyleQString(ThemedStyle style)
Helper to get css style strings which are injected into rich text through qt.
Definition: guiutil.cpp:210
double dMinPing
Definition: net.h:740
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:89
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:97
static const int RangeMinutes[]
void setIcon(QAbstractButton *button, const QString &strIcon, const ThemedColor color, const ThemedColor colorAlternative, const QSize &size)
Helper to set an icon for a button with the given color (replaces black) and colorAlternative (replac...
Definition: guiutil.cpp:247
static int count
Definition: tests.c:45
const char fontSizeSettingsKey[]
Definition: rpcconsole.cpp:53
void peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
Handle selection of peer in peers list.
int consoleFontSize
Definition: rpcconsole.h:173
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:928
const QSize FONT_RANGE(4, 40)
QString dataDir() const
void clear()
Definition: univalue.cpp:17
int getNumBlocks() const
void loadStyleSheet(QWidget *widget, bool fForceUpdate)
Updates the widgets stylesheet and adds it to the list of ui debug elements.
Definition: guiutil.cpp:1155
bool fWhitelisted
Definition: net.h:737
bool HasWallets()
Definition: wallet.cpp:73
Ui::RPCConsole * ui
Definition: rpcconsole.h:163
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:567
QCompleter * autoCompleter
Definition: rpcconsole.h:174
void stopExecutor()
double dPingWait
Definition: net.h:739
static const int BUTTON_ICONSIZE
Definition: guiconstants.h:19
void cmdRequest(const QString &command)
bool isArray() const
Definition: univalue.h:84
int64_t nLastSend
Definition: net.h:723
int atoi(const std::string &str)
NodeId nodeid
Definition: net.h:720
void showBanTableContextMenu(const QPoint &point)
Show custom context menu on Bans tab.
int64_t nLastRecv
Definition: net.h:724
CAddress addr
Definition: net.h:744
QString formatFullVersion() const
Released under the MIT license