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.

addresstablemodel.cpp 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // Copyright (c) 2011-2015 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.
  4. #include "addresstablemodel.h"
  5. #include "guiutil.h"
  6. #include "walletmodel.h"
  7. #include "base58.h"
  8. #include "wallet/wallet.h"
  9. #include <boost/foreach.hpp>
  10. #include <QFont>
  11. #include <QDebug>
  12. const QString AddressTableModel::Send = "S";
  13. const QString AddressTableModel::Receive = "R";
  14. struct AddressTableEntry
  15. {
  16. enum Type {
  17. Sending,
  18. Receiving,
  19. Hidden /* QSortFilterProxyModel will filter these out */
  20. };
  21. Type type;
  22. QString label;
  23. QString address;
  24. AddressTableEntry() {}
  25. AddressTableEntry(Type type, const QString &label, const QString &address):
  26. type(type), label(label), address(address) {}
  27. };
  28. struct AddressTableEntryLessThan
  29. {
  30. bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const
  31. {
  32. return a.address < b.address;
  33. }
  34. bool operator()(const AddressTableEntry &a, const QString &b) const
  35. {
  36. return a.address < b;
  37. }
  38. bool operator()(const QString &a, const AddressTableEntry &b) const
  39. {
  40. return a < b.address;
  41. }
  42. };
  43. /* Determine address type from address purpose */
  44. static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine)
  45. {
  46. AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
  47. // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
  48. if (strPurpose == "send")
  49. addressType = AddressTableEntry::Sending;
  50. else if (strPurpose == "receive")
  51. addressType = AddressTableEntry::Receiving;
  52. else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
  53. addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
  54. return addressType;
  55. }
  56. // Private implementation
  57. class AddressTablePriv
  58. {
  59. public:
  60. CWallet *wallet;
  61. QList<AddressTableEntry> cachedAddressTable;
  62. AddressTableModel *parent;
  63. AddressTablePriv(CWallet *wallet, AddressTableModel *parent):
  64. wallet(wallet), parent(parent) {}
  65. void refreshAddressTable()
  66. {
  67. cachedAddressTable.clear();
  68. {
  69. LOCK(wallet->cs_wallet);
  70. BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook)
  71. {
  72. const CBitcoinAddress& address = item.first;
  73. bool fMine = IsMine(*wallet, address.Get());
  74. AddressTableEntry::Type addressType = translateTransactionType(
  75. QString::fromStdString(item.second.purpose), fMine);
  76. const std::string& strName = item.second.name;
  77. cachedAddressTable.append(AddressTableEntry(addressType,
  78. QString::fromStdString(strName),
  79. QString::fromStdString(address.ToString())));
  80. }
  81. }
  82. // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
  83. // Even though the map is already sorted this re-sorting step is needed because the originating map
  84. // is sorted by binary address, not by base58() address.
  85. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
  86. }
  87. void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status)
  88. {
  89. // Find address / label in model
  90. QList<AddressTableEntry>::iterator lower = qLowerBound(
  91. cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
  92. QList<AddressTableEntry>::iterator upper = qUpperBound(
  93. cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
  94. int lowerIndex = (lower - cachedAddressTable.begin());
  95. int upperIndex = (upper - cachedAddressTable.begin());
  96. bool inModel = (lower != upper);
  97. AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
  98. switch(status)
  99. {
  100. case CT_NEW:
  101. if(inModel)
  102. {
  103. qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
  104. break;
  105. }
  106. parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
  107. cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
  108. parent->endInsertRows();
  109. break;
  110. case CT_UPDATED:
  111. if(!inModel)
  112. {
  113. qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
  114. break;
  115. }
  116. lower->type = newEntryType;
  117. lower->label = label;
  118. parent->emitDataChanged(lowerIndex);
  119. break;
  120. case CT_DELETED:
  121. if(!inModel)
  122. {
  123. qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
  124. break;
  125. }
  126. parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
  127. cachedAddressTable.erase(lower, upper);
  128. parent->endRemoveRows();
  129. break;
  130. }
  131. }
  132. int size()
  133. {
  134. return cachedAddressTable.size();
  135. }
  136. AddressTableEntry *index(int idx)
  137. {
  138. if(idx >= 0 && idx < cachedAddressTable.size())
  139. {
  140. return &cachedAddressTable[idx];
  141. }
  142. else
  143. {
  144. return 0;
  145. }
  146. }
  147. };
  148. AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) :
  149. QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0)
  150. {
  151. columns << tr("Label") << tr("Address");
  152. priv = new AddressTablePriv(wallet, this);
  153. priv->refreshAddressTable();
  154. }
  155. AddressTableModel::~AddressTableModel()
  156. {
  157. delete priv;
  158. }
  159. int AddressTableModel::rowCount(const QModelIndex &parent) const
  160. {
  161. Q_UNUSED(parent);
  162. return priv->size();
  163. }
  164. int AddressTableModel::columnCount(const QModelIndex &parent) const
  165. {
  166. Q_UNUSED(parent);
  167. return columns.length();
  168. }
  169. QVariant AddressTableModel::data(const QModelIndex &index, int role) const
  170. {
  171. if(!index.isValid())
  172. return QVariant();
  173. AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
  174. if(role == Qt::DisplayRole || role == Qt::EditRole)
  175. {
  176. switch(index.column())
  177. {
  178. case Label:
  179. if(rec->label.isEmpty() && role == Qt::DisplayRole)
  180. {
  181. return tr("(no label)");
  182. }
  183. else
  184. {
  185. return rec->label;
  186. }
  187. case Address:
  188. return rec->address;
  189. }
  190. }
  191. else if (role == Qt::FontRole)
  192. {
  193. QFont font;
  194. if(index.column() == Address)
  195. {
  196. font = GUIUtil::fixedPitchFont();
  197. }
  198. return font;
  199. }
  200. else if (role == TypeRole)
  201. {
  202. switch(rec->type)
  203. {
  204. case AddressTableEntry::Sending:
  205. return Send;
  206. case AddressTableEntry::Receiving:
  207. return Receive;
  208. default: break;
  209. }
  210. }
  211. return QVariant();
  212. }
  213. bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
  214. {
  215. if(!index.isValid())
  216. return false;
  217. AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
  218. std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
  219. editStatus = OK;
  220. if(role == Qt::EditRole)
  221. {
  222. LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
  223. CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
  224. if(index.column() == Label)
  225. {
  226. // Do nothing, if old label == new label
  227. if(rec->label == value.toString())
  228. {
  229. editStatus = NO_CHANGES;
  230. return false;
  231. }
  232. wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
  233. } else if(index.column() == Address) {
  234. CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
  235. // Refuse to set invalid address, set error status and return false
  236. if(boost::get<CNoDestination>(&newAddress))
  237. {
  238. editStatus = INVALID_ADDRESS;
  239. return false;
  240. }
  241. // Do nothing, if old address == new address
  242. else if(newAddress == curAddress)
  243. {
  244. editStatus = NO_CHANGES;
  245. return false;
  246. }
  247. // Check for duplicate addresses to prevent accidental deletion of addresses, if you try
  248. // to paste an existing address over another address (with a different label)
  249. else if(wallet->mapAddressBook.count(newAddress))
  250. {
  251. editStatus = DUPLICATE_ADDRESS;
  252. return false;
  253. }
  254. // Double-check that we're not overwriting a receiving address
  255. else if(rec->type == AddressTableEntry::Sending)
  256. {
  257. // Remove old entry
  258. wallet->DelAddressBook(curAddress);
  259. // Add new entry with new address
  260. wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
  261. }
  262. }
  263. return true;
  264. }
  265. return false;
  266. }
  267. QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
  268. {
  269. if(orientation == Qt::Horizontal)
  270. {
  271. if(role == Qt::DisplayRole && section < columns.size())
  272. {
  273. return columns[section];
  274. }
  275. }
  276. return QVariant();
  277. }
  278. Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const
  279. {
  280. if(!index.isValid())
  281. return 0;
  282. AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
  283. Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
  284. // Can edit address and label for sending addresses,
  285. // and only label for receiving addresses.
  286. if(rec->type == AddressTableEntry::Sending ||
  287. (rec->type == AddressTableEntry::Receiving && index.column()==Label))
  288. {
  289. retval |= Qt::ItemIsEditable;
  290. }
  291. return retval;
  292. }
  293. QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const
  294. {
  295. Q_UNUSED(parent);
  296. AddressTableEntry *data = priv->index(row);
  297. if(data)
  298. {
  299. return createIndex(row, column, priv->index(row));
  300. }
  301. else
  302. {
  303. return QModelIndex();
  304. }
  305. }
  306. void AddressTableModel::updateEntry(const QString &address,
  307. const QString &label, bool isMine, const QString &purpose, int status)
  308. {
  309. // Update address book model from Bitcoin core
  310. priv->updateEntry(address, label, isMine, purpose, status);
  311. }
  312. QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address)
  313. {
  314. std::string strLabel = label.toStdString();
  315. std::string strAddress = address.toStdString();
  316. editStatus = OK;
  317. if(type == Send)
  318. {
  319. if(!walletModel->validateAddress(address))
  320. {
  321. editStatus = INVALID_ADDRESS;
  322. return QString();
  323. }
  324. // Check for duplicate addresses
  325. {
  326. LOCK(wallet->cs_wallet);
  327. if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get()))
  328. {
  329. editStatus = DUPLICATE_ADDRESS;
  330. return QString();
  331. }
  332. }
  333. }
  334. else if(type == Receive)
  335. {
  336. // Generate a new address to associate with given label
  337. CPubKey newKey;
  338. if(!wallet->GetKeyFromPool(newKey))
  339. {
  340. WalletModel::UnlockContext ctx(walletModel->requestUnlock());
  341. if(!ctx.isValid())
  342. {
  343. // Unlock wallet failed or was cancelled
  344. editStatus = WALLET_UNLOCK_FAILURE;
  345. return QString();
  346. }
  347. if(!wallet->GetKeyFromPool(newKey))
  348. {
  349. editStatus = KEY_GENERATION_FAILURE;
  350. return QString();
  351. }
  352. }
  353. strAddress = CBitcoinAddress(newKey.GetID()).ToString();
  354. }
  355. else
  356. {
  357. return QString();
  358. }
  359. // Add entry
  360. {
  361. LOCK(wallet->cs_wallet);
  362. wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
  363. (type == Send ? "send" : "receive"));
  364. }
  365. return QString::fromStdString(strAddress);
  366. }
  367. bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent)
  368. {
  369. Q_UNUSED(parent);
  370. AddressTableEntry *rec = priv->index(row);
  371. if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving)
  372. {
  373. // Can only remove one row at a time, and cannot remove rows not in model.
  374. // Also refuse to remove receiving addresses.
  375. return false;
  376. }
  377. {
  378. LOCK(wallet->cs_wallet);
  379. wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
  380. }
  381. return true;
  382. }
  383. /* Look up label for address in address book, if not found return empty string.
  384. */
  385. QString AddressTableModel::labelForAddress(const QString &address) const
  386. {
  387. {
  388. LOCK(wallet->cs_wallet);
  389. CBitcoinAddress address_parsed(address.toStdString());
  390. std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
  391. if (mi != wallet->mapAddressBook.end())
  392. {
  393. return QString::fromStdString(mi->second.name);
  394. }
  395. }
  396. return QString();
  397. }
  398. int AddressTableModel::lookupAddress(const QString &address) const
  399. {
  400. QModelIndexList lst = match(index(0, Address, QModelIndex()),
  401. Qt::EditRole, address, 1, Qt::MatchExactly);
  402. if(lst.isEmpty())
  403. {
  404. return -1;
  405. }
  406. else
  407. {
  408. return lst.at(0).row();
  409. }
  410. }
  411. void AddressTableModel::emitDataChanged(int idx)
  412. {
  413. Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
  414. }