Bitcoin Core  29.1.0
P2P Digital Currency
rpcconsole.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2022 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 <bitcoin-build-config.h> // IWYU pragma: keep
6 
7 #include <qt/rpcconsole.h>
8 #include <qt/forms/ui_debugwindow.h>
9 
10 #include <chainparams.h>
11 #include <common/system.h>
12 #include <interfaces/node.h>
13 #include <node/connection_types.h>
14 #include <qt/bantablemodel.h>
15 #include <qt/clientmodel.h>
16 #include <qt/guiutil.h>
17 #include <qt/peertablesortproxy.h>
18 #include <qt/platformstyle.h>
19 #ifdef ENABLE_WALLET
20 #include <qt/walletmodel.h>
21 #endif // ENABLE_WALLET
22 #include <rpc/client.h>
23 #include <rpc/server.h>
24 #include <util/strencodings.h>
25 #include <util/string.h>
26 #include <util/time.h>
27 #include <util/threadnames.h>
28 
29 #include <univalue.h>
30 
31 #include <QAbstractButton>
32 #include <QAbstractItemModel>
33 #include <QDateTime>
34 #include <QFont>
35 #include <QKeyEvent>
36 #include <QKeySequence>
37 #include <QLatin1String>
38 #include <QLocale>
39 #include <QMenu>
40 #include <QMessageBox>
41 #include <QScreen>
42 #include <QScrollBar>
43 #include <QSettings>
44 #include <QString>
45 #include <QStringList>
46 #include <QStyledItemDelegate>
47 #include <QTime>
48 #include <QTimer>
49 #include <QVariant>
50 
51 #include <chrono>
52 
53 using util::Join;
54 
55 const int CONSOLE_HISTORY = 50;
57 const QSize FONT_RANGE(4, 40);
58 const char fontSizeSettingsKey[] = "consoleFontSize";
59 
60 const struct {
61  const char *url;
62  const char *source;
63 } ICON_MAPPING[] = {
64  {"cmd-request", ":/icons/tx_input"},
65  {"cmd-reply", ":/icons/tx_output"},
66  {"cmd-error", ":/icons/tx_output"},
67  {"misc", ":/icons/tx_inout"},
68  {nullptr, nullptr}
69 };
70 
71 namespace {
72 
73 // don't add private key handling cmd's to the history
74 const QStringList historyFilter = QStringList()
75  << "importprivkey"
76  << "importmulti"
77  << "sethdseed"
78  << "signmessagewithprivkey"
79  << "signrawtransactionwithkey"
80  << "walletpassphrase"
81  << "walletpassphrasechange"
82  << "encryptwallet";
83 
84 }
85 
86 /* Object for executing console RPC commands in a separate thread.
87 */
88 class RPCExecutor : public QObject
89 {
90  Q_OBJECT
91 public:
93 
94 public Q_SLOTS:
95  void request(const QString &command, const WalletModel* wallet_model);
96 
97 Q_SIGNALS:
98  void reply(int category, const QString &command);
99 
100 private:
102 };
103 
107 class QtRPCTimerBase: public QObject, public RPCTimerBase
108 {
109  Q_OBJECT
110 public:
111  QtRPCTimerBase(std::function<void()>& _func, int64_t millis):
112  func(_func)
113  {
114  timer.setSingleShot(true);
115  connect(&timer, &QTimer::timeout, [this]{ func(); });
116  timer.start(millis);
117  }
118  ~QtRPCTimerBase() = default;
119 private:
120  QTimer timer;
121  std::function<void()> func;
122 };
123 
125 {
126 public:
127  ~QtRPCTimerInterface() = default;
128  const char *Name() override { return "Qt"; }
129  RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
130  {
131  return new QtRPCTimerBase(func, millis);
132  }
133 };
134 
135 class PeerIdViewDelegate : public QStyledItemDelegate
136 {
137  Q_OBJECT
138 public:
139  explicit PeerIdViewDelegate(QObject* parent = nullptr)
140  : QStyledItemDelegate(parent) {}
141 
142  QString displayText(const QVariant& value, const QLocale& locale) const override
143  {
144  // Additional spaces should visually separate right-aligned content
145  // from the next column to the right.
146  return value.toString() + QLatin1String(" ");
147  }
148 };
149 
150 #include <qt/rpcconsole.moc>
151 
172 bool RPCConsole::RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const WalletModel* wallet_model)
173 {
174  std::vector< std::vector<std::string> > stack;
175  stack.emplace_back();
176 
177  enum CmdParseState
178  {
179  STATE_EATING_SPACES,
180  STATE_EATING_SPACES_IN_ARG,
181  STATE_EATING_SPACES_IN_BRACKETS,
182  STATE_ARGUMENT,
183  STATE_SINGLEQUOTED,
184  STATE_DOUBLEQUOTED,
185  STATE_ESCAPE_OUTER,
186  STATE_ESCAPE_DOUBLEQUOTED,
187  STATE_COMMAND_EXECUTED,
188  STATE_COMMAND_EXECUTED_INNER
189  } state = STATE_EATING_SPACES;
190  std::string curarg;
191  UniValue lastResult;
192  unsigned nDepthInsideSensitive = 0;
193  size_t filter_begin_pos = 0, chpos;
194  std::vector<std::pair<size_t, size_t>> filter_ranges;
195 
196  auto add_to_current_stack = [&](const std::string& strArg) {
197  if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
198  nDepthInsideSensitive = 1;
199  filter_begin_pos = chpos;
200  }
201  // Make sure stack is not empty before adding something
202  if (stack.empty()) {
203  stack.emplace_back();
204  }
205  stack.back().push_back(strArg);
206  };
207 
208  auto close_out_params = [&]() {
209  if (nDepthInsideSensitive) {
210  if (!--nDepthInsideSensitive) {
211  assert(filter_begin_pos);
212  filter_ranges.emplace_back(filter_begin_pos, chpos);
213  filter_begin_pos = 0;
214  }
215  }
216  stack.pop_back();
217  };
218 
219  std::string strCommandTerminated = strCommand;
220  if (strCommandTerminated.back() != '\n')
221  strCommandTerminated += "\n";
222  for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
223  {
224  char ch = strCommandTerminated[chpos];
225  switch(state)
226  {
227  case STATE_COMMAND_EXECUTED_INNER:
228  case STATE_COMMAND_EXECUTED:
229  {
230  bool breakParsing = true;
231  switch(ch)
232  {
233  case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
234  default:
235  if (state == STATE_COMMAND_EXECUTED_INNER)
236  {
237  if (ch != ']')
238  {
239  // append char to the current argument (which is also used for the query command)
240  curarg += ch;
241  break;
242  }
243  if (curarg.size() && fExecute)
244  {
245  // if we have a value query, query arrays with index and objects with a string key
246  UniValue subelement;
247  if (lastResult.isArray())
248  {
249  const auto parsed{ToIntegral<size_t>(curarg)};
250  if (!parsed) {
251  throw std::runtime_error("Invalid result query");
252  }
253  subelement = lastResult[parsed.value()];
254  }
255  else if (lastResult.isObject())
256  subelement = lastResult.find_value(curarg);
257  else
258  throw std::runtime_error("Invalid result query"); //no array or object: abort
259  lastResult = subelement;
260  }
261 
262  state = STATE_COMMAND_EXECUTED;
263  break;
264  }
265  // don't break parsing when the char is required for the next argument
266  breakParsing = false;
267 
268  // pop the stack and return the result to the current command arguments
269  close_out_params();
270 
271  // don't stringify the json in case of a string to avoid doublequotes
272  if (lastResult.isStr())
273  curarg = lastResult.get_str();
274  else
275  curarg = lastResult.write(2);
276 
277  // if we have a non empty result, use it as stack argument otherwise as general result
278  if (curarg.size())
279  {
280  if (stack.size())
281  add_to_current_stack(curarg);
282  else
283  strResult = curarg;
284  }
285  curarg.clear();
286  // assume eating space state
287  state = STATE_EATING_SPACES;
288  }
289  if (breakParsing)
290  break;
291  [[fallthrough]];
292  }
293  case STATE_ARGUMENT: // In or after argument
294  case STATE_EATING_SPACES_IN_ARG:
295  case STATE_EATING_SPACES_IN_BRACKETS:
296  case STATE_EATING_SPACES: // Handle runs of whitespace
297  switch(ch)
298  {
299  case '"': state = STATE_DOUBLEQUOTED; break;
300  case '\'': state = STATE_SINGLEQUOTED; break;
301  case '\\': state = STATE_ESCAPE_OUTER; break;
302  case '(': case ')': case '\n':
303  if (state == STATE_EATING_SPACES_IN_ARG)
304  throw std::runtime_error("Invalid Syntax");
305  if (state == STATE_ARGUMENT)
306  {
307  if (ch == '(' && stack.size() && stack.back().size() > 0)
308  {
309  if (nDepthInsideSensitive) {
310  ++nDepthInsideSensitive;
311  }
312  stack.emplace_back();
313  }
314 
315  // don't allow commands after executed commands on baselevel
316  if (!stack.size())
317  throw std::runtime_error("Invalid Syntax");
318 
319  add_to_current_stack(curarg);
320  curarg.clear();
321  state = STATE_EATING_SPACES_IN_BRACKETS;
322  }
323  if ((ch == ')' || ch == '\n') && stack.size() > 0)
324  {
325  if (fExecute) {
326  // Convert argument list to JSON objects in method-dependent way,
327  // and pass it along with the method name to the dispatcher.
328  UniValue params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
329  std::string method = stack.back()[0];
330  std::string uri;
331 #ifdef ENABLE_WALLET
332  if (wallet_model) {
333  QByteArray encodedName = QUrl::toPercentEncoding(wallet_model->getWalletName());
334  uri = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
335  }
336 #endif
337  assert(node);
338  lastResult = node->executeRpc(method, params, uri);
339  }
340 
341  state = STATE_COMMAND_EXECUTED;
342  curarg.clear();
343  }
344  break;
345  case ' ': case ',': case '\t':
346  if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
347  throw std::runtime_error("Invalid Syntax");
348 
349  else if(state == STATE_ARGUMENT) // Space ends argument
350  {
351  add_to_current_stack(curarg);
352  curarg.clear();
353  }
354  if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
355  {
356  state = STATE_EATING_SPACES_IN_ARG;
357  break;
358  }
359  state = STATE_EATING_SPACES;
360  break;
361  default: curarg += ch; state = STATE_ARGUMENT;
362  }
363  break;
364  case STATE_SINGLEQUOTED: // Single-quoted string
365  switch(ch)
366  {
367  case '\'': state = STATE_ARGUMENT; break;
368  default: curarg += ch;
369  }
370  break;
371  case STATE_DOUBLEQUOTED: // Double-quoted string
372  switch(ch)
373  {
374  case '"': state = STATE_ARGUMENT; break;
375  case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
376  default: curarg += ch;
377  }
378  break;
379  case STATE_ESCAPE_OUTER: // '\' outside quotes
380  curarg += ch; state = STATE_ARGUMENT;
381  break;
382  case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
383  if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
384  curarg += ch; state = STATE_DOUBLEQUOTED;
385  break;
386  }
387  }
388  if (pstrFilteredOut) {
389  if (STATE_COMMAND_EXECUTED == state) {
390  assert(!stack.empty());
391  close_out_params();
392  }
393  *pstrFilteredOut = strCommand;
394  for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
395  pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
396  }
397  }
398  switch(state) // final state
399  {
400  case STATE_COMMAND_EXECUTED:
401  if (lastResult.isStr())
402  strResult = lastResult.get_str();
403  else
404  strResult = lastResult.write(2);
405  [[fallthrough]];
406  case STATE_ARGUMENT:
407  case STATE_EATING_SPACES:
408  return true;
409  default: // ERROR to end in one of the other states
410  return false;
411  }
412 }
413 
414 void RPCExecutor::request(const QString &command, const WalletModel* wallet_model)
415 {
416  try
417  {
418  std::string result;
419  std::string executableCommand = command.toStdString() + "\n";
420 
421  // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply.
422  if(executableCommand == "help-console\n") {
423  Q_EMIT reply(RPCConsole::CMD_REPLY, QString(("\n"
424  "This console accepts RPC commands using the standard syntax.\n"
425  " example: getblockhash 0\n\n"
426 
427  "This console can also accept RPC commands using the parenthesized syntax.\n"
428  " example: getblockhash(0)\n\n"
429 
430  "Commands may be nested when specified with the parenthesized syntax.\n"
431  " example: getblock(getblockhash(0) 1)\n\n"
432 
433  "A space or a comma can be used to delimit arguments for either syntax.\n"
434  " example: getblockhash 0\n"
435  " getblockhash,0\n\n"
436 
437  "Named results can be queried with a non-quoted key string in brackets using the parenthesized syntax.\n"
438  " example: getblock(getblockhash(0) 1)[tx]\n\n"
439 
440  "Results without keys can be queried with an integer in brackets using the parenthesized syntax.\n"
441  " example: getblock(getblockhash(0),1)[tx][0]\n\n")));
442  return;
443  }
444  if (!RPCConsole::RPCExecuteCommandLine(m_node, result, executableCommand, nullptr, wallet_model)) {
445  Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
446  return;
447  }
448 
449  Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
450  }
451  catch (UniValue& objError)
452  {
453  try // Nice formatting for standard-format error
454  {
455  int code = objError.find_value("code").getInt<int>();
456  std::string message = objError.find_value("message").get_str();
457  Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
458  }
459  catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
460  { // Show raw JSON object
461  Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
462  }
463  }
464  catch (const std::exception& e)
465  {
466  Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
467  }
468 }
469 
470 RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) :
471  QWidget(parent),
472  m_node(node),
473  ui(new Ui::RPCConsole),
474  platformStyle(_platformStyle)
475 {
476  ui->setupUi(this);
477  QSettings settings;
478 #ifdef ENABLE_WALLET
480  // RPCConsole widget is a window.
481  if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) {
482  // Restore failed (perhaps missing setting), center the window
483  move(QGuiApplication::primaryScreen()->availableGeometry().center() - frameGeometry().center());
484  }
485  ui->splitter->restoreState(settings.value("RPCConsoleWindowPeersTabSplitterSizes").toByteArray());
486  } else
487 #endif // ENABLE_WALLET
488  {
489  // RPCConsole is a child widget.
490  ui->splitter->restoreState(settings.value("RPCConsoleWidgetPeersTabSplitterSizes").toByteArray());
491  }
492 
493  m_peer_widget_header_state = settings.value("PeersTabPeerHeaderState").toByteArray();
494  m_banlist_widget_header_state = settings.value("PeersTabBanlistHeaderState").toByteArray();
495 
496  constexpr QChar nonbreaking_hyphen(8209);
497  const std::vector<QString> CONNECTION_TYPE_DOC{
498  //: Explanatory text for an inbound peer connection.
499  tr("Inbound: initiated by peer"),
500  /*: Explanatory text for an outbound peer connection that
501  relays all network information. This is the default behavior for
502  outbound connections. */
503  tr("Outbound Full Relay: default"),
504  /*: Explanatory text for an outbound peer connection that relays
505  network information about blocks and not transactions or addresses. */
506  tr("Outbound Block Relay: does not relay transactions or addresses"),
507  /*: Explanatory text for an outbound peer connection that was
508  established manually through one of several methods. The numbered
509  arguments are stand-ins for the methods available to establish
510  manual connections. */
511  tr("Outbound Manual: added using RPC %1 or %2/%3 configuration options")
512  .arg("addnode")
513  .arg(QString(nonbreaking_hyphen) + "addnode")
514  .arg(QString(nonbreaking_hyphen) + "connect"),
515  /*: Explanatory text for a short-lived outbound peer connection that
516  is used to test the aliveness of known addresses. */
517  tr("Outbound Feeler: short-lived, for testing addresses"),
518  /*: Explanatory text for a short-lived outbound peer connection that is used
519  to request addresses from a peer. */
520  tr("Outbound Address Fetch: short-lived, for soliciting addresses")};
521  const QString connection_types_list{"<ul><li>" + Join(CONNECTION_TYPE_DOC, QString("</li><li>")) + "</li></ul>"};
522  ui->peerConnectionTypeLabel->setToolTip(ui->peerConnectionTypeLabel->toolTip().arg(connection_types_list));
523  const std::vector<QString> TRANSPORT_TYPE_DOC{
524  //: Explanatory text for "detecting" transport type.
525  tr("detecting: peer could be v1 or v2"),
526  //: Explanatory text for v1 transport type.
527  tr("v1: unencrypted, plaintext transport protocol"),
528  //: Explanatory text for v2 transport type.
529  tr("v2: BIP324 encrypted transport protocol")};
530  const QString transport_types_list{"<ul><li>" + Join(TRANSPORT_TYPE_DOC, QString("</li><li>")) + "</li></ul>"};
531  ui->peerTransportTypeLabel->setToolTip(ui->peerTransportTypeLabel->toolTip().arg(transport_types_list));
532  const QString hb_list{"<ul><li>\""
533  + ts.to + "\" – " + tr("we selected the peer for high bandwidth relay") + "</li><li>\""
534  + ts.from + "\" – " + tr("the peer selected us for high bandwidth relay") + "</li><li>\""
535  + ts.no + "\" – " + tr("no high bandwidth relay selected") + "</li></ul>"};
536  ui->peerHighBandwidthLabel->setToolTip(ui->peerHighBandwidthLabel->toolTip().arg(hb_list));
537  ui->dataDir->setToolTip(ui->dataDir->toolTip().arg(QString(nonbreaking_hyphen) + "datadir"));
538  ui->blocksDir->setToolTip(ui->blocksDir->toolTip().arg(QString(nonbreaking_hyphen) + "blocksdir"));
539  ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(CLIENT_NAME));
540 
542  ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
543  }
544  ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
545 
546  ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
547  //: Main shortcut to increase the RPC console font size.
548  ui->fontBiggerButton->setShortcut(tr("Ctrl++"));
549  //: Secondary shortcut to increase the RPC console font size.
550  GUIUtil::AddButtonShortcut(ui->fontBiggerButton, tr("Ctrl+="));
551 
552  ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
553  //: Main shortcut to decrease the RPC console font size.
554  ui->fontSmallerButton->setShortcut(tr("Ctrl+-"));
555  //: Secondary shortcut to decrease the RPC console font size.
556  GUIUtil::AddButtonShortcut(ui->fontSmallerButton, tr("Ctrl+_"));
557 
558  ui->promptIcon->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/prompticon")));
559 
560  // Install event filter for up and down arrow
561  ui->lineEdit->installEventFilter(this);
562  ui->lineEdit->setMaxLength(16 * 1024 * 1024);
563  ui->messagesWidget->installEventFilter(this);
564 
565  connect(ui->hidePeersDetailButton, &QAbstractButton::clicked, this, &RPCConsole::clearSelectedNode);
566  connect(ui->clearButton, &QAbstractButton::clicked, [this] { clear(); });
567  connect(ui->fontBiggerButton, &QAbstractButton::clicked, this, &RPCConsole::fontBigger);
568  connect(ui->fontSmallerButton, &QAbstractButton::clicked, this, &RPCConsole::fontSmaller);
569  connect(ui->btnClearTrafficGraph, &QPushButton::clicked, ui->trafficGraph, &TrafficGraphWidget::clear);
570 
571  // disable the wallet selector by default
572  ui->WalletSelector->setVisible(false);
573  ui->WalletSelectorLabel->setVisible(false);
574 
575  // Register RPC timer interface
577  // avoid accidentally overwriting an existing, non QTThread
578  // based timer interface
580 
583 
584  consoleFontSize = settings.value(fontSizeSettingsKey, QFont().pointSize()).toInt();
585  clear();
586 
588 
590 }
591 
593 {
594  QSettings settings;
595 #ifdef ENABLE_WALLET
597  // RPCConsole widget is a window.
598  settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
599  settings.setValue("RPCConsoleWindowPeersTabSplitterSizes", ui->splitter->saveState());
600  } else
601 #endif // ENABLE_WALLET
602  {
603  // RPCConsole is a child widget.
604  settings.setValue("RPCConsoleWidgetPeersTabSplitterSizes", ui->splitter->saveState());
605  }
606 
607  settings.setValue("PeersTabPeerHeaderState", m_peer_widget_header_state);
608  settings.setValue("PeersTabBanlistHeaderState", m_banlist_widget_header_state);
609 
611  delete rpcTimerInterface;
612  delete ui;
613 }
614 
615 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
616 {
617  if(event->type() == QEvent::KeyPress) // Special key handling
618  {
619  QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
620  int key = keyevt->key();
621  Qt::KeyboardModifiers mod = keyevt->modifiers();
622  switch(key)
623  {
624  case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
625  case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
626  case Qt::Key_PageUp: /* pass paging keys to messages widget */
627  case Qt::Key_PageDown:
628  if (obj == ui->lineEdit) {
629  QApplication::sendEvent(ui->messagesWidget, keyevt);
630  return true;
631  }
632  break;
633  case Qt::Key_Return:
634  case Qt::Key_Enter:
635  // forward these events to lineEdit
636  if (obj == autoCompleter->popup()) {
637  QApplication::sendEvent(ui->lineEdit, keyevt);
638  autoCompleter->popup()->hide();
639  return true;
640  }
641  break;
642  default:
643  // Typing in messages widget brings focus to line edit, and redirects key there
644  // Exclude most combinations and keys that emit no text, except paste shortcuts
645  if(obj == ui->messagesWidget && (
646  (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
647  ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
648  ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
649  {
650  ui->lineEdit->setFocus();
651  QApplication::sendEvent(ui->lineEdit, keyevt);
652  return true;
653  }
654  }
655  }
656  return QWidget::eventFilter(obj, event);
657 }
658 
659 void RPCConsole::setClientModel(ClientModel *model, int bestblock_height, int64_t bestblock_date, double verification_progress)
660 {
661  clientModel = model;
662 
663  bool wallet_enabled{false};
664 #ifdef ENABLE_WALLET
665  wallet_enabled = WalletModel::isWalletEnabled();
666 #endif // ENABLE_WALLET
667  if (model && !wallet_enabled) {
668  // Show warning, for example if this is a prerelease version
669  connect(model, &ClientModel::alertsChanged, this, &RPCConsole::updateAlerts);
671  }
672 
673  ui->trafficGraph->setClientModel(model);
675  // Keep up to date with client
678 
679  setNumBlocks(bestblock_height, QDateTime::fromSecsSinceEpoch(bestblock_date), verification_progress, SyncType::BLOCK_SYNC);
681 
684 
686  updateTrafficStats(node.getTotalBytesRecv(), node.getTotalBytesSent());
688 
690 
691  // set up peer table
692  ui->peerWidget->setModel(model->peerTableSortProxy());
693  ui->peerWidget->verticalHeader()->hide();
694  ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
695  ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
696  ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
697 
698  if (!ui->peerWidget->horizontalHeader()->restoreState(m_peer_widget_header_state)) {
699  ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
700  ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
701  ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
702  }
703  ui->peerWidget->horizontalHeader()->setSectionResizeMode(PeerTableModel::Age, QHeaderView::ResizeToContents);
704  ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
705  ui->peerWidget->setItemDelegateForColumn(PeerTableModel::NetNodeId, new PeerIdViewDelegate(this));
706 
707  // create peer table context menu
708  peersTableContextMenu = new QMenu(this);
709  //: Context menu action to copy the address of a peer.
710  peersTableContextMenu->addAction(tr("&Copy address"), [this] {
711  GUIUtil::copyEntryData(ui->peerWidget, PeerTableModel::Address, Qt::DisplayRole);
712  });
713  peersTableContextMenu->addSeparator();
714  peersTableContextMenu->addAction(tr("&Disconnect"), this, &RPCConsole::disconnectSelectedNode);
715  peersTableContextMenu->addAction(ts.ban_for + " " + tr("1 &hour"), [this] { banSelectedNode(60 * 60); });
716  peersTableContextMenu->addAction(ts.ban_for + " " + tr("1 d&ay"), [this] { banSelectedNode(60 * 60 * 24); });
717  peersTableContextMenu->addAction(ts.ban_for + " " + tr("1 &week"), [this] { banSelectedNode(60 * 60 * 24 * 7); });
718  peersTableContextMenu->addAction(ts.ban_for + " " + tr("1 &year"), [this] { banSelectedNode(60 * 60 * 24 * 365); });
719  connect(ui->peerWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showPeersTableContextMenu);
720 
721  // peer table signal handling - update peer details when selecting new node
722  connect(ui->peerWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &RPCConsole::updateDetailWidget);
723  connect(model->getPeerTableModel(), &QAbstractItemModel::dataChanged, [this] { updateDetailWidget(); });
724 
725  // set up ban table
726  ui->banlistWidget->setModel(model->getBanTableModel());
727  ui->banlistWidget->verticalHeader()->hide();
728  ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
729  ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
730  ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
731 
732  if (!ui->banlistWidget->horizontalHeader()->restoreState(m_banlist_widget_header_state)) {
733  ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
734  ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
735  }
736  ui->banlistWidget->horizontalHeader()->setSectionResizeMode(BanTableModel::Address, QHeaderView::ResizeToContents);
737  ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
738 
739  // create ban table context menu
740  banTableContextMenu = new QMenu(this);
741  /*: Context menu action to copy the IP/Netmask of a banned peer.
742  IP/Netmask is the combination of a peer's IP address and its Netmask.
743  For IP address, see: https://en.wikipedia.org/wiki/IP_address. */
744  banTableContextMenu->addAction(tr("&Copy IP/Netmask"), [this] {
745  GUIUtil::copyEntryData(ui->banlistWidget, BanTableModel::Address, Qt::DisplayRole);
746  });
747  banTableContextMenu->addSeparator();
748  banTableContextMenu->addAction(tr("&Unban"), this, &RPCConsole::unbanSelectedNode);
749  connect(ui->banlistWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showBanTableContextMenu);
750 
751  // ban table signal handling - clear peer details when clicking a peer in the ban table
752  connect(ui->banlistWidget, &QTableView::clicked, this, &RPCConsole::clearSelectedNode);
753  // ban table signal handling - ensure ban table is shown or hidden (if empty)
754  connect(model->getBanTableModel(), &BanTableModel::layoutChanged, this, &RPCConsole::showOrHideBanTableIfRequired);
756 
757  // Provide initial values
758  ui->clientVersion->setText(model->formatFullVersion());
759  ui->clientUserAgent->setText(model->formatSubVersion());
760  ui->dataDir->setText(model->dataDir());
761  ui->blocksDir->setText(model->blocksDir());
762  ui->startupTime->setText(model->formatClientStartupTime());
763  ui->networkName->setText(QString::fromStdString(Params().GetChainTypeString()));
764 
765  //Setup autocomplete and attach it
766  QStringList wordList;
767  std::vector<std::string> commandList = m_node.listRpcCommands();
768  for (size_t i = 0; i < commandList.size(); ++i)
769  {
770  wordList << commandList[i].c_str();
771  wordList << ("help " + commandList[i]).c_str();
772  }
773 
774  wordList << "help-console";
775  wordList.sort();
776  autoCompleter = new QCompleter(wordList, this);
777  autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
778  // ui->lineEdit is initially disabled because running commands is only
779  // possible from now on.
780  ui->lineEdit->setEnabled(true);
781  ui->lineEdit->setCompleter(autoCompleter);
782  autoCompleter->popup()->installEventFilter(this);
783  // Start thread to execute RPC commands.
784  startExecutor();
785  }
786  if (!model) {
787  // Client model is being set to 0, this means shutdown() is about to be called.
788  thread.quit();
789  thread.wait();
790  }
791 }
792 
793 #ifdef ENABLE_WALLET
794 void RPCConsole::addWallet(WalletModel * const walletModel)
795 {
796  // use name for text and wallet model for internal data object (to allow to move to a wallet id later)
797  ui->WalletSelector->addItem(walletModel->getDisplayName(), QVariant::fromValue(walletModel));
798  if (ui->WalletSelector->count() == 2) {
799  // First wallet added, set to default to match wallet RPC behavior
800  ui->WalletSelector->setCurrentIndex(1);
801  }
802  if (ui->WalletSelector->count() > 2) {
803  ui->WalletSelector->setVisible(true);
804  ui->WalletSelectorLabel->setVisible(true);
805  }
806 }
807 
808 void RPCConsole::removeWallet(WalletModel * const walletModel)
809 {
810  ui->WalletSelector->removeItem(ui->WalletSelector->findData(QVariant::fromValue(walletModel)));
811  if (ui->WalletSelector->count() == 2) {
812  ui->WalletSelector->setVisible(false);
813  ui->WalletSelectorLabel->setVisible(false);
814  }
815 }
816 
817 void RPCConsole::setCurrentWallet(WalletModel* const wallet_model)
818 {
819  QVariant data = QVariant::fromValue(wallet_model);
820  ui->WalletSelector->setCurrentIndex(ui->WalletSelector->findData(data));
821 }
822 #endif
823 
824 static QString categoryClass(int category)
825 {
826  switch(category)
827  {
828  case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
829  case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
830  case RPCConsole::CMD_ERROR: return "cmd-error"; break;
831  default: return "misc";
832  }
833 }
834 
836 {
838 }
839 
841 {
843 }
844 
845 void RPCConsole::setFontSize(int newSize)
846 {
847  QSettings settings;
848 
849  //don't allow an insane font size
850  if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
851  return;
852 
853  // temp. store the console content
854  QString str = ui->messagesWidget->toHtml();
855 
856  // replace font tags size in current content
857  str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
858 
859  // store the new font size
860  consoleFontSize = newSize;
861  settings.setValue(fontSizeSettingsKey, consoleFontSize);
862 
863  // clear console (reset icon sizes, default stylesheet) and re-add the content
864  float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
865  clear(/*keep_prompt=*/true);
866  ui->messagesWidget->setHtml(str);
867  ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
868 }
869 
870 void RPCConsole::clear(bool keep_prompt)
871 {
872  ui->messagesWidget->clear();
873  if (!keep_prompt) ui->lineEdit->clear();
874  ui->lineEdit->setFocus();
875 
876  // Add smoothly scaled icon images.
877  // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
878  for(int i=0; ICON_MAPPING[i].url; ++i)
879  {
880  ui->messagesWidget->document()->addResource(
881  QTextDocument::ImageResource,
882  QUrl(ICON_MAPPING[i].url),
883  platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
884  }
885 
886  // Set default style sheet
887 #ifdef Q_OS_MACOS
888  QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont(/*use_embedded_font=*/true));
889 #else
890  QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
891 #endif
892  ui->messagesWidget->document()->setDefaultStyleSheet(
893  QString(
894  "table { }"
895  "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
896  "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
897  "td.cmd-request { color: #006060; } "
898  "td.cmd-error { color: red; } "
899  ".secwarning { color: red; }"
900  "b { color: #006060; } "
901  ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
902  );
903 
904  static const QString welcome_message =
905  /*: RPC console welcome message.
906  Placeholders %7 and %8 are style tags for the warning content, and
907  they are not space separated from the rest of the text intentionally. */
908  tr("Welcome to the %1 RPC console.\n"
909  "Use up and down arrows to navigate history, and %2 to clear screen.\n"
910  "Use %3 and %4 to increase or decrease the font size.\n"
911  "Type %5 for an overview of available commands.\n"
912  "For more information on using this console, type %6.\n"
913  "\n"
914  "%7WARNING: Scammers have been active, telling users to type"
915  " commands here, stealing their wallet contents. Do not use this console"
916  " without fully understanding the ramifications of a command.%8")
917  .arg(CLIENT_NAME,
918  "<b>" + ui->clearButton->shortcut().toString(QKeySequence::NativeText) + "</b>",
919  "<b>" + ui->fontBiggerButton->shortcut().toString(QKeySequence::NativeText) + "</b>",
920  "<b>" + ui->fontSmallerButton->shortcut().toString(QKeySequence::NativeText) + "</b>",
921  "<b>help</b>",
922  "<b>help-console</b>",
923  "<span class=\"secwarning\">",
924  "<span>");
925 
926  message(CMD_REPLY, welcome_message, true);
927 }
928 
929 void RPCConsole::keyPressEvent(QKeyEvent *event)
930 {
931  if (windowType() != Qt::Widget && GUIUtil::IsEscapeOrBack(event->key())) {
932  close();
933  }
934 }
935 
936 void RPCConsole::changeEvent(QEvent* e)
937 {
938  if (e->type() == QEvent::PaletteChange) {
939  ui->clearButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove")));
940  ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/fontbigger")));
941  ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/fontsmaller")));
942  ui->promptIcon->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/prompticon")));
943 
944  for (int i = 0; ICON_MAPPING[i].url; ++i) {
945  ui->messagesWidget->document()->addResource(
946  QTextDocument::ImageResource,
947  QUrl(ICON_MAPPING[i].url),
948  platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize * 2, consoleFontSize * 2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
949  }
950  }
951 
952  QWidget::changeEvent(e);
953 }
954 
955 void RPCConsole::message(int category, const QString &message, bool html)
956 {
957  QTime time = QTime::currentTime();
958  QString timeString = time.toString();
959  QString out;
960  out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
961  out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
962  out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
963  if(html)
964  out += message;
965  else
966  out += GUIUtil::HtmlEscape(message, false);
967  out += "</td></tr></table>";
968  ui->messagesWidget->append(out);
969 }
970 
972 {
973  if (!clientModel) return;
974  QString connections = QString::number(clientModel->getNumConnections()) + " (";
975  connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
976  connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
977 
978  if(!clientModel->node().getNetworkActive()) {
979  connections += " (" + tr("Network activity disabled") + ")";
980  }
981 
982  ui->numberOfConnections->setText(connections);
983 
984  QString local_addresses;
985  std::map<CNetAddr, LocalServiceInfo> hosts = clientModel->getNetLocalAddresses();
986  for (const auto& [addr, info] : hosts) {
987  local_addresses += QString::fromStdString(addr.ToStringAddr());
988  if (!addr.IsI2P()) local_addresses += ":" + QString::number(info.nPort);
989  local_addresses += ", ";
990  }
991  local_addresses.chop(2); // remove last ", "
992  if (local_addresses.isEmpty()) local_addresses = tr("None");
993 
994  ui->localAddresses->setText(local_addresses);
995 }
996 
998 {
999  if (!clientModel)
1000  return;
1001 
1003 }
1004 
1005 void RPCConsole::setNetworkActive(bool networkActive)
1006 {
1008 }
1009 
1010 void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, SyncType synctype)
1011 {
1012  if (synctype == SyncType::BLOCK_SYNC) {
1013  ui->numberOfBlocks->setText(QString::number(count));
1014  ui->lastBlockTime->setText(blockDate.toString());
1015  }
1016 }
1017 
1018 void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage, size_t maxUsage)
1019 {
1020  ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
1021 
1022  const auto cur_usage_str = dynUsage < 1000000 ?
1023  QObject::tr("%1 kB").arg(dynUsage / 1000.0, 0, 'f', 2) :
1024  QObject::tr("%1 MB").arg(dynUsage / 1000000.0, 0, 'f', 2);
1025  const auto max_usage_str = QObject::tr("%1 MB").arg(maxUsage / 1000000.0, 0, 'f', 2);
1026 
1027  ui->mempoolSize->setText(cur_usage_str + " / " + max_usage_str);
1028 }
1029 
1031 {
1032  QString cmd = ui->lineEdit->text().trimmed();
1033 
1034  if (cmd.isEmpty()) {
1035  return;
1036  }
1037 
1038  std::string strFilteredCmd;
1039  try {
1040  std::string dummy;
1041  if (!RPCParseCommandLine(nullptr, dummy, cmd.toStdString(), false, &strFilteredCmd)) {
1042  // Failed to parse command, so we cannot even filter it for the history
1043  throw std::runtime_error("Invalid command line");
1044  }
1045  } catch (const std::exception& e) {
1046  QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
1047  return;
1048  }
1049 
1050  // A special case allows to request shutdown even a long-running command is executed.
1051  if (cmd == QLatin1String("stop")) {
1052  std::string dummy;
1053  RPCExecuteCommandLine(m_node, dummy, cmd.toStdString());
1054  return;
1055  }
1056 
1057  if (m_is_executing) {
1058  return;
1059  }
1060 
1061  ui->lineEdit->clear();
1062 
1063  WalletModel* wallet_model{nullptr};
1064 #ifdef ENABLE_WALLET
1065  wallet_model = ui->WalletSelector->currentData().value<WalletModel*>();
1066 
1067  if (m_last_wallet_model != wallet_model) {
1068  if (wallet_model) {
1069  message(CMD_REQUEST, tr("Executing command using \"%1\" wallet").arg(wallet_model->getWalletName()));
1070  } else {
1071  message(CMD_REQUEST, tr("Executing command without any wallet"));
1072  }
1073  m_last_wallet_model = wallet_model;
1074  }
1075 #endif // ENABLE_WALLET
1076 
1077  message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
1078  //: A console message indicating an entered command is currently being executed.
1079  message(CMD_REPLY, tr("Executing…"));
1080  m_is_executing = true;
1081 
1082  QMetaObject::invokeMethod(m_executor, [this, cmd, wallet_model] {
1083  m_executor->request(cmd, wallet_model);
1084  });
1085 
1086  cmd = QString::fromStdString(strFilteredCmd);
1087 
1088  // Remove command, if already in history
1089  history.removeOne(cmd);
1090  // Append command to history
1091  history.append(cmd);
1092  // Enforce maximum history size
1093  while (history.size() > CONSOLE_HISTORY) {
1094  history.removeFirst();
1095  }
1096  // Set pointer to end of history
1097  historyPtr = history.size();
1098 
1099  // Scroll console view to end
1100  scrollToEnd();
1101 }
1102 
1104 {
1105  // store current text when start browsing through the history
1106  if (historyPtr == history.size()) {
1107  cmdBeforeBrowsing = ui->lineEdit->text();
1108  }
1109 
1110  historyPtr += offset;
1111  if(historyPtr < 0)
1112  historyPtr = 0;
1113  if(historyPtr > history.size())
1114  historyPtr = history.size();
1115  QString cmd;
1116  if(historyPtr < history.size())
1117  cmd = history.at(historyPtr);
1118  else if (!cmdBeforeBrowsing.isNull()) {
1120  }
1121  ui->lineEdit->setText(cmd);
1122 }
1123 
1125 {
1126  m_executor = new RPCExecutor(m_node);
1127  m_executor->moveToThread(&thread);
1128 
1129  // Replies from executor object must go to this object
1130  connect(m_executor, &RPCExecutor::reply, this, [this](int category, const QString& command) {
1131  // Remove "Executing…" message.
1132  ui->messagesWidget->undo();
1133  message(category, command);
1134  scrollToEnd();
1135  m_is_executing = false;
1136  });
1137 
1138  // Make sure executor object is deleted in its own thread
1139  connect(&thread, &QThread::finished, m_executor, &RPCExecutor::deleteLater);
1140 
1141  // Default implementation of QThread::run() simply spins up an event loop in the thread,
1142  // which is what we want.
1143  thread.start();
1144  QTimer::singleShot(0, m_executor, []() {
1145  util::ThreadRename("qt-rpcconsole");
1146  });
1147 }
1148 
1150 {
1151  if (ui->tabWidget->widget(index) == ui->tab_console) {
1152  ui->lineEdit->setFocus();
1153  }
1154 }
1155 
1157 {
1159 }
1160 
1162 {
1163  QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
1164  scrollbar->setValue(scrollbar->maximum());
1165 }
1166 
1168 {
1169  const int multiplier = 5; // each position on the slider represents 5 min
1170  int mins = value * multiplier;
1171  setTrafficGraphRange(mins);
1172 }
1173 
1175 {
1176  ui->trafficGraph->setGraphRange(std::chrono::minutes{mins});
1177  ui->lblGraphRange->setText(GUIUtil::formatDurationStr(std::chrono::minutes{mins}));
1178 }
1179 
1180 void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
1181 {
1182  ui->lblBytesIn->setText(GUIUtil::formatBytes(totalBytesIn));
1183  ui->lblBytesOut->setText(GUIUtil::formatBytes(totalBytesOut));
1184 }
1185 
1187 {
1188  const QList<QModelIndex> selected_peers = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1189  if (!clientModel || !clientModel->getPeerTableModel() || selected_peers.size() != 1) {
1190  ui->peersTabRightPanel->hide();
1191  ui->peerHeading->setText(tr("Select a peer to view detailed information."));
1192  return;
1193  }
1194  const auto stats = selected_peers.first().data(PeerTableModel::StatsRole).value<CNodeCombinedStats*>();
1195  // update the detail ui with latest node information
1196  QString peerAddrDetails(QString::fromStdString(stats->nodeStats.m_addr_name) + " ");
1197  peerAddrDetails += tr("(peer: %1)").arg(QString::number(stats->nodeStats.nodeid));
1198  if (!stats->nodeStats.addrLocal.empty())
1199  peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
1200  ui->peerHeading->setText(peerAddrDetails);
1201  QString bip152_hb_settings;
1202  if (stats->nodeStats.m_bip152_highbandwidth_to) bip152_hb_settings = ts.to;
1203  if (stats->nodeStats.m_bip152_highbandwidth_from) bip152_hb_settings += (bip152_hb_settings.isEmpty() ? ts.from : QLatin1Char('/') + ts.from);
1204  if (bip152_hb_settings.isEmpty()) bip152_hb_settings = ts.no;
1205  ui->peerHighBandwidth->setText(bip152_hb_settings);
1206  const auto time_now{GetTime<std::chrono::seconds>()};
1207  ui->peerConnTime->setText(GUIUtil::formatDurationStr(time_now - stats->nodeStats.m_connected));
1208  ui->peerLastBlock->setText(TimeDurationField(time_now, stats->nodeStats.m_last_block_time));
1209  ui->peerLastTx->setText(TimeDurationField(time_now, stats->nodeStats.m_last_tx_time));
1210  ui->peerLastSend->setText(TimeDurationField(time_now, stats->nodeStats.m_last_send));
1211  ui->peerLastRecv->setText(TimeDurationField(time_now, stats->nodeStats.m_last_recv));
1212  ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes));
1213  ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes));
1214  ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.m_last_ping_time));
1215  ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.m_min_ping_time));
1216  if (stats->nodeStats.nVersion) {
1217  ui->peerVersion->setText(QString::number(stats->nodeStats.nVersion));
1218  }
1219  if (!stats->nodeStats.cleanSubVer.empty()) {
1220  ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
1221  }
1222  ui->peerConnectionType->setText(GUIUtil::ConnectionTypeToQString(stats->nodeStats.m_conn_type, /*prepend_direction=*/true));
1223  ui->peerTransportType->setText(QString::fromStdString(TransportTypeAsString(stats->nodeStats.m_transport_type)));
1224  if (stats->nodeStats.m_transport_type == TransportProtocolType::V2) {
1225  ui->peerSessionIdLabel->setVisible(true);
1226  ui->peerSessionId->setVisible(true);
1227  ui->peerSessionId->setText(QString::fromStdString(stats->nodeStats.m_session_id));
1228  } else {
1229  ui->peerSessionIdLabel->setVisible(false);
1230  ui->peerSessionId->setVisible(false);
1231  }
1232  ui->peerNetwork->setText(GUIUtil::NetworkToQString(stats->nodeStats.m_network));
1233  if (stats->nodeStats.m_permission_flags == NetPermissionFlags::None) {
1234  ui->peerPermissions->setText(ts.na);
1235  } else {
1236  QStringList permissions;
1237  for (const auto& permission : NetPermissions::ToStrings(stats->nodeStats.m_permission_flags)) {
1238  permissions.append(QString::fromStdString(permission));
1239  }
1240  ui->peerPermissions->setText(permissions.join(" & "));
1241  }
1242  ui->peerMappedAS->setText(stats->nodeStats.m_mapped_as != 0 ? QString::number(stats->nodeStats.m_mapped_as) : ts.na);
1243 
1244  // This check fails for example if the lock was busy and
1245  // nodeStateStats couldn't be fetched.
1246  if (stats->fNodeStateStatsAvailable) {
1247  ui->timeoffset->setText(GUIUtil::formatTimeOffset(Ticks<std::chrono::seconds>(stats->nodeStateStats.time_offset)));
1248  ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStateStats.their_services));
1249  // Sync height is init to -1
1250  if (stats->nodeStateStats.nSyncHeight > -1) {
1251  ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
1252  } else {
1253  ui->peerSyncHeight->setText(ts.unknown);
1254  }
1255  // Common height is init to -1
1256  if (stats->nodeStateStats.nCommonHeight > -1) {
1257  ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
1258  } else {
1259  ui->peerCommonHeight->setText(ts.unknown);
1260  }
1261  ui->peerHeight->setText(QString::number(stats->nodeStateStats.m_starting_height));
1262  ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStateStats.m_ping_wait));
1263  ui->peerAddrRelayEnabled->setText(stats->nodeStateStats.m_addr_relay_enabled ? ts.yes : ts.no);
1264  ui->peerAddrProcessed->setText(QString::number(stats->nodeStateStats.m_addr_processed));
1265  ui->peerAddrRateLimited->setText(QString::number(stats->nodeStateStats.m_addr_rate_limited));
1266  ui->peerRelayTxes->setText(stats->nodeStateStats.m_relay_txs ? ts.yes : ts.no);
1267  }
1268 
1269  ui->hidePeersDetailButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove")));
1270  ui->peersTabRightPanel->show();
1271 }
1272 
1273 void RPCConsole::resizeEvent(QResizeEvent *event)
1274 {
1275  QWidget::resizeEvent(event);
1276 }
1277 
1278 void RPCConsole::showEvent(QShowEvent *event)
1279 {
1280  QWidget::showEvent(event);
1281 
1283  return;
1284 
1285  // start PeerTableModel auto refresh
1287 }
1288 
1289 void RPCConsole::hideEvent(QHideEvent *event)
1290 {
1291  // It is too late to call QHeaderView::saveState() in ~RPCConsole(), as all of
1292  // the columns of QTableView child widgets will have zero width at that moment.
1293  m_peer_widget_header_state = ui->peerWidget->horizontalHeader()->saveState();
1294  m_banlist_widget_header_state = ui->banlistWidget->horizontalHeader()->saveState();
1295 
1296  QWidget::hideEvent(event);
1297 
1299  return;
1300 
1301  // stop PeerTableModel auto refresh
1303 }
1304 
1305 void RPCConsole::showPeersTableContextMenu(const QPoint& point)
1306 {
1307  QModelIndex index = ui->peerWidget->indexAt(point);
1308  if (index.isValid())
1309  peersTableContextMenu->exec(QCursor::pos());
1310 }
1311 
1312 void RPCConsole::showBanTableContextMenu(const QPoint& point)
1313 {
1314  QModelIndex index = ui->banlistWidget->indexAt(point);
1315  if (index.isValid())
1316  banTableContextMenu->exec(QCursor::pos());
1317 }
1318 
1320 {
1321  // Get selected peer addresses
1322  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1323  for(int i = 0; i < nodes.count(); i++)
1324  {
1325  // Get currently selected peer address
1326  NodeId id = nodes.at(i).data().toLongLong();
1327  // Find the node, disconnect it and clear the selected node
1328  if(m_node.disconnectById(id))
1330  }
1331 }
1332 
1334 {
1335  if (!clientModel)
1336  return;
1337 
1338  for (const QModelIndex& peer : GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId)) {
1339  // Find possible nodes, ban it and clear the selected node
1340  const auto stats = peer.data(PeerTableModel::StatsRole).value<CNodeCombinedStats*>();
1341  if (stats) {
1342  m_node.ban(stats->nodeStats.addr, bantime);
1343  m_node.disconnectByAddress(stats->nodeStats.addr);
1344  }
1345  }
1348 }
1349 
1351 {
1352  if (!clientModel)
1353  return;
1354 
1355  // Get selected ban addresses
1356  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
1357  BanTableModel* ban_table_model{clientModel->getBanTableModel()};
1358  bool unbanned{false};
1359  for (const auto& node_index : nodes) {
1360  unbanned |= ban_table_model->unban(node_index);
1361  }
1362  if (unbanned) {
1363  ban_table_model->refresh();
1364  }
1365 }
1366 
1368 {
1369  ui->peerWidget->selectionModel()->clearSelection();
1370  cachedNodeids.clear();
1372 }
1373 
1375 {
1376  if (!clientModel)
1377  return;
1378 
1379  bool visible = clientModel->getBanTableModel()->shouldShow();
1380  ui->banlistWidget->setVisible(visible);
1381  ui->banHeading->setVisible(visible);
1382 }
1383 
1385 {
1386  ui->tabWidget->setCurrentIndex(int(tabType));
1387 }
1388 
1389 QString RPCConsole::tabTitle(TabTypes tab_type) const
1390 {
1391  return ui->tabWidget->tabText(int(tab_type));
1392 }
1393 
1394 QKeySequence RPCConsole::tabShortcut(TabTypes tab_type) const
1395 {
1396  switch (tab_type) {
1397  case TabTypes::INFO: return QKeySequence(tr("Ctrl+I"));
1398  case TabTypes::CONSOLE: return QKeySequence(tr("Ctrl+T"));
1399  case TabTypes::GRAPH: return QKeySequence(tr("Ctrl+N"));
1400  case TabTypes::PEERS: return QKeySequence(tr("Ctrl+P"));
1401  } // no default case, so the compiler can warn about missing cases
1402 
1403  assert(false);
1404 }
1405 
1406 void RPCConsole::updateAlerts(const QString& warnings)
1407 {
1408  this->ui->label_alerts->setVisible(!warnings.isEmpty());
1409  this->ui->label_alerts->setText(warnings);
1410 }
1411 
1413 {
1414  const ChainType chain = Params().GetChainType();
1415  if (chain == ChainType::MAIN) return;
1416 
1417  const QString chainType = QString::fromStdString(Params().GetChainTypeString());
1418  const QString title = tr("Node window - [%1]").arg(chainType);
1419  this->setWindowTitle(title);
1420 }
void openDebugLogfile()
Definition: guiutil.cpp:436
QString formatClientStartupTime() const
bool isObject() const
Definition: univalue.h:86
QString formatPingTime(std::chrono::microseconds ping_time)
Format a CNodeStats.m_last_ping_time into a user-readable string or display N/A, if 0...
Definition: guiutil.cpp:775
void push_back(UniValue val)
Definition: univalue.cpp:104
BIP324 protocol.
QString formatSubVersion() const
Local Bitcoin RPC console.
Definition: rpcconsole.h:41
RPC timer "driver".
Definition: server.h:51
QString cmdBeforeBrowsing
Definition: rpcconsole.h:166
virtual bool getNetworkActive()=0
Get network active.
assert(!tx.IsCoinBase())
static bool isWalletEnabled()
void on_lineEdit_returnPressed()
RPCExecutor(interfaces::Node &node)
Definition: rpcconsole.cpp:92
void updateWindowTitle()
QString blocksDir() const
node::NodeContext m_node
Definition: bitcoin-gui.cpp:42
void showPeersTableContextMenu(const QPoint &point)
Show custom context menu on Peers tab.
WalletModel * m_last_wallet_model
Definition: rpcconsole.h:176
void updateDetailWidget()
show detailed information on ui about selected node
virtual void rpcUnsetTimerInterface(RPCTimerInterface *iface)=0
Unset RPC timer interface.
void setClientModel(ClientModel *model=nullptr, int bestblock_height=0, int64_t bestblock_date=0, double verification_progress=0.0)
Definition: rpcconsole.cpp:659
QStringList history
Definition: rpcconsole.h:164
interfaces::Node & m_node
Definition: rpcconsole.h:161
QThread thread
Definition: rpcconsole.h:174
void setNetworkActive(bool networkActive)
Set network state shown in the UI.
void scrollToEnd()
Scroll console view to end.
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:824
void networkActiveChanged(bool networkActive)
const auto cmd
static QString categoryClass(int category)
Definition: rpcconsole.cpp:824
void clearSelectedNode()
clear the selected node
const struct @8 ICON_MAPPING[]
RPCConsole(interfaces::Node &node, const PlatformStyle *platformStyle, QWidget *parent)
Definition: rpcconsole.cpp:470
const std::string & get_str() const
QIcon SingleColorIcon(const QString &filename) const
Colorize an icon (given filename) with the icon color.
bool isStr() const
Definition: univalue.h:83
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:249
void fontSmaller()
Definition: rpcconsole.cpp:840
QFont fixedPitchFont(bool use_embedded_font)
Definition: guiutil.cpp:100
void changeEvent(QEvent *e) override
Definition: rpcconsole.cpp:936
PeerTableModel * getPeerTableModel()
Int getInt() const
Definition: univalue.h:138
void disconnectSelectedNode()
Disconnect a selected node on the Peers tab.
void on_tabWidget_currentChanged(int index)
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
Definition: threadnames.cpp:57
void numConnectionsChanged(int count)
QString formatDurationStr(std::chrono::seconds dur)
Convert seconds into a QString with days, hours, mins, secs.
Definition: guiutil.cpp:736
virtual bool ban(const CNetAddr &net_addr, int64_t ban_time_offset)=0
Ban node.
virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface)=0
Set RPC timer interface if unset.
QString getStatusBarWarnings() const
Return warnings to be displayed in status bar.
QString tabTitle(TabTypes tab_type) const
void alertsChanged(const QString &warnings)
void clear(bool keep_prompt=false)
Definition: rpcconsole.cpp:870
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
Definition: client.cpp:366
RPCExecutor * m_executor
Definition: rpcconsole.h:175
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut)
std::string TransportTypeAsString(TransportProtocolType transport_type)
Convert TransportProtocolType enum to a string value.
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
const PlatformStyle *const platformStyle
Definition: rpcconsole.h:168
const char * url
Definition: rpcconsole.cpp:61
void reply(int category, const QString &command)
struct RPCConsole::TranslatedStrings ts
QMenu * peersTableContextMenu
Definition: rpcconsole.h:170
QString NetworkToQString(Network net)
Convert enum Network to QString.
Definition: guiutil.cpp:687
const char * source
Definition: rpcconsole.cpp:62
void browseHistory(int offset)
Go forward or back in history.
void resizeEvent(QResizeEvent *event) override
ChainType
Definition: chaintype.h:11
void mempoolSizeChanged(long count, size_t mempoolSizeInBytes, size_t mempoolMaxSizeInBytes)
void message(int category, const QString &msg)
Append the message to the message widget.
Definition: rpcconsole.h:115
int getNumConnections(unsigned int flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:84
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Class for handling RPC timers (used for e.g.
Definition: rpcconsole.cpp:107
QByteArray m_banlist_widget_header_state
Definition: rpcconsole.h:179
const int CONSOLE_HISTORY
Definition: rpcconsole.cpp:55
void handleCloseWindowShortcut(QWidget *w)
Definition: guiutil.cpp:431
void setMempoolSize(long numberOfTxs, size_t dynUsage, size_t maxUsage)
Set size (number of transactions and memory usage) of the mempool in the UI.
void setTabFocus(enum TabTypes tabType)
set which tab has the focus (is visible)
bool m_is_executing
Definition: rpcconsole.h:177
void numBlocksChanged(int count, const QDateTime &blockDate, double nVerificationProgress, SyncType header, SynchronizationState sync_state)
QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction)
Convert enum ConnectionType to QString.
Definition: guiutil.cpp:707
BanTableModel * getBanTableModel()
interfaces::Node & node() const
Definition: clientmodel.h:66
int historyPtr
Definition: rpcconsole.h:165
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
RPCTimerInterface * rpcTimerInterface
Definition: rpcconsole.h:169
virtual bool disconnectByAddress(const CNetAddr &net_addr)=0
Disconnect node by address.
void updateNetworkState()
Update UI with latest network info from model.
Definition: rpcconsole.cpp:971
int64_t NodeId
Definition: net.h:97
QByteArray m_peer_widget_header_state
Definition: rpcconsole.h:178
QString displayText(const QVariant &value, const QLocale &locale) const override
Definition: rpcconsole.cpp:142
QString getWalletName() const
~QtRPCTimerInterface()=default
void on_openDebugLogfileButton_clicked()
open the debug.log from the current datadir
const char * Name() override
Implementation name.
Definition: rpcconsole.cpp:128
void copyEntryData(const QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:264
QtRPCTimerBase(std::function< void()> &_func, int64_t millis)
Definition: rpcconsole.cpp:111
Model for Bitcoin network client.
Definition: clientmodel.h:56
void unbanSelectedNode()
Unban a selected node on the Bans tab.
ClientModel * clientModel
Definition: rpcconsole.h:163
QMenu * banTableContextMenu
Definition: rpcconsole.h:171
void setTrafficGraphRange(int mins)
SyncType
Definition: clientmodel.h:42
QKeySequence tabShortcut(TabTypes tab_type) const
Definition: messages.h:20
bool IsEscapeOrBack(int key)
Definition: guiutil.h:430
void showOrHideBanTableIfRequired()
Hides ban table if no bans are present.
void fontBigger()
Definition: rpcconsole.cpp:835
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.cpp:42
void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
update traffic statistics
QList< NodeId > cachedNodeids
Definition: rpcconsole.h:167
ChainType GetChainType() const
Return the chain type.
Definition: chainparams.h:115
void setFontSize(int newSize)
Definition: rpcconsole.cpp:845
std::function< void()> func
Definition: rpcconsole.cpp:121
PeerIdViewDelegate(QObject *parent=nullptr)
Definition: rpcconsole.cpp:139
const auto command
auto result
Definition: common-types.h:74
void setNumConnections(int count)
Set number of connections shown in the UI.
Definition: rpcconsole.cpp:997
void startExecutor()
QImage SingleColorImage(const QString &filename) const
Colorize an image (given filename) with the icon color.
const CChainParams & Params()
Return the currently selected parameters.
static bool RPCParseCommandLine(interfaces::Node *node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string *const pstrFilteredOut=nullptr, const WalletModel *wallet_model=nullptr)
Split shell command line into a list of arguments and optionally execute the command(s).
Definition: rpcconsole.cpp:172
interfaces::Node & m_node
Definition: rpcconsole.cpp:101
Interface to Bitcoin wallet from Qt view code.
Definition: walletmodel.h:47
virtual std::vector< std::string > listRpcCommands()=0
List rpc commands.
~QtRPCTimerBase()=default
bool unban(const QModelIndex &index)
QString formatServicesStr(quint64 mask)
Format CNodeStats.nServices bitmask into a user-readable string.
Definition: guiutil.cpp:761
void on_sldGraphRange_valueChanged(int value)
change the time range of the network traffic graph
Qt model providing information about banned peers, similar to the "getpeerinfo" RPC call...
Definition: bantablemodel.h:43
void banSelectedNode(int bantime)
Ban a selected node on the Peers tab.
void setNumBlocks(int count, const QDateTime &blockDate, double nVerificationProgress, SyncType synctype)
Set number of blocks and last block date shown in the UI.
Ui::RPCConsole *const ui
Definition: rpcconsole.h:162
void updateAlerts(const QString &warnings)
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:42
const int INITIAL_TRAFFIC_GRAPH_MINS
Definition: rpcconsole.cpp:56
QString TimeDurationField(std::chrono::seconds time_now, std::chrono::seconds time_at_event) const
Helper for the output of a time duration field.
Definition: rpcconsole.h:185
static int count
const char fontSizeSettingsKey[]
Definition: rpcconsole.cpp:58
int consoleFontSize
Definition: rpcconsole.h:172
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
Definition: rpcconsole.cpp:129
QString getDisplayName() const
void request(const QString &command, const WalletModel *wallet_model)
Definition: rpcconsole.cpp:414
const QSize FONT_RANGE(4, 40)
QString formatTimeOffset(int64_t time_offset)
Format a CNodeStateStats.time_offset into a user-readable string.
Definition: guiutil.cpp:782
static bool RPCExecuteCommandLine(interfaces::Node &node, std::string &strResult, const std::string &strCommand, std::string *const pstrFilteredOut=nullptr, const WalletModel *wallet_model=nullptr)
Definition: rpcconsole.h:50
QString dataDir() const
const std::vector< std::string > TRANSPORT_TYPE_DOC
Definition: net.cpp:51
PeerTableSortProxy * peerTableSortProxy()
virtual bool disconnectById(NodeId id)=0
Disconnect node by id.
void showEvent(QShowEvent *event) override
QCompleter * autoCompleter
Definition: rpcconsole.h:173
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:192
void AddButtonShortcut(QAbstractButton *button, const QKeySequence &shortcut)
Connects an additional shortcut to a QAbstractButton.
Definition: guiutil.cpp:144
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:70
bool isArray() const
Definition: univalue.h:85
bool getImagesOnButtons() const
Definition: platformstyle.h:21
void showBanTableContextMenu(const QPoint &point)
Show custom context menu on Bans tab.
void keyPressEvent(QKeyEvent *) override
Definition: rpcconsole.cpp:929
void hideEvent(QHideEvent *event) override
virtual bool eventFilter(QObject *obj, QEvent *event) override
Definition: rpcconsole.cpp:615
static std::vector< std::string > ToStrings(NetPermissionFlags flags)
QList< QModelIndex > getEntryData(const QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:277
QString formatFullVersion() const