Merge #10574: Remove includes in .cpp files for things the corresponding .h file...
[bitcoinplatinum.git] / src / qt / rpcconsole.cpp
blob0b90205270b1c26d4d33b250b82d8bc50b195439
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 <qt/rpcconsole.h>
10 #include <qt/forms/ui_debugwindow.h>
12 #include <qt/bantablemodel.h>
13 #include <qt/clientmodel.h>
14 #include <qt/platformstyle.h>
15 #include <chainparams.h>
16 #include <netbase.h>
17 #include <rpc/server.h>
18 #include <rpc/client.h>
19 #include <util.h>
21 #include <openssl/crypto.h>
23 #include <univalue.h>
25 #ifdef ENABLE_WALLET
26 #include <db_cxx.h>
27 #include <wallet/wallet.h>
28 #endif
30 #include <QDesktopWidget>
31 #include <QKeyEvent>
32 #include <QMenu>
33 #include <QMessageBox>
34 #include <QScrollBar>
35 #include <QSettings>
36 #include <QSignalMapper>
37 #include <QTime>
38 #include <QTimer>
39 #include <QStringList>
41 #if QT_VERSION < 0x050000
42 #include <QUrl>
43 #endif
45 // TODO: add a scrollback limit, as there is currently none
46 // TODO: make it possible to filter out categories (esp debug messages when implemented)
47 // TODO: receive errors and debug messages through ClientModel
49 const int CONSOLE_HISTORY = 50;
50 const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
51 const QSize FONT_RANGE(4, 40);
52 const char fontSizeSettingsKey[] = "consoleFontSize";
54 const struct {
55 const char *url;
56 const char *source;
57 } ICON_MAPPING[] = {
58 {"cmd-request", ":/icons/tx_input"},
59 {"cmd-reply", ":/icons/tx_output"},
60 {"cmd-error", ":/icons/tx_output"},
61 {"misc", ":/icons/tx_inout"},
62 {nullptr, nullptr}
65 namespace {
67 // don't add private key handling cmd's to the history
68 const QStringList historyFilter = QStringList()
69 << "importprivkey"
70 << "importmulti"
71 << "signmessagewithprivkey"
72 << "signrawtransaction"
73 << "walletpassphrase"
74 << "walletpassphrasechange"
75 << "encryptwallet";
79 /* Object for executing console RPC commands in a separate thread.
81 class RPCExecutor : public QObject
83 Q_OBJECT
85 public Q_SLOTS:
86 void request(const QString &command);
88 Q_SIGNALS:
89 void reply(int category, const QString &command);
92 /** Class for handling RPC timers
93 * (used for e.g. re-locking the wallet after a timeout)
95 class QtRPCTimerBase: public QObject, public RPCTimerBase
97 Q_OBJECT
98 public:
99 QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis):
100 func(_func)
102 timer.setSingleShot(true);
103 connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
104 timer.start(millis);
106 ~QtRPCTimerBase() {}
107 private Q_SLOTS:
108 void timeout() { func(); }
109 private:
110 QTimer timer;
111 std::function<void(void)> func;
114 class QtRPCTimerInterface: public RPCTimerInterface
116 public:
117 ~QtRPCTimerInterface() {}
118 const char *Name() { return "Qt"; }
119 RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis)
121 return new QtRPCTimerBase(func, millis);
126 #include <qt/rpcconsole.moc>
129 * Split shell command line into a list of arguments and optionally execute the command(s).
130 * Aims to emulate \c bash and friends.
132 * - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress())
133 * - Arguments are delimited with whitespace or comma
134 * - Extra whitespace at the beginning and end and between arguments will be ignored
135 * - Text can be "double" or 'single' quoted
136 * - The backslash \c \ is used as escape character
137 * - Outside quotes, any character can be escaped
138 * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
139 * - Within single quotes, no escaping is possible and no special interpretation takes place
141 * @param[out] result stringified Result from the executed command(chain)
142 * @param[in] strCommand Command line to split
143 * @param[in] fExecute set true if you want the command to be executed
144 * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
147 bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut)
149 std::vector< std::vector<std::string> > stack;
150 stack.push_back(std::vector<std::string>());
152 enum CmdParseState
154 STATE_EATING_SPACES,
155 STATE_EATING_SPACES_IN_ARG,
156 STATE_EATING_SPACES_IN_BRACKETS,
157 STATE_ARGUMENT,
158 STATE_SINGLEQUOTED,
159 STATE_DOUBLEQUOTED,
160 STATE_ESCAPE_OUTER,
161 STATE_ESCAPE_DOUBLEQUOTED,
162 STATE_COMMAND_EXECUTED,
163 STATE_COMMAND_EXECUTED_INNER
164 } state = STATE_EATING_SPACES;
165 std::string curarg;
166 UniValue lastResult;
167 unsigned nDepthInsideSensitive = 0;
168 size_t filter_begin_pos = 0, chpos;
169 std::vector<std::pair<size_t, size_t>> filter_ranges;
171 auto add_to_current_stack = [&](const std::string& strArg) {
172 if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {
173 nDepthInsideSensitive = 1;
174 filter_begin_pos = chpos;
176 // Make sure stack is not empty before adding something
177 if (stack.empty()) {
178 stack.push_back(std::vector<std::string>());
180 stack.back().push_back(strArg);
183 auto close_out_params = [&]() {
184 if (nDepthInsideSensitive) {
185 if (!--nDepthInsideSensitive) {
186 assert(filter_begin_pos);
187 filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos));
188 filter_begin_pos = 0;
191 stack.pop_back();
194 std::string strCommandTerminated = strCommand;
195 if (strCommandTerminated.back() != '\n')
196 strCommandTerminated += "\n";
197 for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos)
199 char ch = strCommandTerminated[chpos];
200 switch(state)
202 case STATE_COMMAND_EXECUTED_INNER:
203 case STATE_COMMAND_EXECUTED:
205 bool breakParsing = true;
206 switch(ch)
208 case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break;
209 default:
210 if (state == STATE_COMMAND_EXECUTED_INNER)
212 if (ch != ']')
214 // append char to the current argument (which is also used for the query command)
215 curarg += ch;
216 break;
218 if (curarg.size() && fExecute)
220 // if we have a value query, query arrays with index and objects with a string key
221 UniValue subelement;
222 if (lastResult.isArray())
224 for(char argch: curarg)
225 if (!std::isdigit(argch))
226 throw std::runtime_error("Invalid result query");
227 subelement = lastResult[atoi(curarg.c_str())];
229 else if (lastResult.isObject())
230 subelement = find_value(lastResult, curarg);
231 else
232 throw std::runtime_error("Invalid result query"); //no array or object: abort
233 lastResult = subelement;
236 state = STATE_COMMAND_EXECUTED;
237 break;
239 // don't break parsing when the char is required for the next argument
240 breakParsing = false;
242 // pop the stack and return the result to the current command arguments
243 close_out_params();
245 // don't stringify the json in case of a string to avoid doublequotes
246 if (lastResult.isStr())
247 curarg = lastResult.get_str();
248 else
249 curarg = lastResult.write(2);
251 // if we have a non empty result, use it as stack argument otherwise as general result
252 if (curarg.size())
254 if (stack.size())
255 add_to_current_stack(curarg);
256 else
257 strResult = curarg;
259 curarg.clear();
260 // assume eating space state
261 state = STATE_EATING_SPACES;
263 if (breakParsing)
264 break;
266 case STATE_ARGUMENT: // In or after argument
267 case STATE_EATING_SPACES_IN_ARG:
268 case STATE_EATING_SPACES_IN_BRACKETS:
269 case STATE_EATING_SPACES: // Handle runs of whitespace
270 switch(ch)
272 case '"': state = STATE_DOUBLEQUOTED; break;
273 case '\'': state = STATE_SINGLEQUOTED; break;
274 case '\\': state = STATE_ESCAPE_OUTER; break;
275 case '(': case ')': case '\n':
276 if (state == STATE_EATING_SPACES_IN_ARG)
277 throw std::runtime_error("Invalid Syntax");
278 if (state == STATE_ARGUMENT)
280 if (ch == '(' && stack.size() && stack.back().size() > 0)
282 if (nDepthInsideSensitive) {
283 ++nDepthInsideSensitive;
285 stack.push_back(std::vector<std::string>());
288 // don't allow commands after executed commands on baselevel
289 if (!stack.size())
290 throw std::runtime_error("Invalid Syntax");
292 add_to_current_stack(curarg);
293 curarg.clear();
294 state = STATE_EATING_SPACES_IN_BRACKETS;
296 if ((ch == ')' || ch == '\n') && stack.size() > 0)
298 if (fExecute) {
299 // Convert argument list to JSON objects in method-dependent way,
300 // and pass it along with the method name to the dispatcher.
301 JSONRPCRequest req;
302 req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
303 req.strMethod = stack.back()[0];
304 #ifdef ENABLE_WALLET
305 // TODO: Move this logic to WalletModel
306 if (!vpwallets.empty()) {
307 // in Qt, use always the wallet with index 0 when running with multiple wallets
308 QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName()));
309 req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
311 #endif
312 lastResult = tableRPC.execute(req);
315 state = STATE_COMMAND_EXECUTED;
316 curarg.clear();
318 break;
319 case ' ': case ',': case '\t':
320 if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
321 throw std::runtime_error("Invalid Syntax");
323 else if(state == STATE_ARGUMENT) // Space ends argument
325 add_to_current_stack(curarg);
326 curarg.clear();
328 if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
330 state = STATE_EATING_SPACES_IN_ARG;
331 break;
333 state = STATE_EATING_SPACES;
334 break;
335 default: curarg += ch; state = STATE_ARGUMENT;
337 break;
338 case STATE_SINGLEQUOTED: // Single-quoted string
339 switch(ch)
341 case '\'': state = STATE_ARGUMENT; break;
342 default: curarg += ch;
344 break;
345 case STATE_DOUBLEQUOTED: // Double-quoted string
346 switch(ch)
348 case '"': state = STATE_ARGUMENT; break;
349 case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
350 default: curarg += ch;
352 break;
353 case STATE_ESCAPE_OUTER: // '\' outside quotes
354 curarg += ch; state = STATE_ARGUMENT;
355 break;
356 case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
357 if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
358 curarg += ch; state = STATE_DOUBLEQUOTED;
359 break;
362 if (pstrFilteredOut) {
363 if (STATE_COMMAND_EXECUTED == state) {
364 assert(!stack.empty());
365 close_out_params();
367 *pstrFilteredOut = strCommand;
368 for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
369 pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
372 switch(state) // final state
374 case STATE_COMMAND_EXECUTED:
375 if (lastResult.isStr())
376 strResult = lastResult.get_str();
377 else
378 strResult = lastResult.write(2);
379 case STATE_ARGUMENT:
380 case STATE_EATING_SPACES:
381 return true;
382 default: // ERROR to end in one of the other states
383 return false;
387 void RPCExecutor::request(const QString &command)
391 std::string result;
392 std::string executableCommand = command.toStdString() + "\n";
394 // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply.
395 if(executableCommand == "help-console\n")
397 Q_EMIT reply(RPCConsole::CMD_REPLY, QString(("\n"
398 "This console accepts RPC commands using the standard syntax.\n"
399 " example: getblockhash 0\n\n"
401 "This console can also accept RPC commands using parenthesized syntax.\n"
402 " example: getblockhash(0)\n\n"
404 "Commands may be nested when specified with the parenthesized syntax.\n"
405 " example: getblock(getblockhash(0) 1)\n\n"
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"
411 "Named results can be queried with a non-quoted key string in brackets.\n"
412 " example: getblock(getblockhash(0) true)[tx]\n\n"
414 "Results without keys can be queried using an integer in brackets.\n"
415 " example: getblock(getblockhash(0),true)[tx][0]\n\n")));
416 return;
418 if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
420 Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
421 return;
424 Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
426 catch (UniValue& objError)
428 try // Nice formatting for standard-format error
430 int code = find_value(objError, "code").get_int();
431 std::string message = find_value(objError, "message").get_str();
432 Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
434 catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
435 { // Show raw JSON object
436 Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
439 catch (const std::exception& e)
441 Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
445 RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
446 QWidget(parent),
447 ui(new Ui::RPCConsole),
448 clientModel(0),
449 historyPtr(0),
450 platformStyle(_platformStyle),
451 peersTableContextMenu(0),
452 banTableContextMenu(0),
453 consoleFontSize(0)
455 ui->setupUi(this);
456 QSettings settings;
457 if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) {
458 // Restore failed (perhaps missing setting), center the window
459 move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());
462 ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
464 if (platformStyle->getImagesOnButtons()) {
465 ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
467 ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
468 ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
469 ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
471 // Install event filter for up and down arrow
472 ui->lineEdit->installEventFilter(this);
473 ui->messagesWidget->installEventFilter(this);
475 connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
476 connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
477 connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
478 connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
480 // set library version labels
481 #ifdef ENABLE_WALLET
482 ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
483 #else
484 ui->label_berkeleyDBVersion->hide();
485 ui->berkeleyDBVersion->hide();
486 #endif
487 // Register RPC timer interface
488 rpcTimerInterface = new QtRPCTimerInterface();
489 // avoid accidentally overwriting an existing, non QTThread
490 // based timer interface
491 RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
493 setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
495 ui->detailWidget->hide();
496 ui->peerHeading->setText(tr("Select a peer to view detailed information."));
498 consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
499 clear();
502 RPCConsole::~RPCConsole()
504 QSettings settings;
505 settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
506 RPCUnsetTimerInterface(rpcTimerInterface);
507 delete rpcTimerInterface;
508 delete ui;
511 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
513 if(event->type() == QEvent::KeyPress) // Special key handling
515 QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
516 int key = keyevt->key();
517 Qt::KeyboardModifiers mod = keyevt->modifiers();
518 switch(key)
520 case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
521 case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
522 case Qt::Key_PageUp: /* pass paging keys to messages widget */
523 case Qt::Key_PageDown:
524 if(obj == ui->lineEdit)
526 QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
527 return true;
529 break;
530 case Qt::Key_Return:
531 case Qt::Key_Enter:
532 // forward these events to lineEdit
533 if(obj == autoCompleter->popup()) {
534 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
535 return true;
537 break;
538 default:
539 // Typing in messages widget brings focus to line edit, and redirects key there
540 // Exclude most combinations and keys that emit no text, except paste shortcuts
541 if(obj == ui->messagesWidget && (
542 (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
543 ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
544 ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
546 ui->lineEdit->setFocus();
547 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
548 return true;
552 return QWidget::eventFilter(obj, event);
555 void RPCConsole::setClientModel(ClientModel *model)
557 clientModel = model;
558 ui->trafficGraph->setClientModel(model);
559 if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
560 // Keep up to date with client
561 setNumConnections(model->getNumConnections());
562 connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
564 setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false);
565 connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
567 updateNetworkState();
568 connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
570 updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
571 connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
573 connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
575 // set up peer table
576 ui->peerWidget->setModel(model->getPeerTableModel());
577 ui->peerWidget->verticalHeader()->hide();
578 ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
579 ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
580 ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
581 ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
582 ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
583 ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
584 ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
585 ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
587 // create peer table context menu actions
588 QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
589 QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
590 QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
591 QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
592 QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
594 // create peer table context menu
595 peersTableContextMenu = new QMenu(this);
596 peersTableContextMenu->addAction(disconnectAction);
597 peersTableContextMenu->addAction(banAction1h);
598 peersTableContextMenu->addAction(banAction24h);
599 peersTableContextMenu->addAction(banAction7d);
600 peersTableContextMenu->addAction(banAction365d);
602 // Add a signal mapping to allow dynamic context menu arguments.
603 // We need to use int (instead of int64_t), because signal mapper only supports
604 // int or objects, which is okay because max bantime (1 year) is < int_max.
605 QSignalMapper* signalMapper = new QSignalMapper(this);
606 signalMapper->setMapping(banAction1h, 60*60);
607 signalMapper->setMapping(banAction24h, 60*60*24);
608 signalMapper->setMapping(banAction7d, 60*60*24*7);
609 signalMapper->setMapping(banAction365d, 60*60*24*365);
610 connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
611 connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
612 connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
613 connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
614 connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
616 // peer table context menu signals
617 connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
618 connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
620 // peer table signal handling - update peer details when selecting new node
621 connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
622 this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
623 // peer table signal handling - update peer details when new nodes are added to the model
624 connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
625 // peer table signal handling - cache selected node ids
626 connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
628 // set up ban table
629 ui->banlistWidget->setModel(model->getBanTableModel());
630 ui->banlistWidget->verticalHeader()->hide();
631 ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
632 ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
633 ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
634 ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
635 ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
636 ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
637 ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
639 // create ban table context menu action
640 QAction* unbanAction = new QAction(tr("&Unban"), this);
642 // create ban table context menu
643 banTableContextMenu = new QMenu(this);
644 banTableContextMenu->addAction(unbanAction);
646 // ban table context menu signals
647 connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
648 connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
650 // ban table signal handling - clear peer details when clicking a peer in the ban table
651 connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
652 // ban table signal handling - ensure ban table is shown or hidden (if empty)
653 connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
654 showOrHideBanTableIfRequired();
656 // Provide initial values
657 ui->clientVersion->setText(model->formatFullVersion());
658 ui->clientUserAgent->setText(model->formatSubVersion());
659 ui->dataDir->setText(model->dataDir());
660 ui->startupTime->setText(model->formatClientStartupTime());
661 ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
663 //Setup autocomplete and attach it
664 QStringList wordList;
665 std::vector<std::string> commandList = tableRPC.listCommands();
666 for (size_t i = 0; i < commandList.size(); ++i)
668 wordList << commandList[i].c_str();
669 wordList << ("help " + commandList[i]).c_str();
672 wordList << "help-console";
673 wordList.sort();
674 autoCompleter = new QCompleter(wordList, this);
675 autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
676 ui->lineEdit->setCompleter(autoCompleter);
677 autoCompleter->popup()->installEventFilter(this);
678 // Start thread to execute RPC commands.
679 startExecutor();
681 if (!model) {
682 // Client model is being set to 0, this means shutdown() is about to be called.
683 // Make sure we clean up the executor thread
684 Q_EMIT stopExecutor();
685 thread.wait();
689 static QString categoryClass(int category)
691 switch(category)
693 case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
694 case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
695 case RPCConsole::CMD_ERROR: return "cmd-error"; break;
696 default: return "misc";
700 void RPCConsole::fontBigger()
702 setFontSize(consoleFontSize+1);
705 void RPCConsole::fontSmaller()
707 setFontSize(consoleFontSize-1);
710 void RPCConsole::setFontSize(int newSize)
712 QSettings settings;
714 //don't allow an insane font size
715 if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
716 return;
718 // temp. store the console content
719 QString str = ui->messagesWidget->toHtml();
721 // replace font tags size in current content
722 str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
724 // store the new font size
725 consoleFontSize = newSize;
726 settings.setValue(fontSizeSettingsKey, consoleFontSize);
728 // clear console (reset icon sizes, default stylesheet) and re-add the content
729 float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
730 clear(false);
731 ui->messagesWidget->setHtml(str);
732 ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
735 void RPCConsole::clear(bool clearHistory)
737 ui->messagesWidget->clear();
738 if(clearHistory)
740 history.clear();
741 historyPtr = 0;
743 ui->lineEdit->clear();
744 ui->lineEdit->setFocus();
746 // Add smoothly scaled icon images.
747 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
748 for(int i=0; ICON_MAPPING[i].url; ++i)
750 ui->messagesWidget->document()->addResource(
751 QTextDocument::ImageResource,
752 QUrl(ICON_MAPPING[i].url),
753 platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
756 // Set default style sheet
757 QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
758 ui->messagesWidget->document()->setDefaultStyleSheet(
759 QString(
760 "table { }"
761 "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
762 "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
763 "td.cmd-request { color: #006060; } "
764 "td.cmd-error { color: red; } "
765 ".secwarning { color: red; }"
766 "b { color: #006060; } "
767 ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
770 #ifdef Q_OS_MAC
771 QString clsKey = "(⌘)-L";
772 #else
773 QString clsKey = "Ctrl-L";
774 #endif
776 message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
777 tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
778 tr("Type %1 for an overview of available commands.").arg("<b>help</b>") + "<br>" +
779 tr("For more information on using this console type %1.").arg("<b>help-console</b>") +
780 "<br><span class=\"secwarning\"><br>" +
781 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.") +
782 "</span>"),
783 true);
786 void RPCConsole::keyPressEvent(QKeyEvent *event)
788 if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
790 close();
794 void RPCConsole::message(int category, const QString &message, bool html)
796 QTime time = QTime::currentTime();
797 QString timeString = time.toString();
798 QString out;
799 out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
800 out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
801 out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
802 if(html)
803 out += message;
804 else
805 out += GUIUtil::HtmlEscape(message, false);
806 out += "</td></tr></table>";
807 ui->messagesWidget->append(out);
810 void RPCConsole::updateNetworkState()
812 QString connections = QString::number(clientModel->getNumConnections()) + " (";
813 connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
814 connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
816 if(!clientModel->getNetworkActive()) {
817 connections += " (" + tr("Network activity disabled") + ")";
820 ui->numberOfConnections->setText(connections);
823 void RPCConsole::setNumConnections(int count)
825 if (!clientModel)
826 return;
828 updateNetworkState();
831 void RPCConsole::setNetworkActive(bool networkActive)
833 updateNetworkState();
836 void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers)
838 if (!headers) {
839 ui->numberOfBlocks->setText(QString::number(count));
840 ui->lastBlockTime->setText(blockDate.toString());
844 void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
846 ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
848 if (dynUsage < 1000000)
849 ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
850 else
851 ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
854 void RPCConsole::on_lineEdit_returnPressed()
856 QString cmd = ui->lineEdit->text();
858 if(!cmd.isEmpty())
860 std::string strFilteredCmd;
861 try {
862 std::string dummy;
863 if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
864 // Failed to parse command, so we cannot even filter it for the history
865 throw std::runtime_error("Invalid command line");
867 } catch (const std::exception& e) {
868 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
869 return;
872 ui->lineEdit->clear();
874 cmdBeforeBrowsing = QString();
876 message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
877 Q_EMIT cmdRequest(cmd);
879 cmd = QString::fromStdString(strFilteredCmd);
881 // Remove command, if already in history
882 history.removeOne(cmd);
883 // Append command to history
884 history.append(cmd);
885 // Enforce maximum history size
886 while(history.size() > CONSOLE_HISTORY)
887 history.removeFirst();
888 // Set pointer to end of history
889 historyPtr = history.size();
891 // Scroll console view to end
892 scrollToEnd();
896 void RPCConsole::browseHistory(int offset)
898 // store current text when start browsing through the history
899 if (historyPtr == history.size()) {
900 cmdBeforeBrowsing = ui->lineEdit->text();
903 historyPtr += offset;
904 if(historyPtr < 0)
905 historyPtr = 0;
906 if(historyPtr > history.size())
907 historyPtr = history.size();
908 QString cmd;
909 if(historyPtr < history.size())
910 cmd = history.at(historyPtr);
911 else if (!cmdBeforeBrowsing.isNull()) {
912 cmd = cmdBeforeBrowsing;
914 ui->lineEdit->setText(cmd);
917 void RPCConsole::startExecutor()
919 RPCExecutor *executor = new RPCExecutor();
920 executor->moveToThread(&thread);
922 // Replies from executor object must go to this object
923 connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
924 // Requests from this object must go to executor
925 connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
927 // On stopExecutor signal
928 // - quit the Qt event loop in the execution thread
929 connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit()));
930 // - queue executor for deletion (in execution thread)
931 connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection);
933 // Default implementation of QThread::run() simply spins up an event loop in the thread,
934 // which is what we want.
935 thread.start();
938 void RPCConsole::on_tabWidget_currentChanged(int index)
940 if (ui->tabWidget->widget(index) == ui->tab_console)
941 ui->lineEdit->setFocus();
942 else if (ui->tabWidget->widget(index) != ui->tab_peers)
943 clearSelectedNode();
946 void RPCConsole::on_openDebugLogfileButton_clicked()
948 GUIUtil::openDebugLogfile();
951 void RPCConsole::scrollToEnd()
953 QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
954 scrollbar->setValue(scrollbar->maximum());
957 void RPCConsole::on_sldGraphRange_valueChanged(int value)
959 const int multiplier = 5; // each position on the slider represents 5 min
960 int mins = value * multiplier;
961 setTrafficGraphRange(mins);
964 void RPCConsole::setTrafficGraphRange(int mins)
966 ui->trafficGraph->setGraphRangeMins(mins);
967 ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
970 void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
972 ui->lblBytesIn->setText(GUIUtil::formatBytes(totalBytesIn));
973 ui->lblBytesOut->setText(GUIUtil::formatBytes(totalBytesOut));
976 void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
978 Q_UNUSED(deselected);
980 if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
981 return;
983 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
984 if (stats)
985 updateNodeDetail(stats);
988 void RPCConsole::peerLayoutAboutToChange()
990 QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
991 cachedNodeids.clear();
992 for(int i = 0; i < selected.size(); i++)
994 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
995 cachedNodeids.append(stats->nodeStats.nodeid);
999 void RPCConsole::peerLayoutChanged()
1001 if (!clientModel || !clientModel->getPeerTableModel())
1002 return;
1004 const CNodeCombinedStats *stats = nullptr;
1005 bool fUnselect = false;
1006 bool fReselect = false;
1008 if (cachedNodeids.empty()) // no node selected yet
1009 return;
1011 // find the currently selected row
1012 int selectedRow = -1;
1013 QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
1014 if (!selectedModelIndex.isEmpty()) {
1015 selectedRow = selectedModelIndex.first().row();
1018 // check if our detail node has a row in the table (it may not necessarily
1019 // be at selectedRow since its position can change after a layout change)
1020 int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
1022 if (detailNodeRow < 0)
1024 // detail node disappeared from table (node disconnected)
1025 fUnselect = true;
1027 else
1029 if (detailNodeRow != selectedRow)
1031 // detail node moved position
1032 fUnselect = true;
1033 fReselect = true;
1036 // get fresh stats on the detail node.
1037 stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1040 if (fUnselect && selectedRow >= 0) {
1041 clearSelectedNode();
1044 if (fReselect)
1046 for(int i = 0; i < cachedNodeids.size(); i++)
1048 ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
1052 if (stats)
1053 updateNodeDetail(stats);
1056 void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
1058 // update the detail ui with latest node information
1059 QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
1060 peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
1061 if (!stats->nodeStats.addrLocal.empty())
1062 peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
1063 ui->peerHeading->setText(peerAddrDetails);
1064 ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
1065 ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
1066 ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
1067 ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes));
1068 ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes));
1069 ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
1070 ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
1071 ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
1072 ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
1073 ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
1074 ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
1075 ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
1076 ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
1077 ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
1078 ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
1080 // This check fails for example if the lock was busy and
1081 // nodeStateStats couldn't be fetched.
1082 if (stats->fNodeStateStatsAvailable) {
1083 // Ban score is init to 0
1084 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
1086 // Sync height is init to -1
1087 if (stats->nodeStateStats.nSyncHeight > -1)
1088 ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
1089 else
1090 ui->peerSyncHeight->setText(tr("Unknown"));
1092 // Common height is init to -1
1093 if (stats->nodeStateStats.nCommonHeight > -1)
1094 ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
1095 else
1096 ui->peerCommonHeight->setText(tr("Unknown"));
1099 ui->detailWidget->show();
1102 void RPCConsole::resizeEvent(QResizeEvent *event)
1104 QWidget::resizeEvent(event);
1107 void RPCConsole::showEvent(QShowEvent *event)
1109 QWidget::showEvent(event);
1111 if (!clientModel || !clientModel->getPeerTableModel())
1112 return;
1114 // start PeerTableModel auto refresh
1115 clientModel->getPeerTableModel()->startAutoRefresh();
1118 void RPCConsole::hideEvent(QHideEvent *event)
1120 QWidget::hideEvent(event);
1122 if (!clientModel || !clientModel->getPeerTableModel())
1123 return;
1125 // stop PeerTableModel auto refresh
1126 clientModel->getPeerTableModel()->stopAutoRefresh();
1129 void RPCConsole::showPeersTableContextMenu(const QPoint& point)
1131 QModelIndex index = ui->peerWidget->indexAt(point);
1132 if (index.isValid())
1133 peersTableContextMenu->exec(QCursor::pos());
1136 void RPCConsole::showBanTableContextMenu(const QPoint& point)
1138 QModelIndex index = ui->banlistWidget->indexAt(point);
1139 if (index.isValid())
1140 banTableContextMenu->exec(QCursor::pos());
1143 void RPCConsole::disconnectSelectedNode()
1145 if(!g_connman)
1146 return;
1148 // Get selected peer addresses
1149 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1150 for(int i = 0; i < nodes.count(); i++)
1152 // Get currently selected peer address
1153 NodeId id = nodes.at(i).data().toLongLong();
1154 // Find the node, disconnect it and clear the selected node
1155 if(g_connman->DisconnectNode(id))
1156 clearSelectedNode();
1160 void RPCConsole::banSelectedNode(int bantime)
1162 if (!clientModel || !g_connman)
1163 return;
1165 // Get selected peer addresses
1166 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1167 for(int i = 0; i < nodes.count(); i++)
1169 // Get currently selected peer address
1170 NodeId id = nodes.at(i).data().toLongLong();
1172 // Get currently selected peer address
1173 int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
1174 if(detailNodeRow < 0)
1175 return;
1177 // Find possible nodes, ban it and clear the selected node
1178 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1179 if(stats) {
1180 g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
1183 clearSelectedNode();
1184 clientModel->getBanTableModel()->refresh();
1187 void RPCConsole::unbanSelectedNode()
1189 if (!clientModel)
1190 return;
1192 // Get selected ban addresses
1193 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
1194 for(int i = 0; i < nodes.count(); i++)
1196 // Get currently selected ban address
1197 QString strNode = nodes.at(i).data().toString();
1198 CSubNet possibleSubnet;
1200 LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
1201 if (possibleSubnet.IsValid() && g_connman)
1203 g_connman->Unban(possibleSubnet);
1204 clientModel->getBanTableModel()->refresh();
1209 void RPCConsole::clearSelectedNode()
1211 ui->peerWidget->selectionModel()->clearSelection();
1212 cachedNodeids.clear();
1213 ui->detailWidget->hide();
1214 ui->peerHeading->setText(tr("Select a peer to view detailed information."));
1217 void RPCConsole::showOrHideBanTableIfRequired()
1219 if (!clientModel)
1220 return;
1222 bool visible = clientModel->getBanTableModel()->shouldShow();
1223 ui->banlistWidget->setVisible(visible);
1224 ui->banHeading->setVisible(visible);
1227 void RPCConsole::setTabFocus(enum TabTypes tabType)
1229 ui->tabWidget->setCurrentIndex(tabType);