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