54f806aa9d0ffb60a0214dd4369f7f4b28d2c1ac
[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     addressTableModel = new AddressTableModel(wallet, this);
25     mintingTableModel = new MintingTableModel(wallet, this);
26     transactionTableModel = new TransactionTableModel(wallet, this);
27
28     // This timer will be fired repeatedly to update the balance
29     pollTimer = new QTimer(this);
30     connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
31     pollTimer->start(MODEL_UPDATE_DELAY);
32
33     subscribeToCoreSignals();
34 }
35
36 WalletModel::~WalletModel()
37 {
38     unsubscribeFromCoreSignals();
39 }
40
41 qint64 WalletModel::getBalance() const
42 {
43     return wallet->GetBalance();
44 }
45
46 qint64 WalletModel::getBalanceWatchOnly() const
47 {
48     return wallet->GetWatchOnlyBalance();
49 }
50
51 qint64 WalletModel::getUnconfirmedBalance() const
52 {
53     return wallet->GetUnconfirmedBalance();
54 }
55
56 qint64 WalletModel::getStake() const
57 {
58     return wallet->GetStake();
59 }
60
61 qint64 WalletModel::getImmatureBalance() const
62 {
63     return wallet->GetImmatureBalance();
64 }
65
66 int WalletModel::getNumTransactions() const
67 {
68     int numTransactions = 0;
69     {
70         LOCK(wallet->cs_wallet);
71         numTransactions = wallet->mapWallet.size();
72     }
73     return numTransactions;
74 }
75
76 void WalletModel::updateStatus()
77 {
78     EncryptionStatus newEncryptionStatus = getEncryptionStatus();
79
80     if(cachedEncryptionStatus != newEncryptionStatus)
81         emit encryptionStatusChanged(newEncryptionStatus);
82 }
83
84 void WalletModel::pollBalanceChanged()
85 {
86     if(nBestHeight != cachedNumBlocks)
87     {
88         // Balance and number of transactions might have changed
89         cachedNumBlocks = nBestHeight;
90         checkBalanceChanged();
91     }
92 }
93
94 void WalletModel::checkBalanceChanged()
95 {
96     qint64 newBalanceTotal=getBalance(), newBalanceWatchOnly=getBalanceWatchOnly();
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_t 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_t> > 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_t 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 MintingTableModel *WalletModel::getMintingTableModel()
258 {
259     return mintingTableModel;
260 }
261
262 TransactionTableModel *WalletModel::getTransactionTableModel()
263 {
264     return transactionTableModel;
265 }
266
267 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
268 {
269     if(!wallet->IsCrypted())
270     {
271         return Unencrypted;
272     }
273     else if(wallet->IsLocked())
274     {
275         return Locked;
276     }
277     else
278     {
279         return Unlocked;
280     }
281 }
282
283 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
284 {
285     if(encrypted)
286     {
287         // Encrypt
288         return wallet->EncryptWallet(passphrase);
289     }
290     else
291     {
292         // Decrypt -- TODO; not supported yet
293         return false;
294     }
295 }
296
297 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
298 {
299     if(locked)
300     {
301         // Lock
302         return wallet->Lock();
303     }
304     else
305     {
306         // Unlock
307         return wallet->Unlock(passPhrase);
308     }
309 }
310
311 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
312 {
313     bool retval;
314     {
315         LOCK(wallet->cs_wallet);
316         wallet->Lock(); // Make sure wallet is locked before attempting pass change
317         retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
318     }
319     return retval;
320 }
321
322 void WalletModel::getStakeStats(float &nKernelsRate, float &nCoinDaysRate)
323 {
324     wallet->GetStakeStats(nKernelsRate, nCoinDaysRate);
325 }
326
327 void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
328 {
329     wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
330 }
331
332 bool WalletModel::dumpWallet(const QString &filename)
333 {
334     return DumpWallet(wallet, filename.toLocal8Bit().data());
335 }
336
337 bool WalletModel::importWallet(const QString &filename)
338 {
339     return ImportWallet(wallet, filename.toLocal8Bit().data());
340 }
341
342 bool WalletModel::backupWallet(const QString &filename)
343 {
344     return BackupWallet(*wallet, filename.toLocal8Bit().data());
345 }
346
347 // Handlers for core signals
348 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
349 {
350     OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
351     QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
352 }
353
354 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
355 {
356     OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
357     QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
358                               Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
359                               Q_ARG(QString, QString::fromStdString(label)),
360                               Q_ARG(bool, isMine),
361                               Q_ARG(int, status));
362 }
363
364 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
365 {
366     OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
367     QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
368                               Q_ARG(QString, QString::fromStdString(hash.GetHex())),
369                               Q_ARG(int, status));
370 }
371
372 void WalletModel::subscribeToCoreSignals()
373 {
374     // Connect signals to wallet
375     wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
376     wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
377     wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
378 }
379
380 void WalletModel::unsubscribeFromCoreSignals()
381 {
382     // Disconnect signals from wallet
383     wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
384     wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
385     wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
386 }
387
388 // WalletModel::UnlockContext implementation
389 WalletModel::UnlockContext WalletModel::requestUnlock()
390 {
391     bool was_locked = getEncryptionStatus() == Locked;
392     
393     if ((!was_locked) && fWalletUnlockMintOnly)
394     {
395        setWalletLocked(true);
396        was_locked = getEncryptionStatus() == Locked;
397
398     }
399     if(was_locked)
400     {
401         // Request UI to unlock wallet
402         emit requireUnlock();
403     }
404     // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
405     bool valid = getEncryptionStatus() != Locked;
406
407     return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
408 }
409
410 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
411         wallet(wallet),
412         valid(valid),
413         relock(relock)
414 {
415 }
416
417 WalletModel::UnlockContext::~UnlockContext()
418 {
419     if(valid && relock)
420     {
421         wallet->setWalletLocked(true);
422     }
423 }
424
425 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
426 {
427     // Transfer context; old object no longer relocks wallet
428     *this = rhs;
429     rhs.relock = false;
430 }
431
432 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
433 {
434     return wallet->GetPubKey(address, vchPubKeyOut);   
435 }
436
437 // returns a list of COutputs from COutPoints
438 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
439 {
440     BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
441     {
442         if (!wallet->mapWallet.count(outpoint.hash)) continue;
443         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
444         vOutputs.push_back(out);
445     }
446 }
447
448 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) 
449 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
450 {
451     std::vector<COutput> vCoins;
452     wallet->AvailableCoins(vCoins);
453     std::vector<COutPoint> vLockedCoins;
454
455     // add locked coins
456     BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
457     {
458         if (!wallet->mapWallet.count(outpoint.hash)) continue;
459         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
460         vCoins.push_back(out);
461     }
462
463     BOOST_FOREACH(const COutput& out, vCoins)
464     {
465         COutput cout = out;
466
467         while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
468         {
469             if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
470             cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
471         }
472
473         CTxDestination address;
474         if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
475             continue;
476         mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
477     }
478 }
479
480 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
481 {
482     return false;
483 }
484
485 void WalletModel::lockCoin(COutPoint& output)
486 {
487     return;
488 }
489
490 void WalletModel::unlockCoin(COutPoint& output)
491 {
492     return;
493 }
494
495 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
496 {
497     return;
498 }
499
500 void WalletModel::clearOrphans()
501 {
502     wallet->ClearOrphans();
503 }
504
505 CWallet* WalletModel::getWallet()
506 {
507     return wallet;
508 }