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