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 fHaveWatchOnly = wallet->HaveWatchOnly();
26 addressTableModel = new AddressTableModel(wallet, this);
27 mintingTableModel = new MintingTableModel(wallet, this);
28 transactionTableModel = new TransactionTableModel(wallet, this);
30 // This timer will be fired repeatedly to update the balance
31 pollTimer = new QTimer(this);
32 connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
33 pollTimer->start(MODEL_UPDATE_DELAY);
35 subscribeToCoreSignals();
38 WalletModel::~WalletModel()
40 unsubscribeFromCoreSignals();
43 bool WalletModel::haveWatchOnly() const
45 return fHaveWatchOnly;
48 qint64 WalletModel::getBalance() const
50 return wallet->GetBalance();
53 qint64 WalletModel::getBalanceWatchOnly() const
55 return wallet->GetWatchOnlyBalance();
58 qint64 WalletModel::getUnconfirmedBalance() const
60 return wallet->GetUnconfirmedBalance();
63 qint64 WalletModel::getStake() const
65 return wallet->GetStake();
68 qint64 WalletModel::getImmatureBalance() const
70 return wallet->GetImmatureBalance();
73 int WalletModel::getNumTransactions() const
75 int numTransactions = 0;
77 LOCK(wallet->cs_wallet);
78 numTransactions = (int)(wallet->mapWallet.size());
80 return numTransactions;
83 void WalletModel::updateStatus()
85 EncryptionStatus newEncryptionStatus = getEncryptionStatus();
87 if(cachedEncryptionStatus != newEncryptionStatus)
88 emit encryptionStatusChanged(newEncryptionStatus);
91 void WalletModel::pollBalanceChanged()
93 if(nBestHeight != cachedNumBlocks)
95 // Balance and number of transactions might have changed
96 cachedNumBlocks = nBestHeight;
97 checkBalanceChanged();
101 void WalletModel::checkBalanceChanged()
103 qint64 newBalanceTotal=getBalance(), newBalanceWatchOnly=getBalanceWatchOnly();
104 qint64 newStake = getStake();
105 qint64 newUnconfirmedBalance = getUnconfirmedBalance();
106 qint64 newImmatureBalance = getImmatureBalance();
108 if(cachedBalance != newBalanceTotal || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
110 cachedBalance = newBalanceTotal;
111 cachedStake = newStake;
112 cachedUnconfirmedBalance = newUnconfirmedBalance;
113 cachedImmatureBalance = newImmatureBalance;
114 emit balanceChanged(newBalanceTotal, newBalanceWatchOnly, newStake, newUnconfirmedBalance, newImmatureBalance);
118 void WalletModel::updateTransaction(const QString &hash, int status)
120 if(transactionTableModel)
121 transactionTableModel->updateTransaction(hash, status);
123 // Balance and number of transactions might have changed
124 checkBalanceChanged();
126 int newNumTransactions = getNumTransactions();
127 if(cachedNumTransactions != newNumTransactions)
129 cachedNumTransactions = newNumTransactions;
130 emit numTransactionsChanged(newNumTransactions);
134 void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
136 if(addressTableModel)
137 addressTableModel->updateEntry(address, label, isMine, status);
140 void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly)
142 fHaveWatchOnly = fHaveWatchonly;
143 emit notifyWatchonlyChanged(fHaveWatchonly);
146 bool WalletModel::validateAddress(const QString &address)
148 CBitcoinAddress addressParsed(address.toStdString());
149 return addressParsed.IsValid();
152 WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
155 QSet<QString> setAddress;
158 if(recipients.empty())
163 // Pre-check input data for validity
164 foreach(const SendCoinsRecipient &rcp, recipients)
166 if(!validateAddress(rcp.address))
168 return InvalidAddress;
170 setAddress.insert(rcp.address);
174 return InvalidAmount;
179 if(recipients.size() > setAddress.size())
181 return DuplicateAddress;
184 int64_t nBalance = 0;
185 std::vector<COutput> vCoins;
186 wallet->AvailableCoins(vCoins, true, coinControl);
188 BOOST_FOREACH(const COutput& out, vCoins)
190 nBalance += out.tx->vout[out.i].nValue;
194 return AmountExceedsBalance;
197 if((total + nTransactionFee) > nBalance)
199 return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
203 LOCK2(cs_main, wallet->cs_wallet);
206 std::vector<std::pair<CScript, int64_t> > vecSend;
207 foreach(const SendCoinsRecipient &rcp, recipients)
209 CScript scriptPubKey;
210 scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
211 vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
215 CReserveKey keyChange(wallet);
216 int64_t nFeeRequired = 0;
217 bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
221 if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
223 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
225 return TransactionCreationFailed;
227 if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
231 if(!wallet->CommitTransaction(wtx, keyChange))
233 return TransactionCommitFailed;
235 hex = QString::fromStdString(wtx.GetHash().GetHex());
238 // Add addresses / update labels that we've sent to to the address book
239 foreach(const SendCoinsRecipient &rcp, recipients)
241 std::string strAddress = rcp.address.toStdString();
242 CTxDestination dest = CBitcoinAddress(strAddress).Get();
243 std::string strLabel = rcp.label.toStdString();
245 LOCK(wallet->cs_wallet);
247 std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
249 // Check if we have a new address or an updated label
250 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
252 wallet->SetAddressBookName(dest, strLabel);
257 return SendCoinsReturn(OK, 0, hex);
260 OptionsModel *WalletModel::getOptionsModel()
265 AddressTableModel *WalletModel::getAddressTableModel()
267 return addressTableModel;
270 MintingTableModel *WalletModel::getMintingTableModel()
272 return mintingTableModel;
275 TransactionTableModel *WalletModel::getTransactionTableModel()
277 return transactionTableModel;
280 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
282 if(!wallet->IsCrypted())
286 else if(wallet->IsLocked())
296 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
301 return wallet->EncryptWallet(passphrase);
306 return wallet->DecryptWallet(passphrase);
310 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
315 return wallet->Lock();
320 return wallet->Unlock(passPhrase);
324 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
328 LOCK(wallet->cs_wallet);
329 wallet->Lock(); // Make sure wallet is locked before attempting pass change
330 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
335 void WalletModel::getStakeStats(float &nKernelsRate, float &nCoinDaysRate)
337 wallet->GetStakeStats(nKernelsRate, nCoinDaysRate);
340 void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
342 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
345 bool WalletModel::dumpWallet(const QString &filename)
347 return DumpWallet(wallet, filename.toLocal8Bit().data());
350 bool WalletModel::importWallet(const QString &filename)
352 return ImportWallet(wallet, filename.toLocal8Bit().data());
355 bool WalletModel::backupWallet(const QString &filename)
357 return BackupWallet(*wallet, filename.toLocal8Bit().data());
360 // Handlers for core signals
361 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
363 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
364 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
367 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
369 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
370 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
371 Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
372 Q_ARG(QString, QString::fromStdString(label)),
377 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
379 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
380 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
381 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
385 static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
387 QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection,
388 Q_ARG(bool, fHaveWatchonly));
391 void WalletModel::subscribeToCoreSignals()
393 // Connect signals to wallet
394 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
395 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
396 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
397 wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1));
400 void WalletModel::unsubscribeFromCoreSignals()
402 // Disconnect signals from wallet
403 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
404 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
405 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
406 wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1));
409 // WalletModel::UnlockContext implementation
410 WalletModel::UnlockContext WalletModel::requestUnlock()
412 bool was_locked = getEncryptionStatus() == Locked;
413 bool mintflag = fWalletUnlockMintOnly;
415 if ((!was_locked) && fWalletUnlockMintOnly)
417 setWalletLocked(true);
418 was_locked = getEncryptionStatus() == Locked;
422 // Request UI to unlock wallet
423 emit requireUnlock();
425 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
426 bool valid = getEncryptionStatus() != Locked;
428 return UnlockContext(this, valid, was_locked, mintflag);
431 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock, bool mintflag):
439 WalletModel::UnlockContext::~UnlockContext()
445 // Restore unlock minting flag
446 fWalletUnlockMintOnly = mintflag;
449 wallet->setWalletLocked(true);
454 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
456 // Transfer context; old object no longer relocks wallet
461 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
463 return wallet->GetPubKey(address, vchPubKeyOut);
466 // returns a list of COutputs from COutPoints
467 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
469 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
471 if (!wallet->mapWallet.count(outpoint.hash)) continue;
472 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
473 vOutputs.push_back(out);
477 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
478 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
480 std::vector<COutput> vCoins;
481 wallet->AvailableCoins(vCoins);
482 std::vector<COutPoint> vLockedCoins;
485 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
487 if (!wallet->mapWallet.count(outpoint.hash)) continue;
488 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
489 if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == MINE_SPENDABLE)
490 vCoins.push_back(out);
493 BOOST_FOREACH(const COutput& out, vCoins)
497 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
499 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
500 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
503 CTxDestination address;
504 if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
506 mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
510 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
515 void WalletModel::lockCoin(COutPoint& output)
520 void WalletModel::unlockCoin(COutPoint& output)
525 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
530 void WalletModel::clearOrphans()
532 wallet->ClearOrphans();
535 CWallet* WalletModel::getWallet()