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 void WalletModel::getBalance(qint64 &nTotal, qint64 &nWatchOnly) const
46 wallet->GetBalance(nTotal, nWatchOnly);
49 qint64 WalletModel::getUnconfirmedBalance() const
51 return wallet->GetUnconfirmedBalance();
54 qint64 WalletModel::getStake() const
56 return wallet->GetStake();
59 qint64 WalletModel::getImmatureBalance() const
61 return wallet->GetImmatureBalance();
64 int WalletModel::getNumTransactions() const
66 int numTransactions = 0;
68 LOCK(wallet->cs_wallet);
69 numTransactions = wallet->mapWallet.size();
71 return numTransactions;
74 void WalletModel::updateStatus()
76 EncryptionStatus newEncryptionStatus = getEncryptionStatus();
78 if(cachedEncryptionStatus != newEncryptionStatus)
79 emit encryptionStatusChanged(newEncryptionStatus);
82 void WalletModel::pollBalanceChanged()
84 if(nBestHeight != cachedNumBlocks)
86 // Balance and number of transactions might have changed
87 cachedNumBlocks = nBestHeight;
88 checkBalanceChanged();
92 void WalletModel::checkBalanceChanged()
94 qint64 newBalanceTotal=0, newBalanceWatchOnly=0;
95 getBalance(newBalanceTotal, newBalanceWatchOnly);
97 qint64 newStake = getStake();
98 qint64 newUnconfirmedBalance = getUnconfirmedBalance();
99 qint64 newImmatureBalance = getImmatureBalance();
101 if(cachedBalance != newBalanceTotal || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
103 cachedBalance = newBalanceTotal;
104 cachedStake = newStake;
105 cachedUnconfirmedBalance = newUnconfirmedBalance;
106 cachedImmatureBalance = newImmatureBalance;
107 emit balanceChanged(newBalanceTotal, newBalanceWatchOnly, newStake, newUnconfirmedBalance, newImmatureBalance);
111 void WalletModel::updateTransaction(const QString &hash, int status)
113 if(transactionTableModel)
114 transactionTableModel->updateTransaction(hash, status);
116 // Balance and number of transactions might have changed
117 checkBalanceChanged();
119 int newNumTransactions = getNumTransactions();
120 if(cachedNumTransactions != newNumTransactions)
122 cachedNumTransactions = newNumTransactions;
123 emit numTransactionsChanged(newNumTransactions);
127 void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
129 if(addressTableModel)
130 addressTableModel->updateEntry(address, label, isMine, status);
133 bool WalletModel::validateAddress(const QString &address)
135 CBitcoinAddress addressParsed(address.toStdString());
136 return addressParsed.IsValid();
139 WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
142 QSet<QString> setAddress;
145 if(recipients.empty())
150 // Pre-check input data for validity
151 foreach(const SendCoinsRecipient &rcp, recipients)
153 if(!validateAddress(rcp.address))
155 return InvalidAddress;
157 setAddress.insert(rcp.address);
161 return InvalidAmount;
166 if(recipients.size() > setAddress.size())
168 return DuplicateAddress;
172 std::vector<COutput> vCoins;
173 wallet->AvailableCoins(vCoins, true, coinControl);
175 BOOST_FOREACH(const COutput& out, vCoins)
177 nBalance += out.tx->vout[out.i].nValue;
181 return AmountExceedsBalance;
184 if((total + nTransactionFee) > nBalance)
186 return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
190 LOCK2(cs_main, wallet->cs_wallet);
193 std::vector<std::pair<CScript, int64> > vecSend;
194 foreach(const SendCoinsRecipient &rcp, recipients)
196 CScript scriptPubKey;
197 scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
198 vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
202 CReserveKey keyChange(wallet);
203 int64 nFeeRequired = 0;
204 bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
208 if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
210 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
212 return TransactionCreationFailed;
214 if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
218 if(!wallet->CommitTransaction(wtx, keyChange))
220 return TransactionCommitFailed;
222 hex = QString::fromStdString(wtx.GetHash().GetHex());
225 // Add addresses / update labels that we've sent to to the address book
226 foreach(const SendCoinsRecipient &rcp, recipients)
228 std::string strAddress = rcp.address.toStdString();
229 CTxDestination dest = CBitcoinAddress(strAddress).Get();
230 std::string strLabel = rcp.label.toStdString();
232 LOCK(wallet->cs_wallet);
234 std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
236 // Check if we have a new address or an updated label
237 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
239 wallet->SetAddressBookName(dest, strLabel);
244 return SendCoinsReturn(OK, 0, hex);
247 OptionsModel *WalletModel::getOptionsModel()
252 AddressTableModel *WalletModel::getAddressTableModel()
254 return addressTableModel;
257 TransactionTableModel *WalletModel::getTransactionTableModel()
259 return transactionTableModel;
262 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
264 if(!wallet->IsCrypted())
268 else if(wallet->IsLocked())
278 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
283 return wallet->EncryptWallet(passphrase);
287 // Decrypt -- TODO; not supported yet
292 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
297 return wallet->Lock();
302 return wallet->Unlock(passPhrase);
306 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
310 LOCK(wallet->cs_wallet);
311 wallet->Lock(); // Make sure wallet is locked before attempting pass change
312 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
317 void WalletModel::getStakeWeight(uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
319 wallet->GetStakeWeight(*wallet, nMinWeight, nMaxWeight, nWeight);
322 void WalletModel::getStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
324 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
327 bool WalletModel::dumpWallet(const QString &filename)
329 return DumpWallet(wallet, filename.toLocal8Bit().data());
332 bool WalletModel::importWallet(const QString &filename)
334 return ImportWallet(wallet, filename.toLocal8Bit().data());
337 bool WalletModel::backupWallet(const QString &filename)
339 return BackupWallet(*wallet, filename.toLocal8Bit().data());
342 // Handlers for core signals
343 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
345 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
346 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
349 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
351 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
352 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
353 Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
354 Q_ARG(QString, QString::fromStdString(label)),
359 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
361 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
362 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
363 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
367 void WalletModel::subscribeToCoreSignals()
369 // Connect signals to wallet
370 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
371 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
372 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
375 void WalletModel::unsubscribeFromCoreSignals()
377 // Disconnect signals from wallet
378 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
379 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
380 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
383 // WalletModel::UnlockContext implementation
384 WalletModel::UnlockContext WalletModel::requestUnlock()
386 bool was_locked = getEncryptionStatus() == Locked;
388 if ((!was_locked) && fWalletUnlockMintOnly)
390 setWalletLocked(true);
391 was_locked = getEncryptionStatus() == Locked;
396 // Request UI to unlock wallet
397 emit requireUnlock();
399 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
400 bool valid = getEncryptionStatus() != Locked;
402 return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
405 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
412 WalletModel::UnlockContext::~UnlockContext()
416 wallet->setWalletLocked(true);
420 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
422 // Transfer context; old object no longer relocks wallet
427 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
429 return wallet->GetPubKey(address, vchPubKeyOut);
432 // returns a list of COutputs from COutPoints
433 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
435 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
437 if (!wallet->mapWallet.count(outpoint.hash)) continue;
438 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
439 vOutputs.push_back(out);
443 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
444 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
446 std::vector<COutput> vCoins;
447 wallet->AvailableCoins(vCoins);
448 std::vector<COutPoint> vLockedCoins;
451 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
453 if (!wallet->mapWallet.count(outpoint.hash)) continue;
454 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
455 vCoins.push_back(out);
458 BOOST_FOREACH(const COutput& out, vCoins)
462 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
464 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
465 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
468 CTxDestination address;
469 if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
471 mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
475 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
480 void WalletModel::lockCoin(COutPoint& output)
485 void WalletModel::unlockCoin(COutPoint& output)
490 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)