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(boost::function
<void(void)>& _func
, int64_t millis
):
104 timer
.setSingleShot(true);
105 connect(&timer
, SIGNAL(timeout()), this, SLOT(timeout()));
110 void timeout() { func(); }
113 boost::function
<void(void)> func
;
116 class QtRPCTimerInterface
: public RPCTimerInterface
119 ~QtRPCTimerInterface() {}
120 const char *Name() { return "Qt"; }
121 RPCTimerBase
* NewTimer(boost::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
))
733 message(CMD_REPLY
, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME
)) + "<br>" +
734 tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
735 tr("Type <b>help</b> for an overview of available commands.")) +
736 "<br><span class=\"secwarning\">" +
737 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 void RPCConsole::keyPressEvent(QKeyEvent
*event
)
744 if(windowType() != Qt::Widget
&& event
->key() == Qt::Key_Escape
)
750 void RPCConsole::message(int category
, const QString
&message
, bool html
)
752 QTime time
= QTime::currentTime();
753 QString timeString
= time
.toString();
755 out
+= "<table><tr><td class=\"time\" width=\"65\">" + timeString
+ "</td>";
756 out
+= "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category
) + "\"></td>";
757 out
+= "<td class=\"message " + categoryClass(category
) + "\" valign=\"middle\">";
761 out
+= GUIUtil::HtmlEscape(message
, false);
762 out
+= "</td></tr></table>";
763 ui
->messagesWidget
->append(out
);
766 void RPCConsole::updateNetworkState()
768 QString connections
= QString::number(clientModel
->getNumConnections()) + " (";
769 connections
+= tr("In:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_IN
)) + " / ";
770 connections
+= tr("Out:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_OUT
)) + ")";
772 if(!clientModel
->getNetworkActive()) {
773 connections
+= " (" + tr("Network activity disabled") + ")";
776 ui
->numberOfConnections
->setText(connections
);
779 void RPCConsole::setNumConnections(int count
)
784 updateNetworkState();
787 void RPCConsole::setNetworkActive(bool networkActive
)
789 updateNetworkState();
792 void RPCConsole::setNumBlocks(int count
, const QDateTime
& blockDate
, double nVerificationProgress
, bool headers
)
795 ui
->numberOfBlocks
->setText(QString::number(count
));
796 ui
->lastBlockTime
->setText(blockDate
.toString());
800 void RPCConsole::setMempoolSize(long numberOfTxs
, size_t dynUsage
)
802 ui
->mempoolNumberTxs
->setText(QString::number(numberOfTxs
));
804 if (dynUsage
< 1000000)
805 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000.0, 'f', 2) + " KB");
807 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000000.0, 'f', 2) + " MB");
810 void RPCConsole::on_lineEdit_returnPressed()
812 QString cmd
= ui
->lineEdit
->text();
816 std::string strFilteredCmd
;
819 if (!RPCParseCommandLine(dummy
, cmd
.toStdString(), false, &strFilteredCmd
)) {
820 // Failed to parse command, so we cannot even filter it for the history
821 throw std::runtime_error("Invalid command line");
823 } catch (const std::exception
& e
) {
824 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e
.what()));
828 ui
->lineEdit
->clear();
830 cmdBeforeBrowsing
= QString();
832 message(CMD_REQUEST
, QString::fromStdString(strFilteredCmd
));
833 Q_EMIT
cmdRequest(cmd
);
835 cmd
= QString::fromStdString(strFilteredCmd
);
837 // Remove command, if already in history
838 history
.removeOne(cmd
);
839 // Append command to history
841 // Enforce maximum history size
842 while(history
.size() > CONSOLE_HISTORY
)
843 history
.removeFirst();
844 // Set pointer to end of history
845 historyPtr
= history
.size();
847 // Scroll console view to end
852 void RPCConsole::browseHistory(int offset
)
854 // store current text when start browsing through the history
855 if (historyPtr
== history
.size()) {
856 cmdBeforeBrowsing
= ui
->lineEdit
->text();
859 historyPtr
+= offset
;
862 if(historyPtr
> history
.size())
863 historyPtr
= history
.size();
865 if(historyPtr
< history
.size())
866 cmd
= history
.at(historyPtr
);
867 else if (!cmdBeforeBrowsing
.isNull()) {
868 cmd
= cmdBeforeBrowsing
;
870 ui
->lineEdit
->setText(cmd
);
873 void RPCConsole::startExecutor()
875 RPCExecutor
*executor
= new RPCExecutor();
876 executor
->moveToThread(&thread
);
878 // Replies from executor object must go to this object
879 connect(executor
, SIGNAL(reply(int,QString
)), this, SLOT(message(int,QString
)));
880 // Requests from this object must go to executor
881 connect(this, SIGNAL(cmdRequest(QString
)), executor
, SLOT(request(QString
)));
883 // On stopExecutor signal
884 // - quit the Qt event loop in the execution thread
885 connect(this, SIGNAL(stopExecutor()), &thread
, SLOT(quit()));
886 // - queue executor for deletion (in execution thread)
887 connect(&thread
, SIGNAL(finished()), executor
, SLOT(deleteLater()), Qt::DirectConnection
);
889 // Default implementation of QThread::run() simply spins up an event loop in the thread,
890 // which is what we want.
894 void RPCConsole::on_tabWidget_currentChanged(int index
)
896 if (ui
->tabWidget
->widget(index
) == ui
->tab_console
)
897 ui
->lineEdit
->setFocus();
898 else if (ui
->tabWidget
->widget(index
) != ui
->tab_peers
)
902 void RPCConsole::on_openDebugLogfileButton_clicked()
904 GUIUtil::openDebugLogfile();
907 void RPCConsole::scrollToEnd()
909 QScrollBar
*scrollbar
= ui
->messagesWidget
->verticalScrollBar();
910 scrollbar
->setValue(scrollbar
->maximum());
913 void RPCConsole::on_sldGraphRange_valueChanged(int value
)
915 const int multiplier
= 5; // each position on the slider represents 5 min
916 int mins
= value
* multiplier
;
917 setTrafficGraphRange(mins
);
920 QString
RPCConsole::FormatBytes(quint64 bytes
)
923 return QString(tr("%1 B")).arg(bytes
);
924 if(bytes
< 1024 * 1024)
925 return QString(tr("%1 KB")).arg(bytes
/ 1024);
926 if(bytes
< 1024 * 1024 * 1024)
927 return QString(tr("%1 MB")).arg(bytes
/ 1024 / 1024);
929 return QString(tr("%1 GB")).arg(bytes
/ 1024 / 1024 / 1024);
932 void RPCConsole::setTrafficGraphRange(int mins
)
934 ui
->trafficGraph
->setGraphRangeMins(mins
);
935 ui
->lblGraphRange
->setText(GUIUtil::formatDurationStr(mins
* 60));
938 void RPCConsole::updateTrafficStats(quint64 totalBytesIn
, quint64 totalBytesOut
)
940 ui
->lblBytesIn
->setText(FormatBytes(totalBytesIn
));
941 ui
->lblBytesOut
->setText(FormatBytes(totalBytesOut
));
944 void RPCConsole::peerSelected(const QItemSelection
&selected
, const QItemSelection
&deselected
)
946 Q_UNUSED(deselected
);
948 if (!clientModel
|| !clientModel
->getPeerTableModel() || selected
.indexes().isEmpty())
951 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(selected
.indexes().first().row());
953 updateNodeDetail(stats
);
956 void RPCConsole::peerLayoutAboutToChange()
958 QModelIndexList selected
= ui
->peerWidget
->selectionModel()->selectedIndexes();
959 cachedNodeids
.clear();
960 for(int i
= 0; i
< selected
.size(); i
++)
962 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(selected
.at(i
).row());
963 cachedNodeids
.append(stats
->nodeStats
.nodeid
);
967 void RPCConsole::peerLayoutChanged()
969 if (!clientModel
|| !clientModel
->getPeerTableModel())
972 const CNodeCombinedStats
*stats
= NULL
;
973 bool fUnselect
= false;
974 bool fReselect
= false;
976 if (cachedNodeids
.empty()) // no node selected yet
979 // find the currently selected row
980 int selectedRow
= -1;
981 QModelIndexList selectedModelIndex
= ui
->peerWidget
->selectionModel()->selectedIndexes();
982 if (!selectedModelIndex
.isEmpty()) {
983 selectedRow
= selectedModelIndex
.first().row();
986 // check if our detail node has a row in the table (it may not necessarily
987 // be at selectedRow since its position can change after a layout change)
988 int detailNodeRow
= clientModel
->getPeerTableModel()->getRowByNodeId(cachedNodeids
.first());
990 if (detailNodeRow
< 0)
992 // detail node disappeared from table (node disconnected)
997 if (detailNodeRow
!= selectedRow
)
999 // detail node moved position
1004 // get fresh stats on the detail node.
1005 stats
= clientModel
->getPeerTableModel()->getNodeStats(detailNodeRow
);
1008 if (fUnselect
&& selectedRow
>= 0) {
1009 clearSelectedNode();
1014 for(int i
= 0; i
< cachedNodeids
.size(); i
++)
1016 ui
->peerWidget
->selectRow(clientModel
->getPeerTableModel()->getRowByNodeId(cachedNodeids
.at(i
)));
1021 updateNodeDetail(stats
);
1024 void RPCConsole::updateNodeDetail(const CNodeCombinedStats
*stats
)
1026 // update the detail ui with latest node information
1027 QString
peerAddrDetails(QString::fromStdString(stats
->nodeStats
.addrName
) + " ");
1028 peerAddrDetails
+= tr("(node id: %1)").arg(QString::number(stats
->nodeStats
.nodeid
));
1029 if (!stats
->nodeStats
.addrLocal
.empty())
1030 peerAddrDetails
+= "<br />" + tr("via %1").arg(QString::fromStdString(stats
->nodeStats
.addrLocal
));
1031 ui
->peerHeading
->setText(peerAddrDetails
);
1032 ui
->peerServices
->setText(GUIUtil::formatServicesStr(stats
->nodeStats
.nServices
));
1033 ui
->peerLastSend
->setText(stats
->nodeStats
.nLastSend
? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nLastSend
) : tr("never"));
1034 ui
->peerLastRecv
->setText(stats
->nodeStats
.nLastRecv
? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nLastRecv
) : tr("never"));
1035 ui
->peerBytesSent
->setText(FormatBytes(stats
->nodeStats
.nSendBytes
));
1036 ui
->peerBytesRecv
->setText(FormatBytes(stats
->nodeStats
.nRecvBytes
));
1037 ui
->peerConnTime
->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nTimeConnected
));
1038 ui
->peerPingTime
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dPingTime
));
1039 ui
->peerPingWait
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dPingWait
));
1040 ui
->peerMinPing
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dMinPing
));
1041 ui
->timeoffset
->setText(GUIUtil::formatTimeOffset(stats
->nodeStats
.nTimeOffset
));
1042 ui
->peerVersion
->setText(QString("%1").arg(QString::number(stats
->nodeStats
.nVersion
)));
1043 ui
->peerSubversion
->setText(QString::fromStdString(stats
->nodeStats
.cleanSubVer
));
1044 ui
->peerDirection
->setText(stats
->nodeStats
.fInbound
? tr("Inbound") : tr("Outbound"));
1045 ui
->peerHeight
->setText(QString("%1").arg(QString::number(stats
->nodeStats
.nStartingHeight
)));
1046 ui
->peerWhitelisted
->setText(stats
->nodeStats
.fWhitelisted
? tr("Yes") : tr("No"));
1048 // This check fails for example if the lock was busy and
1049 // nodeStateStats couldn't be fetched.
1050 if (stats
->fNodeStateStatsAvailable
) {
1051 // Ban score is init to 0
1052 ui
->peerBanScore
->setText(QString("%1").arg(stats
->nodeStateStats
.nMisbehavior
));
1054 // Sync height is init to -1
1055 if (stats
->nodeStateStats
.nSyncHeight
> -1)
1056 ui
->peerSyncHeight
->setText(QString("%1").arg(stats
->nodeStateStats
.nSyncHeight
));
1058 ui
->peerSyncHeight
->setText(tr("Unknown"));
1060 // Common height is init to -1
1061 if (stats
->nodeStateStats
.nCommonHeight
> -1)
1062 ui
->peerCommonHeight
->setText(QString("%1").arg(stats
->nodeStateStats
.nCommonHeight
));
1064 ui
->peerCommonHeight
->setText(tr("Unknown"));
1067 ui
->detailWidget
->show();
1070 void RPCConsole::resizeEvent(QResizeEvent
*event
)
1072 QWidget::resizeEvent(event
);
1075 void RPCConsole::showEvent(QShowEvent
*event
)
1077 QWidget::showEvent(event
);
1079 if (!clientModel
|| !clientModel
->getPeerTableModel())
1082 // start PeerTableModel auto refresh
1083 clientModel
->getPeerTableModel()->startAutoRefresh();
1086 void RPCConsole::hideEvent(QHideEvent
*event
)
1088 QWidget::hideEvent(event
);
1090 if (!clientModel
|| !clientModel
->getPeerTableModel())
1093 // stop PeerTableModel auto refresh
1094 clientModel
->getPeerTableModel()->stopAutoRefresh();
1097 void RPCConsole::showPeersTableContextMenu(const QPoint
& point
)
1099 QModelIndex index
= ui
->peerWidget
->indexAt(point
);
1100 if (index
.isValid())
1101 peersTableContextMenu
->exec(QCursor::pos());
1104 void RPCConsole::showBanTableContextMenu(const QPoint
& point
)
1106 QModelIndex index
= ui
->banlistWidget
->indexAt(point
);
1107 if (index
.isValid())
1108 banTableContextMenu
->exec(QCursor::pos());
1111 void RPCConsole::disconnectSelectedNode()
1116 // Get selected peer addresses
1117 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->peerWidget
, PeerTableModel::NetNodeId
);
1118 for(int i
= 0; i
< nodes
.count(); i
++)
1120 // Get currently selected peer address
1121 NodeId id
= nodes
.at(i
).data().toLongLong();
1122 // Find the node, disconnect it and clear the selected node
1123 if(g_connman
->DisconnectNode(id
))
1124 clearSelectedNode();
1128 void RPCConsole::banSelectedNode(int bantime
)
1130 if (!clientModel
|| !g_connman
)
1133 // Get selected peer addresses
1134 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->peerWidget
, PeerTableModel::NetNodeId
);
1135 for(int i
= 0; i
< nodes
.count(); i
++)
1137 // Get currently selected peer address
1138 NodeId id
= nodes
.at(i
).data().toLongLong();
1140 // Get currently selected peer address
1141 int detailNodeRow
= clientModel
->getPeerTableModel()->getRowByNodeId(id
);
1142 if(detailNodeRow
< 0)
1145 // Find possible nodes, ban it and clear the selected node
1146 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(detailNodeRow
);
1148 g_connman
->Ban(stats
->nodeStats
.addr
, BanReasonManuallyAdded
, bantime
);
1151 clearSelectedNode();
1152 clientModel
->getBanTableModel()->refresh();
1155 void RPCConsole::unbanSelectedNode()
1160 // Get selected ban addresses
1161 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->banlistWidget
, BanTableModel::Address
);
1162 for(int i
= 0; i
< nodes
.count(); i
++)
1164 // Get currently selected ban address
1165 QString strNode
= nodes
.at(i
).data().toString();
1166 CSubNet possibleSubnet
;
1168 LookupSubNet(strNode
.toStdString().c_str(), possibleSubnet
);
1169 if (possibleSubnet
.IsValid() && g_connman
)
1171 g_connman
->Unban(possibleSubnet
);
1172 clientModel
->getBanTableModel()->refresh();
1177 void RPCConsole::clearSelectedNode()
1179 ui
->peerWidget
->selectionModel()->clearSelection();
1180 cachedNodeids
.clear();
1181 ui
->detailWidget
->hide();
1182 ui
->peerHeading
->setText(tr("Select a peer to view detailed information."));
1185 void RPCConsole::showOrHideBanTableIfRequired()
1190 bool visible
= clientModel
->getBanTableModel()->shouldShow();
1191 ui
->banlistWidget
->setVisible(visible
);
1192 ui
->banHeading
->setVisible(visible
);
1195 void RPCConsole::setTabFocus(enum TabTypes tabType
)
1197 ui
->tabWidget
->setCurrentIndex(tabType
);