update to 0.4 preview
[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)
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     if(total > getBalance())
165     {
166         return AmountExceedsBalance;
167     }
168
169     if((total + nTransactionFee) > getBalance())
170     {
171         return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
172     }
173
174     {
175         LOCK2(cs_main, wallet->cs_wallet);
176
177         // Sendmany
178         std::vector<std::pair<CScript, int64> > vecSend;
179         foreach(const SendCoinsRecipient &rcp, recipients)
180         {
181             CScript scriptPubKey;
182             scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
183             vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
184         }
185
186         CWalletTx wtx;
187         CReserveKey keyChange(wallet);
188         int64 nFeeRequired = 0;
189         bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
190
191         if(!fCreated)
192         {
193             if((total + nFeeRequired) > wallet->GetBalance())
194             {
195                 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
196             }
197             return TransactionCreationFailed;
198         }
199         if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
200         {
201             return Aborted;
202         }
203         if(!wallet->CommitTransaction(wtx, keyChange))
204         {
205             return TransactionCommitFailed;
206         }
207         hex = QString::fromStdString(wtx.GetHash().GetHex());
208     }
209
210     // Add addresses / update labels that we've sent to to the address book
211     foreach(const SendCoinsRecipient &rcp, recipients)
212     {
213         std::string strAddress = rcp.address.toStdString();
214         CTxDestination dest = CBitcoinAddress(strAddress).Get();
215         std::string strLabel = rcp.label.toStdString();
216         {
217             LOCK(wallet->cs_wallet);
218
219             std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
220
221             // Check if we have a new address or an updated label
222             if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
223             {
224                 wallet->SetAddressBookName(dest, strLabel);
225             }
226         }
227     }
228
229     return SendCoinsReturn(OK, 0, hex);
230 }
231
232 OptionsModel *WalletModel::getOptionsModel()
233 {
234     return optionsModel;
235 }
236
237 AddressTableModel *WalletModel::getAddressTableModel()
238 {
239     return addressTableModel;
240 }
241
242 TransactionTableModel *WalletModel::getTransactionTableModel()
243 {
244     return transactionTableModel;
245 }
246
247 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
248 {
249     if(!wallet->IsCrypted())
250     {
251         return Unencrypted;
252     }
253     else if(wallet->IsLocked())
254     {
255         return Locked;
256     }
257     else
258     {
259         return Unlocked;
260     }
261 }
262
263 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
264 {
265     if(encrypted)
266     {
267         // Encrypt
268         return wallet->EncryptWallet(passphrase);
269     }
270     else
271     {
272         // Decrypt -- TODO; not supported yet
273         return false;
274     }
275 }
276
277 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
278 {
279     if(locked)
280     {
281         // Lock
282         return wallet->Lock();
283     }
284     else
285     {
286         // Unlock
287         return wallet->Unlock(passPhrase);
288     }
289 }
290
291 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
292 {
293     bool retval;
294     {
295         LOCK(wallet->cs_wallet);
296         wallet->Lock(); // Make sure wallet is locked before attempting pass change
297         retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
298     }
299     return retval;
300 }
301
302 bool WalletModel::backupWallet(const QString &filename)
303 {
304     return BackupWallet(*wallet, filename.toLocal8Bit().data());
305 }
306
307 // Handlers for core signals
308 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
309 {
310     OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
311     QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
312 }
313
314 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
315 {
316     OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
317     QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
318                               Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
319                               Q_ARG(QString, QString::fromStdString(label)),
320                               Q_ARG(bool, isMine),
321                               Q_ARG(int, status));
322 }
323
324 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
325 {
326     OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
327     QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
328                               Q_ARG(QString, QString::fromStdString(hash.GetHex())),
329                               Q_ARG(int, status));
330 }
331
332 void WalletModel::subscribeToCoreSignals()
333 {
334     // Connect signals to wallet
335     wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
336     wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
337     wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
338 }
339
340 void WalletModel::unsubscribeFromCoreSignals()
341 {
342     // Disconnect signals from wallet
343     wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
344     wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
345     wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
346 }
347
348 // WalletModel::UnlockContext implementation
349 WalletModel::UnlockContext WalletModel::requestUnlock()
350 {
351     bool was_locked = getEncryptionStatus() == Locked;
352     if(was_locked)
353     {
354         // Request UI to unlock wallet
355         emit requireUnlock();
356     }
357     // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
358     bool valid = getEncryptionStatus() != Locked;
359
360     return UnlockContext(this, valid, was_locked);
361 }
362
363 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
364         wallet(wallet),
365         valid(valid),
366         relock(relock)
367 {
368 }
369
370 WalletModel::UnlockContext::~UnlockContext()
371 {
372     if(valid && relock)
373     {
374         wallet->setWalletLocked(true);
375     }
376 }
377
378 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
379 {
380     // Transfer context; old object no longer relocks wallet
381     *this = rhs;
382     rhs.relock = false;
383 }