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