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 <qt/rpcconsole.h>
10 #include <qt/forms/ui_debugwindow.h>
12 #include <qt/bantablemodel.h>
13 #include <qt/clientmodel.h>
14 #include <qt/guiutil.h>
15 #include <qt/platformstyle.h>
16 #include <chainparams.h>
18 #include <rpc/server.h>
19 #include <rpc/client.h>
22 #include <openssl/crypto.h>
28 #include <wallet/wallet.h>
31 #include <QDesktopWidget>
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 <qt/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];
307 // TODO: Move this logic to WalletModel
308 if (!vpwallets
.empty()) {
309 // in Qt, use always the wallet with index 0 when running with multiple wallets
310 QByteArray encodedName
= QUrl::toPercentEncoding(QString::fromStdString(vpwallets
[0]->GetName()));
311 req
.URI
= "/wallet/"+std::string(encodedName
.constData(), encodedName
.length());
314 lastResult
= tableRPC
.execute(req
);
317 state
= STATE_COMMAND_EXECUTED
;
321 case ' ': case ',': case '\t':
322 if(state
== STATE_EATING_SPACES_IN_ARG
&& curarg
.empty() && ch
== ',')
323 throw std::runtime_error("Invalid Syntax");
325 else if(state
== STATE_ARGUMENT
) // Space ends argument
327 add_to_current_stack(curarg
);
330 if ((state
== STATE_EATING_SPACES_IN_BRACKETS
|| state
== STATE_ARGUMENT
) && ch
== ',')
332 state
= STATE_EATING_SPACES_IN_ARG
;
335 state
= STATE_EATING_SPACES
;
337 default: curarg
+= ch
; state
= STATE_ARGUMENT
;
340 case STATE_SINGLEQUOTED
: // Single-quoted string
343 case '\'': state
= STATE_ARGUMENT
; break;
344 default: curarg
+= ch
;
347 case STATE_DOUBLEQUOTED
: // Double-quoted string
350 case '"': state
= STATE_ARGUMENT
; break;
351 case '\\': state
= STATE_ESCAPE_DOUBLEQUOTED
; break;
352 default: curarg
+= ch
;
355 case STATE_ESCAPE_OUTER
: // '\' outside quotes
356 curarg
+= ch
; state
= STATE_ARGUMENT
;
358 case STATE_ESCAPE_DOUBLEQUOTED
: // '\' in double-quoted text
359 if(ch
!= '"' && ch
!= '\\') curarg
+= '\\'; // keep '\' for everything but the quote and '\' itself
360 curarg
+= ch
; state
= STATE_DOUBLEQUOTED
;
364 if (pstrFilteredOut
) {
365 if (STATE_COMMAND_EXECUTED
== state
) {
366 assert(!stack
.empty());
369 *pstrFilteredOut
= strCommand
;
370 for (auto i
= filter_ranges
.rbegin(); i
!= filter_ranges
.rend(); ++i
) {
371 pstrFilteredOut
->replace(i
->first
, i
->second
- i
->first
, "(…)");
374 switch(state
) // final state
376 case STATE_COMMAND_EXECUTED
:
377 if (lastResult
.isStr())
378 strResult
= lastResult
.get_str();
380 strResult
= lastResult
.write(2);
382 case STATE_EATING_SPACES
:
384 default: // ERROR to end in one of the other states
389 void RPCExecutor::request(const QString
&command
)
394 std::string executableCommand
= command
.toStdString() + "\n";
395 if(!RPCConsole::RPCExecuteCommandLine(result
, executableCommand
))
397 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString("Parse error: unbalanced ' or \""));
400 Q_EMIT
reply(RPCConsole::CMD_REPLY
, QString::fromStdString(result
));
402 catch (UniValue
& objError
)
404 try // Nice formatting for standard-format error
406 int code
= find_value(objError
, "code").get_int();
407 std::string message
= find_value(objError
, "message").get_str();
408 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString::fromStdString(message
) + " (code " + QString::number(code
) + ")");
410 catch (const std::runtime_error
&) // raised when converting to invalid type, i.e. missing code or message
411 { // Show raw JSON object
412 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString::fromStdString(objError
.write()));
415 catch (const std::exception
& e
)
417 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString("Error: ") + QString::fromStdString(e
.what()));
421 RPCConsole::RPCConsole(const PlatformStyle
*_platformStyle
, QWidget
*parent
) :
423 ui(new Ui::RPCConsole
),
426 platformStyle(_platformStyle
),
427 peersTableContextMenu(0),
428 banTableContextMenu(0),
433 if (!restoreGeometry(settings
.value("RPCConsoleWindowGeometry").toByteArray())) {
434 // Restore failed (perhaps missing setting), center the window
435 move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());
438 ui
->openDebugLogfileButton
->setToolTip(ui
->openDebugLogfileButton
->toolTip().arg(tr(PACKAGE_NAME
)));
440 if (platformStyle
->getImagesOnButtons()) {
441 ui
->openDebugLogfileButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/export"));
443 ui
->clearButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/remove"));
444 ui
->fontBiggerButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/fontbigger"));
445 ui
->fontSmallerButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/fontsmaller"));
447 // Install event filter for up and down arrow
448 ui
->lineEdit
->installEventFilter(this);
449 ui
->messagesWidget
->installEventFilter(this);
451 connect(ui
->clearButton
, SIGNAL(clicked()), this, SLOT(clear()));
452 connect(ui
->fontBiggerButton
, SIGNAL(clicked()), this, SLOT(fontBigger()));
453 connect(ui
->fontSmallerButton
, SIGNAL(clicked()), this, SLOT(fontSmaller()));
454 connect(ui
->btnClearTrafficGraph
, SIGNAL(clicked()), ui
->trafficGraph
, SLOT(clear()));
456 // set library version labels
458 ui
->berkeleyDBVersion
->setText(DbEnv::version(0, 0, 0));
460 ui
->label_berkeleyDBVersion
->hide();
461 ui
->berkeleyDBVersion
->hide();
463 // Register RPC timer interface
464 rpcTimerInterface
= new QtRPCTimerInterface();
465 // avoid accidentally overwriting an existing, non QTThread
466 // based timer interface
467 RPCSetTimerInterfaceIfUnset(rpcTimerInterface
);
469 setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS
);
471 ui
->detailWidget
->hide();
472 ui
->peerHeading
->setText(tr("Select a peer to view detailed information."));
474 consoleFontSize
= settings
.value(fontSizeSettingsKey
, QFontInfo(QFont()).pointSize()).toInt();
478 RPCConsole::~RPCConsole()
481 settings
.setValue("RPCConsoleWindowGeometry", saveGeometry());
482 RPCUnsetTimerInterface(rpcTimerInterface
);
483 delete rpcTimerInterface
;
487 bool RPCConsole::eventFilter(QObject
* obj
, QEvent
*event
)
489 if(event
->type() == QEvent::KeyPress
) // Special key handling
491 QKeyEvent
*keyevt
= static_cast<QKeyEvent
*>(event
);
492 int key
= keyevt
->key();
493 Qt::KeyboardModifiers mod
= keyevt
->modifiers();
496 case Qt::Key_Up
: if(obj
== ui
->lineEdit
) { browseHistory(-1); return true; } break;
497 case Qt::Key_Down
: if(obj
== ui
->lineEdit
) { browseHistory(1); return true; } break;
498 case Qt::Key_PageUp
: /* pass paging keys to messages widget */
499 case Qt::Key_PageDown
:
500 if(obj
== ui
->lineEdit
)
502 QApplication::postEvent(ui
->messagesWidget
, new QKeyEvent(*keyevt
));
508 // forward these events to lineEdit
509 if(obj
== autoCompleter
->popup()) {
510 QApplication::postEvent(ui
->lineEdit
, new QKeyEvent(*keyevt
));
515 // Typing in messages widget brings focus to line edit, and redirects key there
516 // Exclude most combinations and keys that emit no text, except paste shortcuts
517 if(obj
== ui
->messagesWidget
&& (
518 (!mod
&& !keyevt
->text().isEmpty() && key
!= Qt::Key_Tab
) ||
519 ((mod
& Qt::ControlModifier
) && key
== Qt::Key_V
) ||
520 ((mod
& Qt::ShiftModifier
) && key
== Qt::Key_Insert
)))
522 ui
->lineEdit
->setFocus();
523 QApplication::postEvent(ui
->lineEdit
, new QKeyEvent(*keyevt
));
528 return QWidget::eventFilter(obj
, event
);
531 void RPCConsole::setClientModel(ClientModel
*model
)
534 ui
->trafficGraph
->setClientModel(model
);
535 if (model
&& clientModel
->getPeerTableModel() && clientModel
->getBanTableModel()) {
536 // Keep up to date with client
537 setNumConnections(model
->getNumConnections());
538 connect(model
, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
540 setNumBlocks(model
->getNumBlocks(), model
->getLastBlockDate(), model
->getVerificationProgress(nullptr), false);
541 connect(model
, SIGNAL(numBlocksChanged(int,QDateTime
,double,bool)), this, SLOT(setNumBlocks(int,QDateTime
,double,bool)));
543 updateNetworkState();
544 connect(model
, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
546 updateTrafficStats(model
->getTotalBytesRecv(), model
->getTotalBytesSent());
547 connect(model
, SIGNAL(bytesChanged(quint64
,quint64
)), this, SLOT(updateTrafficStats(quint64
, quint64
)));
549 connect(model
, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
552 ui
->peerWidget
->setModel(model
->getPeerTableModel());
553 ui
->peerWidget
->verticalHeader()->hide();
554 ui
->peerWidget
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
555 ui
->peerWidget
->setSelectionBehavior(QAbstractItemView::SelectRows
);
556 ui
->peerWidget
->setSelectionMode(QAbstractItemView::ExtendedSelection
);
557 ui
->peerWidget
->setContextMenuPolicy(Qt::CustomContextMenu
);
558 ui
->peerWidget
->setColumnWidth(PeerTableModel::Address
, ADDRESS_COLUMN_WIDTH
);
559 ui
->peerWidget
->setColumnWidth(PeerTableModel::Subversion
, SUBVERSION_COLUMN_WIDTH
);
560 ui
->peerWidget
->setColumnWidth(PeerTableModel::Ping
, PING_COLUMN_WIDTH
);
561 ui
->peerWidget
->horizontalHeader()->setStretchLastSection(true);
563 // create peer table context menu actions
564 QAction
* disconnectAction
= new QAction(tr("&Disconnect"), this);
565 QAction
* banAction1h
= new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
566 QAction
* banAction24h
= new QAction(tr("Ban for") + " " + tr("1 &day"), this);
567 QAction
* banAction7d
= new QAction(tr("Ban for") + " " + tr("1 &week"), this);
568 QAction
* banAction365d
= new QAction(tr("Ban for") + " " + tr("1 &year"), this);
570 // create peer table context menu
571 peersTableContextMenu
= new QMenu(this);
572 peersTableContextMenu
->addAction(disconnectAction
);
573 peersTableContextMenu
->addAction(banAction1h
);
574 peersTableContextMenu
->addAction(banAction24h
);
575 peersTableContextMenu
->addAction(banAction7d
);
576 peersTableContextMenu
->addAction(banAction365d
);
578 // Add a signal mapping to allow dynamic context menu arguments.
579 // We need to use int (instead of int64_t), because signal mapper only supports
580 // int or objects, which is okay because max bantime (1 year) is < int_max.
581 QSignalMapper
* signalMapper
= new QSignalMapper(this);
582 signalMapper
->setMapping(banAction1h
, 60*60);
583 signalMapper
->setMapping(banAction24h
, 60*60*24);
584 signalMapper
->setMapping(banAction7d
, 60*60*24*7);
585 signalMapper
->setMapping(banAction365d
, 60*60*24*365);
586 connect(banAction1h
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
587 connect(banAction24h
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
588 connect(banAction7d
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
589 connect(banAction365d
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
590 connect(signalMapper
, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
592 // peer table context menu signals
593 connect(ui
->peerWidget
, SIGNAL(customContextMenuRequested(const QPoint
&)), this, SLOT(showPeersTableContextMenu(const QPoint
&)));
594 connect(disconnectAction
, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
596 // peer table signal handling - update peer details when selecting new node
597 connect(ui
->peerWidget
->selectionModel(), SIGNAL(selectionChanged(const QItemSelection
&, const QItemSelection
&)),
598 this, SLOT(peerSelected(const QItemSelection
&, const QItemSelection
&)));
599 // peer table signal handling - update peer details when new nodes are added to the model
600 connect(model
->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
601 // peer table signal handling - cache selected node ids
602 connect(model
->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
605 ui
->banlistWidget
->setModel(model
->getBanTableModel());
606 ui
->banlistWidget
->verticalHeader()->hide();
607 ui
->banlistWidget
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
608 ui
->banlistWidget
->setSelectionBehavior(QAbstractItemView::SelectRows
);
609 ui
->banlistWidget
->setSelectionMode(QAbstractItemView::SingleSelection
);
610 ui
->banlistWidget
->setContextMenuPolicy(Qt::CustomContextMenu
);
611 ui
->banlistWidget
->setColumnWidth(BanTableModel::Address
, BANSUBNET_COLUMN_WIDTH
);
612 ui
->banlistWidget
->setColumnWidth(BanTableModel::Bantime
, BANTIME_COLUMN_WIDTH
);
613 ui
->banlistWidget
->horizontalHeader()->setStretchLastSection(true);
615 // create ban table context menu action
616 QAction
* unbanAction
= new QAction(tr("&Unban"), this);
618 // create ban table context menu
619 banTableContextMenu
= new QMenu(this);
620 banTableContextMenu
->addAction(unbanAction
);
622 // ban table context menu signals
623 connect(ui
->banlistWidget
, SIGNAL(customContextMenuRequested(const QPoint
&)), this, SLOT(showBanTableContextMenu(const QPoint
&)));
624 connect(unbanAction
, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
626 // ban table signal handling - clear peer details when clicking a peer in the ban table
627 connect(ui
->banlistWidget
, SIGNAL(clicked(const QModelIndex
&)), this, SLOT(clearSelectedNode()));
628 // ban table signal handling - ensure ban table is shown or hidden (if empty)
629 connect(model
->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
630 showOrHideBanTableIfRequired();
632 // Provide initial values
633 ui
->clientVersion
->setText(model
->formatFullVersion());
634 ui
->clientUserAgent
->setText(model
->formatSubVersion());
635 ui
->dataDir
->setText(model
->dataDir());
636 ui
->startupTime
->setText(model
->formatClientStartupTime());
637 ui
->networkName
->setText(QString::fromStdString(Params().NetworkIDString()));
639 //Setup autocomplete and attach it
640 QStringList wordList
;
641 std::vector
<std::string
> commandList
= tableRPC
.listCommands();
642 for (size_t i
= 0; i
< commandList
.size(); ++i
)
644 wordList
<< commandList
[i
].c_str();
645 wordList
<< ("help " + commandList
[i
]).c_str();
649 autoCompleter
= new QCompleter(wordList
, this);
650 autoCompleter
->setModelSorting(QCompleter::CaseSensitivelySortedModel
);
651 ui
->lineEdit
->setCompleter(autoCompleter
);
652 autoCompleter
->popup()->installEventFilter(this);
653 // Start thread to execute RPC commands.
657 // Client model is being set to 0, this means shutdown() is about to be called.
658 // Make sure we clean up the executor thread
659 Q_EMIT
stopExecutor();
664 static QString
categoryClass(int category
)
668 case RPCConsole::CMD_REQUEST
: return "cmd-request"; break;
669 case RPCConsole::CMD_REPLY
: return "cmd-reply"; break;
670 case RPCConsole::CMD_ERROR
: return "cmd-error"; break;
671 default: return "misc";
675 void RPCConsole::fontBigger()
677 setFontSize(consoleFontSize
+1);
680 void RPCConsole::fontSmaller()
682 setFontSize(consoleFontSize
-1);
685 void RPCConsole::setFontSize(int newSize
)
689 //don't allow an insane font size
690 if (newSize
< FONT_RANGE
.width() || newSize
> FONT_RANGE
.height())
693 // temp. store the console content
694 QString str
= ui
->messagesWidget
->toHtml();
696 // replace font tags size in current content
697 str
.replace(QString("font-size:%1pt").arg(consoleFontSize
), QString("font-size:%1pt").arg(newSize
));
699 // store the new font size
700 consoleFontSize
= newSize
;
701 settings
.setValue(fontSizeSettingsKey
, consoleFontSize
);
703 // clear console (reset icon sizes, default stylesheet) and re-add the content
704 float oldPosFactor
= 1.0 / ui
->messagesWidget
->verticalScrollBar()->maximum() * ui
->messagesWidget
->verticalScrollBar()->value();
706 ui
->messagesWidget
->setHtml(str
);
707 ui
->messagesWidget
->verticalScrollBar()->setValue(oldPosFactor
* ui
->messagesWidget
->verticalScrollBar()->maximum());
710 void RPCConsole::clear(bool clearHistory
)
712 ui
->messagesWidget
->clear();
718 ui
->lineEdit
->clear();
719 ui
->lineEdit
->setFocus();
721 // Add smoothly scaled icon images.
722 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
723 for(int i
=0; ICON_MAPPING
[i
].url
; ++i
)
725 ui
->messagesWidget
->document()->addResource(
726 QTextDocument::ImageResource
,
727 QUrl(ICON_MAPPING
[i
].url
),
728 platformStyle
->SingleColorImage(ICON_MAPPING
[i
].source
).scaled(QSize(consoleFontSize
*2, consoleFontSize
*2), Qt::IgnoreAspectRatio
, Qt::SmoothTransformation
));
731 // Set default style sheet
732 QFontInfo
fixedFontInfo(GUIUtil::fixedPitchFont());
733 ui
->messagesWidget
->document()->setDefaultStyleSheet(
736 "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
737 "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
738 "td.cmd-request { color: #006060; } "
739 "td.cmd-error { color: red; } "
740 ".secwarning { color: red; }"
741 "b { color: #006060; } "
742 ).arg(fixedFontInfo
.family(), QString("%1pt").arg(consoleFontSize
))
746 QString clsKey
= "(⌘)-L";
748 QString clsKey
= "Ctrl-L";
751 message(CMD_REPLY
, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME
)) + "<br>" +
752 tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey
+"</b>") + "<br>" +
753 tr("Type <b>help</b> for an overview of available commands.")) +
754 "<br><span class=\"secwarning\">" +
755 tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
760 void RPCConsole::keyPressEvent(QKeyEvent
*event
)
762 if(windowType() != Qt::Widget
&& event
->key() == Qt::Key_Escape
)
768 void RPCConsole::message(int category
, const QString
&message
, bool html
)
770 QTime time
= QTime::currentTime();
771 QString timeString
= time
.toString();
773 out
+= "<table><tr><td class=\"time\" width=\"65\">" + timeString
+ "</td>";
774 out
+= "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category
) + "\"></td>";
775 out
+= "<td class=\"message " + categoryClass(category
) + "\" valign=\"middle\">";
779 out
+= GUIUtil::HtmlEscape(message
, false);
780 out
+= "</td></tr></table>";
781 ui
->messagesWidget
->append(out
);
784 void RPCConsole::updateNetworkState()
786 QString connections
= QString::number(clientModel
->getNumConnections()) + " (";
787 connections
+= tr("In:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_IN
)) + " / ";
788 connections
+= tr("Out:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_OUT
)) + ")";
790 if(!clientModel
->getNetworkActive()) {
791 connections
+= " (" + tr("Network activity disabled") + ")";
794 ui
->numberOfConnections
->setText(connections
);
797 void RPCConsole::setNumConnections(int count
)
802 updateNetworkState();
805 void RPCConsole::setNetworkActive(bool networkActive
)
807 updateNetworkState();
810 void RPCConsole::setNumBlocks(int count
, const QDateTime
& blockDate
, double nVerificationProgress
, bool headers
)
813 ui
->numberOfBlocks
->setText(QString::number(count
));
814 ui
->lastBlockTime
->setText(blockDate
.toString());
818 void RPCConsole::setMempoolSize(long numberOfTxs
, size_t dynUsage
)
820 ui
->mempoolNumberTxs
->setText(QString::number(numberOfTxs
));
822 if (dynUsage
< 1000000)
823 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000.0, 'f', 2) + " KB");
825 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000000.0, 'f', 2) + " MB");
828 void RPCConsole::on_lineEdit_returnPressed()
830 QString cmd
= ui
->lineEdit
->text();
834 std::string strFilteredCmd
;
837 if (!RPCParseCommandLine(dummy
, cmd
.toStdString(), false, &strFilteredCmd
)) {
838 // Failed to parse command, so we cannot even filter it for the history
839 throw std::runtime_error("Invalid command line");
841 } catch (const std::exception
& e
) {
842 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e
.what()));
846 ui
->lineEdit
->clear();
848 cmdBeforeBrowsing
= QString();
850 message(CMD_REQUEST
, QString::fromStdString(strFilteredCmd
));
851 Q_EMIT
cmdRequest(cmd
);
853 cmd
= QString::fromStdString(strFilteredCmd
);
855 // Remove command, if already in history
856 history
.removeOne(cmd
);
857 // Append command to history
859 // Enforce maximum history size
860 while(history
.size() > CONSOLE_HISTORY
)
861 history
.removeFirst();
862 // Set pointer to end of history
863 historyPtr
= history
.size();
865 // Scroll console view to end
870 void RPCConsole::browseHistory(int offset
)
872 // store current text when start browsing through the history
873 if (historyPtr
== history
.size()) {
874 cmdBeforeBrowsing
= ui
->lineEdit
->text();
877 historyPtr
+= offset
;
880 if(historyPtr
> history
.size())
881 historyPtr
= history
.size();
883 if(historyPtr
< history
.size())
884 cmd
= history
.at(historyPtr
);
885 else if (!cmdBeforeBrowsing
.isNull()) {
886 cmd
= cmdBeforeBrowsing
;
888 ui
->lineEdit
->setText(cmd
);
891 void RPCConsole::startExecutor()
893 RPCExecutor
*executor
= new RPCExecutor();
894 executor
->moveToThread(&thread
);
896 // Replies from executor object must go to this object
897 connect(executor
, SIGNAL(reply(int,QString
)), this, SLOT(message(int,QString
)));
898 // Requests from this object must go to executor
899 connect(this, SIGNAL(cmdRequest(QString
)), executor
, SLOT(request(QString
)));
901 // On stopExecutor signal
902 // - quit the Qt event loop in the execution thread
903 connect(this, SIGNAL(stopExecutor()), &thread
, SLOT(quit()));
904 // - queue executor for deletion (in execution thread)
905 connect(&thread
, SIGNAL(finished()), executor
, SLOT(deleteLater()), Qt::DirectConnection
);
907 // Default implementation of QThread::run() simply spins up an event loop in the thread,
908 // which is what we want.
912 void RPCConsole::on_tabWidget_currentChanged(int index
)
914 if (ui
->tabWidget
->widget(index
) == ui
->tab_console
)
915 ui
->lineEdit
->setFocus();
916 else if (ui
->tabWidget
->widget(index
) != ui
->tab_peers
)
920 void RPCConsole::on_openDebugLogfileButton_clicked()
922 GUIUtil::openDebugLogfile();
925 void RPCConsole::scrollToEnd()
927 QScrollBar
*scrollbar
= ui
->messagesWidget
->verticalScrollBar();
928 scrollbar
->setValue(scrollbar
->maximum());
931 void RPCConsole::on_sldGraphRange_valueChanged(int value
)
933 const int multiplier
= 5; // each position on the slider represents 5 min
934 int mins
= value
* multiplier
;
935 setTrafficGraphRange(mins
);
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(GUIUtil::formatBytes(totalBytesIn
));
947 ui
->lblBytesOut
->setText(GUIUtil::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
= nullptr;
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(GUIUtil::formatBytes(stats
->nodeStats
.nSendBytes
));
1042 ui
->peerBytesRecv
->setText(GUIUtil::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
);