1 #include "walletmodel.h"
2 #include "guiconstants.h"
3 #include "optionsmodel.h"
4 #include "addresstablemodel.h"
5 #include "mintingtablemodel.h"
6 #include "transactiontablemodel.h"
8 #include "ui_interface.h"
10 #include "walletdb.h" // for BackupWallet
16 WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
17 QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
18 transactionTableModel(0),
19 cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
20 cachedNumTransactions(0),
21 cachedEncryptionStatus(Unencrypted),
24 addressTableModel = new AddressTableModel(wallet, this);
25 mintingTableModel = new MintingTableModel(wallet, this);
26 transactionTableModel = new TransactionTableModel(wallet, this);
28 // This timer will be fired repeatedly to update the balance
29 pollTimer = new QTimer(this);
30 connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
31 pollTimer->start(MODEL_UPDATE_DELAY);
33 subscribeToCoreSignals();
36 WalletModel::~WalletModel()
38 unsubscribeFromCoreSignals();
41 qint64 WalletModel::getBalance() const
43 return wallet->GetBalance();
46 qint64 WalletModel::getBalanceWatchOnly() const
48 return wallet->GetWatchOnlyBalance();
51 qint64 WalletModel::getUnconfirmedBalance() const
53 return wallet->GetUnconfirmedBalance();
56 qint64 WalletModel::getStake() const
58 return wallet->GetStake();
61 qint64 WalletModel::getImmatureBalance() const
63 return wallet->GetImmatureBalance();
66 int WalletModel::getNumTransactions() const
68 int numTransactions = 0;
70 LOCK(wallet->cs_wallet);
71 numTransactions = wallet->mapWallet.size();
73 return numTransactions;
76 void WalletModel::updateStatus()
78 EncryptionStatus newEncryptionStatus = getEncryptionStatus();
80 if(cachedEncryptionStatus != newEncryptionStatus)
81 emit encryptionStatusChanged(newEncryptionStatus);
84 void WalletModel::pollBalanceChanged()
86 if(nBestHeight != cachedNumBlocks)
88 // Balance and number of transactions might have changed
89 cachedNumBlocks = nBestHeight;
90 checkBalanceChanged();
94 void WalletModel::checkBalanceChanged()
96 qint64 newBalanceTotal=getBalance(), newBalanceWatchOnly=getBalanceWatchOnly();
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 MintingTableModel *WalletModel::getMintingTableModel()
259 return mintingTableModel;
262 TransactionTableModel *WalletModel::getTransactionTableModel()
264 return transactionTableModel;
267 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
269 if(!wallet->IsCrypted())
273 else if(wallet->IsLocked())
283 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
288 return wallet->EncryptWallet(passphrase);
292 // Decrypt -- TODO; not supported yet
297 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
302 return wallet->Lock();
307 return wallet->Unlock(passPhrase);
311 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
315 LOCK(wallet->cs_wallet);
316 wallet->Lock(); // Make sure wallet is locked before attempting pass change
317 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
322 void WalletModel::getStakeWeight(uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
324 wallet->GetStakeWeight(*wallet, nMinWeight, nMaxWeight, nWeight);
327 void WalletModel::getStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
329 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
332 bool WalletModel::dumpWallet(const QString &filename)
334 return DumpWallet(wallet, filename.toLocal8Bit().data());
337 bool WalletModel::importWallet(const QString &filename)
339 return ImportWallet(wallet, filename.toLocal8Bit().data());
342 bool WalletModel::backupWallet(const QString &filename)
344 return BackupWallet(*wallet, filename.toLocal8Bit().data());
347 // Handlers for core signals
348 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
350 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
351 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
354 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
356 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
357 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
358 Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
359 Q_ARG(QString, QString::fromStdString(label)),
364 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
366 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
367 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
368 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
372 void WalletModel::subscribeToCoreSignals()
374 // Connect signals to wallet
375 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
376 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
377 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
380 void WalletModel::unsubscribeFromCoreSignals()
382 // Disconnect signals from wallet
383 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
384 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
385 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
388 // WalletModel::UnlockContext implementation
389 WalletModel::UnlockContext WalletModel::requestUnlock()
391 bool was_locked = getEncryptionStatus() == Locked;
393 if ((!was_locked) && fWalletUnlockMintOnly)
395 setWalletLocked(true);
396 was_locked = getEncryptionStatus() == Locked;
401 // Request UI to unlock wallet
402 emit requireUnlock();
404 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
405 bool valid = getEncryptionStatus() != Locked;
407 return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
410 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
417 WalletModel::UnlockContext::~UnlockContext()
421 wallet->setWalletLocked(true);
425 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
427 // Transfer context; old object no longer relocks wallet
432 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
434 return wallet->GetPubKey(address, vchPubKeyOut);
437 // returns a list of COutputs from COutPoints
438 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
440 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
442 if (!wallet->mapWallet.count(outpoint.hash)) continue;
443 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
444 vOutputs.push_back(out);
448 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
449 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
451 std::vector<COutput> vCoins;
452 wallet->AvailableCoins(vCoins);
453 std::vector<COutPoint> vLockedCoins;
456 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
458 if (!wallet->mapWallet.count(outpoint.hash)) continue;
459 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
460 vCoins.push_back(out);
463 BOOST_FOREACH(const COutput& out, vCoins)
467 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
469 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
470 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
473 CTxDestination address;
474 if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
476 mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
480 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
485 void WalletModel::lockCoin(COutPoint& output)
490 void WalletModel::unlockCoin(COutPoint& output)
495 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)