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