Implement IsMine filter
[novacoin.git] / src / qt / walletmodel.cpp
1 #include "walletmodel.h"
2 #include "guiconstants.h"
3 #include "optionsmodel.h"
4 #include "addresstablemodel.h"
5 #include "transactiontablemodel.h"
6
7 #include "ui_interface.h"
8 #include "wallet.h"
9 #include "walletdb.h" // for BackupWallet
10 #include "base58.h"
11
12 #include <QSet>
13 #include <QTimer>
14
15 WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
16     QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
17     transactionTableModel(0),
18     cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
19     cachedNumTransactions(0),
20     cachedEncryptionStatus(Unencrypted),
21     cachedNumBlocks(0)
22 {
23     addressTableModel = new AddressTableModel(wallet, this);
24     transactionTableModel = new TransactionTableModel(wallet, this);
25
26     // This timer will be fired repeatedly to update the balance
27     pollTimer = new QTimer(this);
28     connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
29     pollTimer->start(MODEL_UPDATE_DELAY);
30
31     subscribeToCoreSignals();
32 }
33
34 WalletModel::~WalletModel()
35 {
36     unsubscribeFromCoreSignals();
37 }
38
39 qint64 WalletModel::getBalance() const
40 {
41     return wallet->GetBalance();
42 }
43
44 qint64 WalletModel::getBalanceWatchOnly() const
45 {
46     return wallet->GetWatchOnlyBalance();
47 }
48
49 qint64 WalletModel::getUnconfirmedBalance() const
50 {
51     return wallet->GetUnconfirmedBalance();
52 }
53
54 qint64 WalletModel::getStake() const
55 {
56     return wallet->GetStake();
57 }
58
59 qint64 WalletModel::getImmatureBalance() const
60 {
61     return wallet->GetImmatureBalance();
62 }
63
64 int WalletModel::getNumTransactions() const
65 {
66     int numTransactions = 0;
67     {
68         LOCK(wallet->cs_wallet);
69         numTransactions = wallet->mapWallet.size();
70     }
71     return numTransactions;
72 }
73
74 void WalletModel::updateStatus()
75 {
76     EncryptionStatus newEncryptionStatus = getEncryptionStatus();
77
78     if(cachedEncryptionStatus != newEncryptionStatus)
79         emit encryptionStatusChanged(newEncryptionStatus);
80 }
81
82 void WalletModel::pollBalanceChanged()
83 {
84     if(nBestHeight != cachedNumBlocks)
85     {
86         // Balance and number of transactions might have changed
87         cachedNumBlocks = nBestHeight;
88         checkBalanceChanged();
89     }
90 }
91
92 void WalletModel::checkBalanceChanged()
93 {
94     qint64 newBalanceTotal=getBalance(), newBalanceWatchOnly=getBalanceWatchOnly();
95     qint64 newStake = getStake();
96     qint64 newUnconfirmedBalance = getUnconfirmedBalance();
97     qint64 newImmatureBalance = getImmatureBalance();
98
99     if(cachedBalance != newBalanceTotal || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
100     {
101         cachedBalance = newBalanceTotal;
102         cachedStake = newStake;
103         cachedUnconfirmedBalance = newUnconfirmedBalance;
104         cachedImmatureBalance = newImmatureBalance;
105         emit balanceChanged(newBalanceTotal, newBalanceWatchOnly, newStake, newUnconfirmedBalance, newImmatureBalance);
106     }
107 }
108
109 void WalletModel::updateTransaction(const QString &hash, int status)
110 {
111     if(transactionTableModel)
112         transactionTableModel->updateTransaction(hash, status);
113
114     // Balance and number of transactions might have changed
115     checkBalanceChanged();
116
117     int newNumTransactions = getNumTransactions();
118     if(cachedNumTransactions != newNumTransactions)
119     {
120         cachedNumTransactions = newNumTransactions;
121         emit numTransactionsChanged(newNumTransactions);
122     }
123 }
124
125 void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
126 {
127     if(addressTableModel)
128         addressTableModel->updateEntry(address, label, isMine, status);
129 }
130
131 bool WalletModel::validateAddress(const QString &address)
132 {
133     CBitcoinAddress addressParsed(address.toStdString());
134     return addressParsed.IsValid();
135 }
136
137 WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
138 {
139     qint64 total = 0;
140     QSet<QString> setAddress;
141     QString hex;
142
143     if(recipients.empty())
144     {
145         return OK;
146     }
147
148     // Pre-check input data for validity
149     foreach(const SendCoinsRecipient &rcp, recipients)
150     {
151         if(!validateAddress(rcp.address))
152         {
153             return InvalidAddress;
154         }
155         setAddress.insert(rcp.address);
156
157         if(rcp.amount <= 0)
158         {
159             return InvalidAmount;
160         }
161         total += rcp.amount;
162     }
163
164     if(recipients.size() > setAddress.size())
165     {
166         return DuplicateAddress;
167     }
168
169     int64 nBalance = 0;
170     std::vector<COutput> vCoins;
171     wallet->AvailableCoins(vCoins, true, coinControl);
172
173     BOOST_FOREACH(const COutput& out, vCoins)
174         if(out.fSpendable)
175             nBalance += out.tx->vout[out.i].nValue;
176
177     if(total > nBalance)
178     {
179         return AmountExceedsBalance;
180     }
181
182     if((total + nTransactionFee) > nBalance)
183     {
184         return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
185     }
186
187     {
188         LOCK2(cs_main, wallet->cs_wallet);
189
190         // Sendmany
191         std::vector<std::pair<CScript, int64> > vecSend;
192         foreach(const SendCoinsRecipient &rcp, recipients)
193         {
194             CScript scriptPubKey;
195             scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
196             vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
197         }
198
199         CWalletTx wtx;
200         CReserveKey keyChange(wallet);
201         int64 nFeeRequired = 0;
202         bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
203
204         if(!fCreated)
205         {
206             if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
207             {
208                 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
209             }
210             return TransactionCreationFailed;
211         }
212         if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
213         {
214             return Aborted;
215         }
216         if(!wallet->CommitTransaction(wtx, keyChange))
217         {
218             return TransactionCommitFailed;
219         }
220         hex = QString::fromStdString(wtx.GetHash().GetHex());
221     }
222
223     // Add addresses / update labels that we've sent to to the address book
224     foreach(const SendCoinsRecipient &rcp, recipients)
225     {
226         std::string strAddress = rcp.address.toStdString();
227         CTxDestination dest = CBitcoinAddress(strAddress).Get();
228         std::string strLabel = rcp.label.toStdString();
229         {
230             LOCK(wallet->cs_wallet);
231
232             std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
233
234             // Check if we have a new address or an updated label
235             if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
236             {
237                 wallet->SetAddressBookName(dest, strLabel);
238             }
239         }
240     }
241
242     return SendCoinsReturn(OK, 0, hex);
243 }
244
245 OptionsModel *WalletModel::getOptionsModel()
246 {
247     return optionsModel;
248 }
249
250 AddressTableModel *WalletModel::getAddressTableModel()
251 {
252     return addressTableModel;
253 }
254
255 TransactionTableModel *WalletModel::getTransactionTableModel()
256 {
257     return transactionTableModel;
258 }
259
260 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
261 {
262     if(!wallet->IsCrypted())
263     {
264         return Unencrypted;
265     }
266     else if(wallet->IsLocked())
267     {
268         return Locked;
269     }
270     else
271     {
272         return Unlocked;
273     }
274 }
275
276 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
277 {
278     if(encrypted)
279     {
280         // Encrypt
281         return wallet->EncryptWallet(passphrase);
282     }
283     else
284     {
285         // Decrypt -- TODO; not supported yet
286         return false;
287     }
288 }
289
290 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
291 {
292     if(locked)
293     {
294         // Lock
295         return wallet->Lock();
296     }
297     else
298     {
299         // Unlock
300         return wallet->Unlock(passPhrase);
301     }
302 }
303
304 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
305 {
306     bool retval;
307     {
308         LOCK(wallet->cs_wallet);
309         wallet->Lock(); // Make sure wallet is locked before attempting pass change
310         retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
311     }
312     return retval;
313 }
314
315 void WalletModel::getStakeWeight(uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
316 {
317     wallet->GetStakeWeight(*wallet, nMinWeight, nMaxWeight, nWeight);
318 }
319
320 void WalletModel::getStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
321 {
322     wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
323 }
324
325 bool WalletModel::dumpWallet(const QString &filename)
326 {
327     return DumpWallet(wallet, filename.toLocal8Bit().data());
328 }
329
330 bool WalletModel::importWallet(const QString &filename)
331 {
332     return ImportWallet(wallet, filename.toLocal8Bit().data());
333 }
334
335 bool WalletModel::backupWallet(const QString &filename)
336 {
337     return BackupWallet(*wallet, filename.toLocal8Bit().data());
338 }
339
340 // Handlers for core signals
341 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
342 {
343     OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
344     QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
345 }
346
347 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
348 {
349     OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
350     QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
351                               Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
352                               Q_ARG(QString, QString::fromStdString(label)),
353                               Q_ARG(bool, isMine),
354                               Q_ARG(int, status));
355 }
356
357 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
358 {
359     OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
360     QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
361                               Q_ARG(QString, QString::fromStdString(hash.GetHex())),
362                               Q_ARG(int, status));
363 }
364
365 void WalletModel::subscribeToCoreSignals()
366 {
367     // Connect signals to wallet
368     wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
369     wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
370     wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
371 }
372
373 void WalletModel::unsubscribeFromCoreSignals()
374 {
375     // Disconnect signals from wallet
376     wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
377     wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
378     wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
379 }
380
381 // WalletModel::UnlockContext implementation
382 WalletModel::UnlockContext WalletModel::requestUnlock()
383 {
384     bool was_locked = getEncryptionStatus() == Locked;
385     
386     if ((!was_locked) && fWalletUnlockMintOnly)
387     {
388        setWalletLocked(true);
389        was_locked = getEncryptionStatus() == Locked;
390
391     }
392     if(was_locked)
393     {
394         // Request UI to unlock wallet
395         emit requireUnlock();
396     }
397     // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
398     bool valid = getEncryptionStatus() != Locked;
399
400     return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
401 }
402
403 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
404         wallet(wallet),
405         valid(valid),
406         relock(relock)
407 {
408 }
409
410 WalletModel::UnlockContext::~UnlockContext()
411 {
412     if(valid && relock)
413     {
414         wallet->setWalletLocked(true);
415     }
416 }
417
418 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
419 {
420     // Transfer context; old object no longer relocks wallet
421     *this = rhs;
422     rhs.relock = false;
423 }
424
425 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
426 {
427     return wallet->GetPubKey(address, vchPubKeyOut);   
428 }
429
430 // returns a list of COutputs from COutPoints
431 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
432 {
433     BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
434     {
435         if (!wallet->mapWallet.count(outpoint.hash)) continue;
436         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
437         vOutputs.push_back(out);
438     }
439 }
440
441 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) 
442 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
443 {
444     std::vector<COutput> vCoins;
445     wallet->AvailableCoins(vCoins);
446     std::vector<COutPoint> vLockedCoins;
447
448     // add locked coins
449     BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
450     {
451         if (!wallet->mapWallet.count(outpoint.hash)) continue;
452         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
453         vCoins.push_back(out);
454     }
455
456     BOOST_FOREACH(const COutput& out, vCoins)
457     {
458         COutput cout = out;
459
460         while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
461         {
462             if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
463             cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
464         }
465
466         CTxDestination address;
467         if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
468             continue;
469         mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
470     }
471 }
472
473 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
474 {
475     return false;
476 }
477
478 void WalletModel::lockCoin(COutPoint& output)
479 {
480     return;
481 }
482
483 void WalletModel::unlockCoin(COutPoint& output)
484 {
485     return;
486 }
487
488 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
489 {
490     return;
491 }