baa8e7ed774f8f25ae8a2a59ffa22c47814329f7
[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 = 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 -- TODO; not supported yet
306         return false;
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::getStakeStats(float &nKernelsRate, float &nCoinDaysRate)
336 {
337     wallet->GetStakeStats(nKernelsRate, nCoinDaysRate);
338 }
339
340 void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
341 {
342     wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
343 }
344
345 bool WalletModel::dumpWallet(const QString &filename)
346 {
347     return DumpWallet(wallet, filename.toLocal8Bit().data());
348 }
349
350 bool WalletModel::importWallet(const QString &filename)
351 {
352     return ImportWallet(wallet, filename.toLocal8Bit().data());
353 }
354
355 bool WalletModel::backupWallet(const QString &filename)
356 {
357     return BackupWallet(*wallet, filename.toLocal8Bit().data());
358 }
359
360 // Handlers for core signals
361 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
362 {
363     OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
364     QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
365 }
366
367 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
368 {
369     OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
370     QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
371                               Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
372                               Q_ARG(QString, QString::fromStdString(label)),
373                               Q_ARG(bool, isMine),
374                               Q_ARG(int, status));
375 }
376
377 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
378 {
379     OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
380     QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
381                               Q_ARG(QString, QString::fromStdString(hash.GetHex())),
382                               Q_ARG(int, status));
383 }
384
385 static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
386 {
387     QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection,
388     Q_ARG(bool, fHaveWatchonly));
389 }
390
391 void WalletModel::subscribeToCoreSignals()
392 {
393     // Connect signals to wallet
394     wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
395     wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
396     wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
397     wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1));
398 }
399
400 void WalletModel::unsubscribeFromCoreSignals()
401 {
402     // Disconnect signals from wallet
403     wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
404     wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
405     wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
406     wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1));
407 }
408
409 // WalletModel::UnlockContext implementation
410 WalletModel::UnlockContext WalletModel::requestUnlock()
411 {
412     bool was_locked = getEncryptionStatus() == Locked;
413     
414     if ((!was_locked) && fWalletUnlockMintOnly)
415     {
416        setWalletLocked(true);
417        was_locked = getEncryptionStatus() == Locked;
418
419     }
420     if(was_locked)
421     {
422         // Request UI to unlock wallet
423         emit requireUnlock();
424     }
425     // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
426     bool valid = getEncryptionStatus() != Locked;
427
428     return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
429 }
430
431 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
432         wallet(wallet),
433         valid(valid),
434         relock(relock)
435 {
436 }
437
438 WalletModel::UnlockContext::~UnlockContext()
439 {
440     if(valid && relock)
441     {
442         wallet->setWalletLocked(true);
443     }
444 }
445
446 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
447 {
448     // Transfer context; old object no longer relocks wallet
449     *this = rhs;
450     rhs.relock = false;
451 }
452
453 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
454 {
455     return wallet->GetPubKey(address, vchPubKeyOut);   
456 }
457
458 // returns a list of COutputs from COutPoints
459 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
460 {
461     BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
462     {
463         if (!wallet->mapWallet.count(outpoint.hash)) continue;
464         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
465         vOutputs.push_back(out);
466     }
467 }
468
469 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) 
470 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
471 {
472     std::vector<COutput> vCoins;
473     wallet->AvailableCoins(vCoins);
474     std::vector<COutPoint> vLockedCoins;
475
476     // add locked coins
477     BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
478     {
479         if (!wallet->mapWallet.count(outpoint.hash)) continue;
480         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
481         if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == MINE_SPENDABLE)
482             vCoins.push_back(out);
483     }
484
485     BOOST_FOREACH(const COutput& out, vCoins)
486     {
487         COutput cout = out;
488
489         while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
490         {
491             if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
492             cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
493         }
494
495         CTxDestination address;
496         if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
497             continue;
498         mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
499     }
500 }
501
502 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
503 {
504     return false;
505 }
506
507 void WalletModel::lockCoin(COutPoint& output)
508 {
509     return;
510 }
511
512 void WalletModel::unlockCoin(COutPoint& output)
513 {
514     return;
515 }
516
517 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
518 {
519     return;
520 }
521
522 void WalletModel::clearOrphans()
523 {
524     wallet->ClearOrphans();
525 }
526
527 CWallet* WalletModel::getWallet()
528 {
529     return wallet;
530 }