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"
9 #include "rpcconsole.h"
10 #include "ui_debugwindow.h"
12 #include "bantablemodel.h"
13 #include "clientmodel.h"
15 #include "platformstyle.h"
16 #include "bantablemodel.h"
18 #include "chainparams.h"
20 #include "rpc/server.h"
21 #include "rpc/client.h"
24 #include <openssl/crypto.h>
34 #include <QMessageBox>
37 #include <QSignalMapper>
41 #include <QStringList>
43 #if QT_VERSION < 0x050000
47 // TODO: add a scrollback limit, as there is currently none
48 // TODO: make it possible to filter out categories (esp debug messages when implemented)
49 // TODO: receive errors and debug messages through ClientModel
51 const int CONSOLE_HISTORY
= 50;
52 const int INITIAL_TRAFFIC_GRAPH_MINS
= 30;
53 const QSize
FONT_RANGE(4, 40);
54 const char fontSizeSettingsKey
[] = "consoleFontSize";
60 {"cmd-request", ":/icons/tx_input"},
61 {"cmd-reply", ":/icons/tx_output"},
62 {"cmd-error", ":/icons/tx_output"},
63 {"misc", ":/icons/tx_inout"},
69 // don't add private key handling cmd's to the history
70 const QStringList historyFilter
= QStringList()
73 << "signmessagewithprivkey"
74 << "signrawtransaction"
76 << "walletpassphrasechange"
81 /* Object for executing console RPC commands in a separate thread.
83 class RPCExecutor
: public QObject
88 void request(const QString
&command
);
91 void reply(int category
, const QString
&command
);
94 /** Class for handling RPC timers
95 * (used for e.g. re-locking the wallet after a timeout)
97 class QtRPCTimerBase
: public QObject
, public RPCTimerBase
101 QtRPCTimerBase(std::function
<void(void)>& _func
, int64_t millis
):
104 timer
.setSingleShot(true);
105 connect(&timer
, SIGNAL(timeout()), this, SLOT(timeout()));
110 void timeout() { func(); }
113 std::function
<void(void)> func
;
116 class QtRPCTimerInterface
: public RPCTimerInterface
119 ~QtRPCTimerInterface() {}
120 const char *Name() { return "Qt"; }
121 RPCTimerBase
* NewTimer(std::function
<void(void)>& func
, int64_t millis
)
123 return new QtRPCTimerBase(func
, millis
);
128 #include "rpcconsole.moc"
131 * Split shell command line into a list of arguments and optionally execute the command(s).
132 * Aims to emulate \c bash and friends.
134 * - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress())
135 * - Arguments are delimited with whitespace or comma
136 * - Extra whitespace at the beginning and end and between arguments will be ignored
137 * - Text can be "double" or 'single' quoted
138 * - The backslash \c \ is used as escape character
139 * - Outside quotes, any character can be escaped
140 * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
141 * - Within single quotes, no escaping is possible and no special interpretation takes place
143 * @param[out] result stringified Result from the executed command(chain)
144 * @param[in] strCommand Command line to split
145 * @param[in] fExecute set true if you want the command to be executed
146 * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
149 bool RPCConsole::RPCParseCommandLine(std::string
&strResult
, const std::string
&strCommand
, const bool fExecute
, std::string
* const pstrFilteredOut
)
151 std::vector
< std::vector
<std::string
> > stack
;
152 stack
.push_back(std::vector
<std::string
>());
157 STATE_EATING_SPACES_IN_ARG
,
158 STATE_EATING_SPACES_IN_BRACKETS
,
163 STATE_ESCAPE_DOUBLEQUOTED
,
164 STATE_COMMAND_EXECUTED
,
165 STATE_COMMAND_EXECUTED_INNER
166 } state
= STATE_EATING_SPACES
;
169 unsigned nDepthInsideSensitive
= 0;
170 size_t filter_begin_pos
= 0, chpos
;
171 std::vector
<std::pair
<size_t, size_t>> filter_ranges
;
173 auto add_to_current_stack
= [&](const std::string
& strArg
) {
174 if (stack
.back().empty() && (!nDepthInsideSensitive
) && historyFilter
.contains(QString::fromStdString(strArg
), Qt::CaseInsensitive
)) {
175 nDepthInsideSensitive
= 1;
176 filter_begin_pos
= chpos
;
178 // Make sure stack is not empty before adding something
180 stack
.push_back(std::vector
<std::string
>());
182 stack
.back().push_back(strArg
);
185 auto close_out_params
= [&]() {
186 if (nDepthInsideSensitive
) {
187 if (!--nDepthInsideSensitive
) {
188 assert(filter_begin_pos
);
189 filter_ranges
.push_back(std::make_pair(filter_begin_pos
, chpos
));
190 filter_begin_pos
= 0;
196 std::string strCommandTerminated
= strCommand
;
197 if (strCommandTerminated
.back() != '\n')
198 strCommandTerminated
+= "\n";
199 for (chpos
= 0; chpos
< strCommandTerminated
.size(); ++chpos
)
201 char ch
= strCommandTerminated
[chpos
];
204 case STATE_COMMAND_EXECUTED_INNER
:
205 case STATE_COMMAND_EXECUTED
:
207 bool breakParsing
= true;
210 case '[': curarg
.clear(); state
= STATE_COMMAND_EXECUTED_INNER
; break;
212 if (state
== STATE_COMMAND_EXECUTED_INNER
)
216 // append char to the current argument (which is also used for the query command)
220 if (curarg
.size() && fExecute
)
222 // if we have a value query, query arrays with index and objects with a string key
224 if (lastResult
.isArray())
226 for(char argch
: curarg
)
227 if (!std::isdigit(argch
))
228 throw std::runtime_error("Invalid result query");
229 subelement
= lastResult
[atoi(curarg
.c_str())];
231 else if (lastResult
.isObject())
232 subelement
= find_value(lastResult
, curarg
);
234 throw std::runtime_error("Invalid result query"); //no array or object: abort
235 lastResult
= subelement
;
238 state
= STATE_COMMAND_EXECUTED
;
241 // don't break parsing when the char is required for the next argument
242 breakParsing
= false;
244 // pop the stack and return the result to the current command arguments
247 // don't stringify the json in case of a string to avoid doublequotes
248 if (lastResult
.isStr())
249 curarg
= lastResult
.get_str();
251 curarg
= lastResult
.write(2);
253 // if we have a non empty result, use it as stack argument otherwise as general result
257 add_to_current_stack(curarg
);
262 // assume eating space state
263 state
= STATE_EATING_SPACES
;
268 case STATE_ARGUMENT
: // In or after argument
269 case STATE_EATING_SPACES_IN_ARG
:
270 case STATE_EATING_SPACES_IN_BRACKETS
:
271 case STATE_EATING_SPACES
: // Handle runs of whitespace
274 case '"': state
= STATE_DOUBLEQUOTED
; break;
275 case '\'': state
= STATE_SINGLEQUOTED
; break;
276 case '\\': state
= STATE_ESCAPE_OUTER
; break;
277 case '(': case ')': case '\n':
278 if (state
== STATE_EATING_SPACES_IN_ARG
)
279 throw std::runtime_error("Invalid Syntax");
280 if (state
== STATE_ARGUMENT
)
282 if (ch
== '(' && stack
.size() && stack
.back().size() > 0)
284 if (nDepthInsideSensitive
) {
285 ++nDepthInsideSensitive
;
287 stack
.push_back(std::vector
<std::string
>());
290 // don't allow commands after executed commands on baselevel
292 throw std::runtime_error("Invalid Syntax");
294 add_to_current_stack(curarg
);
296 state
= STATE_EATING_SPACES_IN_BRACKETS
;
298 if ((ch
== ')' || ch
== '\n') && stack
.size() > 0)
301 // Convert argument list to JSON objects in method-dependent way,
302 // and pass it along with the method name to the dispatcher.
304 req
.params
= RPCConvertValues(stack
.back()[0], std::vector
<std::string
>(stack
.back().begin() + 1, stack
.back().end()));
305 req
.strMethod
= stack
.back()[0];
306 lastResult
= tableRPC
.execute(req
);
309 state
= STATE_COMMAND_EXECUTED
;
313 case ' ': case ',': case '\t':
314 if(state
== STATE_EATING_SPACES_IN_ARG
&& curarg
.empty() && ch
== ',')
315 throw std::runtime_error("Invalid Syntax");
317 else if(state
== STATE_ARGUMENT
) // Space ends argument
319 add_to_current_stack(curarg
);
322 if ((state
== STATE_EATING_SPACES_IN_BRACKETS
|| state
== STATE_ARGUMENT
) && ch
== ',')
324 state
= STATE_EATING_SPACES_IN_ARG
;
327 state
= STATE_EATING_SPACES
;
329 default: curarg
+= ch
; state
= STATE_ARGUMENT
;
332 case STATE_SINGLEQUOTED
: // Single-quoted string
335 case '\'': state
= STATE_ARGUMENT
; break;
336 default: curarg
+= ch
;
339 case STATE_DOUBLEQUOTED
: // Double-quoted string
342 case '"': state
= STATE_ARGUMENT
; break;
343 case '\\': state
= STATE_ESCAPE_DOUBLEQUOTED
; break;
344 default: curarg
+= ch
;
347 case STATE_ESCAPE_OUTER
: // '\' outside quotes
348 curarg
+= ch
; state
= STATE_ARGUMENT
;
350 case STATE_ESCAPE_DOUBLEQUOTED
: // '\' in double-quoted text
351 if(ch
!= '"' && ch
!= '\\') curarg
+= '\\'; // keep '\' for everything but the quote and '\' itself
352 curarg
+= ch
; state
= STATE_DOUBLEQUOTED
;
356 if (pstrFilteredOut
) {
357 if (STATE_COMMAND_EXECUTED
== state
) {
358 assert(!stack
.empty());
361 *pstrFilteredOut
= strCommand
;
362 for (auto i
= filter_ranges
.rbegin(); i
!= filter_ranges
.rend(); ++i
) {
363 pstrFilteredOut
->replace(i
->first
, i
->second
- i
->first
, "(…)");
366 switch(state
) // final state
368 case STATE_COMMAND_EXECUTED
:
369 if (lastResult
.isStr())
370 strResult
= lastResult
.get_str();
372 strResult
= lastResult
.write(2);
374 case STATE_EATING_SPACES
:
376 default: // ERROR to end in one of the other states
381 void RPCExecutor::request(const QString
&command
)
386 std::string executableCommand
= command
.toStdString() + "\n";
387 if(!RPCConsole::RPCExecuteCommandLine(result
, executableCommand
))
389 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString("Parse error: unbalanced ' or \""));
392 Q_EMIT
reply(RPCConsole::CMD_REPLY
, QString::fromStdString(result
));
394 catch (UniValue
& objError
)
396 try // Nice formatting for standard-format error
398 int code
= find_value(objError
, "code").get_int();
399 std::string message
= find_value(objError
, "message").get_str();
400 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString::fromStdString(message
) + " (code " + QString::number(code
) + ")");
402 catch (const std::runtime_error
&) // raised when converting to invalid type, i.e. missing code or message
403 { // Show raw JSON object
404 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString::fromStdString(objError
.write()));
407 catch (const std::exception
& e
)
409 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString("Error: ") + QString::fromStdString(e
.what()));
413 RPCConsole::RPCConsole(const PlatformStyle
*_platformStyle
, QWidget
*parent
) :
415 ui(new Ui::RPCConsole
),
418 platformStyle(_platformStyle
),
419 peersTableContextMenu(0),
420 banTableContextMenu(0),
424 GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
426 ui
->openDebugLogfileButton
->setToolTip(ui
->openDebugLogfileButton
->toolTip().arg(tr(PACKAGE_NAME
)));
428 if (platformStyle
->getImagesOnButtons()) {
429 ui
->openDebugLogfileButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/export"));
431 ui
->clearButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/remove"));
432 ui
->fontBiggerButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/fontbigger"));
433 ui
->fontSmallerButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/fontsmaller"));
435 // Install event filter for up and down arrow
436 ui
->lineEdit
->installEventFilter(this);
437 ui
->messagesWidget
->installEventFilter(this);
439 connect(ui
->clearButton
, SIGNAL(clicked()), this, SLOT(clear()));
440 connect(ui
->fontBiggerButton
, SIGNAL(clicked()), this, SLOT(fontBigger()));
441 connect(ui
->fontSmallerButton
, SIGNAL(clicked()), this, SLOT(fontSmaller()));
442 connect(ui
->btnClearTrafficGraph
, SIGNAL(clicked()), ui
->trafficGraph
, SLOT(clear()));
444 // set library version labels
446 ui
->berkeleyDBVersion
->setText(DbEnv::version(0, 0, 0));
448 ui
->label_berkeleyDBVersion
->hide();
449 ui
->berkeleyDBVersion
->hide();
451 // Register RPC timer interface
452 rpcTimerInterface
= new QtRPCTimerInterface();
453 // avoid accidentally overwriting an existing, non QTThread
454 // based timer interface
455 RPCSetTimerInterfaceIfUnset(rpcTimerInterface
);
457 setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS
);
459 ui
->detailWidget
->hide();
460 ui
->peerHeading
->setText(tr("Select a peer to view detailed information."));
463 consoleFontSize
= settings
.value(fontSizeSettingsKey
, QFontInfo(QFont()).pointSize()).toInt();
467 RPCConsole::~RPCConsole()
469 GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
470 RPCUnsetTimerInterface(rpcTimerInterface
);
471 delete rpcTimerInterface
;
475 bool RPCConsole::eventFilter(QObject
* obj
, QEvent
*event
)
477 if(event
->type() == QEvent::KeyPress
) // Special key handling
479 QKeyEvent
*keyevt
= static_cast<QKeyEvent
*>(event
);
480 int key
= keyevt
->key();
481 Qt::KeyboardModifiers mod
= keyevt
->modifiers();
484 case Qt::Key_Up
: if(obj
== ui
->lineEdit
) { browseHistory(-1); return true; } break;
485 case Qt::Key_Down
: if(obj
== ui
->lineEdit
) { browseHistory(1); return true; } break;
486 case Qt::Key_PageUp
: /* pass paging keys to messages widget */
487 case Qt::Key_PageDown
:
488 if(obj
== ui
->lineEdit
)
490 QApplication::postEvent(ui
->messagesWidget
, new QKeyEvent(*keyevt
));
496 // forward these events to lineEdit
497 if(obj
== autoCompleter
->popup()) {
498 QApplication::postEvent(ui
->lineEdit
, new QKeyEvent(*keyevt
));
503 // Typing in messages widget brings focus to line edit, and redirects key there
504 // Exclude most combinations and keys that emit no text, except paste shortcuts
505 if(obj
== ui
->messagesWidget
&& (
506 (!mod
&& !keyevt
->text().isEmpty() && key
!= Qt::Key_Tab
) ||
507 ((mod
& Qt::ControlModifier
) && key
== Qt::Key_V
) ||
508 ((mod
& Qt::ShiftModifier
) && key
== Qt::Key_Insert
)))
510 ui
->lineEdit
->setFocus();
511 QApplication::postEvent(ui
->lineEdit
, new QKeyEvent(*keyevt
));
516 return QWidget::eventFilter(obj
, event
);
519 void RPCConsole::setClientModel(ClientModel
*model
)
522 ui
->trafficGraph
->setClientModel(model
);
523 if (model
&& clientModel
->getPeerTableModel() && clientModel
->getBanTableModel()) {
524 // Keep up to date with client
525 setNumConnections(model
->getNumConnections());
526 connect(model
, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
528 setNumBlocks(model
->getNumBlocks(), model
->getLastBlockDate(), model
->getVerificationProgress(NULL
), false);
529 connect(model
, SIGNAL(numBlocksChanged(int,QDateTime
,double,bool)), this, SLOT(setNumBlocks(int,QDateTime
,double,bool)));
531 updateNetworkState();
532 connect(model
, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
534 updateTrafficStats(model
->getTotalBytesRecv(), model
->getTotalBytesSent());
535 connect(model
, SIGNAL(bytesChanged(quint64
,quint64
)), this, SLOT(updateTrafficStats(quint64
, quint64
)));
537 connect(model
, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
540 ui
->peerWidget
->setModel(model
->getPeerTableModel());
541 ui
->peerWidget
->verticalHeader()->hide();
542 ui
->peerWidget
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
543 ui
->peerWidget
->setSelectionBehavior(QAbstractItemView::SelectRows
);
544 ui
->peerWidget
->setSelectionMode(QAbstractItemView::ExtendedSelection
);
545 ui
->peerWidget
->setContextMenuPolicy(Qt::CustomContextMenu
);
546 ui
->peerWidget
->setColumnWidth(PeerTableModel::Address
, ADDRESS_COLUMN_WIDTH
);
547 ui
->peerWidget
->setColumnWidth(PeerTableModel::Subversion
, SUBVERSION_COLUMN_WIDTH
);
548 ui
->peerWidget
->setColumnWidth(PeerTableModel::Ping
, PING_COLUMN_WIDTH
);
549 ui
->peerWidget
->horizontalHeader()->setStretchLastSection(true);
551 // create peer table context menu actions
552 QAction
* disconnectAction
= new QAction(tr("&Disconnect"), this);
553 QAction
* banAction1h
= new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
554 QAction
* banAction24h
= new QAction(tr("Ban for") + " " + tr("1 &day"), this);
555 QAction
* banAction7d
= new QAction(tr("Ban for") + " " + tr("1 &week"), this);
556 QAction
* banAction365d
= new QAction(tr("Ban for") + " " + tr("1 &year"), this);
558 // create peer table context menu
559 peersTableContextMenu
= new QMenu(this);
560 peersTableContextMenu
->addAction(disconnectAction
);
561 peersTableContextMenu
->addAction(banAction1h
);
562 peersTableContextMenu
->addAction(banAction24h
);
563 peersTableContextMenu
->addAction(banAction7d
);
564 peersTableContextMenu
->addAction(banAction365d
);
566 // Add a signal mapping to allow dynamic context menu arguments.
567 // We need to use int (instead of int64_t), because signal mapper only supports
568 // int or objects, which is okay because max bantime (1 year) is < int_max.
569 QSignalMapper
* signalMapper
= new QSignalMapper(this);
570 signalMapper
->setMapping(banAction1h
, 60*60);
571 signalMapper
->setMapping(banAction24h
, 60*60*24);
572 signalMapper
->setMapping(banAction7d
, 60*60*24*7);
573 signalMapper
->setMapping(banAction365d
, 60*60*24*365);
574 connect(banAction1h
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
575 connect(banAction24h
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
576 connect(banAction7d
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
577 connect(banAction365d
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
578 connect(signalMapper
, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
580 // peer table context menu signals
581 connect(ui
->peerWidget
, SIGNAL(customContextMenuRequested(const QPoint
&)), this, SLOT(showPeersTableContextMenu(const QPoint
&)));
582 connect(disconnectAction
, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
584 // peer table signal handling - update peer details when selecting new node
585 connect(ui
->peerWidget
->selectionModel(), SIGNAL(selectionChanged(const QItemSelection
&, const QItemSelection
&)),
586 this, SLOT(peerSelected(const QItemSelection
&, const QItemSelection
&)));
587 // peer table signal handling - update peer details when new nodes are added to the model
588 connect(model
->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
589 // peer table signal handling - cache selected node ids
590 connect(model
->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
593 ui
->banlistWidget
->setModel(model
->getBanTableModel());
594 ui
->banlistWidget
->verticalHeader()->hide();
595 ui
->banlistWidget
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
596 ui
->banlistWidget
->setSelectionBehavior(QAbstractItemView::SelectRows
);
597 ui
->banlistWidget
->setSelectionMode(QAbstractItemView::SingleSelection
);
598 ui
->banlistWidget
->setContextMenuPolicy(Qt::CustomContextMenu
);
599 ui
->banlistWidget
->setColumnWidth(BanTableModel::Address
, BANSUBNET_COLUMN_WIDTH
);
600 ui
->banlistWidget
->setColumnWidth(BanTableModel::Bantime
, BANTIME_COLUMN_WIDTH
);
601 ui
->banlistWidget
->horizontalHeader()->setStretchLastSection(true);
603 // create ban table context menu action
604 QAction
* unbanAction
= new QAction(tr("&Unban"), this);
606 // create ban table context menu
607 banTableContextMenu
= new QMenu(this);
608 banTableContextMenu
->addAction(unbanAction
);
610 // ban table context menu signals
611 connect(ui
->banlistWidget
, SIGNAL(customContextMenuRequested(const QPoint
&)), this, SLOT(showBanTableContextMenu(const QPoint
&)));
612 connect(unbanAction
, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
614 // ban table signal handling - clear peer details when clicking a peer in the ban table
615 connect(ui
->banlistWidget
, SIGNAL(clicked(const QModelIndex
&)), this, SLOT(clearSelectedNode()));
616 // ban table signal handling - ensure ban table is shown or hidden (if empty)
617 connect(model
->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
618 showOrHideBanTableIfRequired();
620 // Provide initial values
621 ui
->clientVersion
->setText(model
->formatFullVersion());
622 ui
->clientUserAgent
->setText(model
->formatSubVersion());
623 ui
->dataDir
->setText(model
->dataDir());
624 ui
->startupTime
->setText(model
->formatClientStartupTime());
625 ui
->networkName
->setText(QString::fromStdString(Params().NetworkIDString()));
627 //Setup autocomplete and attach it
628 QStringList wordList
;
629 std::vector
<std::string
> commandList
= tableRPC
.listCommands();
630 for (size_t i
= 0; i
< commandList
.size(); ++i
)
632 wordList
<< commandList
[i
].c_str();
633 wordList
<< ("help " + commandList
[i
]).c_str();
637 autoCompleter
= new QCompleter(wordList
, this);
638 autoCompleter
->setModelSorting(QCompleter::CaseSensitivelySortedModel
);
639 ui
->lineEdit
->setCompleter(autoCompleter
);
640 autoCompleter
->popup()->installEventFilter(this);
641 // Start thread to execute RPC commands.
645 // Client model is being set to 0, this means shutdown() is about to be called.
646 // Make sure we clean up the executor thread
647 Q_EMIT
stopExecutor();
652 static QString
categoryClass(int category
)
656 case RPCConsole::CMD_REQUEST
: return "cmd-request"; break;
657 case RPCConsole::CMD_REPLY
: return "cmd-reply"; break;
658 case RPCConsole::CMD_ERROR
: return "cmd-error"; break;
659 default: return "misc";
663 void RPCConsole::fontBigger()
665 setFontSize(consoleFontSize
+1);
668 void RPCConsole::fontSmaller()
670 setFontSize(consoleFontSize
-1);
673 void RPCConsole::setFontSize(int newSize
)
677 //don't allow a insane font size
678 if (newSize
< FONT_RANGE
.width() || newSize
> FONT_RANGE
.height())
681 // temp. store the console content
682 QString str
= ui
->messagesWidget
->toHtml();
684 // replace font tags size in current content
685 str
.replace(QString("font-size:%1pt").arg(consoleFontSize
), QString("font-size:%1pt").arg(newSize
));
687 // store the new font size
688 consoleFontSize
= newSize
;
689 settings
.setValue(fontSizeSettingsKey
, consoleFontSize
);
691 // clear console (reset icon sizes, default stylesheet) and re-add the content
692 float oldPosFactor
= 1.0 / ui
->messagesWidget
->verticalScrollBar()->maximum() * ui
->messagesWidget
->verticalScrollBar()->value();
694 ui
->messagesWidget
->setHtml(str
);
695 ui
->messagesWidget
->verticalScrollBar()->setValue(oldPosFactor
* ui
->messagesWidget
->verticalScrollBar()->maximum());
698 void RPCConsole::clear(bool clearHistory
)
700 ui
->messagesWidget
->clear();
706 ui
->lineEdit
->clear();
707 ui
->lineEdit
->setFocus();
709 // Add smoothly scaled icon images.
710 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
711 for(int i
=0; ICON_MAPPING
[i
].url
; ++i
)
713 ui
->messagesWidget
->document()->addResource(
714 QTextDocument::ImageResource
,
715 QUrl(ICON_MAPPING
[i
].url
),
716 platformStyle
->SingleColorImage(ICON_MAPPING
[i
].source
).scaled(QSize(consoleFontSize
*2, consoleFontSize
*2), Qt::IgnoreAspectRatio
, Qt::SmoothTransformation
));
719 // Set default style sheet
720 QFontInfo
fixedFontInfo(GUIUtil::fixedPitchFont());
721 ui
->messagesWidget
->document()->setDefaultStyleSheet(
724 "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
725 "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
726 "td.cmd-request { color: #006060; } "
727 "td.cmd-error { color: red; } "
728 ".secwarning { color: red; }"
729 "b { color: #006060; } "
730 ).arg(fixedFontInfo
.family(), QString("%1pt").arg(consoleFontSize
))
734 QString clsKey
= "(⌘)-L";
736 QString clsKey
= "Ctrl-L";
739 message(CMD_REPLY
, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME
)) + "<br>" +
740 tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey
+"</b>") + "<br>" +
741 tr("Type <b>help</b> for an overview of available commands.")) +
742 "<br><span class=\"secwarning\">" +
743 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.") +
748 void RPCConsole::keyPressEvent(QKeyEvent
*event
)
750 if(windowType() != Qt::Widget
&& event
->key() == Qt::Key_Escape
)
756 void RPCConsole::message(int category
, const QString
&message
, bool html
)
758 QTime time
= QTime::currentTime();
759 QString timeString
= time
.toString();
761 out
+= "<table><tr><td class=\"time\" width=\"65\">" + timeString
+ "</td>";
762 out
+= "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category
) + "\"></td>";
763 out
+= "<td class=\"message " + categoryClass(category
) + "\" valign=\"middle\">";
767 out
+= GUIUtil::HtmlEscape(message
, false);
768 out
+= "</td></tr></table>";
769 ui
->messagesWidget
->append(out
);
772 void RPCConsole::updateNetworkState()
774 QString connections
= QString::number(clientModel
->getNumConnections()) + " (";
775 connections
+= tr("In:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_IN
)) + " / ";
776 connections
+= tr("Out:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_OUT
)) + ")";
778 if(!clientModel
->getNetworkActive()) {
779 connections
+= " (" + tr("Network activity disabled") + ")";
782 ui
->numberOfConnections
->setText(connections
);
785 void RPCConsole::setNumConnections(int count
)
790 updateNetworkState();
793 void RPCConsole::setNetworkActive(bool networkActive
)
795 updateNetworkState();
798 void RPCConsole::setNumBlocks(int count
, const QDateTime
& blockDate
, double nVerificationProgress
, bool headers
)
801 ui
->numberOfBlocks
->setText(QString::number(count
));
802 ui
->lastBlockTime
->setText(blockDate
.toString());
806 void RPCConsole::setMempoolSize(long numberOfTxs
, size_t dynUsage
)
808 ui
->mempoolNumberTxs
->setText(QString::number(numberOfTxs
));
810 if (dynUsage
< 1000000)
811 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000.0, 'f', 2) + " KB");
813 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000000.0, 'f', 2) + " MB");
816 void RPCConsole::on_lineEdit_returnPressed()
818 QString cmd
= ui
->lineEdit
->text();
822 std::string strFilteredCmd
;
825 if (!RPCParseCommandLine(dummy
, cmd
.toStdString(), false, &strFilteredCmd
)) {
826 // Failed to parse command, so we cannot even filter it for the history
827 throw std::runtime_error("Invalid command line");
829 } catch (const std::exception
& e
) {
830 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e
.what()));
834 ui
->lineEdit
->clear();
836 cmdBeforeBrowsing
= QString();
838 message(CMD_REQUEST
, QString::fromStdString(strFilteredCmd
));
839 Q_EMIT
cmdRequest(cmd
);
841 cmd
= QString::fromStdString(strFilteredCmd
);
843 // Remove command, if already in history
844 history
.removeOne(cmd
);
845 // Append command to history
847 // Enforce maximum history size
848 while(history
.size() > CONSOLE_HISTORY
)
849 history
.removeFirst();
850 // Set pointer to end of history
851 historyPtr
= history
.size();
853 // Scroll console view to end
858 void RPCConsole::browseHistory(int offset
)
860 // store current text when start browsing through the history
861 if (historyPtr
== history
.size()) {
862 cmdBeforeBrowsing
= ui
->lineEdit
->text();
865 historyPtr
+= offset
;
868 if(historyPtr
> history
.size())
869 historyPtr
= history
.size();
871 if(historyPtr
< history
.size())
872 cmd
= history
.at(historyPtr
);
873 else if (!cmdBeforeBrowsing
.isNull()) {
874 cmd
= cmdBeforeBrowsing
;
876 ui
->lineEdit
->setText(cmd
);
879 void RPCConsole::startExecutor()
881 RPCExecutor
*executor
= new RPCExecutor();
882 executor
->moveToThread(&thread
);
884 // Replies from executor object must go to this object
885 connect(executor
, SIGNAL(reply(int,QString
)), this, SLOT(message(int,QString
)));
886 // Requests from this object must go to executor
887 connect(this, SIGNAL(cmdRequest(QString
)), executor
, SLOT(request(QString
)));
889 // On stopExecutor signal
890 // - quit the Qt event loop in the execution thread
891 connect(this, SIGNAL(stopExecutor()), &thread
, SLOT(quit()));
892 // - queue executor for deletion (in execution thread)
893 connect(&thread
, SIGNAL(finished()), executor
, SLOT(deleteLater()), Qt::DirectConnection
);
895 // Default implementation of QThread::run() simply spins up an event loop in the thread,
896 // which is what we want.
900 void RPCConsole::on_tabWidget_currentChanged(int index
)
902 if (ui
->tabWidget
->widget(index
) == ui
->tab_console
)
903 ui
->lineEdit
->setFocus();
904 else if (ui
->tabWidget
->widget(index
) != ui
->tab_peers
)
908 void RPCConsole::on_openDebugLogfileButton_clicked()
910 GUIUtil::openDebugLogfile();
913 void RPCConsole::scrollToEnd()
915 QScrollBar
*scrollbar
= ui
->messagesWidget
->verticalScrollBar();
916 scrollbar
->setValue(scrollbar
->maximum());
919 void RPCConsole::on_sldGraphRange_valueChanged(int value
)
921 const int multiplier
= 5; // each position on the slider represents 5 min
922 int mins
= value
* multiplier
;
923 setTrafficGraphRange(mins
);
926 QString
RPCConsole::FormatBytes(quint64 bytes
)
929 return QString(tr("%1 B")).arg(bytes
);
930 if(bytes
< 1024 * 1024)
931 return QString(tr("%1 KB")).arg(bytes
/ 1024);
932 if(bytes
< 1024 * 1024 * 1024)
933 return QString(tr("%1 MB")).arg(bytes
/ 1024 / 1024);
935 return QString(tr("%1 GB")).arg(bytes
/ 1024 / 1024 / 1024);
938 void RPCConsole::setTrafficGraphRange(int mins
)
940 ui
->trafficGraph
->setGraphRangeMins(mins
);
941 ui
->lblGraphRange
->setText(GUIUtil::formatDurationStr(mins
* 60));
944 void RPCConsole::updateTrafficStats(quint64 totalBytesIn
, quint64 totalBytesOut
)
946 ui
->lblBytesIn
->setText(FormatBytes(totalBytesIn
));
947 ui
->lblBytesOut
->setText(FormatBytes(totalBytesOut
));
950 void RPCConsole::peerSelected(const QItemSelection
&selected
, const QItemSelection
&deselected
)
952 Q_UNUSED(deselected
);
954 if (!clientModel
|| !clientModel
->getPeerTableModel() || selected
.indexes().isEmpty())
957 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(selected
.indexes().first().row());
959 updateNodeDetail(stats
);
962 void RPCConsole::peerLayoutAboutToChange()
964 QModelIndexList selected
= ui
->peerWidget
->selectionModel()->selectedIndexes();
965 cachedNodeids
.clear();
966 for(int i
= 0; i
< selected
.size(); i
++)
968 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(selected
.at(i
).row());
969 cachedNodeids
.append(stats
->nodeStats
.nodeid
);
973 void RPCConsole::peerLayoutChanged()
975 if (!clientModel
|| !clientModel
->getPeerTableModel())
978 const CNodeCombinedStats
*stats
= NULL
;
979 bool fUnselect
= false;
980 bool fReselect
= false;
982 if (cachedNodeids
.empty()) // no node selected yet
985 // find the currently selected row
986 int selectedRow
= -1;
987 QModelIndexList selectedModelIndex
= ui
->peerWidget
->selectionModel()->selectedIndexes();
988 if (!selectedModelIndex
.isEmpty()) {
989 selectedRow
= selectedModelIndex
.first().row();
992 // check if our detail node has a row in the table (it may not necessarily
993 // be at selectedRow since its position can change after a layout change)
994 int detailNodeRow
= clientModel
->getPeerTableModel()->getRowByNodeId(cachedNodeids
.first());
996 if (detailNodeRow
< 0)
998 // detail node disappeared from table (node disconnected)
1003 if (detailNodeRow
!= selectedRow
)
1005 // detail node moved position
1010 // get fresh stats on the detail node.
1011 stats
= clientModel
->getPeerTableModel()->getNodeStats(detailNodeRow
);
1014 if (fUnselect
&& selectedRow
>= 0) {
1015 clearSelectedNode();
1020 for(int i
= 0; i
< cachedNodeids
.size(); i
++)
1022 ui
->peerWidget
->selectRow(clientModel
->getPeerTableModel()->getRowByNodeId(cachedNodeids
.at(i
)));
1027 updateNodeDetail(stats
);
1030 void RPCConsole::updateNodeDetail(const CNodeCombinedStats
*stats
)
1032 // update the detail ui with latest node information
1033 QString
peerAddrDetails(QString::fromStdString(stats
->nodeStats
.addrName
) + " ");
1034 peerAddrDetails
+= tr("(node id: %1)").arg(QString::number(stats
->nodeStats
.nodeid
));
1035 if (!stats
->nodeStats
.addrLocal
.empty())
1036 peerAddrDetails
+= "<br />" + tr("via %1").arg(QString::fromStdString(stats
->nodeStats
.addrLocal
));
1037 ui
->peerHeading
->setText(peerAddrDetails
);
1038 ui
->peerServices
->setText(GUIUtil::formatServicesStr(stats
->nodeStats
.nServices
));
1039 ui
->peerLastSend
->setText(stats
->nodeStats
.nLastSend
? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nLastSend
) : tr("never"));
1040 ui
->peerLastRecv
->setText(stats
->nodeStats
.nLastRecv
? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nLastRecv
) : tr("never"));
1041 ui
->peerBytesSent
->setText(FormatBytes(stats
->nodeStats
.nSendBytes
));
1042 ui
->peerBytesRecv
->setText(FormatBytes(stats
->nodeStats
.nRecvBytes
));
1043 ui
->peerConnTime
->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nTimeConnected
));
1044 ui
->peerPingTime
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dPingTime
));
1045 ui
->peerPingWait
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dPingWait
));
1046 ui
->peerMinPing
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dMinPing
));
1047 ui
->timeoffset
->setText(GUIUtil::formatTimeOffset(stats
->nodeStats
.nTimeOffset
));
1048 ui
->peerVersion
->setText(QString("%1").arg(QString::number(stats
->nodeStats
.nVersion
)));
1049 ui
->peerSubversion
->setText(QString::fromStdString(stats
->nodeStats
.cleanSubVer
));
1050 ui
->peerDirection
->setText(stats
->nodeStats
.fInbound
? tr("Inbound") : tr("Outbound"));
1051 ui
->peerHeight
->setText(QString("%1").arg(QString::number(stats
->nodeStats
.nStartingHeight
)));
1052 ui
->peerWhitelisted
->setText(stats
->nodeStats
.fWhitelisted
? tr("Yes") : tr("No"));
1054 // This check fails for example if the lock was busy and
1055 // nodeStateStats couldn't be fetched.
1056 if (stats
->fNodeStateStatsAvailable
) {
1057 // Ban score is init to 0
1058 ui
->peerBanScore
->setText(QString("%1").arg(stats
->nodeStateStats
.nMisbehavior
));
1060 // Sync height is init to -1
1061 if (stats
->nodeStateStats
.nSyncHeight
> -1)
1062 ui
->peerSyncHeight
->setText(QString("%1").arg(stats
->nodeStateStats
.nSyncHeight
));
1064 ui
->peerSyncHeight
->setText(tr("Unknown"));
1066 // Common height is init to -1
1067 if (stats
->nodeStateStats
.nCommonHeight
> -1)
1068 ui
->peerCommonHeight
->setText(QString("%1").arg(stats
->nodeStateStats
.nCommonHeight
));
1070 ui
->peerCommonHeight
->setText(tr("Unknown"));
1073 ui
->detailWidget
->show();
1076 void RPCConsole::resizeEvent(QResizeEvent
*event
)
1078 QWidget::resizeEvent(event
);
1081 void RPCConsole::showEvent(QShowEvent
*event
)
1083 QWidget::showEvent(event
);
1085 if (!clientModel
|| !clientModel
->getPeerTableModel())
1088 // start PeerTableModel auto refresh
1089 clientModel
->getPeerTableModel()->startAutoRefresh();
1092 void RPCConsole::hideEvent(QHideEvent
*event
)
1094 QWidget::hideEvent(event
);
1096 if (!clientModel
|| !clientModel
->getPeerTableModel())
1099 // stop PeerTableModel auto refresh
1100 clientModel
->getPeerTableModel()->stopAutoRefresh();
1103 void RPCConsole::showPeersTableContextMenu(const QPoint
& point
)
1105 QModelIndex index
= ui
->peerWidget
->indexAt(point
);
1106 if (index
.isValid())
1107 peersTableContextMenu
->exec(QCursor::pos());
1110 void RPCConsole::showBanTableContextMenu(const QPoint
& point
)
1112 QModelIndex index
= ui
->banlistWidget
->indexAt(point
);
1113 if (index
.isValid())
1114 banTableContextMenu
->exec(QCursor::pos());
1117 void RPCConsole::disconnectSelectedNode()
1122 // Get selected peer addresses
1123 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->peerWidget
, PeerTableModel::NetNodeId
);
1124 for(int i
= 0; i
< nodes
.count(); i
++)
1126 // Get currently selected peer address
1127 NodeId id
= nodes
.at(i
).data().toLongLong();
1128 // Find the node, disconnect it and clear the selected node
1129 if(g_connman
->DisconnectNode(id
))
1130 clearSelectedNode();
1134 void RPCConsole::banSelectedNode(int bantime
)
1136 if (!clientModel
|| !g_connman
)
1139 // Get selected peer addresses
1140 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->peerWidget
, PeerTableModel::NetNodeId
);
1141 for(int i
= 0; i
< nodes
.count(); i
++)
1143 // Get currently selected peer address
1144 NodeId id
= nodes
.at(i
).data().toLongLong();
1146 // Get currently selected peer address
1147 int detailNodeRow
= clientModel
->getPeerTableModel()->getRowByNodeId(id
);
1148 if(detailNodeRow
< 0)
1151 // Find possible nodes, ban it and clear the selected node
1152 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(detailNodeRow
);
1154 g_connman
->Ban(stats
->nodeStats
.addr
, BanReasonManuallyAdded
, bantime
);
1157 clearSelectedNode();
1158 clientModel
->getBanTableModel()->refresh();
1161 void RPCConsole::unbanSelectedNode()
1166 // Get selected ban addresses
1167 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->banlistWidget
, BanTableModel::Address
);
1168 for(int i
= 0; i
< nodes
.count(); i
++)
1170 // Get currently selected ban address
1171 QString strNode
= nodes
.at(i
).data().toString();
1172 CSubNet possibleSubnet
;
1174 LookupSubNet(strNode
.toStdString().c_str(), possibleSubnet
);
1175 if (possibleSubnet
.IsValid() && g_connman
)
1177 g_connman
->Unban(possibleSubnet
);
1178 clientModel
->getBanTableModel()->refresh();
1183 void RPCConsole::clearSelectedNode()
1185 ui
->peerWidget
->selectionModel()->clearSelection();
1186 cachedNodeids
.clear();
1187 ui
->detailWidget
->hide();
1188 ui
->peerHeading
->setText(tr("Select a peer to view detailed information."));
1191 void RPCConsole::showOrHideBanTableIfRequired()
1196 bool visible
= clientModel
->getBanTableModel()->shouldShow();
1197 ui
->banlistWidget
->setVisible(visible
);
1198 ui
->banHeading
->setVisible(visible
);
1201 void RPCConsole::setTabFocus(enum TabTypes tabType
)
1203 ui
->tabWidget
->setCurrentIndex(tabType
);