ac8b68f0526e37bcb4ae2e024ca52cb2ed0eee0a
[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 bool WalletModel::backupWallet(const QString &filename)
310 {
311     return BackupWallet(*wallet, filename.toLocal8Bit().data());
312 }
313
314 // Handlers for core signals
315 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
316 {
317     OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
318     QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
319 }
320
321 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
322 {
323     OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
324     QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
325                               Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
326                               Q_ARG(QString, QString::fromStdString(label)),
327                               Q_ARG(bool, isMine),
328                               Q_ARG(int, status));
329 }
330
331 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
332 {
333     OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
334     QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
335                               Q_ARG(QString, QString::fromStdString(hash.GetHex())),
336                               Q_ARG(int, status));
337 }
338
339 void WalletModel::subscribeToCoreSignals()
340 {
341     // Connect signals to wallet
342     wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
343     wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
344     wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
345 }
346
347 void WalletModel::unsubscribeFromCoreSignals()
348 {
349     // Disconnect signals from wallet
350     wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
351     wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
352     wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
353 }
354
355 // WalletModel::UnlockContext implementation
356 WalletModel::UnlockContext WalletModel::requestUnlock()
357 {
358     bool was_locked = getEncryptionStatus() == Locked;
359     
360     if ((!was_locked) && fWalletUnlockMintOnly)
361     {
362        setWalletLocked(true);
363        was_locked = getEncryptionStatus() == Locked;
364
365     }
366     if(was_locked)
367     {
368         // Request UI to unlock wallet
369         emit requireUnlock();
370     }
371     // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
372     bool valid = getEncryptionStatus() != Locked;
373
374     return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
375 }
376
377 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
378         wallet(wallet),
379         valid(valid),
380         relock(relock)
381 {
382 }
383
384 WalletModel::UnlockContext::~UnlockContext()
385 {
386     if(valid && relock)
387     {
388         wallet->setWalletLocked(true);
389     }
390 }
391
392 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
393 {
394     // Transfer context; old object no longer relocks wallet
395     *this = rhs;
396     rhs.relock = false;
397 }
398
399 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
400 {
401     return wallet->GetPubKey(address, vchPubKeyOut);   
402 }
403
404 // returns a list of COutputs from COutPoints
405 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
406 {
407     BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
408     {
409         if (!wallet->mapWallet.count(outpoint.hash)) continue;
410         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain());
411         vOutputs.push_back(out);
412     }
413 }
414
415 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) 
416 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
417 {
418     std::vector<COutput> vCoins;
419     wallet->AvailableCoins(vCoins);
420     std::vector<COutPoint> vLockedCoins;
421
422     // add locked coins
423     BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
424     {
425         if (!wallet->mapWallet.count(outpoint.hash)) continue;
426         COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain());
427         vCoins.push_back(out);
428     }
429
430     BOOST_FOREACH(const COutput& out, vCoins)
431     {
432         COutput cout = out;
433
434         while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
435         {
436             if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
437             cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0);
438         }
439
440         CTxDestination address;
441         if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue;
442         mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
443     }
444 }
445
446 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
447 {
448     return false;
449 }
450
451 void WalletModel::lockCoin(COutPoint& output)
452 {
453     return;
454 }
455
456 void WalletModel::unlockCoin(COutPoint& output)
457 {
458     return;
459 }
460
461 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
462 {
463     return;
464 }