You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

transactiontablemodel.cpp 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. #include "transactiontablemodel.h"
  2. #include "guiutil.h"
  3. #include "transactionrecord.h"
  4. #include "guiconstants.h"
  5. #include "transactiondesc.h"
  6. #include "walletmodel.h"
  7. #include "addresstablemodel.h"
  8. #include "headers.h"
  9. #include <QLocale>
  10. #include <QDebug>
  11. #include <QList>
  12. #include <QColor>
  13. #include <QTimer>
  14. #include <QIcon>
  15. #include <QDateTime>
  16. #include <QtAlgorithms>
  17. // Credit and Debit columns are right-aligned as they contain numbers
  18. static int column_alignments[] = {
  19. Qt::AlignLeft|Qt::AlignVCenter,
  20. Qt::AlignLeft|Qt::AlignVCenter,
  21. Qt::AlignLeft|Qt::AlignVCenter,
  22. Qt::AlignLeft|Qt::AlignVCenter,
  23. Qt::AlignRight|Qt::AlignVCenter
  24. };
  25. // Comparison operator for sort/binary search of model tx list
  26. struct TxLessThan
  27. {
  28. bool operator()(const TransactionRecord &a, const TransactionRecord &b) const
  29. {
  30. return a.hash < b.hash;
  31. }
  32. bool operator()(const TransactionRecord &a, const uint256 &b) const
  33. {
  34. return a.hash < b;
  35. }
  36. bool operator()(const uint256 &a, const TransactionRecord &b) const
  37. {
  38. return a < b.hash;
  39. }
  40. };
  41. // Private implementation
  42. struct TransactionTablePriv
  43. {
  44. TransactionTablePriv(CWallet *wallet, TransactionTableModel *parent):
  45. wallet(wallet),
  46. parent(parent)
  47. {
  48. }
  49. CWallet *wallet;
  50. TransactionTableModel *parent;
  51. /* Local cache of wallet.
  52. * As it is in the same order as the CWallet, by definition
  53. * this is sorted by sha256.
  54. */
  55. QList<TransactionRecord> cachedWallet;
  56. /* Query entire wallet anew from core.
  57. */
  58. void refreshWallet()
  59. {
  60. #ifdef WALLET_UPDATE_DEBUG
  61. qDebug() << "refreshWallet";
  62. #endif
  63. cachedWallet.clear();
  64. CRITICAL_BLOCK(wallet->cs_mapWallet)
  65. {
  66. for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it)
  67. {
  68. cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second));
  69. }
  70. }
  71. }
  72. /* Update our model of the wallet incrementally, to synchronize our model of the wallet
  73. with that of the core.
  74. Call with list of hashes of transactions that were added, removed or changed.
  75. */
  76. void updateWallet(const QList<uint256> &updated)
  77. {
  78. // Walk through updated transactions, update model as needed.
  79. #ifdef WALLET_UPDATE_DEBUG
  80. qDebug() << "updateWallet";
  81. #endif
  82. // Sort update list, and iterate through it in reverse, so that model updates
  83. // can be emitted from end to beginning (so that earlier updates will not influence
  84. // the indices of latter ones).
  85. QList<uint256> updated_sorted = updated;
  86. qSort(updated_sorted);
  87. CRITICAL_BLOCK(wallet->cs_mapWallet)
  88. {
  89. for(int update_idx = updated_sorted.size()-1; update_idx >= 0; --update_idx)
  90. {
  91. const uint256 &hash = updated_sorted.at(update_idx);
  92. /* Find transaction in wallet */
  93. std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
  94. bool inWallet = mi != wallet->mapWallet.end();
  95. /* Find bounds of this transaction in model */
  96. QList<TransactionRecord>::iterator lower = qLowerBound(
  97. cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
  98. QList<TransactionRecord>::iterator upper = qUpperBound(
  99. cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
  100. int lowerIndex = (lower - cachedWallet.begin());
  101. int upperIndex = (upper - cachedWallet.begin());
  102. // Determine if transaction is in model already
  103. bool inModel = false;
  104. if(lower != upper)
  105. {
  106. inModel = true;
  107. }
  108. #ifdef WALLET_UPDATE_DEBUG
  109. qDebug() << " " << QString::fromStdString(hash.ToString()) << inWallet << " " << inModel
  110. << lowerIndex << "-" << upperIndex;
  111. #endif
  112. if(inWallet && !inModel)
  113. {
  114. // Added -- insert at the right position
  115. QList<TransactionRecord> toInsert =
  116. TransactionRecord::decomposeTransaction(wallet, mi->second);
  117. if(!toInsert.isEmpty()) /* only if something to insert */
  118. {
  119. parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);
  120. int insert_idx = lowerIndex;
  121. foreach(const TransactionRecord &rec, toInsert)
  122. {
  123. cachedWallet.insert(insert_idx, rec);
  124. insert_idx += 1;
  125. }
  126. parent->endInsertRows();
  127. }
  128. }
  129. else if(!inWallet && inModel)
  130. {
  131. // Removed -- remove entire transaction from table
  132. parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
  133. cachedWallet.erase(lower, upper);
  134. parent->endRemoveRows();
  135. }
  136. else if(inWallet && inModel)
  137. {
  138. // Updated -- nothing to do, status update will take care of this
  139. }
  140. }
  141. }
  142. }
  143. int size()
  144. {
  145. return cachedWallet.size();
  146. }
  147. TransactionRecord *index(int idx)
  148. {
  149. if(idx >= 0 && idx < cachedWallet.size())
  150. {
  151. TransactionRecord *rec = &cachedWallet[idx];
  152. // If a status update is needed (blocks came in since last check),
  153. // update the status of this transaction from the wallet. Otherwise,
  154. // simply re-use the cached status.
  155. if(rec->statusUpdateNeeded())
  156. {
  157. CRITICAL_BLOCK(wallet->cs_mapWallet)
  158. {
  159. std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
  160. if(mi != wallet->mapWallet.end())
  161. {
  162. rec->updateStatus(mi->second);
  163. }
  164. }
  165. }
  166. return rec;
  167. }
  168. else
  169. {
  170. return 0;
  171. }
  172. }
  173. QString describe(TransactionRecord *rec)
  174. {
  175. CRITICAL_BLOCK(wallet->cs_mapWallet)
  176. {
  177. std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
  178. if(mi != wallet->mapWallet.end())
  179. {
  180. return QString::fromStdString(TransactionDesc::toHTML(wallet, mi->second));
  181. }
  182. }
  183. return QString("");
  184. }
  185. };
  186. TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel *parent):
  187. QAbstractTableModel(parent),
  188. wallet(wallet),
  189. walletModel(parent),
  190. priv(new TransactionTablePriv(wallet, this))
  191. {
  192. columns << QString() << tr("Date") << tr("Type") << tr("Address") << tr("Amount");
  193. priv->refreshWallet();
  194. QTimer *timer = new QTimer(this);
  195. connect(timer, SIGNAL(timeout()), this, SLOT(update()));
  196. timer->start(MODEL_UPDATE_DELAY);
  197. }
  198. TransactionTableModel::~TransactionTableModel()
  199. {
  200. delete priv;
  201. }
  202. void TransactionTableModel::update()
  203. {
  204. QList<uint256> updated;
  205. // Check if there are changes to wallet map
  206. TRY_CRITICAL_BLOCK(wallet->cs_mapWallet)
  207. {
  208. if(!wallet->vWalletUpdated.empty())
  209. {
  210. BOOST_FOREACH(uint256 hash, wallet->vWalletUpdated)
  211. {
  212. updated.append(hash);
  213. }
  214. wallet->vWalletUpdated.clear();
  215. }
  216. }
  217. if(!updated.empty())
  218. {
  219. priv->updateWallet(updated);
  220. // Status (number of confirmations) and (possibly) description
  221. // columns changed for all rows.
  222. emit dataChanged(index(0, Status), index(priv->size()-1, Status));
  223. emit dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress));
  224. }
  225. }
  226. int TransactionTableModel::rowCount(const QModelIndex &parent) const
  227. {
  228. Q_UNUSED(parent);
  229. return priv->size();
  230. }
  231. int TransactionTableModel::columnCount(const QModelIndex &parent) const
  232. {
  233. Q_UNUSED(parent);
  234. return columns.length();
  235. }
  236. QVariant TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const
  237. {
  238. QString status;
  239. switch(wtx->status.status)
  240. {
  241. case TransactionStatus::OpenUntilBlock:
  242. status = tr("Open for %n block(s)","",wtx->status.open_for);
  243. break;
  244. case TransactionStatus::OpenUntilDate:
  245. status = tr("Open until %1").arg(GUIUtil::DateTimeStr(wtx->status.open_for));
  246. break;
  247. case TransactionStatus::Offline:
  248. status = tr("Offline (%1 confirmations)").arg(wtx->status.depth);
  249. break;
  250. case TransactionStatus::Unconfirmed:
  251. status = tr("Unconfirmed (%1 of %2 confirmations required)").arg(wtx->status.depth).arg(TransactionRecord::NumConfirmations);
  252. break;
  253. case TransactionStatus::HaveConfirmations:
  254. status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth);
  255. break;
  256. }
  257. if(wtx->type == TransactionRecord::Generated)
  258. {
  259. status += "\n\n";
  260. switch(wtx->status.maturity)
  261. {
  262. case TransactionStatus::Immature:
  263. status += tr("Mined balance will be available in %n more blocks", "",
  264. wtx->status.matures_in);
  265. break;
  266. case TransactionStatus::Mature:
  267. break;
  268. case TransactionStatus::MaturesWarning:
  269. status += tr("This block was not received by any other nodes and will probably not be accepted!");
  270. break;
  271. case TransactionStatus::NotAccepted:
  272. status += tr("Generated but not accepted");
  273. break;
  274. }
  275. }
  276. return QVariant(status);
  277. }
  278. QVariant TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const
  279. {
  280. if(wtx->time)
  281. {
  282. return QVariant(GUIUtil::DateTimeStr(wtx->time));
  283. }
  284. else
  285. {
  286. return QVariant();
  287. }
  288. }
  289. /* Look up address in address book, if found return
  290. address (label)
  291. otherwise just return address
  292. */
  293. QString TransactionTableModel::lookupAddress(const std::string &address) const
  294. {
  295. QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address));
  296. QString description;
  297. if(label.isEmpty())
  298. {
  299. description = QString::fromStdString(address);
  300. }
  301. else
  302. {
  303. description = label + QString(" (") + QString::fromStdString(address) + QString(")");
  304. }
  305. return description;
  306. }
  307. QVariant TransactionTableModel::formatTxType(const TransactionRecord *wtx) const
  308. {
  309. QString description;
  310. switch(wtx->type)
  311. {
  312. case TransactionRecord::RecvWithAddress:
  313. description = tr("Received with");
  314. break;
  315. case TransactionRecord::RecvFromIP:
  316. description = tr("Received from IP");
  317. break;
  318. case TransactionRecord::SendToAddress:
  319. description = tr("Sent to");
  320. break;
  321. case TransactionRecord::SendToIP:
  322. description = tr("Sent to IP");
  323. break;
  324. case TransactionRecord::SendToSelf:
  325. description = tr("Payment to yourself");
  326. break;
  327. case TransactionRecord::Generated:
  328. description = tr("Mined");
  329. break;
  330. }
  331. return QVariant(description);
  332. }
  333. QVariant TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx) const
  334. {
  335. QString description;
  336. switch(wtx->type)
  337. {
  338. case TransactionRecord::RecvWithAddress:
  339. description = lookupAddress(wtx->address);
  340. break;
  341. case TransactionRecord::RecvFromIP:
  342. description = QString::fromStdString(wtx->address);
  343. break;
  344. case TransactionRecord::SendToAddress:
  345. description = lookupAddress(wtx->address);
  346. break;
  347. case TransactionRecord::SendToIP:
  348. description = QString::fromStdString(wtx->address);
  349. break;
  350. case TransactionRecord::SendToSelf:
  351. description = QString();
  352. break;
  353. case TransactionRecord::Generated:
  354. description = QString();
  355. break;
  356. }
  357. return QVariant(description);
  358. }
  359. QVariant TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed) const
  360. {
  361. QString str = QString::fromStdString(FormatMoney(wtx->credit + wtx->debit));
  362. if(showUnconfirmed)
  363. {
  364. if(!wtx->status.confirmed || wtx->status.maturity != TransactionStatus::Mature)
  365. {
  366. str = QString("[") + str + QString("]");
  367. }
  368. }
  369. return QVariant(str);
  370. }
  371. QVariant TransactionTableModel::formatTxDecoration(const TransactionRecord *wtx) const
  372. {
  373. if(wtx->type == TransactionRecord::Generated)
  374. {
  375. switch(wtx->status.maturity)
  376. {
  377. case TransactionStatus::Immature: {
  378. int total = wtx->status.depth + wtx->status.matures_in;
  379. int part = (wtx->status.depth * 4 / total) + 1;
  380. return QIcon(QString(":/icons/transaction_%1").arg(part));
  381. }
  382. case TransactionStatus::Mature:
  383. return QIcon(":/icons/transaction_confirmed");
  384. case TransactionStatus::MaturesWarning:
  385. case TransactionStatus::NotAccepted:
  386. return QIcon(":/icons/transaction_0");
  387. }
  388. }
  389. else
  390. {
  391. switch(wtx->status.status)
  392. {
  393. case TransactionStatus::OpenUntilBlock:
  394. case TransactionStatus::OpenUntilDate:
  395. return QColor(64,64,255);
  396. break;
  397. case TransactionStatus::Offline:
  398. return QColor(192,192,192);
  399. case TransactionStatus::Unconfirmed:
  400. switch(wtx->status.depth)
  401. {
  402. case 0: return QIcon(":/icons/transaction_0");
  403. case 1: return QIcon(":/icons/transaction_1");
  404. case 2: return QIcon(":/icons/transaction_2");
  405. case 3: return QIcon(":/icons/transaction_3");
  406. case 4: return QIcon(":/icons/transaction_4");
  407. default: return QIcon(":/icons/transaction_5");
  408. };
  409. case TransactionStatus::HaveConfirmations:
  410. return QIcon(":/icons/transaction_confirmed");
  411. }
  412. }
  413. return QColor(0,0,0);
  414. }
  415. QVariant TransactionTableModel::data(const QModelIndex &index, int role) const
  416. {
  417. if(!index.isValid())
  418. return QVariant();
  419. TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer());
  420. if(role == Qt::DecorationRole)
  421. {
  422. if(index.column() == Status)
  423. {
  424. return formatTxDecoration(rec);
  425. }
  426. }
  427. else if(role == Qt::DisplayRole)
  428. {
  429. // Delegate to specific column handlers
  430. switch(index.column())
  431. {
  432. case Date:
  433. return formatTxDate(rec);
  434. case Type:
  435. return formatTxType(rec);
  436. case ToAddress:
  437. return formatTxToAddress(rec);
  438. case Amount:
  439. return formatTxAmount(rec);
  440. }
  441. }
  442. else if(role == Qt::EditRole)
  443. {
  444. // Edit role is used for sorting so return the real values
  445. switch(index.column())
  446. {
  447. case Status:
  448. return QString::fromStdString(rec->status.sortKey);
  449. case Date:
  450. return rec->time;
  451. case Type:
  452. return formatTxType(rec);
  453. case ToAddress:
  454. return formatTxToAddress(rec);
  455. case Amount:
  456. return rec->credit + rec->debit;
  457. }
  458. }
  459. else if (role == Qt::ToolTipRole)
  460. {
  461. if(index.column() == Status)
  462. {
  463. return formatTxStatus(rec);
  464. }
  465. }
  466. else if (role == Qt::TextAlignmentRole)
  467. {
  468. return column_alignments[index.column()];
  469. }
  470. else if (role == Qt::ForegroundRole)
  471. {
  472. /* Non-confirmed transactions are grey */
  473. if(!rec->status.confirmed)
  474. {
  475. return COLOR_UNCONFIRMED;
  476. }
  477. if(index.column() == Amount && (rec->credit+rec->debit) < 0)
  478. {
  479. return COLOR_NEGATIVE;
  480. }
  481. }
  482. else if (role == TypeRole)
  483. {
  484. return rec->type;
  485. }
  486. else if (role == DateRole)
  487. {
  488. return QDateTime::fromTime_t(static_cast<uint>(rec->time));
  489. }
  490. else if (role == LongDescriptionRole)
  491. {
  492. return priv->describe(rec);
  493. }
  494. else if (role == AddressRole)
  495. {
  496. return QString::fromStdString(rec->address);
  497. }
  498. else if (role == LabelRole)
  499. {
  500. return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address));
  501. }
  502. else if (role == AbsoluteAmountRole)
  503. {
  504. return llabs(rec->credit + rec->debit);
  505. }
  506. else if (role == TxIDRole)
  507. {
  508. return QString::fromStdString(rec->getTxID());
  509. }
  510. else if (role == ConfirmedRole)
  511. {
  512. return rec->status.status == TransactionStatus::HaveConfirmations;
  513. }
  514. else if (role == FormattedAmountRole)
  515. {
  516. return formatTxAmount(rec, false);
  517. }
  518. return QVariant();
  519. }
  520. QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
  521. {
  522. if(orientation == Qt::Horizontal)
  523. {
  524. if(role == Qt::DisplayRole)
  525. {
  526. return columns[section];
  527. }
  528. else if (role == Qt::TextAlignmentRole)
  529. {
  530. return column_alignments[section];
  531. } else if (role == Qt::ToolTipRole)
  532. {
  533. switch(section)
  534. {
  535. case Status:
  536. return tr("Transaction status. Hover over this field to show number of confirmations.");
  537. case Date:
  538. return tr("Date and time that the transaction was received.");
  539. case Type:
  540. return tr("Type of transaction.");
  541. case ToAddress:
  542. return tr("Destination address of transaction.");
  543. case Amount:
  544. return tr("Amount removed from or added to balance.");
  545. }
  546. }
  547. }
  548. return QVariant();
  549. }
  550. Qt::ItemFlags TransactionTableModel::flags(const QModelIndex &index) const
  551. {
  552. return QAbstractTableModel::flags(index);
  553. }
  554. QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const
  555. {
  556. Q_UNUSED(parent);
  557. TransactionRecord *data = priv->index(row);
  558. if(data)
  559. {
  560. return createIndex(row, column, priv->index(row));
  561. }
  562. else
  563. {
  564. return QModelIndex();
  565. }
  566. }