BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
rpcconsole.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2018 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 <qt/bantablemodel.h>
13 #include <qt/clientmodel.h>
14 #include <qt/platformstyle.h>
15 #include <qt/walletmodel.h>
16 #include <chainparams.h>
17 #include <interfaces/node.h>
18 #include <netbase.h>
19 #include <rpc/server.h>
20 #include <rpc/client.h>
21 #include <util.h>
22 
23 #include <openssl/crypto.h>
24 
25 #include <univalue.h>
26 
27 #ifdef ENABLE_WALLET
28 #include <db_cxx.h>
29 #include <wallet/wallet.h>
30 #endif
31 
32 #include <QDesktopWidget>
33 #include <QKeyEvent>
34 #include <QMenu>
35 #include <QMessageBox>
36 #include <QScrollBar>
37 #include <QSettings>
38 #include <QSignalMapper>
39 #include <QTime>
40 #include <QTimer>
41 #include <QStringList>
42 
43 // TODO: add a scrollback limit, as there is currently none
44 // TODO: make it possible to filter out categories (esp debug messages when implemented)
45 // TODO: receive errors and debug messages through ClientModel
46 
47 const int CONSOLE_HISTORY = 50;
49 const QSize FONT_RANGE(4, 40);
50 const char fontSizeSettingsKey[] = "consoleFontSize";
51 
52 const struct {
53  const char *url;
54  const char *source;
55 } ICON_MAPPING[] = {
56  {"cmd-request", ":/icons/tx_input"},
57  {"cmd-reply", ":/icons/tx_output"},
58  {"cmd-error", ":/icons/tx_output"},
59  {"misc", ":/icons/tx_inout"},
60  {nullptr, nullptr}
61 };
62 
63 namespace {
64 
65 // don't add private key handling cmd's to the history
66 const QStringList historyFilter = QStringList()
67  << "importprivkey"
68  << "importmulti"
69  << "sethdseed"
70  << "signmessagewithprivkey"
71  << "signrawtransaction"
72  << "signrawtransactionwithkey"
73  << "walletpassphrase"
74  << "walletpassphrasechange"
75  << "encryptwallet";
76 
77 }
78 
79 /* Object for executing console RPC commands in a separate thread.
80 */
81 class RPCExecutor : public QObject
82 {
83  Q_OBJECT
84 public:
85  explicit RPCExecutor(interfaces::Node& node) : m_node(node) {}
86 
87 public Q_SLOTS:
88  void request(const QString &command, const QString &walletID);
89 
90 Q_SIGNALS:
91  void reply(int category, const QString &command);
92 
93 private:
95 };
96 
100 class QtRPCTimerBase: public QObject, public RPCTimerBase
101 {
102  Q_OBJECT
103 public:
104  QtRPCTimerBase(std::function<void()>& _func, int64_t millis):
105  func(_func)
106  {
107  timer.setSingleShot(true);
108  connect(&timer, &QTimer::timeout, [this]{ func(); });
109  timer.start(millis);
110  }
112 private:
113  QTimer timer;
114  std::function<void()> func;
115 };
116 
118 {
119 public:
121  const char *Name() { return "Qt"; }
122  RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis)
123  {
124  return new QtRPCTimerBase(func, millis);
125  }
126 };
127 
128 
129 #include <qt/rpcconsole.moc>
130 
151 bool RPCConsole::RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const std::string *walletID)
152 {
153  std::vector< std::vector<std::string> > stack;
154  stack.push_back(std::vector<std::string>());
155 
156  enum CmdParseState
157  {
158  STATE_EATING_SPACES,
159  STATE_EATING_SPACES_IN_ARG,
160  STATE_EATING_SPACES_IN_BRACKETS,
161  STATE_ARGUMENT,
162  STATE_SINGLEQUOTED,
163  STATE_DOUBLEQUOTED,
164  STATE_ESCAPE_OUTER,
165  STATE_ESCAPE_DOUBLEQUOTED,
166  STATE_COMMAND_EXECUTED,
167  STATE_COMMAND_EXECUTED_INNER
168  } state = STATE_EATING_SPACES;
169  std::string curarg;
170  UniValue lastResult;
171  unsigned nDepthInsideSensitive = 0;
172  size_t filter_begin_pos = 0, chpos;
173  std::vector<std::pair<size_t, size_t>> filter_ranges;
174 
175  auto add_to_current_stack = [&](const std::string& strArg) {
176  if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
177  nDepthInsideSensitive = 1;
178  filter_begin_pos = chpos;
179  }
180  // Make sure stack is not empty before adding something
181  if (stack.empty()) {
182  stack.push_back(std::vector<std::string>());
183  }
184  stack.back().push_back(strArg);
185  };
186 
187  auto close_out_params = [&]() {
188  if (nDepthInsideSensitive) {
189  if (!--nDepthInsideSensitive) {
190  assert(filter_begin_pos);
191  filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos));
192  filter_begin_pos = 0;
193  }
194  }
195  stack.pop_back();
196  };
197 
198  std::string strCommandTerminated = strCommand;
199  if (strCommandTerminated.back() != '\n')
200  strCommandTerminated += "\n";
201  for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
202  {
203  char ch = strCommandTerminated[chpos];
204  switch(state)
205  {
206  case STATE_COMMAND_EXECUTED_INNER:
207  case STATE_COMMAND_EXECUTED:
208  {
209  bool breakParsing = true;
210  switch(ch)
211  {
212  case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
213  default:
214  if (state == STATE_COMMAND_EXECUTED_INNER)
215  {
216  if (ch != ']')
217  {
218  // append char to the current argument (which is also used for the query command)
219  curarg += ch;
220  break;
221  }
222  if (curarg.size() && fExecute)
223  {
224  // if we have a value query, query arrays with index and objects with a string key
225  UniValue subelement;
226  if (lastResult.isArray())
227  {
228  for(char argch: curarg)
229  if (!std::isdigit(argch))
230  throw std::runtime_error("Invalid result query");
231  subelement = lastResult[atoi(curarg.c_str())];
232  }
233  else if (lastResult.isObject())
234  subelement = find_value(lastResult, curarg);
235  else
236  throw std::runtime_error("Invalid result query"); //no array or object: abort
237  lastResult = subelement;
238  }
239 
240  state = STATE_COMMAND_EXECUTED;
241  break;
242  }
243  // don't break parsing when the char is required for the next argument
244  breakParsing = false;
245 
246  // pop the stack and return the result to the current command arguments
247  close_out_params();
248 
249  // don't stringify the json in case of a string to avoid doublequotes
250  if (lastResult.isStr())
251  curarg = lastResult.get_str();
252  else
253  curarg = lastResult.write(2);
254 
255  // if we have a non empty result, use it as stack argument otherwise as general result
256  if (curarg.size())
257  {
258  if (stack.size())
259  add_to_current_stack(curarg);
260  else
261  strResult = curarg;
262  }
263  curarg.clear();
264  // assume eating space state
265  state = STATE_EATING_SPACES;
266  }
267  if (breakParsing)
268  break;
269  }
270  case STATE_ARGUMENT: // In or after argument
271  case STATE_EATING_SPACES_IN_ARG:
272  case STATE_EATING_SPACES_IN_BRACKETS:
273  case STATE_EATING_SPACES: // Handle runs of whitespace
274  switch(ch)
275  {
276  case '"': state = STATE_DOUBLEQUOTED; break;
277  case '\'': state = STATE_SINGLEQUOTED; break;
278  case '\\': state = STATE_ESCAPE_OUTER; break;
279  case '(': case ')': case '\n':
280  if (state == STATE_EATING_SPACES_IN_ARG)
281  throw std::runtime_error("Invalid Syntax");
282  if (state == STATE_ARGUMENT)
283  {
284  if (ch == '(' && stack.size() && stack.back().size() > 0)
285  {
286  if (nDepthInsideSensitive) {
287  ++nDepthInsideSensitive;
288  }
289  stack.push_back(std::vector<std::string>());
290  }
291 
292  // don't allow commands after executed commands on baselevel
293  if (!stack.size())
294  throw std::runtime_error("Invalid Syntax");
295 
296  add_to_current_stack(curarg);
297  curarg.clear();
298  state = STATE_EATING_SPACES_IN_BRACKETS;
299  }
300  if ((ch == ')' || ch == '\n') && stack.size() > 0)
301  {
302  if (fExecute) {
303  // Convert argument list to JSON objects in method-dependent way,
304  // and pass it along with the method name to the dispatcher.
305  UniValue params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
306  std::string method = stack.back()[0];
307  std::string uri;
308 #ifdef ENABLE_WALLET
309  if (walletID) {
310  QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(*walletID));
311  uri = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
312  }
313 #endif
314  assert(node);
315  lastResult = node->executeRpc(method, params, uri);
316  }
317 
318  state = STATE_COMMAND_EXECUTED;
319  curarg.clear();
320  }
321  break;
322  case ' ': case ',': case '\t':
323  if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
324  throw std::runtime_error("Invalid Syntax");
325 
326  else if(state == STATE_ARGUMENT) // Space ends argument
327  {
328  add_to_current_stack(curarg);
329  curarg.clear();
330  }
331  if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
332  {
333  state = STATE_EATING_SPACES_IN_ARG;
334  break;
335  }
336  state = STATE_EATING_SPACES;
337  break;
338  default: curarg += ch; state = STATE_ARGUMENT;
339  }
340  break;
341  case STATE_SINGLEQUOTED: // Single-quoted string
342  switch(ch)
343  {
344  case '\'': state = STATE_ARGUMENT; break;
345  default: curarg += ch;
346  }
347  break;
348  case STATE_DOUBLEQUOTED: // Double-quoted string
349  switch(ch)
350  {
351  case '"': state = STATE_ARGUMENT; break;
352  case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
353  default: curarg += ch;
354  }
355  break;
356  case STATE_ESCAPE_OUTER: // '\' outside quotes
357  curarg += ch; state = STATE_ARGUMENT;
358  break;
359  case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
360  if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
361  curarg += ch; state = STATE_DOUBLEQUOTED;
362  break;
363  }
364  }
365  if (pstrFilteredOut) {
366  if (STATE_COMMAND_EXECUTED == state) {
367  assert(!stack.empty());
368  close_out_params();
369  }
370  *pstrFilteredOut = strCommand;
371  for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
372  pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
373  }
374  }
375  switch(state) // final state
376  {
377  case STATE_COMMAND_EXECUTED:
378  if (lastResult.isStr())
379  strResult = lastResult.get_str();
380  else
381  strResult = lastResult.write(2);
382  case STATE_ARGUMENT:
383  case STATE_EATING_SPACES:
384  return true;
385  default: // ERROR to end in one of the other states
386  return false;
387  }
388 }
389 
390 void RPCExecutor::request(const QString &command, const QString &walletID)
391 {
392  try
393  {
394  std::string result;
395  std::string executableCommand = command.toStdString() + "\n";
396 
397  // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply.
398  if(executableCommand == "help-console\n")
399  {
400  Q_EMIT reply(RPCConsole::CMD_REPLY, QString(("\n"
401  "This console accepts RPC commands using the standard syntax.\n"
402  " example: getblockhash 0\n\n"
403 
404  "This console can also accept RPC commands using parenthesized syntax.\n"
405  " example: getblockhash(0)\n\n"
406 
407  "Commands may be nested when specified with the parenthesized syntax.\n"
408  " example: getblock(getblockhash(0) 1)\n\n"
409 
410  "A space or a comma can be used to delimit arguments for either syntax.\n"
411  " example: getblockhash 0\n"
412  " getblockhash,0\n\n"
413 
414  "Named results can be queried with a non-quoted key string in brackets.\n"
415  " example: getblock(getblockhash(0) true)[tx]\n\n"
416 
417  "Results without keys can be queried using an integer in brackets.\n"
418  " example: getblock(getblockhash(0),true)[tx][0]\n\n")));
419  return;
420  }
421  std::string wallet_id = walletID.toStdString();
422  if (!RPCConsole::RPCExecuteCommandLine(m_node, result, executableCommand, nullptr, walletID.isNull() ? nullptr : &wallet_id))
423  {
424  Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
425  return;
426  }
427 
428  Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
429  }
430  catch (UniValue& objError)
431  {
432  try // Nice formatting for standard-format error
433  {
434  int code = find_value(objError, "code").get_int();
435  std::string message = find_value(objError, "message").get_str();
436  Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
437  }
438  catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
439  { // Show raw JSON object
440  Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
441  }
442  }
443  catch (const std::exception& e)
444  {
445  Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
446  }
447 }
448 
449 RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) :
450  QWidget(parent),
451  m_node(node),
452  ui(new Ui::RPCConsole),
453  platformStyle(_platformStyle)
454 {
455  ui->setupUi(this);
456  QSettings settings;
457  if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) {
458  // Restore failed (perhaps missing setting), center the window
459  move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());
460  }
461 
462  QChar nonbreaking_hyphen(8209);
463  ui->dataDir->setToolTip(ui->dataDir->toolTip().arg(QString(nonbreaking_hyphen) + "datadir"));
464  ui->blocksDir->setToolTip(ui->blocksDir->toolTip().arg(QString(nonbreaking_hyphen) + "blocksdir"));
465  ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
466 
468  ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
469  }
470  ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
471  ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
472  ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
473 
474  // Install event filter for up and down arrow
475  ui->lineEdit->installEventFilter(this);
476  ui->messagesWidget->installEventFilter(this);
477 
478  connect(ui->clearButton, &QPushButton::clicked, this, &RPCConsole::clear);
479  connect(ui->fontBiggerButton, &QPushButton::clicked, this, &RPCConsole::fontBigger);
480  connect(ui->fontSmallerButton, &QPushButton::clicked, this, &RPCConsole::fontSmaller);
481  connect(ui->btnClearTrafficGraph, &QPushButton::clicked, ui->trafficGraph, &TrafficGraphWidget::clear);
482 
483  // disable the wallet selector by default
484  ui->WalletSelector->setVisible(false);
485  ui->WalletSelectorLabel->setVisible(false);
486 
487  // set library version labels
488 #ifdef ENABLE_WALLET
489  ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
490 #else
491  ui->label_berkeleyDBVersion->hide();
492  ui->berkeleyDBVersion->hide();
493 #endif
494  // Register RPC timer interface
496  // avoid accidentally overwriting an existing, non QTThread
497  // based timer interface
499 
501 
502  ui->detailWidget->hide();
503  ui->peerHeading->setText(tr("Select a peer to view detailed information."));
504 
505  consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
506  clear();
507 }
508 
510 {
511  QSettings settings;
512  settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
514  delete rpcTimerInterface;
515  delete ui;
516 }
517 
518 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
519 {
520  if(event->type() == QEvent::KeyPress) // Special key handling
521  {
522  QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
523  int key = keyevt->key();
524  Qt::KeyboardModifiers mod = keyevt->modifiers();
525  switch(key)
526  {
527  case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
528  case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
529  case Qt::Key_PageUp: /* pass paging keys to messages widget */
530  case Qt::Key_PageDown:
531  if(obj == ui->lineEdit)
532  {
533  QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
534  return true;
535  }
536  break;
537  case Qt::Key_Return:
538  case Qt::Key_Enter:
539  // forward these events to lineEdit
540  if(obj == autoCompleter->popup()) {
541  QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
542  autoCompleter->popup()->hide();
543  return true;
544  }
545  break;
546  default:
547  // Typing in messages widget brings focus to line edit, and redirects key there
548  // Exclude most combinations and keys that emit no text, except paste shortcuts
549  if(obj == ui->messagesWidget && (
550  (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
551  ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
552  ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
553  {
554  ui->lineEdit->setFocus();
555  QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
556  return true;
557  }
558  }
559  }
560  return QWidget::eventFilter(obj, event);
561 }
562 
564 {
565  clientModel = model;
566  ui->trafficGraph->setClientModel(model);
568  // Keep up to date with client
571 
572  interfaces::Node& node = clientModel->node();
573  setNumBlocks(node.getNumBlocks(), QDateTime::fromTime_t(node.getLastBlockTime()), node.getVerificationProgress(), false);
575 
578 
581 
583 
584  // set up peer table
585  ui->peerWidget->setModel(model->getPeerTableModel());
586  ui->peerWidget->verticalHeader()->hide();
587  ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
588  ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
589  ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
590  ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
591  ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
592  ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
593  ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
594  ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
595 
596  // create peer table context menu actions
597  QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
598  QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
599  QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
600  QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
601  QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
602 
603  // create peer table context menu
604  peersTableContextMenu = new QMenu(this);
605  peersTableContextMenu->addAction(disconnectAction);
606  peersTableContextMenu->addAction(banAction1h);
607  peersTableContextMenu->addAction(banAction24h);
608  peersTableContextMenu->addAction(banAction7d);
609  peersTableContextMenu->addAction(banAction365d);
610 
611  // Add a signal mapping to allow dynamic context menu arguments.
612  // We need to use int (instead of int64_t), because signal mapper only supports
613  // int or objects, which is okay because max bantime (1 year) is < int_max.
614  QSignalMapper* signalMapper = new QSignalMapper(this);
615  signalMapper->setMapping(banAction1h, 60*60);
616  signalMapper->setMapping(banAction24h, 60*60*24);
617  signalMapper->setMapping(banAction7d, 60*60*24*7);
618  signalMapper->setMapping(banAction365d, 60*60*24*365);
619  connect(banAction1h, &QAction::triggered, signalMapper, static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map));
620  connect(banAction24h, &QAction::triggered, signalMapper, static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map));
621  connect(banAction7d, &QAction::triggered, signalMapper, static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map));
622  connect(banAction365d, &QAction::triggered, signalMapper, static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map));
623  connect(signalMapper, static_cast<void (QSignalMapper::*)(int)>(&QSignalMapper::mapped), this, &RPCConsole::banSelectedNode);
624 
625  // peer table context menu signals
626  connect(ui->peerWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showPeersTableContextMenu);
627  connect(disconnectAction, &QAction::triggered, this, &RPCConsole::disconnectSelectedNode);
628 
629  // peer table signal handling - update peer details when selecting new node
630  connect(ui->peerWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &RPCConsole::peerSelected);
631  // peer table signal handling - update peer details when new nodes are added to the model
632  connect(model->getPeerTableModel(), &PeerTableModel::layoutChanged, this, &RPCConsole::peerLayoutChanged);
633  // peer table signal handling - cache selected node ids
634  connect(model->getPeerTableModel(), &PeerTableModel::layoutAboutToBeChanged, this, &RPCConsole::peerLayoutAboutToChange);
635 
636  // set up ban table
637  ui->banlistWidget->setModel(model->getBanTableModel());
638  ui->banlistWidget->verticalHeader()->hide();
639  ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
640  ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
641  ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
642  ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
643  ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
644  ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
645  ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
646 
647  // create ban table context menu action
648  QAction* unbanAction = new QAction(tr("&Unban"), this);
649 
650  // create ban table context menu
651  banTableContextMenu = new QMenu(this);
652  banTableContextMenu->addAction(unbanAction);
653 
654  // ban table context menu signals
655  connect(ui->banlistWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showBanTableContextMenu);
656  connect(unbanAction, &QAction::triggered, this, &RPCConsole::unbanSelectedNode);
657 
658  // ban table signal handling - clear peer details when clicking a peer in the ban table
659  connect(ui->banlistWidget, &QTableView::clicked, this, &RPCConsole::clearSelectedNode);
660  // ban table signal handling - ensure ban table is shown or hidden (if empty)
661  connect(model->getBanTableModel(), &BanTableModel::layoutChanged, this, &RPCConsole::showOrHideBanTableIfRequired);
663 
664  // Provide initial values
665  ui->clientVersion->setText(model->formatFullVersion());
666  ui->clientUserAgent->setText(model->formatSubVersion());
667  ui->dataDir->setText(model->dataDir());
668  ui->blocksDir->setText(model->blocksDir());
669  ui->startupTime->setText(model->formatClientStartupTime());
670  ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
671 
672  //Setup autocomplete and attach it
673  QStringList wordList;
674  std::vector<std::string> commandList = m_node.listRpcCommands();
675  for (size_t i = 0; i < commandList.size(); ++i)
676  {
677  wordList << commandList[i].c_str();
678  wordList << ("help " + commandList[i]).c_str();
679  }
680 
681  wordList << "help-console";
682  wordList.sort();
683  autoCompleter = new QCompleter(wordList, this);
684  autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
685  ui->lineEdit->setCompleter(autoCompleter);
686  autoCompleter->popup()->installEventFilter(this);
687  // Start thread to execute RPC commands.
688  startExecutor();
689  }
690  if (!model) {
691  // Client model is being set to 0, this means shutdown() is about to be called.
692  // Make sure we clean up the executor thread
693  Q_EMIT stopExecutor();
694  thread.wait();
695  }
696 }
697 
698 #ifdef ENABLE_WALLET
699 void RPCConsole::addWallet(WalletModel * const walletModel)
700 {
701  const QString name = walletModel->getWalletName();
702  // use name for text and internal data object (to allow to move to a wallet id later)
703  QString display_name = name.isEmpty() ? "["+tr("default wallet")+"]" : name;
704  ui->WalletSelector->addItem(display_name, name);
705  if (ui->WalletSelector->count() == 2 && !isVisible()) {
706  // First wallet added, set to default so long as the window isn't presently visible (and potentially in use)
707  ui->WalletSelector->setCurrentIndex(1);
708  }
709  if (ui->WalletSelector->count() > 2) {
710  ui->WalletSelector->setVisible(true);
711  ui->WalletSelectorLabel->setVisible(true);
712  }
713 }
714 
715 void RPCConsole::removeWallet(WalletModel * const walletModel)
716 {
717  const QString name = walletModel->getWalletName();
718  ui->WalletSelector->removeItem(ui->WalletSelector->findData(name));
719  if (ui->WalletSelector->count() == 2) {
720  ui->WalletSelector->setVisible(false);
721  ui->WalletSelectorLabel->setVisible(false);
722  }
723 }
724 #endif
725 
726 static QString categoryClass(int category)
727 {
728  switch(category)
729  {
730  case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
731  case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
732  case RPCConsole::CMD_ERROR: return "cmd-error"; break;
733  default: return "misc";
734  }
735 }
736 
738 {
740 }
741 
743 {
745 }
746 
747 void RPCConsole::setFontSize(int newSize)
748 {
749  QSettings settings;
750 
751  //don't allow an insane font size
752  if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
753  return;
754 
755  // temp. store the console content
756  QString str = ui->messagesWidget->toHtml();
757 
758  // replace font tags size in current content
759  str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
760 
761  // store the new font size
762  consoleFontSize = newSize;
763  settings.setValue(fontSizeSettingsKey, consoleFontSize);
764 
765  // clear console (reset icon sizes, default stylesheet) and re-add the content
766  float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
767  clear(false);
768  ui->messagesWidget->setHtml(str);
769  ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
770 }
771 
772 void RPCConsole::clear(bool clearHistory)
773 {
774  ui->messagesWidget->clear();
775  if(clearHistory)
776  {
777  history.clear();
778  historyPtr = 0;
779  }
780  ui->lineEdit->clear();
781  ui->lineEdit->setFocus();
782 
783  // Add smoothly scaled icon images.
784  // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
785  for(int i=0; ICON_MAPPING[i].url; ++i)
786  {
787  ui->messagesWidget->document()->addResource(
788  QTextDocument::ImageResource,
789  QUrl(ICON_MAPPING[i].url),
790  platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
791  }
792 
793  // Set default style sheet
794  QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
795  ui->messagesWidget->document()->setDefaultStyleSheet(
796  QString(
797  "table { }"
798  "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
799  "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
800  "td.cmd-request { color: #006060; } "
801  "td.cmd-error { color: red; } "
802  ".secwarning { color: red; }"
803  "b { color: #006060; } "
804  ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
805  );
806 
807 #ifdef Q_OS_MAC
808  QString clsKey = "(⌘)-L";
809 #else
810  QString clsKey = "Ctrl-L";
811 #endif
812 
813  message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
814  tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
815  tr("Type %1 for an overview of available commands.").arg("<b>help</b>") + "<br>" +
816  tr("For more information on using this console type %1.").arg("<b>help-console</b>") +
817  "<br><span class=\"secwarning\"><br>" +
818  tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
819  "</span>"),
820  true);
821 }
822 
823 void RPCConsole::keyPressEvent(QKeyEvent *event)
824 {
825  if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
826  {
827  close();
828  }
829 }
830 
831 void RPCConsole::message(int category, const QString &message, bool html)
832 {
833  QTime time = QTime::currentTime();
834  QString timeString = time.toString();
835  QString out;
836  out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
837  out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
838  out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
839  if(html)
840  out += message;
841  else
842  out += GUIUtil::HtmlEscape(message, false);
843  out += "</td></tr></table>";
844  ui->messagesWidget->append(out);
845 }
846 
848 {
849  QString connections = QString::number(clientModel->getNumConnections()) + " (";
850  connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
851  connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
852 
853  if(!clientModel->node().getNetworkActive()) {
854  connections += " (" + tr("Network activity disabled") + ")";
855  }
856 
857  ui->numberOfConnections->setText(connections);
858 }
859 
861 {
862  if (!clientModel)
863  return;
864 
866 }
867 
868 void RPCConsole::setNetworkActive(bool networkActive)
869 {
871 }
872 
873 void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers)
874 {
875  if (!headers) {
876  ui->numberOfBlocks->setText(QString::number(count));
877  ui->lastBlockTime->setText(blockDate.toString());
878  }
879 }
880 
881 void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
882 {
883  ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
884 
885  if (dynUsage < 1000000)
886  ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
887  else
888  ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
889 }
890 
892 {
893  QString cmd = ui->lineEdit->text();
894 
895  if(!cmd.isEmpty())
896  {
897  std::string strFilteredCmd;
898  try {
899  std::string dummy;
900  if (!RPCParseCommandLine(nullptr, dummy, cmd.toStdString(), false, &strFilteredCmd)) {
901  // Failed to parse command, so we cannot even filter it for the history
902  throw std::runtime_error("Invalid command line");
903  }
904  } catch (const std::exception& e) {
905  QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
906  return;
907  }
908 
909  ui->lineEdit->clear();
910 
911  cmdBeforeBrowsing = QString();
912 
913  QString walletID;
914 #ifdef ENABLE_WALLET
915  const int wallet_index = ui->WalletSelector->currentIndex();
916  if (wallet_index > 0) {
917  walletID = (QString)ui->WalletSelector->itemData(wallet_index).value<QString>();
918  }
919 
920  if (m_last_wallet_id != walletID) {
921  if (walletID.isNull()) {
922  message(CMD_REQUEST, tr("Executing command without any wallet"));
923  } else {
924  message(CMD_REQUEST, tr("Executing command using \"%1\" wallet").arg(walletID));
925  }
926  m_last_wallet_id = walletID;
927  }
928 #endif
929 
930  message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
931  Q_EMIT cmdRequest(cmd, walletID);
932 
933  cmd = QString::fromStdString(strFilteredCmd);
934 
935  // Remove command, if already in history
936  history.removeOne(cmd);
937  // Append command to history
938  history.append(cmd);
939  // Enforce maximum history size
940  while(history.size() > CONSOLE_HISTORY)
941  history.removeFirst();
942  // Set pointer to end of history
943  historyPtr = history.size();
944 
945  // Scroll console view to end
946  scrollToEnd();
947  }
948 }
949 
951 {
952  // store current text when start browsing through the history
953  if (historyPtr == history.size()) {
954  cmdBeforeBrowsing = ui->lineEdit->text();
955  }
956 
957  historyPtr += offset;
958  if(historyPtr < 0)
959  historyPtr = 0;
960  if(historyPtr > history.size())
961  historyPtr = history.size();
962  QString cmd;
963  if(historyPtr < history.size())
964  cmd = history.at(historyPtr);
965  else if (!cmdBeforeBrowsing.isNull()) {
966  cmd = cmdBeforeBrowsing;
967  }
968  ui->lineEdit->setText(cmd);
969 }
970 
972 {
973  RPCExecutor *executor = new RPCExecutor(m_node);
974  executor->moveToThread(&thread);
975 
976  // Replies from executor object must go to this object
977  connect(executor, &RPCExecutor::reply, this, static_cast<void (RPCConsole::*)(int, const QString&)>(&RPCConsole::message));
978 
979  // Requests from this object must go to executor
980  connect(this, &RPCConsole::cmdRequest, executor, &RPCExecutor::request);
981 
982  // On stopExecutor signal
983  // - quit the Qt event loop in the execution thread
984  connect(this, &RPCConsole::stopExecutor, &thread, &QThread::quit);
985  // - queue executor for deletion (in execution thread)
986  connect(&thread, &QThread::finished, executor, &RPCExecutor::deleteLater, Qt::DirectConnection);
987 
988  // Default implementation of QThread::run() simply spins up an event loop in the thread,
989  // which is what we want.
990  thread.start();
991 }
992 
994 {
995  if (ui->tabWidget->widget(index) == ui->tab_console)
996  ui->lineEdit->setFocus();
997  else if (ui->tabWidget->widget(index) != ui->tab_peers)
999 }
1000 
1002 {
1004 }
1005 
1007 {
1008  QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
1009  scrollbar->setValue(scrollbar->maximum());
1010 }
1011 
1013 {
1014  const int multiplier = 5; // each position on the slider represents 5 min
1015  int mins = value * multiplier;
1016  setTrafficGraphRange(mins);
1017 }
1018 
1020 {
1021  ui->trafficGraph->setGraphRangeMins(mins);
1022  ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
1023 }
1024 
1025 void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
1026 {
1027  ui->lblBytesIn->setText(GUIUtil::formatBytes(totalBytesIn));
1028  ui->lblBytesOut->setText(GUIUtil::formatBytes(totalBytesOut));
1029 }
1030 
1031 void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
1032 {
1033  Q_UNUSED(deselected);
1034 
1035  if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
1036  return;
1037 
1038  const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
1039  if (stats)
1040  updateNodeDetail(stats);
1041 }
1042 
1044 {
1045  QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
1046  cachedNodeids.clear();
1047  for(int i = 0; i < selected.size(); i++)
1048  {
1049  const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
1050  cachedNodeids.append(stats->nodeStats.nodeid);
1051  }
1052 }
1053 
1055 {
1057  return;
1058 
1059  const CNodeCombinedStats *stats = nullptr;
1060  bool fUnselect = false;
1061  bool fReselect = false;
1062 
1063  if (cachedNodeids.empty()) // no node selected yet
1064  return;
1065 
1066  // find the currently selected row
1067  int selectedRow = -1;
1068  QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
1069  if (!selectedModelIndex.isEmpty()) {
1070  selectedRow = selectedModelIndex.first().row();
1071  }
1072 
1073  // check if our detail node has a row in the table (it may not necessarily
1074  // be at selectedRow since its position can change after a layout change)
1075  int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
1076 
1077  if (detailNodeRow < 0)
1078  {
1079  // detail node disappeared from table (node disconnected)
1080  fUnselect = true;
1081  }
1082  else
1083  {
1084  if (detailNodeRow != selectedRow)
1085  {
1086  // detail node moved position
1087  fUnselect = true;
1088  fReselect = true;
1089  }
1090 
1091  // get fresh stats on the detail node.
1092  stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1093  }
1094 
1095  if (fUnselect && selectedRow >= 0) {
1097  }
1098 
1099  if (fReselect)
1100  {
1101  for(int i = 0; i < cachedNodeids.size(); i++)
1102  {
1103  ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
1104  }
1105  }
1106 
1107  if (stats)
1108  updateNodeDetail(stats);
1109 }
1110 
1112 {
1113  // update the detail ui with latest node information
1114  QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
1115  peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
1116  if (!stats->nodeStats.addrLocal.empty())
1117  peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
1118  ui->peerHeading->setText(peerAddrDetails);
1119  ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
1120  ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
1121  ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
1122  ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes));
1123  ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes));
1124  ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
1125  ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
1126  ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
1127  ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
1128  ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
1129  ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
1130  ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
1131  ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
1132  ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
1133  ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
1134 
1135  // This check fails for example if the lock was busy and
1136  // nodeStateStats couldn't be fetched.
1137  if (stats->fNodeStateStatsAvailable) {
1138  // Ban score is init to 0
1139  ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
1140 
1141  // Sync height is init to -1
1142  if (stats->nodeStateStats.nSyncHeight > -1)
1143  ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
1144  else
1145  ui->peerSyncHeight->setText(tr("Unknown"));
1146 
1147  // Common height is init to -1
1148  if (stats->nodeStateStats.nCommonHeight > -1)
1149  ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
1150  else
1151  ui->peerCommonHeight->setText(tr("Unknown"));
1152  }
1153 
1154  ui->detailWidget->show();
1155 }
1156 
1157 void RPCConsole::resizeEvent(QResizeEvent *event)
1158 {
1159  QWidget::resizeEvent(event);
1160 }
1161 
1162 void RPCConsole::showEvent(QShowEvent *event)
1163 {
1164  QWidget::showEvent(event);
1165 
1167  return;
1168 
1169  // start PeerTableModel auto refresh
1171 }
1172 
1173 void RPCConsole::hideEvent(QHideEvent *event)
1174 {
1175  QWidget::hideEvent(event);
1176 
1178  return;
1179 
1180  // stop PeerTableModel auto refresh
1182 }
1183 
1184 void RPCConsole::showPeersTableContextMenu(const QPoint& point)
1185 {
1186  QModelIndex index = ui->peerWidget->indexAt(point);
1187  if (index.isValid())
1188  peersTableContextMenu->exec(QCursor::pos());
1189 }
1190 
1191 void RPCConsole::showBanTableContextMenu(const QPoint& point)
1192 {
1193  QModelIndex index = ui->banlistWidget->indexAt(point);
1194  if (index.isValid())
1195  banTableContextMenu->exec(QCursor::pos());
1196 }
1197 
1199 {
1200  // Get selected peer addresses
1201  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1202  for(int i = 0; i < nodes.count(); i++)
1203  {
1204  // Get currently selected peer address
1205  NodeId id = nodes.at(i).data().toLongLong();
1206  // Find the node, disconnect it and clear the selected node
1207  if(m_node.disconnect(id))
1209  }
1210 }
1211 
1213 {
1214  if (!clientModel)
1215  return;
1216 
1217  // Get selected peer addresses
1218  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1219  for(int i = 0; i < nodes.count(); i++)
1220  {
1221  // Get currently selected peer address
1222  NodeId id = nodes.at(i).data().toLongLong();
1223 
1224  // Get currently selected peer address
1225  int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
1226  if(detailNodeRow < 0)
1227  return;
1228 
1229  // Find possible nodes, ban it and clear the selected node
1230  const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1231  if(stats) {
1232  m_node.ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
1233  }
1234  }
1237 }
1238 
1240 {
1241  if (!clientModel)
1242  return;
1243 
1244  // Get selected ban addresses
1245  QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
1246  for(int i = 0; i < nodes.count(); i++)
1247  {
1248  // Get currently selected ban address
1249  QString strNode = nodes.at(i).data().toString();
1250  CSubNet possibleSubnet;
1251 
1252  LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
1253  if (possibleSubnet.IsValid() && m_node.unban(possibleSubnet))
1254  {
1256  }
1257  }
1258 }
1259 
1261 {
1262  ui->peerWidget->selectionModel()->clearSelection();
1263  cachedNodeids.clear();
1264  ui->detailWidget->hide();
1265  ui->peerHeading->setText(tr("Select a peer to view detailed information."));
1266 }
1267 
1269 {
1270  if (!clientModel)
1271  return;
1272 
1273  bool visible = clientModel->getBanTableModel()->shouldShow();
1274  ui->banlistWidget->setVisible(visible);
1275  ui->banHeading->setVisible(visible);
1276 }
1277 
1279 {
1280  ui->tabWidget->setCurrentIndex(tabType);
1281 }
void openDebugLogfile()
Definition: guiutil.cpp:356
QString formatClientStartupTime() const
int getRowByNodeId(NodeId nodeid)
const char * Name()
Implementation name.
Definition: rpcconsole.cpp:121
bool isObject() const
Definition: univalue.h:85
void addWallet(WalletModel *const walletModel)
int nStartingHeight
Definition: net.h:560
QString formatSubVersion() const
QString m_last_wallet_id
Definition: rpcconsole.h:163
Local Bitcoin RPC console.
Definition: rpcconsole.h:36
RPC timer "driver".
Definition: server.h:101
void keyPressEvent(QKeyEvent *)
Definition: rpcconsole.cpp:823
QString cmdBeforeBrowsing
Definition: rpcconsole.h:154
QFont fixedPitchFont()
Definition: guiutil.cpp:75
CNodeStateStats nodeStateStats
virtual bool getNetworkActive()=0
Get network active.
QList< QModelIndex > getEntryData(QAbstractItemView *view, int column)
Return a field of the currently selected entry as a QString.
Definition: guiutil.cpp:244
int64_t nTimeOffset
Definition: net.h:554
void showEvent(QShowEvent *event)
void on_lineEdit_returnPressed()
Definition: rpcconsole.cpp:891
RPCExecutor(interfaces::Node &node)
Definition: rpcconsole.cpp:85
QString blocksDir() const
virtual double getVerificationProgress()=0
Get verification progress.
void showPeersTableContextMenu(const QPoint &point)
Show custom context menu on Peers tab.
virtual bool unban(const CSubNet &ip)=0
Unban node.
virtual UniValue executeRpc(const std::string &command, const UniValue &params, const std::string &uri)=0
Execute rpc command.
virtual void rpcUnsetTimerInterface(RPCTimerInterface *iface)=0
Unset RPC timer interface.
QStringList history
Definition: rpcconsole.h:152
virtual int64_t getTotalBytesRecv()=0
Get total bytes recv.
interfaces::Node & m_node
Definition: rpcconsole.h:149
QThread thread
Definition: rpcconsole.h:162
ServiceFlags nServices
Definition: net.h:549
void setNetworkActive(bool networkActive)
Set network state shown in the UI.
Definition: rpcconsole.cpp:868
void scrollToEnd()
Scroll console view to end.
QString formatBytes(uint64_t bytes)
Definition: guiutil.cpp:878
QString formatTimeOffset(int64_t nTimeOffset)
Definition: guiutil.cpp:836
void networkActiveChanged(bool networkActive)
std::string cleanSubVer
Definition: net.h:557
void clearSelectedNode()
clear the selected node
#define PACKAGE_NAME
const struct @8 ICON_MAPPING[]
RPCConsole(interfaces::Node &node, const PlatformStyle *platformStyle, QWidget *parent)
Definition: rpcconsole.cpp:449
const std::string & get_str() const
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis)
Factory function for timers.
Definition: rpcconsole.cpp:122
QIcon SingleColorIcon(const QString &filename) const
Colorize an icon (given filename) with the icon color.
int64_t nTimeConnected
Definition: net.h:553
bool isStr() const
Definition: univalue.h:82
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:216
void fontSmaller()
Definition: rpcconsole.cpp:742
PeerTableModel * getPeerTableModel()
void disconnectSelectedNode()
Disconnect a selected node on the Peers tab.
CNodeStats nodeStats
void cmdRequest(const QString &command, const QString &walletID)
void on_tabWidget_currentChanged(int index)
Definition: rpcconsole.cpp:993
void numConnectionsChanged(int count)
void updateNodeDetail(const CNodeCombinedStats *stats)
show detailed information on ui about selected node
virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface)=0
Set RPC timer interface if unset.
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
UniValue RPCConvertValues(const std::string &strMethod, const std::vector< std::string > &strParams)
Convert positional arguments to command-specific RPC representation.
Definition: client.cpp:214
void setClientModel(ClientModel *model)
Definition: rpcconsole.cpp:563
void resizeEvent(QResizeEvent *event)
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut)
const PlatformStyle *const platformStyle
Definition: rpcconsole.h:156
const char * url
Definition: rpcconsole.cpp:53
void reply(int category, const QString &command)
QMenu * peersTableContextMenu
Definition: rpcconsole.h:158
int nVersion
Definition: net.h:556
const char * source
Definition: rpcconsole.cpp:54
void browseHistory(int offset)
Go forward or back in history.
Definition: rpcconsole.cpp:950
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
void message(int category, const QString &msg)
Append the message to the message widget.
Definition: rpcconsole.h:99
int getNumConnections(unsigned int flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:58
int64_t GetSystemTimeInSeconds()
Definition: utiltime.cpp:56
Class for handling RPC timers (used for e.g.
Definition: rpcconsole.cpp:100
QString formatDurationStr(int secs)
Definition: guiutil.cpp:773
const int CONSOLE_HISTORY
Definition: rpcconsole.cpp:47
const char * name
Definition: rest.cpp:37
void setTabFocus(enum TabTypes tabType)
set which tab has the focus (is visible)
bool fInbound
Definition: net.h:558
BanTableModel * getBanTableModel()
interfaces::Node & node() const
Definition: clientmodel.h:52
uint64_t nRecvBytes
Definition: net.h:563
int historyPtr
Definition: rpcconsole.h:153
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void peerLayoutChanged()
Handle updated peer information.
RPCTimerInterface * rpcTimerInterface
Definition: rpcconsole.h:157
double dPingTime
Definition: net.h:566
std::string addrName
Definition: net.h:555
void updateNetworkState()
Update UI with latest network info from model.
Definition: rpcconsole.cpp:847
int64_t NodeId
Definition: net.h:88
const CNodeCombinedStats * getNodeStats(int idx)
void request(const QString &command, const QString &walletID)
Definition: rpcconsole.cpp:390
int get_int() const
virtual bool disconnect(NodeId id)=0
Disconnect node.
void numBlocksChanged(int count, const QDateTime &blockDate, double nVerificationProgress, bool header)
QString getWalletName() const
static bool RPCParseCommandLine(interfaces::Node *node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string *const pstrFilteredOut=nullptr, const std::string *walletID=nullptr)
Split shell command line into a list of arguments and optionally execute the command(s).
Definition: rpcconsole.cpp:151
uint64_t nSendBytes
Definition: net.h:561
void on_openDebugLogfileButton_clicked()
open the debug.log from the current datadir
QtRPCTimerBase(std::function< void()> &_func, int64_t millis)
Definition: rpcconsole.cpp:104
Model for Bitcoin network client.
Definition: clientmodel.h:44
void unbanSelectedNode()
Unban a selected node on the Bans tab.
void hideEvent(QHideEvent *event)
ClientModel * clientModel
Definition: rpcconsole.h:151
QString formatPingTime(double dPingTime)
Definition: guiutil.cpp:831
virtual bool eventFilter(QObject *obj, QEvent *event)
Definition: rpcconsole.cpp:518
QMenu * banTableContextMenu
Definition: rpcconsole.h:159
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:614
void setTrafficGraphRange(int mins)
void clear(bool clearHistory=true)
Definition: rpcconsole.cpp:772
void showOrHideBanTableIfRequired()
Hides ban table if no bans are present.
void fontBigger()
Definition: rpcconsole.cpp:737
virtual bool ban(const CNetAddr &net_addr, BanReason reason, int64_t ban_time_offset)=0
Ban node.
void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
update traffic statistics
bool IsValid() const
Definition: netaddress.cpp:699
virtual int64_t getLastBlockTime()=0
Get last block time.
QList< NodeId > cachedNodeids
Definition: rpcconsole.h:155
void setMempoolSize(long numberOfTxs, size_t dynUsage)
Set size (number of transactions and memory usage) of the mempool in the UI.
Definition: rpcconsole.cpp:881
void setFontSize(int newSize)
Definition: rpcconsole.cpp:747
std::function< void()> func
Definition: rpcconsole.cpp:114
void setNumConnections(int count)
Set number of connections shown in the UI.
Definition: rpcconsole.cpp:860
void startExecutor()
Definition: rpcconsole.cpp:971
QImage SingleColorImage(const QString &filename) const
Colorize an image (given filename) with the icon color.
const CChainParams & Params()
Return the currently selected parameters.
interfaces::Node & m_node
Definition: rpcconsole.cpp:94
void peerLayoutAboutToChange()
Handle selection caching before update.
Interface to Bitcoin wallet from Qt view code.
Definition: walletmodel.h:125
virtual std::vector< std::string > listRpcCommands()=0
List rpc commands.
QString formatServicesStr(quint64 mask)
Definition: guiutil.cpp:793
std::string addrLocal
Definition: net.h:571
void on_sldGraphRange_valueChanged(int value)
change the time range of the network traffic graph
void banSelectedNode(int bantime)
Ban a selected node on the Peers tab.
Ui::RPCConsole *const ui
Definition: rpcconsole.h:150
double dMinPing
Definition: net.h:568
Opaque base class for timers returned by NewTimerFunc.
Definition: server.h:92
void removeWallet(WalletModel *const walletModel)
const int INITIAL_TRAFFIC_GRAPH_MINS
Definition: rpcconsole.cpp:48
const char fontSizeSettingsKey[]
Definition: rpcconsole.cpp:50
void peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
Handle selection of peer in peers list.
int consoleFontSize
Definition: rpcconsole.h:160
void mempoolSizeChanged(long count, size_t mempoolSizeInBytes)
const QSize FONT_RANGE(4, 40)
static bool RPCExecuteCommandLine(interfaces::Node &node, std::string &strResult, const std::string &strCommand, std::string *const pstrFilteredOut=nullptr, const std::string *walletID=nullptr)
Definition: rpcconsole.h:45
QString dataDir() const
void clear()
Definition: univalue.cpp:15
virtual int getNumBlocks()=0
Get num blocks.
bool fWhitelisted
Definition: net.h:565
QCompleter * autoCompleter
Definition: rpcconsole.h:161
void stopExecutor()
double dPingWait
Definition: net.h:567
virtual int64_t getTotalBytesSent()=0
Get total bytes sent.
Top-level interface for a bitcoin node (bsha3d process).
Definition: node.h:35
bool isArray() const
Definition: univalue.h:84
bool getImagesOnButtons() const
Definition: platformstyle.h:21
int64_t nLastSend
Definition: net.h:551
void setNumBlocks(int count, const QDateTime &blockDate, double nVerificationProgress, bool headers)
Set number of blocks and last block date shown in the UI.
Definition: rpcconsole.cpp:873
int atoi(const std::string &str)
NodeId nodeid
Definition: net.h:548
void showBanTableContextMenu(const QPoint &point)
Show custom context menu on Bans tab.
int64_t nLastRecv
Definition: net.h:552
CAddress addr
Definition: net.h:573
QString formatFullVersion() const