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 20KB

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