Remove duplicate includes
[bitcoinplatinum.git] / src / qt / rpcconsole.cpp
blobb17693e1cac6446835da72ae10befd494b49eec9
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 #endif
30 #include <QKeyEvent>
31 #include <QMenu>
32 #include <QMessageBox>
33 #include <QScrollBar>
34 #include <QSettings>
35 #include <QSignalMapper>
36 #include <QThread>
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 {NULL, NULL}
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 "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 lastResult = tableRPC.execute(req);
307 state = STATE_COMMAND_EXECUTED;
308 curarg.clear();
310 break;
311 case ' ': case ',': case '\t':
312 if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',')
313 throw std::runtime_error("Invalid Syntax");
315 else if(state == STATE_ARGUMENT) // Space ends argument
317 add_to_current_stack(curarg);
318 curarg.clear();
320 if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',')
322 state = STATE_EATING_SPACES_IN_ARG;
323 break;
325 state = STATE_EATING_SPACES;
326 break;
327 default: curarg += ch; state = STATE_ARGUMENT;
329 break;
330 case STATE_SINGLEQUOTED: // Single-quoted string
331 switch(ch)
333 case '\'': state = STATE_ARGUMENT; break;
334 default: curarg += ch;
336 break;
337 case STATE_DOUBLEQUOTED: // Double-quoted string
338 switch(ch)
340 case '"': state = STATE_ARGUMENT; break;
341 case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
342 default: curarg += ch;
344 break;
345 case STATE_ESCAPE_OUTER: // '\' outside quotes
346 curarg += ch; state = STATE_ARGUMENT;
347 break;
348 case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
349 if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
350 curarg += ch; state = STATE_DOUBLEQUOTED;
351 break;
354 if (pstrFilteredOut) {
355 if (STATE_COMMAND_EXECUTED == state) {
356 assert(!stack.empty());
357 close_out_params();
359 *pstrFilteredOut = strCommand;
360 for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) {
361 pstrFilteredOut->replace(i->first, i->second - i->first, "(…)");
364 switch(state) // final state
366 case STATE_COMMAND_EXECUTED:
367 if (lastResult.isStr())
368 strResult = lastResult.get_str();
369 else
370 strResult = lastResult.write(2);
371 case STATE_ARGUMENT:
372 case STATE_EATING_SPACES:
373 return true;
374 default: // ERROR to end in one of the other states
375 return false;
379 void RPCExecutor::request(const QString &command)
383 std::string result;
384 std::string executableCommand = command.toStdString() + "\n";
385 if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
387 Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
388 return;
390 Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result));
392 catch (UniValue& objError)
394 try // Nice formatting for standard-format error
396 int code = find_value(objError, "code").get_int();
397 std::string message = find_value(objError, "message").get_str();
398 Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
400 catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
401 { // Show raw JSON object
402 Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
405 catch (const std::exception& e)
407 Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
411 RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
412 QWidget(parent),
413 ui(new Ui::RPCConsole),
414 clientModel(0),
415 historyPtr(0),
416 platformStyle(_platformStyle),
417 peersTableContextMenu(0),
418 banTableContextMenu(0),
419 consoleFontSize(0)
421 ui->setupUi(this);
422 GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
424 ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
426 if (platformStyle->getImagesOnButtons()) {
427 ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
429 ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
430 ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
431 ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
433 // Install event filter for up and down arrow
434 ui->lineEdit->installEventFilter(this);
435 ui->messagesWidget->installEventFilter(this);
437 connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
438 connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
439 connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
440 connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
442 // set library version labels
443 #ifdef ENABLE_WALLET
444 ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
445 #else
446 ui->label_berkeleyDBVersion->hide();
447 ui->berkeleyDBVersion->hide();
448 #endif
449 // Register RPC timer interface
450 rpcTimerInterface = new QtRPCTimerInterface();
451 // avoid accidentally overwriting an existing, non QTThread
452 // based timer interface
453 RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
455 setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
457 ui->detailWidget->hide();
458 ui->peerHeading->setText(tr("Select a peer to view detailed information."));
460 QSettings settings;
461 consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
462 clear();
465 RPCConsole::~RPCConsole()
467 GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
468 RPCUnsetTimerInterface(rpcTimerInterface);
469 delete rpcTimerInterface;
470 delete ui;
473 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
475 if(event->type() == QEvent::KeyPress) // Special key handling
477 QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
478 int key = keyevt->key();
479 Qt::KeyboardModifiers mod = keyevt->modifiers();
480 switch(key)
482 case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
483 case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
484 case Qt::Key_PageUp: /* pass paging keys to messages widget */
485 case Qt::Key_PageDown:
486 if(obj == ui->lineEdit)
488 QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
489 return true;
491 break;
492 case Qt::Key_Return:
493 case Qt::Key_Enter:
494 // forward these events to lineEdit
495 if(obj == autoCompleter->popup()) {
496 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
497 return true;
499 break;
500 default:
501 // Typing in messages widget brings focus to line edit, and redirects key there
502 // Exclude most combinations and keys that emit no text, except paste shortcuts
503 if(obj == ui->messagesWidget && (
504 (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
505 ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
506 ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
508 ui->lineEdit->setFocus();
509 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
510 return true;
514 return QWidget::eventFilter(obj, event);
517 void RPCConsole::setClientModel(ClientModel *model)
519 clientModel = model;
520 ui->trafficGraph->setClientModel(model);
521 if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
522 // Keep up to date with client
523 setNumConnections(model->getNumConnections());
524 connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
526 setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(NULL), false);
527 connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
529 updateNetworkState();
530 connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
532 updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
533 connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
535 connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
537 // set up peer table
538 ui->peerWidget->setModel(model->getPeerTableModel());
539 ui->peerWidget->verticalHeader()->hide();
540 ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
541 ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
542 ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
543 ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
544 ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
545 ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
546 ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
547 ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
549 // create peer table context menu actions
550 QAction* disconnectAction = new QAction(tr("&Disconnect"), this);
551 QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
552 QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this);
553 QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this);
554 QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this);
556 // create peer table context menu
557 peersTableContextMenu = new QMenu(this);
558 peersTableContextMenu->addAction(disconnectAction);
559 peersTableContextMenu->addAction(banAction1h);
560 peersTableContextMenu->addAction(banAction24h);
561 peersTableContextMenu->addAction(banAction7d);
562 peersTableContextMenu->addAction(banAction365d);
564 // Add a signal mapping to allow dynamic context menu arguments.
565 // We need to use int (instead of int64_t), because signal mapper only supports
566 // int or objects, which is okay because max bantime (1 year) is < int_max.
567 QSignalMapper* signalMapper = new QSignalMapper(this);
568 signalMapper->setMapping(banAction1h, 60*60);
569 signalMapper->setMapping(banAction24h, 60*60*24);
570 signalMapper->setMapping(banAction7d, 60*60*24*7);
571 signalMapper->setMapping(banAction365d, 60*60*24*365);
572 connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
573 connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
574 connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
575 connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
576 connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
578 // peer table context menu signals
579 connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
580 connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
582 // peer table signal handling - update peer details when selecting new node
583 connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
584 this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
585 // peer table signal handling - update peer details when new nodes are added to the model
586 connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
587 // peer table signal handling - cache selected node ids
588 connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
590 // set up ban table
591 ui->banlistWidget->setModel(model->getBanTableModel());
592 ui->banlistWidget->verticalHeader()->hide();
593 ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
594 ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
595 ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
596 ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
597 ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
598 ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
599 ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
601 // create ban table context menu action
602 QAction* unbanAction = new QAction(tr("&Unban"), this);
604 // create ban table context menu
605 banTableContextMenu = new QMenu(this);
606 banTableContextMenu->addAction(unbanAction);
608 // ban table context menu signals
609 connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
610 connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
612 // ban table signal handling - clear peer details when clicking a peer in the ban table
613 connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
614 // ban table signal handling - ensure ban table is shown or hidden (if empty)
615 connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
616 showOrHideBanTableIfRequired();
618 // Provide initial values
619 ui->clientVersion->setText(model->formatFullVersion());
620 ui->clientUserAgent->setText(model->formatSubVersion());
621 ui->dataDir->setText(model->dataDir());
622 ui->startupTime->setText(model->formatClientStartupTime());
623 ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
625 //Setup autocomplete and attach it
626 QStringList wordList;
627 std::vector<std::string> commandList = tableRPC.listCommands();
628 for (size_t i = 0; i < commandList.size(); ++i)
630 wordList << commandList[i].c_str();
631 wordList << ("help " + commandList[i]).c_str();
634 wordList.sort();
635 autoCompleter = new QCompleter(wordList, this);
636 autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
637 ui->lineEdit->setCompleter(autoCompleter);
638 autoCompleter->popup()->installEventFilter(this);
639 // Start thread to execute RPC commands.
640 startExecutor();
642 if (!model) {
643 // Client model is being set to 0, this means shutdown() is about to be called.
644 // Make sure we clean up the executor thread
645 Q_EMIT stopExecutor();
646 thread.wait();
650 static QString categoryClass(int category)
652 switch(category)
654 case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
655 case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
656 case RPCConsole::CMD_ERROR: return "cmd-error"; break;
657 default: return "misc";
661 void RPCConsole::fontBigger()
663 setFontSize(consoleFontSize+1);
666 void RPCConsole::fontSmaller()
668 setFontSize(consoleFontSize-1);
671 void RPCConsole::setFontSize(int newSize)
673 QSettings settings;
675 //don't allow a insane font size
676 if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
677 return;
679 // temp. store the console content
680 QString str = ui->messagesWidget->toHtml();
682 // replace font tags size in current content
683 str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
685 // store the new font size
686 consoleFontSize = newSize;
687 settings.setValue(fontSizeSettingsKey, consoleFontSize);
689 // clear console (reset icon sizes, default stylesheet) and re-add the content
690 float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
691 clear(false);
692 ui->messagesWidget->setHtml(str);
693 ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
696 void RPCConsole::clear(bool clearHistory)
698 ui->messagesWidget->clear();
699 if(clearHistory)
701 history.clear();
702 historyPtr = 0;
704 ui->lineEdit->clear();
705 ui->lineEdit->setFocus();
707 // Add smoothly scaled icon images.
708 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
709 for(int i=0; ICON_MAPPING[i].url; ++i)
711 ui->messagesWidget->document()->addResource(
712 QTextDocument::ImageResource,
713 QUrl(ICON_MAPPING[i].url),
714 platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
717 // Set default style sheet
718 QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
719 ui->messagesWidget->document()->setDefaultStyleSheet(
720 QString(
721 "table { }"
722 "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
723 "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
724 "td.cmd-request { color: #006060; } "
725 "td.cmd-error { color: red; } "
726 ".secwarning { color: red; }"
727 "b { color: #006060; } "
728 ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
731 #ifdef Q_OS_MAC
732 QString clsKey = "(⌘)-L";
733 #else
734 QString clsKey = "Ctrl-L";
735 #endif
737 message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
738 tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
739 tr("Type <b>help</b> for an overview of available commands.")) +
740 "<br><span class=\"secwarning\">" +
741 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 ramification of a command.") +
742 "</span>",
743 true);
746 void RPCConsole::keyPressEvent(QKeyEvent *event)
748 if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
750 close();
754 void RPCConsole::message(int category, const QString &message, bool html)
756 QTime time = QTime::currentTime();
757 QString timeString = time.toString();
758 QString out;
759 out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
760 out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
761 out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
762 if(html)
763 out += message;
764 else
765 out += GUIUtil::HtmlEscape(message, false);
766 out += "</td></tr></table>";
767 ui->messagesWidget->append(out);
770 void RPCConsole::updateNetworkState()
772 QString connections = QString::number(clientModel->getNumConnections()) + " (";
773 connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
774 connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
776 if(!clientModel->getNetworkActive()) {
777 connections += " (" + tr("Network activity disabled") + ")";
780 ui->numberOfConnections->setText(connections);
783 void RPCConsole::setNumConnections(int count)
785 if (!clientModel)
786 return;
788 updateNetworkState();
791 void RPCConsole::setNetworkActive(bool networkActive)
793 updateNetworkState();
796 void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers)
798 if (!headers) {
799 ui->numberOfBlocks->setText(QString::number(count));
800 ui->lastBlockTime->setText(blockDate.toString());
804 void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
806 ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
808 if (dynUsage < 1000000)
809 ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
810 else
811 ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
814 void RPCConsole::on_lineEdit_returnPressed()
816 QString cmd = ui->lineEdit->text();
818 if(!cmd.isEmpty())
820 std::string strFilteredCmd;
821 try {
822 std::string dummy;
823 if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
824 // Failed to parse command, so we cannot even filter it for the history
825 throw std::runtime_error("Invalid command line");
827 } catch (const std::exception& e) {
828 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what()));
829 return;
832 ui->lineEdit->clear();
834 cmdBeforeBrowsing = QString();
836 message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
837 Q_EMIT cmdRequest(cmd);
839 cmd = QString::fromStdString(strFilteredCmd);
841 // Remove command, if already in history
842 history.removeOne(cmd);
843 // Append command to history
844 history.append(cmd);
845 // Enforce maximum history size
846 while(history.size() > CONSOLE_HISTORY)
847 history.removeFirst();
848 // Set pointer to end of history
849 historyPtr = history.size();
851 // Scroll console view to end
852 scrollToEnd();
856 void RPCConsole::browseHistory(int offset)
858 // store current text when start browsing through the history
859 if (historyPtr == history.size()) {
860 cmdBeforeBrowsing = ui->lineEdit->text();
863 historyPtr += offset;
864 if(historyPtr < 0)
865 historyPtr = 0;
866 if(historyPtr > history.size())
867 historyPtr = history.size();
868 QString cmd;
869 if(historyPtr < history.size())
870 cmd = history.at(historyPtr);
871 else if (!cmdBeforeBrowsing.isNull()) {
872 cmd = cmdBeforeBrowsing;
874 ui->lineEdit->setText(cmd);
877 void RPCConsole::startExecutor()
879 RPCExecutor *executor = new RPCExecutor();
880 executor->moveToThread(&thread);
882 // Replies from executor object must go to this object
883 connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
884 // Requests from this object must go to executor
885 connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
887 // On stopExecutor signal
888 // - quit the Qt event loop in the execution thread
889 connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit()));
890 // - queue executor for deletion (in execution thread)
891 connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection);
893 // Default implementation of QThread::run() simply spins up an event loop in the thread,
894 // which is what we want.
895 thread.start();
898 void RPCConsole::on_tabWidget_currentChanged(int index)
900 if (ui->tabWidget->widget(index) == ui->tab_console)
901 ui->lineEdit->setFocus();
902 else if (ui->tabWidget->widget(index) != ui->tab_peers)
903 clearSelectedNode();
906 void RPCConsole::on_openDebugLogfileButton_clicked()
908 GUIUtil::openDebugLogfile();
911 void RPCConsole::scrollToEnd()
913 QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
914 scrollbar->setValue(scrollbar->maximum());
917 void RPCConsole::on_sldGraphRange_valueChanged(int value)
919 const int multiplier = 5; // each position on the slider represents 5 min
920 int mins = value * multiplier;
921 setTrafficGraphRange(mins);
924 QString RPCConsole::FormatBytes(quint64 bytes)
926 if(bytes < 1024)
927 return QString(tr("%1 B")).arg(bytes);
928 if(bytes < 1024 * 1024)
929 return QString(tr("%1 KB")).arg(bytes / 1024);
930 if(bytes < 1024 * 1024 * 1024)
931 return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
933 return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
936 void RPCConsole::setTrafficGraphRange(int mins)
938 ui->trafficGraph->setGraphRangeMins(mins);
939 ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
942 void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
944 ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
945 ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
948 void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
950 Q_UNUSED(deselected);
952 if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
953 return;
955 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
956 if (stats)
957 updateNodeDetail(stats);
960 void RPCConsole::peerLayoutAboutToChange()
962 QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes();
963 cachedNodeids.clear();
964 for(int i = 0; i < selected.size(); i++)
966 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row());
967 cachedNodeids.append(stats->nodeStats.nodeid);
971 void RPCConsole::peerLayoutChanged()
973 if (!clientModel || !clientModel->getPeerTableModel())
974 return;
976 const CNodeCombinedStats *stats = NULL;
977 bool fUnselect = false;
978 bool fReselect = false;
980 if (cachedNodeids.empty()) // no node selected yet
981 return;
983 // find the currently selected row
984 int selectedRow = -1;
985 QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
986 if (!selectedModelIndex.isEmpty()) {
987 selectedRow = selectedModelIndex.first().row();
990 // check if our detail node has a row in the table (it may not necessarily
991 // be at selectedRow since its position can change after a layout change)
992 int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first());
994 if (detailNodeRow < 0)
996 // detail node disappeared from table (node disconnected)
997 fUnselect = true;
999 else
1001 if (detailNodeRow != selectedRow)
1003 // detail node moved position
1004 fUnselect = true;
1005 fReselect = true;
1008 // get fresh stats on the detail node.
1009 stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1012 if (fUnselect && selectedRow >= 0) {
1013 clearSelectedNode();
1016 if (fReselect)
1018 for(int i = 0; i < cachedNodeids.size(); i++)
1020 ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i)));
1024 if (stats)
1025 updateNodeDetail(stats);
1028 void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
1030 // update the detail ui with latest node information
1031 QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
1032 peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
1033 if (!stats->nodeStats.addrLocal.empty())
1034 peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
1035 ui->peerHeading->setText(peerAddrDetails);
1036 ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
1037 ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
1038 ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
1039 ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
1040 ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
1041 ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
1042 ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
1043 ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
1044 ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing));
1045 ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
1046 ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
1047 ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
1048 ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
1049 ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
1050 ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
1052 // This check fails for example if the lock was busy and
1053 // nodeStateStats couldn't be fetched.
1054 if (stats->fNodeStateStatsAvailable) {
1055 // Ban score is init to 0
1056 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
1058 // Sync height is init to -1
1059 if (stats->nodeStateStats.nSyncHeight > -1)
1060 ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
1061 else
1062 ui->peerSyncHeight->setText(tr("Unknown"));
1064 // Common height is init to -1
1065 if (stats->nodeStateStats.nCommonHeight > -1)
1066 ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
1067 else
1068 ui->peerCommonHeight->setText(tr("Unknown"));
1071 ui->detailWidget->show();
1074 void RPCConsole::resizeEvent(QResizeEvent *event)
1076 QWidget::resizeEvent(event);
1079 void RPCConsole::showEvent(QShowEvent *event)
1081 QWidget::showEvent(event);
1083 if (!clientModel || !clientModel->getPeerTableModel())
1084 return;
1086 // start PeerTableModel auto refresh
1087 clientModel->getPeerTableModel()->startAutoRefresh();
1090 void RPCConsole::hideEvent(QHideEvent *event)
1092 QWidget::hideEvent(event);
1094 if (!clientModel || !clientModel->getPeerTableModel())
1095 return;
1097 // stop PeerTableModel auto refresh
1098 clientModel->getPeerTableModel()->stopAutoRefresh();
1101 void RPCConsole::showPeersTableContextMenu(const QPoint& point)
1103 QModelIndex index = ui->peerWidget->indexAt(point);
1104 if (index.isValid())
1105 peersTableContextMenu->exec(QCursor::pos());
1108 void RPCConsole::showBanTableContextMenu(const QPoint& point)
1110 QModelIndex index = ui->banlistWidget->indexAt(point);
1111 if (index.isValid())
1112 banTableContextMenu->exec(QCursor::pos());
1115 void RPCConsole::disconnectSelectedNode()
1117 if(!g_connman)
1118 return;
1120 // Get selected peer addresses
1121 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1122 for(int i = 0; i < nodes.count(); i++)
1124 // Get currently selected peer address
1125 NodeId id = nodes.at(i).data().toLongLong();
1126 // Find the node, disconnect it and clear the selected node
1127 if(g_connman->DisconnectNode(id))
1128 clearSelectedNode();
1132 void RPCConsole::banSelectedNode(int bantime)
1134 if (!clientModel || !g_connman)
1135 return;
1137 // Get selected peer addresses
1138 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
1139 for(int i = 0; i < nodes.count(); i++)
1141 // Get currently selected peer address
1142 NodeId id = nodes.at(i).data().toLongLong();
1144 // Get currently selected peer address
1145 int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id);
1146 if(detailNodeRow < 0)
1147 return;
1149 // Find possible nodes, ban it and clear the selected node
1150 const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
1151 if(stats) {
1152 g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
1155 clearSelectedNode();
1156 clientModel->getBanTableModel()->refresh();
1159 void RPCConsole::unbanSelectedNode()
1161 if (!clientModel)
1162 return;
1164 // Get selected ban addresses
1165 QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address);
1166 for(int i = 0; i < nodes.count(); i++)
1168 // Get currently selected ban address
1169 QString strNode = nodes.at(i).data().toString();
1170 CSubNet possibleSubnet;
1172 LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
1173 if (possibleSubnet.IsValid() && g_connman)
1175 g_connman->Unban(possibleSubnet);
1176 clientModel->getBanTableModel()->refresh();
1181 void RPCConsole::clearSelectedNode()
1183 ui->peerWidget->selectionModel()->clearSelection();
1184 cachedNodeids.clear();
1185 ui->detailWidget->hide();
1186 ui->peerHeading->setText(tr("Select a peer to view detailed information."));
1189 void RPCConsole::showOrHideBanTableIfRequired()
1191 if (!clientModel)
1192 return;
1194 bool visible = clientModel->getBanTableModel()->shouldShow();
1195 ui->banlistWidget->setVisible(visible);
1196 ui->banHeading->setVisible(visible);
1199 void RPCConsole::setTabFocus(enum TabTypes tabType)
1201 ui->tabWidget->setCurrentIndex(tabType);