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 || cachedStake != newStake || 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, const CCoinControl *coinControl)
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;
165 std::vector<COutput> vCoins;
166 wallet->AvailableCoins(vCoins, true, coinControl);
168 BOOST_FOREACH(const COutput& out, vCoins)
170 nBalance += out.tx->vout[out.i].nValue;
174 return AmountExceedsBalance;
177 if((total + nTransactionFee) > nBalance)
179 return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
183 LOCK2(cs_main, wallet->cs_wallet);
186 std::vector<std::pair<CScript, int64> > vecSend;
187 foreach(const SendCoinsRecipient &rcp, recipients)
189 CScript scriptPubKey;
190 scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
191 vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
195 CReserveKey keyChange(wallet);
196 int64 nFeeRequired = 0;
197 bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
201 if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
203 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
205 return TransactionCreationFailed;
207 if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
211 if(!wallet->CommitTransaction(wtx, keyChange))
213 return TransactionCommitFailed;
215 hex = QString::fromStdString(wtx.GetHash().GetHex());
218 // Add addresses / update labels that we've sent to to the address book
219 foreach(const SendCoinsRecipient &rcp, recipients)
221 std::string strAddress = rcp.address.toStdString();
222 CTxDestination dest = CBitcoinAddress(strAddress).Get();
223 std::string strLabel = rcp.label.toStdString();
225 LOCK(wallet->cs_wallet);
227 std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
229 // Check if we have a new address or an updated label
230 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
232 wallet->SetAddressBookName(dest, strLabel);
237 return SendCoinsReturn(OK, 0, hex);
240 OptionsModel *WalletModel::getOptionsModel()
245 AddressTableModel *WalletModel::getAddressTableModel()
247 return addressTableModel;
250 TransactionTableModel *WalletModel::getTransactionTableModel()
252 return transactionTableModel;
255 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
257 if(!wallet->IsCrypted())
261 else if(wallet->IsLocked())
271 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
276 return wallet->EncryptWallet(passphrase);
280 // Decrypt -- TODO; not supported yet
285 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
290 return wallet->Lock();
295 return wallet->Unlock(passPhrase);
299 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
303 LOCK(wallet->cs_wallet);
304 wallet->Lock(); // Make sure wallet is locked before attempting pass change
305 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
310 void WalletModel::getStakeWeight(uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
312 wallet->GetStakeWeight(*wallet, nMinWeight, nMaxWeight, nWeight);
315 void WalletModel::getStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
317 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
320 bool WalletModel::dumpWallet(const QString &filename)
322 return DumpWallet(wallet, filename.toLocal8Bit().data());
325 bool WalletModel::importWallet(const QString &filename)
327 return ImportWallet(wallet, filename.toLocal8Bit().data());
330 bool WalletModel::backupWallet(const QString &filename)
332 return BackupWallet(*wallet, filename.toLocal8Bit().data());
335 // Handlers for core signals
336 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
338 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
339 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
342 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
344 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
345 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
346 Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
347 Q_ARG(QString, QString::fromStdString(label)),
352 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
354 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
355 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
356 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
360 void WalletModel::subscribeToCoreSignals()
362 // Connect signals to wallet
363 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
364 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
365 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
368 void WalletModel::unsubscribeFromCoreSignals()
370 // Disconnect signals from wallet
371 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
372 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
373 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
376 // WalletModel::UnlockContext implementation
377 WalletModel::UnlockContext WalletModel::requestUnlock()
379 bool was_locked = getEncryptionStatus() == Locked;
381 if ((!was_locked) && fWalletUnlockMintOnly)
383 setWalletLocked(true);
384 was_locked = getEncryptionStatus() == Locked;
389 // Request UI to unlock wallet
390 emit requireUnlock();
392 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
393 bool valid = getEncryptionStatus() != Locked;
395 return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
398 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
405 WalletModel::UnlockContext::~UnlockContext()
409 wallet->setWalletLocked(true);
413 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
415 // Transfer context; old object no longer relocks wallet
420 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
422 return wallet->GetPubKey(address, vchPubKeyOut);
425 // returns a list of COutputs from COutPoints
426 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
428 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
430 if (!wallet->mapWallet.count(outpoint.hash)) continue;
431 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
432 vOutputs.push_back(out);
436 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
437 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
439 std::vector<COutput> vCoins;
440 wallet->AvailableCoins(vCoins);
441 std::vector<COutPoint> vLockedCoins;
444 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
446 if (!wallet->mapWallet.count(outpoint.hash)) continue;
447 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
448 vCoins.push_back(out);
451 BOOST_FOREACH(const COutput& out, vCoins)
455 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
457 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
458 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
461 CTxDestination address;
462 if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
464 mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
468 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
473 void WalletModel::lockCoin(COutPoint& output)
478 void WalletModel::unlockCoin(COutPoint& output)
483 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)