1 #include "walletmodel.h"
2 #include "guiconstants.h"
3 #include "optionsmodel.h"
4 #include "addresstablemodel.h"
5 #include "transactiontablemodel.h"
7 #include "ui_interface.h"
9 #include "walletdb.h" // for BackupWallet
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),
23 addressTableModel = new AddressTableModel(wallet, this);
24 transactionTableModel = new TransactionTableModel(wallet, this);
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);
31 subscribeToCoreSignals();
34 WalletModel::~WalletModel()
36 unsubscribeFromCoreSignals();
39 qint64 WalletModel::getBalance() const
41 return wallet->GetBalance();
44 qint64 WalletModel::getUnconfirmedBalance() const
46 return wallet->GetUnconfirmedBalance();
49 qint64 WalletModel::getStake() const
51 return wallet->GetStake();
54 qint64 WalletModel::getImmatureBalance() const
56 return wallet->GetImmatureBalance();
59 int WalletModel::getNumTransactions() const
61 int numTransactions = 0;
63 LOCK(wallet->cs_wallet);
64 numTransactions = wallet->mapWallet.size();
66 return numTransactions;
69 void WalletModel::updateStatus()
71 EncryptionStatus newEncryptionStatus = getEncryptionStatus();
73 if(cachedEncryptionStatus != newEncryptionStatus)
74 emit encryptionStatusChanged(newEncryptionStatus);
77 void WalletModel::pollBalanceChanged()
79 if(nBestHeight != cachedNumBlocks)
81 // Balance and number of transactions might have changed
82 cachedNumBlocks = nBestHeight;
83 checkBalanceChanged();
87 void WalletModel::checkBalanceChanged()
89 qint64 newBalance = getBalance();
90 qint64 newStake = getStake();
91 qint64 newUnconfirmedBalance = getUnconfirmedBalance();
92 qint64 newImmatureBalance = getImmatureBalance();
94 if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
96 cachedBalance = newBalance;
97 cachedStake = newStake;
98 cachedUnconfirmedBalance = newUnconfirmedBalance;
99 cachedImmatureBalance = newImmatureBalance;
100 emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance);
104 void WalletModel::updateTransaction(const QString &hash, int status)
106 if(transactionTableModel)
107 transactionTableModel->updateTransaction(hash, status);
109 // Balance and number of transactions might have changed
110 checkBalanceChanged();
112 int newNumTransactions = getNumTransactions();
113 if(cachedNumTransactions != newNumTransactions)
115 cachedNumTransactions = newNumTransactions;
116 emit numTransactionsChanged(newNumTransactions);
120 void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
122 if(addressTableModel)
123 addressTableModel->updateEntry(address, label, isMine, status);
126 bool WalletModel::validateAddress(const QString &address)
128 CBitcoinAddress addressParsed(address.toStdString());
129 return addressParsed.IsValid();
132 WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
135 QSet<QString> setAddress;
138 if(recipients.empty())
143 // Pre-check input data for validity
144 foreach(const SendCoinsRecipient &rcp, recipients)
146 if(!validateAddress(rcp.address))
148 return InvalidAddress;
150 setAddress.insert(rcp.address);
154 return InvalidAmount;
159 if(recipients.size() > setAddress.size())
161 return DuplicateAddress;
164 if(total > getBalance())
166 return AmountExceedsBalance;
169 if((total + nTransactionFee) > getBalance())
171 return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
175 LOCK2(cs_main, wallet->cs_wallet);
178 std::vector<std::pair<CScript, int64> > vecSend;
179 foreach(const SendCoinsRecipient &rcp, recipients)
181 CScript scriptPubKey;
182 scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
183 vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
187 CReserveKey keyChange(wallet);
188 int64 nFeeRequired = 0;
189 bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
193 if((total + nFeeRequired) > wallet->GetBalance())
195 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
197 return TransactionCreationFailed;
199 if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
203 if(!wallet->CommitTransaction(wtx, keyChange))
205 return TransactionCommitFailed;
207 hex = QString::fromStdString(wtx.GetHash().GetHex());
210 // Add addresses / update labels that we've sent to to the address book
211 foreach(const SendCoinsRecipient &rcp, recipients)
213 std::string strAddress = rcp.address.toStdString();
214 CTxDestination dest = CBitcoinAddress(strAddress).Get();
215 std::string strLabel = rcp.label.toStdString();
217 LOCK(wallet->cs_wallet);
219 std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
221 // Check if we have a new address or an updated label
222 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
224 wallet->SetAddressBookName(dest, strLabel);
229 return SendCoinsReturn(OK, 0, hex);
232 OptionsModel *WalletModel::getOptionsModel()
237 AddressTableModel *WalletModel::getAddressTableModel()
239 return addressTableModel;
242 TransactionTableModel *WalletModel::getTransactionTableModel()
244 return transactionTableModel;
247 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
249 if(!wallet->IsCrypted())
253 else if(wallet->IsLocked())
263 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
268 return wallet->EncryptWallet(passphrase);
272 // Decrypt -- TODO; not supported yet
277 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
282 return wallet->Lock();
287 return wallet->Unlock(passPhrase);
291 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
295 LOCK(wallet->cs_wallet);
296 wallet->Lock(); // Make sure wallet is locked before attempting pass change
297 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
302 bool WalletModel::backupWallet(const QString &filename)
304 return BackupWallet(*wallet, filename.toLocal8Bit().data());
307 // Handlers for core signals
308 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
310 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
311 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
314 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
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)),
324 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
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())),
332 void WalletModel::subscribeToCoreSignals()
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));
340 void WalletModel::unsubscribeFromCoreSignals()
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));
348 // WalletModel::UnlockContext implementation
349 WalletModel::UnlockContext WalletModel::requestUnlock()
351 bool was_locked = getEncryptionStatus() == Locked;
354 // Request UI to unlock wallet
355 emit requireUnlock();
357 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
358 bool valid = getEncryptionStatus() != Locked;
360 return UnlockContext(this, valid, was_locked);
363 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
370 WalletModel::UnlockContext::~UnlockContext()
374 wallet->setWalletLocked(true);
378 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
380 // Transfer context; old object no longer relocks wallet