Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

rpcconsole.cpp 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. // Copyright (c) 2011-2014 The Bitcoin developers
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include "rpcconsole.h"
  5. #include "ui_rpcconsole.h"
  6. #include "clientmodel.h"
  7. #include "guiutil.h"
  8. #include "peertablemodel.h"
  9. #include "main.h"
  10. #include "chainparams.h"
  11. #include "rpcserver.h"
  12. #include "rpcclient.h"
  13. #include "util.h"
  14. #include "json/json_spirit_value.h"
  15. #include <openssl/crypto.h>
  16. #ifdef ENABLE_WALLET
  17. #include <db_cxx.h>
  18. #endif
  19. #include <QKeyEvent>
  20. #include <QScrollBar>
  21. #include <QThread>
  22. #include <QTime>
  23. #if QT_VERSION < 0x050000
  24. #include <QUrl>
  25. #endif
  26. // TODO: add a scrollback limit, as there is currently none
  27. // TODO: make it possible to filter out categories (esp debug messages when implemented)
  28. // TODO: receive errors and debug messages through ClientModel
  29. const int CONSOLE_HISTORY = 50;
  30. const QSize ICON_SIZE(24, 24);
  31. const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
  32. const struct {
  33. const char *url;
  34. const char *source;
  35. } ICON_MAPPING[] = {
  36. {"cmd-request", ":/icons/tx_input"},
  37. {"cmd-reply", ":/icons/tx_output"},
  38. {"cmd-error", ":/icons/tx_output"},
  39. {"misc", ":/icons/tx_inout"},
  40. {NULL, NULL}
  41. };
  42. /* Object for executing console RPC commands in a separate thread.
  43. */
  44. class RPCExecutor : public QObject
  45. {
  46. Q_OBJECT
  47. public slots:
  48. void request(const QString &command);
  49. signals:
  50. void reply(int category, const QString &command);
  51. };
  52. #include "rpcconsole.moc"
  53. /**
  54. * Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
  55. *
  56. * - Arguments are delimited with whitespace
  57. * - Extra whitespace at the beginning and end and between arguments will be ignored
  58. * - Text can be "double" or 'single' quoted
  59. * - The backslash \c \ is used as escape character
  60. * - Outside quotes, any character can be escaped
  61. * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
  62. * - Within single quotes, no escaping is possible and no special interpretation takes place
  63. *
  64. * @param[out] args Parsed arguments will be appended to this list
  65. * @param[in] strCommand Command line to split
  66. */
  67. bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
  68. {
  69. enum CmdParseState
  70. {
  71. STATE_EATING_SPACES,
  72. STATE_ARGUMENT,
  73. STATE_SINGLEQUOTED,
  74. STATE_DOUBLEQUOTED,
  75. STATE_ESCAPE_OUTER,
  76. STATE_ESCAPE_DOUBLEQUOTED
  77. } state = STATE_EATING_SPACES;
  78. std::string curarg;
  79. foreach(char ch, strCommand)
  80. {
  81. switch(state)
  82. {
  83. case STATE_ARGUMENT: // In or after argument
  84. case STATE_EATING_SPACES: // Handle runs of whitespace
  85. switch(ch)
  86. {
  87. case '"': state = STATE_DOUBLEQUOTED; break;
  88. case '\'': state = STATE_SINGLEQUOTED; break;
  89. case '\\': state = STATE_ESCAPE_OUTER; break;
  90. case ' ': case '\n': case '\t':
  91. if(state == STATE_ARGUMENT) // Space ends argument
  92. {
  93. args.push_back(curarg);
  94. curarg.clear();
  95. }
  96. state = STATE_EATING_SPACES;
  97. break;
  98. default: curarg += ch; state = STATE_ARGUMENT;
  99. }
  100. break;
  101. case STATE_SINGLEQUOTED: // Single-quoted string
  102. switch(ch)
  103. {
  104. case '\'': state = STATE_ARGUMENT; break;
  105. default: curarg += ch;
  106. }
  107. break;
  108. case STATE_DOUBLEQUOTED: // Double-quoted string
  109. switch(ch)
  110. {
  111. case '"': state = STATE_ARGUMENT; break;
  112. case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
  113. default: curarg += ch;
  114. }
  115. break;
  116. case STATE_ESCAPE_OUTER: // '\' outside quotes
  117. curarg += ch; state = STATE_ARGUMENT;
  118. break;
  119. case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
  120. if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
  121. curarg += ch; state = STATE_DOUBLEQUOTED;
  122. break;
  123. }
  124. }
  125. switch(state) // final state
  126. {
  127. case STATE_EATING_SPACES:
  128. return true;
  129. case STATE_ARGUMENT:
  130. args.push_back(curarg);
  131. return true;
  132. default: // ERROR to end in one of the other states
  133. return false;
  134. }
  135. }
  136. void RPCExecutor::request(const QString &command)
  137. {
  138. std::vector<std::string> args;
  139. if(!parseCommandLine(args, command.toStdString()))
  140. {
  141. emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
  142. return;
  143. }
  144. if(args.empty())
  145. return; // Nothing to do
  146. try
  147. {
  148. std::string strPrint;
  149. // Convert argument list to JSON objects in method-dependent way,
  150. // and pass it along with the method name to the dispatcher.
  151. json_spirit::Value result = tableRPC.execute(
  152. args[0],
  153. RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
  154. // Format result reply
  155. if (result.type() == json_spirit::null_type)
  156. strPrint = "";
  157. else if (result.type() == json_spirit::str_type)
  158. strPrint = result.get_str();
  159. else
  160. strPrint = write_string(result, true);
  161. emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
  162. }
  163. catch (json_spirit::Object& objError)
  164. {
  165. try // Nice formatting for standard-format error
  166. {
  167. int code = find_value(objError, "code").get_int();
  168. std::string message = find_value(objError, "message").get_str();
  169. emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
  170. }
  171. catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
  172. { // Show raw JSON object
  173. emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
  174. }
  175. }
  176. catch (std::exception& e)
  177. {
  178. emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
  179. }
  180. }
  181. RPCConsole::RPCConsole(QWidget *parent) :
  182. QDialog(parent),
  183. ui(new Ui::RPCConsole),
  184. clientModel(0),
  185. historyPtr(0),
  186. cachedNodeid(-1)
  187. {
  188. ui->setupUi(this);
  189. GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
  190. #ifndef Q_OS_MAC
  191. ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
  192. #endif
  193. // Install event filter for up and down arrow
  194. ui->lineEdit->installEventFilter(this);
  195. ui->messagesWidget->installEventFilter(this);
  196. connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
  197. connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
  198. // set library version labels
  199. ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
  200. #ifdef ENABLE_WALLET
  201. ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
  202. #else
  203. ui->label_berkeleyDBVersion->hide();
  204. ui->berkeleyDBVersion->hide();
  205. #endif
  206. startExecutor();
  207. setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
  208. ui->detailWidget->hide();
  209. ui->peerHeading->setText(tr("Select a peer to view detailed information."));
  210. clear();
  211. }
  212. RPCConsole::~RPCConsole()
  213. {
  214. GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
  215. emit stopExecutor();
  216. delete ui;
  217. }
  218. bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
  219. {
  220. if(event->type() == QEvent::KeyPress) // Special key handling
  221. {
  222. QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
  223. int key = keyevt->key();
  224. Qt::KeyboardModifiers mod = keyevt->modifiers();
  225. switch(key)
  226. {
  227. case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
  228. case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
  229. case Qt::Key_PageUp: /* pass paging keys to messages widget */
  230. case Qt::Key_PageDown:
  231. if(obj == ui->lineEdit)
  232. {
  233. QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
  234. return true;
  235. }
  236. break;
  237. default:
  238. // Typing in messages widget brings focus to line edit, and redirects key there
  239. // Exclude most combinations and keys that emit no text, except paste shortcuts
  240. if(obj == ui->messagesWidget && (
  241. (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
  242. ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
  243. ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
  244. {
  245. ui->lineEdit->setFocus();
  246. QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
  247. return true;
  248. }
  249. }
  250. }
  251. return QDialog::eventFilter(obj, event);
  252. }
  253. void RPCConsole::setClientModel(ClientModel *model)
  254. {
  255. clientModel = model;
  256. ui->trafficGraph->setClientModel(model);
  257. if(model)
  258. {
  259. // Keep up to date with client
  260. setNumConnections(model->getNumConnections());
  261. connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
  262. setNumBlocks(model->getNumBlocks());
  263. connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
  264. updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
  265. connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
  266. // set up peer table
  267. ui->peerWidget->setModel(model->getPeerTableModel());
  268. ui->peerWidget->verticalHeader()->hide();
  269. ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
  270. ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
  271. ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
  272. ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
  273. ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
  274. ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
  275. // connect the peerWidget selection model to our peerSelected() handler
  276. connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
  277. this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
  278. connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
  279. // Provide initial values
  280. ui->clientVersion->setText(model->formatFullVersion());
  281. ui->clientName->setText(model->clientName());
  282. ui->buildDate->setText(model->formatBuildDate());
  283. ui->startupTime->setText(model->formatClientStartupTime());
  284. ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
  285. }
  286. }
  287. static QString categoryClass(int category)
  288. {
  289. switch(category)
  290. {
  291. case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
  292. case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
  293. case RPCConsole::CMD_ERROR: return "cmd-error"; break;
  294. default: return "misc";
  295. }
  296. }
  297. void RPCConsole::clear()
  298. {
  299. ui->messagesWidget->clear();
  300. history.clear();
  301. historyPtr = 0;
  302. ui->lineEdit->clear();
  303. ui->lineEdit->setFocus();
  304. // Add smoothly scaled icon images.
  305. // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
  306. for(int i=0; ICON_MAPPING[i].url; ++i)
  307. {
  308. ui->messagesWidget->document()->addResource(
  309. QTextDocument::ImageResource,
  310. QUrl(ICON_MAPPING[i].url),
  311. QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
  312. }
  313. // Set default style sheet
  314. ui->messagesWidget->document()->setDefaultStyleSheet(
  315. "table { }"
  316. "td.time { color: #808080; padding-top: 3px; } "
  317. "td.message { font-family: monospace; font-size: 12px; } " // Todo: Remove fixed font-size
  318. "td.cmd-request { color: #006060; } "
  319. "td.cmd-error { color: red; } "
  320. "b { color: #006060; } "
  321. );
  322. message(CMD_REPLY, (tr("Welcome to the Bitcoin RPC console.") + "<br>" +
  323. tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
  324. tr("Type <b>help</b> for an overview of available commands.")), true);
  325. }
  326. void RPCConsole::reject()
  327. {
  328. // Ignore escape keypress if this is not a seperate window
  329. if(windowType() != Qt::Widget)
  330. QDialog::reject();
  331. }
  332. void RPCConsole::message(int category, const QString &message, bool html)
  333. {
  334. QTime time = QTime::currentTime();
  335. QString timeString = time.toString();
  336. QString out;
  337. out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
  338. out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
  339. out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
  340. if(html)
  341. out += message;
  342. else
  343. out += GUIUtil::HtmlEscape(message, true);
  344. out += "</td></tr></table>";
  345. ui->messagesWidget->append(out);
  346. }
  347. void RPCConsole::setNumConnections(int count)
  348. {
  349. if (!clientModel)
  350. return;
  351. QString connections = QString::number(count) + " (";
  352. connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
  353. connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
  354. ui->numberOfConnections->setText(connections);
  355. }
  356. void RPCConsole::setNumBlocks(int count)
  357. {
  358. ui->numberOfBlocks->setText(QString::number(count));
  359. if(clientModel)
  360. ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
  361. }
  362. void RPCConsole::on_lineEdit_returnPressed()
  363. {
  364. QString cmd = ui->lineEdit->text();
  365. ui->lineEdit->clear();
  366. if(!cmd.isEmpty())
  367. {
  368. message(CMD_REQUEST, cmd);
  369. emit cmdRequest(cmd);
  370. // Remove command, if already in history
  371. history.removeOne(cmd);
  372. // Append command to history
  373. history.append(cmd);
  374. // Enforce maximum history size
  375. while(history.size() > CONSOLE_HISTORY)
  376. history.removeFirst();
  377. // Set pointer to end of history
  378. historyPtr = history.size();
  379. // Scroll console view to end
  380. scrollToEnd();
  381. }
  382. }
  383. void RPCConsole::browseHistory(int offset)
  384. {
  385. historyPtr += offset;
  386. if(historyPtr < 0)
  387. historyPtr = 0;
  388. if(historyPtr > history.size())
  389. historyPtr = history.size();
  390. QString cmd;
  391. if(historyPtr < history.size())
  392. cmd = history.at(historyPtr);
  393. ui->lineEdit->setText(cmd);
  394. }
  395. void RPCConsole::startExecutor()
  396. {
  397. QThread *thread = new QThread;
  398. RPCExecutor *executor = new RPCExecutor();
  399. executor->moveToThread(thread);
  400. // Replies from executor object must go to this object
  401. connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
  402. // Requests from this object must go to executor
  403. connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
  404. // On stopExecutor signal
  405. // - queue executor for deletion (in execution thread)
  406. // - quit the Qt event loop in the execution thread
  407. connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
  408. connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
  409. // Queue the thread for deletion (in this thread) when it is finished
  410. connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
  411. // Default implementation of QThread::run() simply spins up an event loop in the thread,
  412. // which is what we want.
  413. thread->start();
  414. }
  415. void RPCConsole::on_tabWidget_currentChanged(int index)
  416. {
  417. if(ui->tabWidget->widget(index) == ui->tab_console)
  418. {
  419. ui->lineEdit->setFocus();
  420. }
  421. }
  422. void RPCConsole::on_openDebugLogfileButton_clicked()
  423. {
  424. GUIUtil::openDebugLogfile();
  425. }
  426. void RPCConsole::scrollToEnd()
  427. {
  428. QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
  429. scrollbar->setValue(scrollbar->maximum());
  430. }
  431. void RPCConsole::on_sldGraphRange_valueChanged(int value)
  432. {
  433. const int multiplier = 5; // each position on the slider represents 5 min
  434. int mins = value * multiplier;
  435. setTrafficGraphRange(mins);
  436. }
  437. QString RPCConsole::FormatBytes(quint64 bytes)
  438. {
  439. if(bytes < 1024)
  440. return QString(tr("%1 B")).arg(bytes);
  441. if(bytes < 1024 * 1024)
  442. return QString(tr("%1 KB")).arg(bytes / 1024);
  443. if(bytes < 1024 * 1024 * 1024)
  444. return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
  445. return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
  446. }
  447. void RPCConsole::setTrafficGraphRange(int mins)
  448. {
  449. ui->trafficGraph->setGraphRangeMins(mins);
  450. ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
  451. }
  452. void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
  453. {
  454. ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
  455. ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
  456. }
  457. void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
  458. {
  459. Q_UNUSED(deselected);
  460. if (!clientModel || selected.indexes().isEmpty())
  461. return;
  462. const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
  463. if (stats)
  464. updateNodeDetail(stats);
  465. }
  466. void RPCConsole::peerLayoutChanged()
  467. {
  468. if (!clientModel)
  469. return;
  470. const CNodeCombinedStats *stats = NULL;
  471. bool fUnselect = false;
  472. bool fReselect = false;
  473. if (cachedNodeid == -1) // no node selected yet
  474. return;
  475. // find the currently selected row
  476. int selectedRow;
  477. QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
  478. if (selectedModelIndex.isEmpty())
  479. selectedRow = -1;
  480. else
  481. selectedRow = selectedModelIndex.first().row();
  482. // check if our detail node has a row in the table (it may not necessarily
  483. // be at selectedRow since its position can change after a layout change)
  484. int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);
  485. if (detailNodeRow < 0)
  486. {
  487. // detail node dissapeared from table (node disconnected)
  488. fUnselect = true;
  489. cachedNodeid = -1;
  490. ui->detailWidget->hide();
  491. ui->peerHeading->setText(tr("Select a peer to view detailed information."));
  492. }
  493. else
  494. {
  495. if (detailNodeRow != selectedRow)
  496. {
  497. // detail node moved position
  498. fUnselect = true;
  499. fReselect = true;
  500. }
  501. // get fresh stats on the detail node.
  502. stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
  503. }
  504. if (fUnselect && selectedRow >= 0)
  505. {
  506. ui->peerWidget->selectionModel()->select(QItemSelection(selectedModelIndex.first(), selectedModelIndex.last()),
  507. QItemSelectionModel::Deselect);
  508. }
  509. if (fReselect)
  510. {
  511. ui->peerWidget->selectRow(detailNodeRow);
  512. }
  513. if (stats)
  514. updateNodeDetail(stats);
  515. }
  516. void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
  517. {
  518. // Update cached nodeid
  519. cachedNodeid = stats->nodeStats.nodeid;
  520. // update the detail ui with latest node information
  521. QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName));
  522. if (!stats->nodeStats.addrLocal.empty())
  523. peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
  524. ui->peerHeading->setText(peerAddrDetails);
  525. ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
  526. ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never"));
  527. ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never"));
  528. ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
  529. ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
  530. ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected));
  531. ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
  532. ui->peerVersion->setText(QString("%1").arg(stats->nodeStats.nVersion));
  533. ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
  534. ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
  535. ui->peerHeight->setText(QString("%1").arg(stats->nodeStats.nStartingHeight));
  536. // This check fails for example if the lock was busy and
  537. // nodeStateStats couldn't be fetched.
  538. if (stats->fNodeStateStatsAvailable) {
  539. // Ban score is init to 0
  540. ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
  541. // Sync height is init to -1
  542. if (stats->nodeStateStats.nSyncHeight > -1)
  543. ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
  544. else
  545. ui->peerSyncHeight->setText(tr("Unknown"));
  546. } else {
  547. ui->peerBanScore->setText(tr("Fetching..."));
  548. ui->peerSyncHeight->setText(tr("Fetching..."));
  549. }
  550. ui->detailWidget->show();
  551. }
  552. void RPCConsole::resizeEvent(QResizeEvent *event)
  553. {
  554. QWidget::resizeEvent(event);
  555. }
  556. void RPCConsole::showEvent(QShowEvent *event)
  557. {
  558. QWidget::showEvent(event);
  559. if (!clientModel)
  560. return;
  561. // start PeerTableModel auto refresh
  562. clientModel->getPeerTableModel()->startAutoRefresh();
  563. }
  564. void RPCConsole::hideEvent(QHideEvent *event)
  565. {
  566. QWidget::hideEvent(event);
  567. if (!clientModel)
  568. return;
  569. // stop PeerTableModel auto refresh
  570. clientModel->getPeerTableModel()->stopAutoRefresh();
  571. }