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