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