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