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::getBalanceWatchOnly() const
46 return wallet->GetWatchOnlyBalance();
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=getBalance(), newBalanceWatchOnly=getBalanceWatchOnly();
95 qint64 newStake = getStake();
96 qint64 newUnconfirmedBalance = getUnconfirmedBalance();
97 qint64 newImmatureBalance = getImmatureBalance();
99 if(cachedBalance != newBalanceTotal || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
101 cachedBalance = newBalanceTotal;
102 cachedStake = newStake;
103 cachedUnconfirmedBalance = newUnconfirmedBalance;
104 cachedImmatureBalance = newImmatureBalance;
105 emit balanceChanged(newBalanceTotal, newBalanceWatchOnly, newStake, newUnconfirmedBalance, newImmatureBalance);
109 void WalletModel::updateTransaction(const QString &hash, int status)
111 if(transactionTableModel)
112 transactionTableModel->updateTransaction(hash, status);
114 // Balance and number of transactions might have changed
115 checkBalanceChanged();
117 int newNumTransactions = getNumTransactions();
118 if(cachedNumTransactions != newNumTransactions)
120 cachedNumTransactions = newNumTransactions;
121 emit numTransactionsChanged(newNumTransactions);
125 void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
127 if(addressTableModel)
128 addressTableModel->updateEntry(address, label, isMine, status);
131 bool WalletModel::validateAddress(const QString &address)
133 CBitcoinAddress addressParsed(address.toStdString());
134 return addressParsed.IsValid();
137 WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
140 QSet<QString> setAddress;
143 if(recipients.empty())
148 // Pre-check input data for validity
149 foreach(const SendCoinsRecipient &rcp, recipients)
151 if(!validateAddress(rcp.address))
153 return InvalidAddress;
155 setAddress.insert(rcp.address);
159 return InvalidAmount;
164 if(recipients.size() > setAddress.size())
166 return DuplicateAddress;
170 std::vector<COutput> vCoins;
171 wallet->AvailableCoins(vCoins, true, coinControl);
173 BOOST_FOREACH(const COutput& out, vCoins)
175 nBalance += out.tx->vout[out.i].nValue;
179 return AmountExceedsBalance;
182 if((total + nTransactionFee) > nBalance)
184 return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
188 LOCK2(cs_main, wallet->cs_wallet);
191 std::vector<std::pair<CScript, int64> > vecSend;
192 foreach(const SendCoinsRecipient &rcp, recipients)
194 CScript scriptPubKey;
195 scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
196 vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
200 CReserveKey keyChange(wallet);
201 int64 nFeeRequired = 0;
202 bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
206 if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
208 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
210 return TransactionCreationFailed;
212 if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
216 if(!wallet->CommitTransaction(wtx, keyChange))
218 return TransactionCommitFailed;
220 hex = QString::fromStdString(wtx.GetHash().GetHex());
223 // Add addresses / update labels that we've sent to to the address book
224 foreach(const SendCoinsRecipient &rcp, recipients)
226 std::string strAddress = rcp.address.toStdString();
227 CTxDestination dest = CBitcoinAddress(strAddress).Get();
228 std::string strLabel = rcp.label.toStdString();
230 LOCK(wallet->cs_wallet);
232 std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
234 // Check if we have a new address or an updated label
235 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
237 wallet->SetAddressBookName(dest, strLabel);
242 return SendCoinsReturn(OK, 0, hex);
245 OptionsModel *WalletModel::getOptionsModel()
250 AddressTableModel *WalletModel::getAddressTableModel()
252 return addressTableModel;
255 TransactionTableModel *WalletModel::getTransactionTableModel()
257 return transactionTableModel;
260 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
262 if(!wallet->IsCrypted())
266 else if(wallet->IsLocked())
276 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
281 return wallet->EncryptWallet(passphrase);
285 // Decrypt -- TODO; not supported yet
290 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
295 return wallet->Lock();
300 return wallet->Unlock(passPhrase);
304 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
308 LOCK(wallet->cs_wallet);
309 wallet->Lock(); // Make sure wallet is locked before attempting pass change
310 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
315 void WalletModel::getStakeWeight(uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
317 wallet->GetStakeWeight(*wallet, nMinWeight, nMaxWeight, nWeight);
320 void WalletModel::getStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
322 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
325 bool WalletModel::dumpWallet(const QString &filename)
327 return DumpWallet(wallet, filename.toLocal8Bit().data());
330 bool WalletModel::importWallet(const QString &filename)
332 return ImportWallet(wallet, filename.toLocal8Bit().data());
335 bool WalletModel::backupWallet(const QString &filename)
337 return BackupWallet(*wallet, filename.toLocal8Bit().data());
340 // Handlers for core signals
341 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
343 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
344 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
347 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
349 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
350 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
351 Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
352 Q_ARG(QString, QString::fromStdString(label)),
357 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
359 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
360 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
361 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
365 void WalletModel::subscribeToCoreSignals()
367 // Connect signals to wallet
368 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
369 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
370 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
373 void WalletModel::unsubscribeFromCoreSignals()
375 // Disconnect signals from wallet
376 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
377 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
378 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
381 // WalletModel::UnlockContext implementation
382 WalletModel::UnlockContext WalletModel::requestUnlock()
384 bool was_locked = getEncryptionStatus() == Locked;
386 if ((!was_locked) && fWalletUnlockMintOnly)
388 setWalletLocked(true);
389 was_locked = getEncryptionStatus() == Locked;
394 // Request UI to unlock wallet
395 emit requireUnlock();
397 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
398 bool valid = getEncryptionStatus() != Locked;
400 return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
403 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
410 WalletModel::UnlockContext::~UnlockContext()
414 wallet->setWalletLocked(true);
418 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
420 // Transfer context; old object no longer relocks wallet
425 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
427 return wallet->GetPubKey(address, vchPubKeyOut);
430 // returns a list of COutputs from COutPoints
431 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
433 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
435 if (!wallet->mapWallet.count(outpoint.hash)) continue;
436 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
437 vOutputs.push_back(out);
441 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
442 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
444 std::vector<COutput> vCoins;
445 wallet->AvailableCoins(vCoins);
446 std::vector<COutPoint> vLockedCoins;
449 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
451 if (!wallet->mapWallet.count(outpoint.hash)) continue;
452 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
453 vCoins.push_back(out);
456 BOOST_FOREACH(const COutput& out, vCoins)
460 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
462 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
463 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
466 CTxDestination address;
467 if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
469 mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
473 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
478 void WalletModel::lockCoin(COutPoint& output)
483 void WalletModel::unlockCoin(COutPoint& output)
488 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)