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