scripted-diff: Use the C++11 keyword nullptr to denote the pointer literal instead...
[bitcoinplatinum.git] / src / qt / rpcconsole.cpp
blob3590a98efac1893ebb89a489e147f38e3801d39c
1 // Copyright (c) 2011-2016 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.
5 #if defined(HAVE_CONFIG_H)
6 #include "config/bitcoin-config.h"
7 #endif
9 #include "rpcconsole.h"
10 #include "ui_debugwindow.h"
12 #include "bantablemodel.h"
13 #include "clientmodel.h"
14 #include "guiutil.h"
15 #include "platformstyle.h"
16 #include "chainparams.h"
17 #include "netbase.h"
18 #include "rpc/server.h"
19 #include "rpc/client.h"
20 #include "util.h"
22 #include <openssl/crypto.h>
24 #include <univalue.h>
26 #ifdef ENABLE_WALLET
27 #include <db_cxx.h>
28 #include <wallet/wallet.h>
29 #endif
31 #include <QKeyEvent>
32 #include <QMenu>
33 #include <QMessageBox>
34 #include <QScrollBar>
35 #include <QSettings>
36 #include <QSignalMapper>
37 #include <QThread>
38 #include <QTime>
39 #include <QTimer>
40 #include <QStringList>
42 #if QT_VERSION < 0x050000
43 #include <QUrl>
44 #endif
46 // TODO: add a scrollback limit, as there is currently none
47 // TODO: make it possible to filter out categories (esp debug messages when implemented)
48 // TODO: receive errors and debug messages through ClientModel
50 const int CONSOLE_HISTORY = 50;
51 const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
52 const QSize FONT_RANGE(4, 40);
53 const char fontSizeSettingsKey[] = "consoleFontSize";
55 const struct {
56 const char *url;
57 const char *source;
58 } ICON_MAPPING[] = {
59 {"cmd-request", ":/icons/tx_input"},
60 {"cmd-reply", ":/icons/tx_output"},
61 {"cmd-error", ":/icons/tx_output"},
62 {"misc", ":/icons/tx_inout"},
63 {nullptr, nullptr}
66 namespace {
68 // don't add private key handling cmd's to the history
69 const QStringList historyFilter = QStringList()
70 << "importprivkey"
71 << "importmulti"
72 << "signmessagewithprivkey"
73 << "signrawtransaction"
74 << "walletpassphrase"
75 << "walletpassphrasechange"
76 << "encryptwallet";
80 /* Object for executing console RPC commands in a separate thread.
82 class RPCExecutor : public QObject
84 Q_OBJECT
86 public Q_SLOTS:
87 void request(const QString &command);
89 Q_SIGNALS:
90 void reply(int category, const QString &command);
93 /** Class for handling RPC timers
94 * (used for e.g. re-locking the wallet after a timeout)
96 class QtRPCTimerBase: public QObject, public RPCTimerBase
98 Q_OBJECT
99 public:
100 QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis):
101 func(_func)
103 timer.setSingleShot(true);
104 connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
105 timer.start(millis);
107 ~QtRPCTimerBase() {}
108 private Q_SLOTS:
109 void timeout() { func(); }
110 private:
111 QTimer timer;
112 std::function<void(void)> func;
115 class QtRPCTimerInterface: public RPCTimerInterface
117 public:
118 ~QtRPCTimerInterface() {}
119 const char *Name() { return "Qt"; }
120 RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis)
122 return new QtRPCTimerBase(func, millis);
127 #include "rpcconsole.moc"
130 * Split shell command line into a list of arguments and optionally execute the command(s).
131 * Aims to emulate \c bash and friends.
133 * - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress())
134 * - Arguments are delimited with whitespace or comma
135 * - Extra whitespace at the beginning and end and between arguments will be ignored
136 * - Text can be "double" or 'single' quoted
137 * - The backslash \c \ is used as escape character
138 * - Outside quotes, any character can be escaped
139 * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
140 * - Within single quotes, no escaping is possible and no special interpretation takes place
142 * @param[out] result stringified Result from the executed command(chain)
143 * @param[in] strCommand Command line to split
144 * @param[in] fExecute set true if you want the command to be executed
145 * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
148 bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut)
150 std::vector< std::vector<std::string> > stack;
151 stack.push_back(std::vector<std::string>());
153 enum CmdParseState
155 STATE_EATING_SPACES,
156 STATE_EATING_SPACES_IN_ARG,
157 STATE_EATING_SPACES_IN_BRACKETS,
158 STATE_ARGUMENT,
159 STATE_SINGLEQUOTED,
160 STATE_DOUBLEQUOTED,
161 STATE_ESCAPE_OUTER,
162 STATE_ESCAPE_DOUBLEQUOTED,
163 STATE_COMMAND_EXECUTED,
164 STATE_COMMAND_EXECUTED_INNER
165 } state = STATE_EATING_SPACES;
166 std::string curarg;
167 UniValue lastResult;
168 unsigned nDepthInsideSensitive = 0;
169 size_t filter_begin_pos = 0, chpos;
170 std::vector<std::pair<size_t, size_t>> filter_ranges;
172 auto add_to_current_stack = [&](const std::string& strArg) {
173 if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
174 nDepthInsideSensitive = 1;
175 filter_begin_pos = chpos;
177 // Make sure stack is not empty before adding something
178 if (stack.empty()) {
179 stack.push_back(std::vector<std::string>());
181 stack.back().push_back(strArg);
184 auto close_out_params = [&]() {
185 if (nDepthInsideSensitive) {
186 if (!--nDepthInsideSensitive) {
187 assert(filter_begin_pos);
188 filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos));
189 filter_begin_pos = 0;
192 stack.pop_back();
195 std::string strCommandTerminated = strCommand;
196 if (strCommandTerminated.back() != '\n')
197 strCommandTerminated += "\n";
198 for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
200 char ch = strCommandTerminated[chpos];
201 switch(state)
203 case STATE_COMMAND_EXECUTED_INNER:
204 case STATE_COMMAND_EXECUTED:
206 bool breakParsing = true;
207 switch(ch)
209 case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
210 default:
211 if (state == STATE_COMMAND_EXECUTED_INNER)
213 if (ch != ']')
215 // append char to the current argument (which is also used for the query command)
216 curarg += ch;
217 break;
219 if (curarg.size() && fExecute)
221 // if we have a value query, query arrays with index and objects with a string key
222 UniValue subelement;
223 if (lastResult.isArray())
225 for(char argch: curarg)
226 if (!std::isdigit(argch))
227 throw std::runtime_error("Invalid result query");
228 subelement = lastResult[atoi(curarg.c_str())];
230 else if (lastResult.isObject())
231 subelement = find_value(lastResult, curarg);
232 else
233 throw std::runtime_error("Invalid result query"); //no array or object: abort
234 lastResult = subelement;
237 state = STATE_COMMAND_EXECUTED;
238 break;
240 // don't break parsing when the char is required for the next argument
241 breakParsing = false;
243 // pop the stack and return the result to the current command arguments
244 close_out_params();
246 // don't stringify the json in case of a string to avoid doublequotes
247 if (lastResult.isStr())
248 curarg = lastResult.get_str();
249 else
250 curarg = lastResult.write(2);
252 // if we have a non empty result, use it as stack argument otherwise as general result
253 if (curarg.size())
255 if (stack.size())
256 add_to_current_stack(curarg);
257 else
258 strResult = curarg;
260 curarg.clear();
261 // assume eating space state
262 state = STATE_EATING_SPACES;
264 if (breakParsing)
265 break;
267 case STATE_ARGUMENT: // In or after argument
268 case STATE_EATING_SPACES_IN_ARG:
269 case STATE_EATING_SPACES_IN_BRACKETS:
270 case STATE_EATING_SPACES: // Handle runs of whitespace
271 switch(ch)
273 case '"': state = STATE_DOUBLEQUOTED; break;
274 case '\'': state = STATE_SINGLEQUOTED; break;
275 case '\\': state = STATE_ESCAPE_OUTER; break;
276 case '(': case ')': case '\n':
277 if (state == STATE_EATING_SPACES_IN_ARG)
278 throw std::runtime_error("Invalid Syntax");
279 if (state == STATE_ARGUMENT)
281 if (ch == '(' && stack.size() && stack.back().size() > 0)
283 if (nDepthInsideSensitive) {
284 ++nDepthInsideSensitive;
286 stack.push_back(std::vector<std::string>());
289 // don't allow commands after executed commands on baselevel
290 if (!stack.size())
291 throw std::runtime_error("Invalid Syntax");
293 add_to_current_stack(curarg);
294 curarg.clear();
295 state = STATE_EATING_SPACES_IN_BRACKETS;
297 if ((ch == ')' || ch == '\n') && stack.size() > 0)
299 if (fExecute) {
300 // Convert argument list to JSON objects in method-dependent way,
301 // and pass it along with the method name to the dispatcher.
302 JSONRPCRequest req;
303 req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
304 req.strMethod = stack.back()[0];
305 #ifdef ENABLE_WALLET
306 // TODO: Move this logic to WalletModel
307 if (!vpwallets.empty()) {
308 // in Qt, use always the wallet with index 0 when running with multiple wallets
309 QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName()));
310 req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
312 #endif
313 lastResult = tableRPC.execute(req);
316 state = STATE_COMMAND_EXECUTED;
317 curarg.clear();
319 break;
320 case ' ': case ',': case '\t':
321 if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
322 throw std::runtime_error("Invalid Syntax");
324 else if(state == STATE_ARGUMENT) // Space ends argument
326 add_to_current_stack(curarg);
327 curarg.clear();
329 if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
331 state = STATE_EATING_SPACES_IN_ARG;
332 break;
334 state = STATE_EATING_SPACES;
335 break;
336 default: curarg += ch; state = STATE_ARGUMENT;
338 break;
339 case STATE_SINGLEQUOTED: // Single-quoted string
340 switch(ch)
342 case '\'': state = STATE_ARGUMENT; break;
343 default: curarg += ch;
345 break;
346 case STATE_DOUBLEQUOTED: // Double-quoted string
347 switch(ch)
349 case '"': state = STATE_ARGUMENT; break;
350 case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
351 default: curarg += ch;
353 break;
354 case STATE_ESCAPE_OUTER: // '\' outside quotes
355 curarg += ch; state = STATE_ARGUMENT;
356 break;
357 case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
358 if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
359 curarg += ch; state = STATE_DOUBLEQUOTED;
360 break;
363 if (pstrFilteredOut) {
364 if (STATE_COMMAND_EXECUTED == state) {
365 assert(!stack.empty());
366 close_out_params();
368 *pstrFilteredOut = strCommand;
369 for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
370 pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
373 switch(state) // final state
375 case STATE_COMMAND_EXECUTED:
376 if (lastResult.isStr())
377 strResult = lastResult.get_str();
378 else
379 strResult = lastResult.write(2);
380 case STATE_ARGUMENT:
381 case STATE_EATING_SPACES:
382 return true;
383 default: // ERROR to end in one of the other states
384 return false;
388 void RPCExecutor::request(const QString &command)
392 std::string result;
393 std::string executableCommand = command.toStdString() + "\n";
394 if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
396 Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
397 return;
399 Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
401 catch (UniValue& objError)
403 try // Nice formatting for standard-format error
405 int code = find_value(objError, "code").get_int();
406 std::string message = find_value(objError, "message").get_str();
407 Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
409 catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
410 { // Show raw JSON object
411 Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
414 catch (const std::exception& e)
416 Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
420 RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
421 QWidget(parent),
422 ui(new Ui::RPCConsole),
423 clientModel(0),
424 historyPtr(0),
425 platformStyle(_platformStyle),
426 peersTableContextMenu(0),
427 banTableContextMenu(0),
428 consoleFontSize(0)
430 ui->setupUi(this);
431 GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
433 ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
435 if (platformStyle->getImagesOnButtons()) {
436 ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
438 ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
439 ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
440 ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
442 // Install event filter for up and down arrow
443 ui->lineEdit->installEventFilter(this);
444 ui->messagesWidget->installEventFilter(this);
446 connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
447 connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
448 connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
449 connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
451 // set library version labels
452 #ifdef ENABLE_WALLET
453 ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
454 #else
455 ui->label_berkeleyDBVersion->hide();
456 ui->berkeleyDBVersion->hide();
457 #endif
458 // Register RPC timer interface
459 rpcTimerInterface = new QtRPCTimerInterface();
460 // avoid accidentally overwriting an existing, non QTThread
461 // based timer interface
462 RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
464 setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
466 ui->detailWidget->hide();
467 ui->peerHeading->setText(tr("Select a peer to view detailed information."));
469 QSettings settings;
470 consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
471 clear();
474 RPCConsole::~RPCConsole()
476 GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
477 RPCUnsetTimerInterface(rpcTimerInterface);
478 delete rpcTimerInterface;
479 delete ui;
482 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
484 if(event->type() == QEvent::KeyPress) // Special key handling
486 QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
487 int key = keyevt->key();
488 Qt::KeyboardModifiers mod = keyevt->modifiers();
489 switch(key)
491 case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
492 case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
493 case Qt::Key_PageUp: /* pass paging keys to messages widget */
494 case Qt::Key_PageDown:
495 if(obj == ui->lineEdit)
497 QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
498 return true;
500 break;
501 case Qt::Key_Return:
502 case Qt::Key_Enter:
503 // forward these events to lineEdit
504 if(obj == autoCompleter->popup()) {
505 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
506 return true;
508 break;
509 default:
510 // Typing in messages widget brings focus to line edit, and redirects key there
511 // Exclude most combinations and keys that emit no text, except paste shortcuts
512 if(obj == ui->messagesWidget && (
513 (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
514 ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
515 ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
517 ui->lineEdit->setFocus();
518 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
519 return true;
523 return QWidget::eventFilter(obj, event);
526 void RPCConsole::setClientModel(ClientModel *model)
528 clientModel = model;
529 ui->trafficGraph->setClientModel(model);
530 if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
531 // Keep up to date with client
532 setNumConnections(model->getNumConnections());
533 connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
535 setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false);
536 connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
538 updateNetworkState();
539 connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
541 updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
542 connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
544 connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
546 // set up peer table
547 ui->peerWidget->setModel(model->getPeerTableModel());
548 ui->peerWidget->verticalHeader()->hide();
549 ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
550 ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
551 ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
552 ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
553 ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
554 ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
555 ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
556 ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
558 // create peer table context menu actions
559 QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
560 QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
561 QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
562 QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
563 QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
565 // create peer table context menu
566 peersTableContextMenu = new QMenu(this);
567 peersTableContextMenu->addAction(disconnectAction);
568 peersTableContextMenu->addAction(banAction1h);
569 peersTableContextMenu->addAction(banAction24h);
570 peersTableContextMenu->addAction(banAction7d);
571 peersTableContextMenu->addAction(banAction365d);
573 // Add a signal mapping to allow dynamic context menu arguments.
574 // We need to use int (instead of int64_t), because signal mapper only supports
575 // int or objects, which is okay because max bantime (1 year) is < int_max.
576 QSignalMapper* signalMapper = new QSignalMapper(this);
577 signalMapper->setMapping(banAction1h, 60*60);
578 signalMapper->setMapping(banAction24h, 60*60*24);
579 signalMapper->setMapping(banAction7d, 60*60*24*7);
580 signalMapper->setMapping(banAction365d, 60*60*24*365);
581 connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
582 connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
583 connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
584 connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
585 connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
587 // peer table context menu signals
588 connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
589 connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
591 // peer table signal handling - update peer details when selecting new node
592 connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
593 this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
594 // peer table signal handling - update peer details when new nodes are added to the model
595 connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
596 // peer table signal handling - cache selected node ids
597 connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
599 // set up ban table
600 ui->banlistWidget->setModel(model->getBanTableModel());
601 ui->banlistWidget->verticalHeader()->hide();
602 ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
603 ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
604 ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
605 ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
606 ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
607 ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
608 ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
610 // create ban table context menu action
611 QAction* unbanAction = new QAction(tr("&Unban"), this);
613 // create ban table context menu
614 banTableContextMenu = new QMenu(this);
615 banTableContextMenu->addAction(unbanAction);
617 // ban table context menu signals
618 connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
619 connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
621 // ban table signal handling - clear peer details when clicking a peer in the ban table
622 connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
623 // ban table signal handling - ensure ban table is shown or hidden (if empty)
624 connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
625 showOrHideBanTableIfRequired();
627 // Provide initial values
628 ui->clientVersion->setText(model->formatFullVersion());
629 ui->clientUserAgent->setText(model->formatSubVersion());
630 ui->dataDir->setText(model->dataDir());
631 ui->startupTime->setText(model->formatClientStartupTime());
632 ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
634 //Setup autocomplete and attach it
635 QStringList wordList;
636 std::vector<std::string> commandList = tableRPC.listCommands();
637 for (size_t i = 0; i < commandList.size(); ++i)
639 wordList << commandList[i].c_str();
640 wordList << ("help " + commandList[i]).c_str();
643 wordList.sort();
644 autoCompleter = new QCompleter(wordList, this);
645 autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
646 ui->lineEdit->setCompleter(autoCompleter);
647 autoCompleter->popup()->installEventFilter(this);
648 // Start thread to execute RPC commands.
649 startExecutor();
651 if (!model) {
652 // Client model is being set to 0, this means shutdown() is about to be called.
653 // Make sure we clean up the executor thread
654 Q_EMIT stopExecutor();
655 thread.wait();
659 static QString categoryClass(int category)
661 switch(category)
663 case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
664 case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
665 case RPCConsole::CMD_ERROR: return "cmd-error"; break;
666 default: return "misc";
670 void RPCConsole::fontBigger()
672 setFontSize(consoleFontSize+1);
675 void RPCConsole::fontSmaller()
677 setFontSize(consoleFontSize-1);
680 void RPCConsole::setFontSize(int newSize)
682 QSettings settings;
684 //don't allow an insane font size
685 if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
686 return;
688 // temp. store the console content
689 QString str = ui->messagesWidget->toHtml();
691 // replace font tags size in current content
692 str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
694 // store the new font size
695 consoleFontSize = newSize;
696 settings.setValue(fontSizeSettingsKey, consoleFontSize);
698 // clear console (reset icon sizes, default stylesheet) and re-add the content
699 float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
700 clear(false);
701 ui->messagesWidget->setHtml(str);
702 ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
705 void RPCConsole::clear(bool clearHistory)
707 ui->messagesWidget->clear();
708 if(clearHistory)
710 history.clear();
711 historyPtr = 0;
713 ui->lineEdit->clear();
714 ui->lineEdit->setFocus();
716 // Add smoothly scaled icon images.
717 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
718 for(int i=0; ICON_MAPPING[i].url; ++i)
720 ui->messagesWidget->document()->addResource(
721 QTextDocument::ImageResource,
722 QUrl(ICON_MAPPING[i].url),
723 platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
726 // Set default style sheet
727 QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
728 ui->messagesWidget->document()->setDefaultStyleSheet(
729 QString(
730 "table { }"
731 "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
732 "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
733 "td.cmd-request { color: #006060; } "
734 "td.cmd-error { color: red; } "
735 ".secwarning { color: red; }"
736 "b { color: #006060; } "
737 ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
740 #ifdef Q_OS_MAC
741 QString clsKey = "(⌘)-L";
742 #else
743 QString clsKey = "Ctrl-L";
744 #endif
746 message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
747 tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
748 tr("Type <b>help</b> for an overview of available commands.")) +
749 "<br><span class=\"secwarning\">" +
750 tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
751 "</span>",
752 true);
755 void RPCConsole::keyPressEvent(QKeyEvent *event)
757 if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
759 close();
763 void RPCConsole::message(int category, const QString &message, bool html)
765 QTime time = QTime::currentTime();
766 QString timeString = time.toString();
767 QString out;
768 out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
769 out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
770 out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
771 if(html)
772 out += message;
773 else
774 out += GUIUtil::HtmlEscape(message, false);
775 out += "</td></tr></table>";
776 ui->messagesWidget->append(out);
779 void RPCConsole::updateNetworkState()
781 QString connections = QString::number(clientModel->getNumConnections()) + " (";
782 connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
783 connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
785 if(!clientModel->getNetworkActive()) {
786 connections += " (" + tr("Network activity disabled") + ")";
789 ui->numberOfConnections->setText(connections);
792 void RPCConsole::setNumConnections(int count)
794 if (!clientModel)
795 return;
797 updateNetworkState();
800 void RPCConsole::setNetworkActive(bool networkActive)
802 updateNetworkState();
805 void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers)
807 if (!headers) {
808 ui->numberOfBlocks->setText(QString::number(count));
809 ui->lastBlockTime->setText(blockDate.toString());
813 void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
815 ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
817 if (dynUsage < 1000000)
818 ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
819 else
820 ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
823 void RPCConsole::on_lineEdit_returnPressed()
825 QString cmd = ui->lineEdit->text();
827 if(!cmd.isEmpty())
829 std::string strFilteredCmd;
830 try {
831 std::string dummy;
832 if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
833 // Failed to parse command, so we cannot even filter it for the history
834 throw std::runtime_error("Invalid command line");
836 } catch (const std::exception& e) {
837 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
838 return;
841 ui->lineEdit->clear();
843 cmdBeforeBrowsing = QString();
845 message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
846 Q_EMIT cmdRequest(cmd);
848 cmd = QString::fromStdString(strFilteredCmd);
850 // Remove command, if already in history
851 history.removeOne(cmd);
852 // Append command to history
853 history.append(cmd);
854 // Enforce maximum history size
855 while(history.size() > CONSOLE_HISTORY)
856 history.removeFirst();
857 // Set pointer to end of history
858 historyPtr = history.size();
860 // Scroll console view to end
861 scrollToEnd();
865 void RPCConsole::browseHistory(int offset)
867 // store current text when start browsing through the history
868 if (historyPtr == history.size()) {
869 cmdBeforeBrowsing = ui->lineEdit->text();
872 historyPtr += offset;
873 if(historyPtr < 0)
874 historyPtr = 0;
875 if(historyPtr > history.size())
876 historyPtr = history.size();
877 QString cmd;
878 if(historyPtr < history.size())
879 cmd = history.at(historyPtr);
880 else if (!cmdBeforeBrowsing.isNull()) {
881 cmd = cmdBeforeBrowsing;
883 ui->lineEdit->setText(cmd);
886 void RPCConsole::startExecutor()
888 RPCExecutor *executor = new RPCExecutor();
889 executor->moveToThread(&thread);
891 // Replies from executor object must go to this object
892 connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
893 // Requests from this object must go to executor
894 connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
896 // On stopExecutor signal
897 // - quit the Qt event loop in the execution thread
898 connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit()));
899 // - queue executor for deletion (in execution thread)
900 connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection);
902 // Default implementation of QThread::run() simply spins up an event loop in the thread,
903 // which is what we want.
904 thread.start();
907 void RPCConsole::on_tabWidget_currentChanged(int index)
909 if (ui->tabWidget->widget(index) == ui->tab_console)
910 ui->lineEdit->setFocus();
911 else if (ui->tabWidget->widget(index) != ui->tab_peers)
912 clearSelectedNode();
915 void RPCConsole::on_openDebugLogfileButton_clicked()
917 GUIUtil::openDebugLogfile();
920 void RPCConsole::scrollToEnd()
922 QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
923 scrollbar->setValue(scrollbar->maximum());
926 void RPCConsole::on_sldGraphRange_valueChanged(int value)
928 const int multiplier = 5; // each position on the slider represents 5 min
929 int mins = value * multiplier;
930 setTrafficGraphRange(mins);
933 QString RPCConsole::FormatBytes(quint64 bytes)
935 if(bytes < 1024)
936 return QString(tr("%1 B")).arg(bytes);
937 if(bytes < 1024 * 1024)
938 return QString(tr("%1 KB")).arg(bytes / 1024);
939 if(bytes < 1024 * 1024 * 1024)
940 return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
942 return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
945 void RPCConsole::setTrafficGraphRange(int mins)
947 ui->trafficGraph->setGraphRangeMins(mins);
948 ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
951 void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
953 ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
954 ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
957 void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
959 Q_UNUSED(deselected);
961 if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
962 return;
964 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
965 if (stats)
966 updateNodeDetail(stats);
969 void RPCConsole::peerLayoutAboutToChange()
971 QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
972 cachedNodeids.clear();
973 for(int i = 0; i < selected.size(); i++)
975 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
976 cachedNodeids.append(stats->nodeStats.nodeid);
980 void RPCConsole::peerLayoutChanged()
982 if (!clientModel || !clientModel->getPeerTableModel())
983 return;
985 const CNodeCombinedStats *stats = nullptr;
986 bool fUnselect = false;
987 bool fReselect = false;
989 if (cachedNodeids.empty()) // no node selected yet
990 return;
992 // find the currently selected row
993 int selectedRow = -1;
994 QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
995 if (!selectedModelIndex.isEmpty()) {
996 selectedRow = selectedModelIndex.first().row();
999 // check if our detail node has a row in the table (it may not necessarily
1000 // be at selectedRow since its position can change after a layout change)
1001 int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
1003 if (detailNodeRow < 0)
1005 // detail node disappeared from table (node disconnected)
1006 fUnselect = true;
1008 else
1010 if (detailNodeRow != selectedRow)
1012 // detail node moved position
1013 fUnselect = true;
1014 fReselect = true;
1017 // get fresh stats on the detail node.
1018 stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1021 if (fUnselect && selectedRow >= 0) {
1022 clearSelectedNode();
1025 if (fReselect)
1027 for(int i = 0; i < cachedNodeids.size(); i++)
1029 ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
1033 if (stats)
1034 updateNodeDetail(stats);
1037 void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
1039 // update the detail ui with latest node information
1040 QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
1041 peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
1042 if (!stats->nodeStats.addrLocal.empty())
1043 peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
1044 ui->peerHeading->setText(peerAddrDetails);
1045 ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
1046 ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
1047 ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
1048 ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
1049 ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
1050 ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
1051 ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
1052 ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
1053 ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
1054 ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
1055 ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
1056 ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
1057 ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
1058 ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
1059 ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
1061 // This check fails for example if the lock was busy and
1062 // nodeStateStats couldn't be fetched.
1063 if (stats->fNodeStateStatsAvailable) {
1064 // Ban score is init to 0
1065 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
1067 // Sync height is init to -1
1068 if (stats->nodeStateStats.nSyncHeight > -1)
1069 ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
1070 else
1071 ui->peerSyncHeight->setText(tr("Unknown"));
1073 // Common height is init to -1
1074 if (stats->nodeStateStats.nCommonHeight > -1)
1075 ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
1076 else
1077 ui->peerCommonHeight->setText(tr("Unknown"));
1080 ui->detailWidget->show();
1083 void RPCConsole::resizeEvent(QResizeEvent *event)
1085 QWidget::resizeEvent(event);
1088 void RPCConsole::showEvent(QShowEvent *event)
1090 QWidget::showEvent(event);
1092 if (!clientModel || !clientModel->getPeerTableModel())
1093 return;
1095 // start PeerTableModel auto refresh
1096 clientModel->getPeerTableModel()->startAutoRefresh();
1099 void RPCConsole::hideEvent(QHideEvent *event)
1101 QWidget::hideEvent(event);
1103 if (!clientModel || !clientModel->getPeerTableModel())
1104 return;
1106 // stop PeerTableModel auto refresh
1107 clientModel->getPeerTableModel()->stopAutoRefresh();
1110 void RPCConsole::showPeersTableContextMenu(const QPoint& point)
1112 QModelIndex index = ui->peerWidget->indexAt(point);
1113 if (index.isValid())
1114 peersTableContextMenu->exec(QCursor::pos());
1117 void RPCConsole::showBanTableContextMenu(const QPoint& point)
1119 QModelIndex index = ui->banlistWidget->indexAt(point);
1120 if (index.isValid())
1121 banTableContextMenu->exec(QCursor::pos());
1124 void RPCConsole::disconnectSelectedNode()
1126 if(!g_connman)
1127 return;
1129 // Get selected peer addresses
1130 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1131 for(int i = 0; i < nodes.count(); i++)
1133 // Get currently selected peer address
1134 NodeId id = nodes.at(i).data().toLongLong();
1135 // Find the node, disconnect it and clear the selected node
1136 if(g_connman->DisconnectNode(id))
1137 clearSelectedNode();
1141 void RPCConsole::banSelectedNode(int bantime)
1143 if (!clientModel || !g_connman)
1144 return;
1146 // Get selected peer addresses
1147 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1148 for(int i = 0; i < nodes.count(); i++)
1150 // Get currently selected peer address
1151 NodeId id = nodes.at(i).data().toLongLong();
1153 // Get currently selected peer address
1154 int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
1155 if(detailNodeRow < 0)
1156 return;
1158 // Find possible nodes, ban it and clear the selected node
1159 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1160 if(stats) {
1161 g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
1164 clearSelectedNode();
1165 clientModel->getBanTableModel()->refresh();
1168 void RPCConsole::unbanSelectedNode()
1170 if (!clientModel)
1171 return;
1173 // Get selected ban addresses
1174 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
1175 for(int i = 0; i < nodes.count(); i++)
1177 // Get currently selected ban address
1178 QString strNode = nodes.at(i).data().toString();
1179 CSubNet possibleSubnet;
1181 LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
1182 if (possibleSubnet.IsValid() && g_connman)
1184 g_connman->Unban(possibleSubnet);
1185 clientModel->getBanTableModel()->refresh();
1190 void RPCConsole::clearSelectedNode()
1192 ui->peerWidget->selectionModel()->clearSelection();
1193 cachedNodeids.clear();
1194 ui->detailWidget->hide();
1195 ui->peerHeading->setText(tr("Select a peer to view detailed information."));
1198 void RPCConsole::showOrHideBanTableIfRequired()
1200 if (!clientModel)
1201 return;
1203 bool visible = clientModel->getBanTableModel()->shouldShow();
1204 ui->banlistWidget->setVisible(visible);
1205 ui->banHeading->setVisible(visible);
1208 void RPCConsole::setTabFocus(enum TabTypes tabType)
1210 ui->tabWidget->setCurrentIndex(tabType);