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";
396 // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply.
397 if(executableCommand
== "help-console\n")
399 Q_EMIT
reply(RPCConsole::CMD_REPLY
, QString(("\n"
400 "This console accepts RPC commands using the standard syntax.\n"
401 " example: getblockhash 0\n\n"
403 "This console can also accept RPC commands using parenthesized syntax.\n"
404 " example: getblockhash(0)\n\n"
406 "Commands may be nested when specified with the parenthesized syntax.\n"
407 " example: getblock(getblockhash(0) 1)\n\n"
409 "A space or a comma can be used to delimit arguments for either syntax.\n"
410 " example: getblockhash 0\n"
411 " getblockhash,0\n\n"
413 "Named results can be queried with a non-quoted key string in brackets.\n"
414 " example: getblock(getblockhash(0) true)[tx]\n\n"
416 "Results without keys can be queried using an integer in brackets.\n"
417 " example: getblock(getblockhash(0),true)[tx][0]\n\n")));
420 if(!RPCConsole::RPCExecuteCommandLine(result
, executableCommand
))
422 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString("Parse error: unbalanced ' or \""));
426 Q_EMIT
reply(RPCConsole::CMD_REPLY
, QString::fromStdString(result
));
428 catch (UniValue
& objError
)
430 try // Nice formatting for standard-format error
432 int code
= find_value(objError
, "code").get_int();
433 std::string message
= find_value(objError
, "message").get_str();
434 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString::fromStdString(message
) + " (code " + QString::number(code
) + ")");
436 catch (const std::runtime_error
&) // raised when converting to invalid type, i.e. missing code or message
437 { // Show raw JSON object
438 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString::fromStdString(objError
.write()));
441 catch (const std::exception
& e
)
443 Q_EMIT
reply(RPCConsole::CMD_ERROR
, QString("Error: ") + QString::fromStdString(e
.what()));
447 RPCConsole::RPCConsole(const PlatformStyle
*_platformStyle
, QWidget
*parent
) :
449 ui(new Ui::RPCConsole
),
452 platformStyle(_platformStyle
),
453 peersTableContextMenu(0),
454 banTableContextMenu(0),
459 if (!restoreGeometry(settings
.value("RPCConsoleWindowGeometry").toByteArray())) {
460 // Restore failed (perhaps missing setting), center the window
461 move(QApplication::desktop()->availableGeometry().center() - frameGeometry().center());
464 ui
->openDebugLogfileButton
->setToolTip(ui
->openDebugLogfileButton
->toolTip().arg(tr(PACKAGE_NAME
)));
466 if (platformStyle
->getImagesOnButtons()) {
467 ui
->openDebugLogfileButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/export"));
469 ui
->clearButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/remove"));
470 ui
->fontBiggerButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/fontbigger"));
471 ui
->fontSmallerButton
->setIcon(platformStyle
->SingleColorIcon(":/icons/fontsmaller"));
473 // Install event filter for up and down arrow
474 ui
->lineEdit
->installEventFilter(this);
475 ui
->messagesWidget
->installEventFilter(this);
477 connect(ui
->clearButton
, SIGNAL(clicked()), this, SLOT(clear()));
478 connect(ui
->fontBiggerButton
, SIGNAL(clicked()), this, SLOT(fontBigger()));
479 connect(ui
->fontSmallerButton
, SIGNAL(clicked()), this, SLOT(fontSmaller()));
480 connect(ui
->btnClearTrafficGraph
, SIGNAL(clicked()), ui
->trafficGraph
, SLOT(clear()));
482 // set library version labels
484 ui
->berkeleyDBVersion
->setText(DbEnv::version(0, 0, 0));
486 ui
->label_berkeleyDBVersion
->hide();
487 ui
->berkeleyDBVersion
->hide();
489 // Register RPC timer interface
490 rpcTimerInterface
= new QtRPCTimerInterface();
491 // avoid accidentally overwriting an existing, non QTThread
492 // based timer interface
493 RPCSetTimerInterfaceIfUnset(rpcTimerInterface
);
495 setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS
);
497 ui
->detailWidget
->hide();
498 ui
->peerHeading
->setText(tr("Select a peer to view detailed information."));
500 consoleFontSize
= settings
.value(fontSizeSettingsKey
, QFontInfo(QFont()).pointSize()).toInt();
504 RPCConsole::~RPCConsole()
507 settings
.setValue("RPCConsoleWindowGeometry", saveGeometry());
508 RPCUnsetTimerInterface(rpcTimerInterface
);
509 delete rpcTimerInterface
;
513 bool RPCConsole::eventFilter(QObject
* obj
, QEvent
*event
)
515 if(event
->type() == QEvent::KeyPress
) // Special key handling
517 QKeyEvent
*keyevt
= static_cast<QKeyEvent
*>(event
);
518 int key
= keyevt
->key();
519 Qt::KeyboardModifiers mod
= keyevt
->modifiers();
522 case Qt::Key_Up
: if(obj
== ui
->lineEdit
) { browseHistory(-1); return true; } break;
523 case Qt::Key_Down
: if(obj
== ui
->lineEdit
) { browseHistory(1); return true; } break;
524 case Qt::Key_PageUp
: /* pass paging keys to messages widget */
525 case Qt::Key_PageDown
:
526 if(obj
== ui
->lineEdit
)
528 QApplication::postEvent(ui
->messagesWidget
, new QKeyEvent(*keyevt
));
534 // forward these events to lineEdit
535 if(obj
== autoCompleter
->popup()) {
536 QApplication::postEvent(ui
->lineEdit
, new QKeyEvent(*keyevt
));
541 // Typing in messages widget brings focus to line edit, and redirects key there
542 // Exclude most combinations and keys that emit no text, except paste shortcuts
543 if(obj
== ui
->messagesWidget
&& (
544 (!mod
&& !keyevt
->text().isEmpty() && key
!= Qt::Key_Tab
) ||
545 ((mod
& Qt::ControlModifier
) && key
== Qt::Key_V
) ||
546 ((mod
& Qt::ShiftModifier
) && key
== Qt::Key_Insert
)))
548 ui
->lineEdit
->setFocus();
549 QApplication::postEvent(ui
->lineEdit
, new QKeyEvent(*keyevt
));
554 return QWidget::eventFilter(obj
, event
);
557 void RPCConsole::setClientModel(ClientModel
*model
)
560 ui
->trafficGraph
->setClientModel(model
);
561 if (model
&& clientModel
->getPeerTableModel() && clientModel
->getBanTableModel()) {
562 // Keep up to date with client
563 setNumConnections(model
->getNumConnections());
564 connect(model
, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
566 setNumBlocks(model
->getNumBlocks(), model
->getLastBlockDate(), model
->getVerificationProgress(nullptr), false);
567 connect(model
, SIGNAL(numBlocksChanged(int,QDateTime
,double,bool)), this, SLOT(setNumBlocks(int,QDateTime
,double,bool)));
569 updateNetworkState();
570 connect(model
, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
572 updateTrafficStats(model
->getTotalBytesRecv(), model
->getTotalBytesSent());
573 connect(model
, SIGNAL(bytesChanged(quint64
,quint64
)), this, SLOT(updateTrafficStats(quint64
, quint64
)));
575 connect(model
, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
578 ui
->peerWidget
->setModel(model
->getPeerTableModel());
579 ui
->peerWidget
->verticalHeader()->hide();
580 ui
->peerWidget
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
581 ui
->peerWidget
->setSelectionBehavior(QAbstractItemView::SelectRows
);
582 ui
->peerWidget
->setSelectionMode(QAbstractItemView::ExtendedSelection
);
583 ui
->peerWidget
->setContextMenuPolicy(Qt::CustomContextMenu
);
584 ui
->peerWidget
->setColumnWidth(PeerTableModel::Address
, ADDRESS_COLUMN_WIDTH
);
585 ui
->peerWidget
->setColumnWidth(PeerTableModel::Subversion
, SUBVERSION_COLUMN_WIDTH
);
586 ui
->peerWidget
->setColumnWidth(PeerTableModel::Ping
, PING_COLUMN_WIDTH
);
587 ui
->peerWidget
->horizontalHeader()->setStretchLastSection(true);
589 // create peer table context menu actions
590 QAction
* disconnectAction
= new QAction(tr("&Disconnect"), this);
591 QAction
* banAction1h
= new QAction(tr("Ban for") + " " + tr("1 &hour"), this);
592 QAction
* banAction24h
= new QAction(tr("Ban for") + " " + tr("1 &day"), this);
593 QAction
* banAction7d
= new QAction(tr("Ban for") + " " + tr("1 &week"), this);
594 QAction
* banAction365d
= new QAction(tr("Ban for") + " " + tr("1 &year"), this);
596 // create peer table context menu
597 peersTableContextMenu
= new QMenu(this);
598 peersTableContextMenu
->addAction(disconnectAction
);
599 peersTableContextMenu
->addAction(banAction1h
);
600 peersTableContextMenu
->addAction(banAction24h
);
601 peersTableContextMenu
->addAction(banAction7d
);
602 peersTableContextMenu
->addAction(banAction365d
);
604 // Add a signal mapping to allow dynamic context menu arguments.
605 // We need to use int (instead of int64_t), because signal mapper only supports
606 // int or objects, which is okay because max bantime (1 year) is < int_max.
607 QSignalMapper
* signalMapper
= new QSignalMapper(this);
608 signalMapper
->setMapping(banAction1h
, 60*60);
609 signalMapper
->setMapping(banAction24h
, 60*60*24);
610 signalMapper
->setMapping(banAction7d
, 60*60*24*7);
611 signalMapper
->setMapping(banAction365d
, 60*60*24*365);
612 connect(banAction1h
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
613 connect(banAction24h
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
614 connect(banAction7d
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
615 connect(banAction365d
, SIGNAL(triggered()), signalMapper
, SLOT(map()));
616 connect(signalMapper
, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
618 // peer table context menu signals
619 connect(ui
->peerWidget
, SIGNAL(customContextMenuRequested(const QPoint
&)), this, SLOT(showPeersTableContextMenu(const QPoint
&)));
620 connect(disconnectAction
, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
622 // peer table signal handling - update peer details when selecting new node
623 connect(ui
->peerWidget
->selectionModel(), SIGNAL(selectionChanged(const QItemSelection
&, const QItemSelection
&)),
624 this, SLOT(peerSelected(const QItemSelection
&, const QItemSelection
&)));
625 // peer table signal handling - update peer details when new nodes are added to the model
626 connect(model
->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
627 // peer table signal handling - cache selected node ids
628 connect(model
->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange()));
631 ui
->banlistWidget
->setModel(model
->getBanTableModel());
632 ui
->banlistWidget
->verticalHeader()->hide();
633 ui
->banlistWidget
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
634 ui
->banlistWidget
->setSelectionBehavior(QAbstractItemView::SelectRows
);
635 ui
->banlistWidget
->setSelectionMode(QAbstractItemView::SingleSelection
);
636 ui
->banlistWidget
->setContextMenuPolicy(Qt::CustomContextMenu
);
637 ui
->banlistWidget
->setColumnWidth(BanTableModel::Address
, BANSUBNET_COLUMN_WIDTH
);
638 ui
->banlistWidget
->setColumnWidth(BanTableModel::Bantime
, BANTIME_COLUMN_WIDTH
);
639 ui
->banlistWidget
->horizontalHeader()->setStretchLastSection(true);
641 // create ban table context menu action
642 QAction
* unbanAction
= new QAction(tr("&Unban"), this);
644 // create ban table context menu
645 banTableContextMenu
= new QMenu(this);
646 banTableContextMenu
->addAction(unbanAction
);
648 // ban table context menu signals
649 connect(ui
->banlistWidget
, SIGNAL(customContextMenuRequested(const QPoint
&)), this, SLOT(showBanTableContextMenu(const QPoint
&)));
650 connect(unbanAction
, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
652 // ban table signal handling - clear peer details when clicking a peer in the ban table
653 connect(ui
->banlistWidget
, SIGNAL(clicked(const QModelIndex
&)), this, SLOT(clearSelectedNode()));
654 // ban table signal handling - ensure ban table is shown or hidden (if empty)
655 connect(model
->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
656 showOrHideBanTableIfRequired();
658 // Provide initial values
659 ui
->clientVersion
->setText(model
->formatFullVersion());
660 ui
->clientUserAgent
->setText(model
->formatSubVersion());
661 ui
->dataDir
->setText(model
->dataDir());
662 ui
->startupTime
->setText(model
->formatClientStartupTime());
663 ui
->networkName
->setText(QString::fromStdString(Params().NetworkIDString()));
665 //Setup autocomplete and attach it
666 QStringList wordList
;
667 std::vector
<std::string
> commandList
= tableRPC
.listCommands();
668 for (size_t i
= 0; i
< commandList
.size(); ++i
)
670 wordList
<< commandList
[i
].c_str();
671 wordList
<< ("help " + commandList
[i
]).c_str();
674 wordList
<< "help-console";
676 autoCompleter
= new QCompleter(wordList
, this);
677 autoCompleter
->setModelSorting(QCompleter::CaseSensitivelySortedModel
);
678 ui
->lineEdit
->setCompleter(autoCompleter
);
679 autoCompleter
->popup()->installEventFilter(this);
680 // Start thread to execute RPC commands.
684 // Client model is being set to 0, this means shutdown() is about to be called.
685 // Make sure we clean up the executor thread
686 Q_EMIT
stopExecutor();
691 static QString
categoryClass(int category
)
695 case RPCConsole::CMD_REQUEST
: return "cmd-request"; break;
696 case RPCConsole::CMD_REPLY
: return "cmd-reply"; break;
697 case RPCConsole::CMD_ERROR
: return "cmd-error"; break;
698 default: return "misc";
702 void RPCConsole::fontBigger()
704 setFontSize(consoleFontSize
+1);
707 void RPCConsole::fontSmaller()
709 setFontSize(consoleFontSize
-1);
712 void RPCConsole::setFontSize(int newSize
)
716 //don't allow an insane font size
717 if (newSize
< FONT_RANGE
.width() || newSize
> FONT_RANGE
.height())
720 // temp. store the console content
721 QString str
= ui
->messagesWidget
->toHtml();
723 // replace font tags size in current content
724 str
.replace(QString("font-size:%1pt").arg(consoleFontSize
), QString("font-size:%1pt").arg(newSize
));
726 // store the new font size
727 consoleFontSize
= newSize
;
728 settings
.setValue(fontSizeSettingsKey
, consoleFontSize
);
730 // clear console (reset icon sizes, default stylesheet) and re-add the content
731 float oldPosFactor
= 1.0 / ui
->messagesWidget
->verticalScrollBar()->maximum() * ui
->messagesWidget
->verticalScrollBar()->value();
733 ui
->messagesWidget
->setHtml(str
);
734 ui
->messagesWidget
->verticalScrollBar()->setValue(oldPosFactor
* ui
->messagesWidget
->verticalScrollBar()->maximum());
737 void RPCConsole::clear(bool clearHistory
)
739 ui
->messagesWidget
->clear();
745 ui
->lineEdit
->clear();
746 ui
->lineEdit
->setFocus();
748 // Add smoothly scaled icon images.
749 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
750 for(int i
=0; ICON_MAPPING
[i
].url
; ++i
)
752 ui
->messagesWidget
->document()->addResource(
753 QTextDocument::ImageResource
,
754 QUrl(ICON_MAPPING
[i
].url
),
755 platformStyle
->SingleColorImage(ICON_MAPPING
[i
].source
).scaled(QSize(consoleFontSize
*2, consoleFontSize
*2), Qt::IgnoreAspectRatio
, Qt::SmoothTransformation
));
758 // Set default style sheet
759 QFontInfo
fixedFontInfo(GUIUtil::fixedPitchFont());
760 ui
->messagesWidget
->document()->setDefaultStyleSheet(
763 "td.time { color: #808080; font-size: %2; padding-top: 3px; } "
764 "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
765 "td.cmd-request { color: #006060; } "
766 "td.cmd-error { color: red; } "
767 ".secwarning { color: red; }"
768 "b { color: #006060; } "
769 ).arg(fixedFontInfo
.family(), QString("%1pt").arg(consoleFontSize
))
773 QString clsKey
= "(⌘)-L";
775 QString clsKey
= "Ctrl-L";
778 message(CMD_REPLY
, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME
)) + "<br>" +
779 tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey
+"</b>") + "<br>" +
780 tr("Type %1 for an overview of available commands.").arg("<b>help</b>") + "<br>" +
781 tr("For more information on using this console type %1.").arg("<b>help-console</b>") +
782 "<br><span class=\"secwarning\"><br>" +
783 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.") +
788 void RPCConsole::keyPressEvent(QKeyEvent
*event
)
790 if(windowType() != Qt::Widget
&& event
->key() == Qt::Key_Escape
)
796 void RPCConsole::message(int category
, const QString
&message
, bool html
)
798 QTime time
= QTime::currentTime();
799 QString timeString
= time
.toString();
801 out
+= "<table><tr><td class=\"time\" width=\"65\">" + timeString
+ "</td>";
802 out
+= "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category
) + "\"></td>";
803 out
+= "<td class=\"message " + categoryClass(category
) + "\" valign=\"middle\">";
807 out
+= GUIUtil::HtmlEscape(message
, false);
808 out
+= "</td></tr></table>";
809 ui
->messagesWidget
->append(out
);
812 void RPCConsole::updateNetworkState()
814 QString connections
= QString::number(clientModel
->getNumConnections()) + " (";
815 connections
+= tr("In:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_IN
)) + " / ";
816 connections
+= tr("Out:") + " " + QString::number(clientModel
->getNumConnections(CONNECTIONS_OUT
)) + ")";
818 if(!clientModel
->getNetworkActive()) {
819 connections
+= " (" + tr("Network activity disabled") + ")";
822 ui
->numberOfConnections
->setText(connections
);
825 void RPCConsole::setNumConnections(int count
)
830 updateNetworkState();
833 void RPCConsole::setNetworkActive(bool networkActive
)
835 updateNetworkState();
838 void RPCConsole::setNumBlocks(int count
, const QDateTime
& blockDate
, double nVerificationProgress
, bool headers
)
841 ui
->numberOfBlocks
->setText(QString::number(count
));
842 ui
->lastBlockTime
->setText(blockDate
.toString());
846 void RPCConsole::setMempoolSize(long numberOfTxs
, size_t dynUsage
)
848 ui
->mempoolNumberTxs
->setText(QString::number(numberOfTxs
));
850 if (dynUsage
< 1000000)
851 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000.0, 'f', 2) + " KB");
853 ui
->mempoolSize
->setText(QString::number(dynUsage
/1000000.0, 'f', 2) + " MB");
856 void RPCConsole::on_lineEdit_returnPressed()
858 QString cmd
= ui
->lineEdit
->text();
862 std::string strFilteredCmd
;
865 if (!RPCParseCommandLine(dummy
, cmd
.toStdString(), false, &strFilteredCmd
)) {
866 // Failed to parse command, so we cannot even filter it for the history
867 throw std::runtime_error("Invalid command line");
869 } catch (const std::exception
& e
) {
870 QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e
.what()));
874 ui
->lineEdit
->clear();
876 cmdBeforeBrowsing
= QString();
878 message(CMD_REQUEST
, QString::fromStdString(strFilteredCmd
));
879 Q_EMIT
cmdRequest(cmd
);
881 cmd
= QString::fromStdString(strFilteredCmd
);
883 // Remove command, if already in history
884 history
.removeOne(cmd
);
885 // Append command to history
887 // Enforce maximum history size
888 while(history
.size() > CONSOLE_HISTORY
)
889 history
.removeFirst();
890 // Set pointer to end of history
891 historyPtr
= history
.size();
893 // Scroll console view to end
898 void RPCConsole::browseHistory(int offset
)
900 // store current text when start browsing through the history
901 if (historyPtr
== history
.size()) {
902 cmdBeforeBrowsing
= ui
->lineEdit
->text();
905 historyPtr
+= offset
;
908 if(historyPtr
> history
.size())
909 historyPtr
= history
.size();
911 if(historyPtr
< history
.size())
912 cmd
= history
.at(historyPtr
);
913 else if (!cmdBeforeBrowsing
.isNull()) {
914 cmd
= cmdBeforeBrowsing
;
916 ui
->lineEdit
->setText(cmd
);
919 void RPCConsole::startExecutor()
921 RPCExecutor
*executor
= new RPCExecutor();
922 executor
->moveToThread(&thread
);
924 // Replies from executor object must go to this object
925 connect(executor
, SIGNAL(reply(int,QString
)), this, SLOT(message(int,QString
)));
926 // Requests from this object must go to executor
927 connect(this, SIGNAL(cmdRequest(QString
)), executor
, SLOT(request(QString
)));
929 // On stopExecutor signal
930 // - quit the Qt event loop in the execution thread
931 connect(this, SIGNAL(stopExecutor()), &thread
, SLOT(quit()));
932 // - queue executor for deletion (in execution thread)
933 connect(&thread
, SIGNAL(finished()), executor
, SLOT(deleteLater()), Qt::DirectConnection
);
935 // Default implementation of QThread::run() simply spins up an event loop in the thread,
936 // which is what we want.
940 void RPCConsole::on_tabWidget_currentChanged(int index
)
942 if (ui
->tabWidget
->widget(index
) == ui
->tab_console
)
943 ui
->lineEdit
->setFocus();
944 else if (ui
->tabWidget
->widget(index
) != ui
->tab_peers
)
948 void RPCConsole::on_openDebugLogfileButton_clicked()
950 GUIUtil::openDebugLogfile();
953 void RPCConsole::scrollToEnd()
955 QScrollBar
*scrollbar
= ui
->messagesWidget
->verticalScrollBar();
956 scrollbar
->setValue(scrollbar
->maximum());
959 void RPCConsole::on_sldGraphRange_valueChanged(int value
)
961 const int multiplier
= 5; // each position on the slider represents 5 min
962 int mins
= value
* multiplier
;
963 setTrafficGraphRange(mins
);
966 void RPCConsole::setTrafficGraphRange(int mins
)
968 ui
->trafficGraph
->setGraphRangeMins(mins
);
969 ui
->lblGraphRange
->setText(GUIUtil::formatDurationStr(mins
* 60));
972 void RPCConsole::updateTrafficStats(quint64 totalBytesIn
, quint64 totalBytesOut
)
974 ui
->lblBytesIn
->setText(GUIUtil::formatBytes(totalBytesIn
));
975 ui
->lblBytesOut
->setText(GUIUtil::formatBytes(totalBytesOut
));
978 void RPCConsole::peerSelected(const QItemSelection
&selected
, const QItemSelection
&deselected
)
980 Q_UNUSED(deselected
);
982 if (!clientModel
|| !clientModel
->getPeerTableModel() || selected
.indexes().isEmpty())
985 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(selected
.indexes().first().row());
987 updateNodeDetail(stats
);
990 void RPCConsole::peerLayoutAboutToChange()
992 QModelIndexList selected
= ui
->peerWidget
->selectionModel()->selectedIndexes();
993 cachedNodeids
.clear();
994 for(int i
= 0; i
< selected
.size(); i
++)
996 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(selected
.at(i
).row());
997 cachedNodeids
.append(stats
->nodeStats
.nodeid
);
1001 void RPCConsole::peerLayoutChanged()
1003 if (!clientModel
|| !clientModel
->getPeerTableModel())
1006 const CNodeCombinedStats
*stats
= nullptr;
1007 bool fUnselect
= false;
1008 bool fReselect
= false;
1010 if (cachedNodeids
.empty()) // no node selected yet
1013 // find the currently selected row
1014 int selectedRow
= -1;
1015 QModelIndexList selectedModelIndex
= ui
->peerWidget
->selectionModel()->selectedIndexes();
1016 if (!selectedModelIndex
.isEmpty()) {
1017 selectedRow
= selectedModelIndex
.first().row();
1020 // check if our detail node has a row in the table (it may not necessarily
1021 // be at selectedRow since its position can change after a layout change)
1022 int detailNodeRow
= clientModel
->getPeerTableModel()->getRowByNodeId(cachedNodeids
.first());
1024 if (detailNodeRow
< 0)
1026 // detail node disappeared from table (node disconnected)
1031 if (detailNodeRow
!= selectedRow
)
1033 // detail node moved position
1038 // get fresh stats on the detail node.
1039 stats
= clientModel
->getPeerTableModel()->getNodeStats(detailNodeRow
);
1042 if (fUnselect
&& selectedRow
>= 0) {
1043 clearSelectedNode();
1048 for(int i
= 0; i
< cachedNodeids
.size(); i
++)
1050 ui
->peerWidget
->selectRow(clientModel
->getPeerTableModel()->getRowByNodeId(cachedNodeids
.at(i
)));
1055 updateNodeDetail(stats
);
1058 void RPCConsole::updateNodeDetail(const CNodeCombinedStats
*stats
)
1060 // update the detail ui with latest node information
1061 QString
peerAddrDetails(QString::fromStdString(stats
->nodeStats
.addrName
) + " ");
1062 peerAddrDetails
+= tr("(node id: %1)").arg(QString::number(stats
->nodeStats
.nodeid
));
1063 if (!stats
->nodeStats
.addrLocal
.empty())
1064 peerAddrDetails
+= "<br />" + tr("via %1").arg(QString::fromStdString(stats
->nodeStats
.addrLocal
));
1065 ui
->peerHeading
->setText(peerAddrDetails
);
1066 ui
->peerServices
->setText(GUIUtil::formatServicesStr(stats
->nodeStats
.nServices
));
1067 ui
->peerLastSend
->setText(stats
->nodeStats
.nLastSend
? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nLastSend
) : tr("never"));
1068 ui
->peerLastRecv
->setText(stats
->nodeStats
.nLastRecv
? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nLastRecv
) : tr("never"));
1069 ui
->peerBytesSent
->setText(GUIUtil::formatBytes(stats
->nodeStats
.nSendBytes
));
1070 ui
->peerBytesRecv
->setText(GUIUtil::formatBytes(stats
->nodeStats
.nRecvBytes
));
1071 ui
->peerConnTime
->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats
->nodeStats
.nTimeConnected
));
1072 ui
->peerPingTime
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dPingTime
));
1073 ui
->peerPingWait
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dPingWait
));
1074 ui
->peerMinPing
->setText(GUIUtil::formatPingTime(stats
->nodeStats
.dMinPing
));
1075 ui
->timeoffset
->setText(GUIUtil::formatTimeOffset(stats
->nodeStats
.nTimeOffset
));
1076 ui
->peerVersion
->setText(QString("%1").arg(QString::number(stats
->nodeStats
.nVersion
)));
1077 ui
->peerSubversion
->setText(QString::fromStdString(stats
->nodeStats
.cleanSubVer
));
1078 ui
->peerDirection
->setText(stats
->nodeStats
.fInbound
? tr("Inbound") : tr("Outbound"));
1079 ui
->peerHeight
->setText(QString("%1").arg(QString::number(stats
->nodeStats
.nStartingHeight
)));
1080 ui
->peerWhitelisted
->setText(stats
->nodeStats
.fWhitelisted
? tr("Yes") : tr("No"));
1082 // This check fails for example if the lock was busy and
1083 // nodeStateStats couldn't be fetched.
1084 if (stats
->fNodeStateStatsAvailable
) {
1085 // Ban score is init to 0
1086 ui
->peerBanScore
->setText(QString("%1").arg(stats
->nodeStateStats
.nMisbehavior
));
1088 // Sync height is init to -1
1089 if (stats
->nodeStateStats
.nSyncHeight
> -1)
1090 ui
->peerSyncHeight
->setText(QString("%1").arg(stats
->nodeStateStats
.nSyncHeight
));
1092 ui
->peerSyncHeight
->setText(tr("Unknown"));
1094 // Common height is init to -1
1095 if (stats
->nodeStateStats
.nCommonHeight
> -1)
1096 ui
->peerCommonHeight
->setText(QString("%1").arg(stats
->nodeStateStats
.nCommonHeight
));
1098 ui
->peerCommonHeight
->setText(tr("Unknown"));
1101 ui
->detailWidget
->show();
1104 void RPCConsole::resizeEvent(QResizeEvent
*event
)
1106 QWidget::resizeEvent(event
);
1109 void RPCConsole::showEvent(QShowEvent
*event
)
1111 QWidget::showEvent(event
);
1113 if (!clientModel
|| !clientModel
->getPeerTableModel())
1116 // start PeerTableModel auto refresh
1117 clientModel
->getPeerTableModel()->startAutoRefresh();
1120 void RPCConsole::hideEvent(QHideEvent
*event
)
1122 QWidget::hideEvent(event
);
1124 if (!clientModel
|| !clientModel
->getPeerTableModel())
1127 // stop PeerTableModel auto refresh
1128 clientModel
->getPeerTableModel()->stopAutoRefresh();
1131 void RPCConsole::showPeersTableContextMenu(const QPoint
& point
)
1133 QModelIndex index
= ui
->peerWidget
->indexAt(point
);
1134 if (index
.isValid())
1135 peersTableContextMenu
->exec(QCursor::pos());
1138 void RPCConsole::showBanTableContextMenu(const QPoint
& point
)
1140 QModelIndex index
= ui
->banlistWidget
->indexAt(point
);
1141 if (index
.isValid())
1142 banTableContextMenu
->exec(QCursor::pos());
1145 void RPCConsole::disconnectSelectedNode()
1150 // Get selected peer addresses
1151 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->peerWidget
, PeerTableModel::NetNodeId
);
1152 for(int i
= 0; i
< nodes
.count(); i
++)
1154 // Get currently selected peer address
1155 NodeId id
= nodes
.at(i
).data().toLongLong();
1156 // Find the node, disconnect it and clear the selected node
1157 if(g_connman
->DisconnectNode(id
))
1158 clearSelectedNode();
1162 void RPCConsole::banSelectedNode(int bantime
)
1164 if (!clientModel
|| !g_connman
)
1167 // Get selected peer addresses
1168 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->peerWidget
, PeerTableModel::NetNodeId
);
1169 for(int i
= 0; i
< nodes
.count(); i
++)
1171 // Get currently selected peer address
1172 NodeId id
= nodes
.at(i
).data().toLongLong();
1174 // Get currently selected peer address
1175 int detailNodeRow
= clientModel
->getPeerTableModel()->getRowByNodeId(id
);
1176 if(detailNodeRow
< 0)
1179 // Find possible nodes, ban it and clear the selected node
1180 const CNodeCombinedStats
*stats
= clientModel
->getPeerTableModel()->getNodeStats(detailNodeRow
);
1182 g_connman
->Ban(stats
->nodeStats
.addr
, BanReasonManuallyAdded
, bantime
);
1185 clearSelectedNode();
1186 clientModel
->getBanTableModel()->refresh();
1189 void RPCConsole::unbanSelectedNode()
1194 // Get selected ban addresses
1195 QList
<QModelIndex
> nodes
= GUIUtil::getEntryData(ui
->banlistWidget
, BanTableModel::Address
);
1196 for(int i
= 0; i
< nodes
.count(); i
++)
1198 // Get currently selected ban address
1199 QString strNode
= nodes
.at(i
).data().toString();
1200 CSubNet possibleSubnet
;
1202 LookupSubNet(strNode
.toStdString().c_str(), possibleSubnet
);
1203 if (possibleSubnet
.IsValid() && g_connman
)
1205 g_connman
->Unban(possibleSubnet
);
1206 clientModel
->getBanTableModel()->refresh();
1211 void RPCConsole::clearSelectedNode()
1213 ui
->peerWidget
->selectionModel()->clearSelection();
1214 cachedNodeids
.clear();
1215 ui
->detailWidget
->hide();
1216 ui
->peerHeading
->setText(tr("Select a peer to view detailed information."));
1219 void RPCConsole::showOrHideBanTableIfRequired()
1224 bool visible
= clientModel
->getBanTableModel()->shouldShow();
1225 ui
->banlistWidget
->setVisible(visible
);
1226 ui
->banHeading
->setVisible(visible
);
1229 void RPCConsole::setTabFocus(enum TabTypes tabType
)
1231 ui
->tabWidget
->setCurrentIndex(tabType
);