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)
169 nBalance += out.tx->vout[out.i].nValue;
173 return AmountExceedsBalance;
176 if((total + nTransactionFee) > nBalance)
178 return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
182 LOCK2(cs_main, wallet->cs_wallet);
185 std::vector<std::pair<CScript, int64> > vecSend;
186 foreach(const SendCoinsRecipient &rcp, recipients)
188 CScript scriptPubKey;
189 scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
190 vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
194 CReserveKey keyChange(wallet);
195 int64 nFeeRequired = 0;
196 bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
200 if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
202 return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
204 return TransactionCreationFailed;
206 if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
210 if(!wallet->CommitTransaction(wtx, keyChange))
212 return TransactionCommitFailed;
214 hex = QString::fromStdString(wtx.GetHash().GetHex());
217 // Add addresses / update labels that we've sent to to the address book
218 foreach(const SendCoinsRecipient &rcp, recipients)
220 std::string strAddress = rcp.address.toStdString();
221 CTxDestination dest = CBitcoinAddress(strAddress).Get();
222 std::string strLabel = rcp.label.toStdString();
224 LOCK(wallet->cs_wallet);
226 std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
228 // Check if we have a new address or an updated label
229 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
231 wallet->SetAddressBookName(dest, strLabel);
236 return SendCoinsReturn(OK, 0, hex);
239 OptionsModel *WalletModel::getOptionsModel()
244 AddressTableModel *WalletModel::getAddressTableModel()
246 return addressTableModel;
249 TransactionTableModel *WalletModel::getTransactionTableModel()
251 return transactionTableModel;
254 WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
256 if(!wallet->IsCrypted())
260 else if(wallet->IsLocked())
270 bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
275 return wallet->EncryptWallet(passphrase);
279 // Decrypt -- TODO; not supported yet
284 bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
289 return wallet->Lock();
294 return wallet->Unlock(passPhrase);
298 bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
302 LOCK(wallet->cs_wallet);
303 wallet->Lock(); // Make sure wallet is locked before attempting pass change
304 retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
309 void WalletModel::getStakeWeight(uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
311 wallet->GetStakeWeight(*wallet, nMinWeight, nMaxWeight, nWeight);
314 void WalletModel::getStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
316 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
319 bool WalletModel::dumpWallet(const QString &filename)
321 return DumpWallet(wallet, filename.toLocal8Bit().data());
324 bool WalletModel::importWallet(const QString &filename)
326 return ImportWallet(wallet, filename.toLocal8Bit().data());
329 bool WalletModel::backupWallet(const QString &filename)
331 return BackupWallet(*wallet, filename.toLocal8Bit().data());
334 // Handlers for core signals
335 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
337 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
338 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
341 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
343 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status);
344 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
345 Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())),
346 Q_ARG(QString, QString::fromStdString(label)),
351 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
353 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
354 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
355 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
359 void WalletModel::subscribeToCoreSignals()
361 // Connect signals to wallet
362 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
363 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
364 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
367 void WalletModel::unsubscribeFromCoreSignals()
369 // Disconnect signals from wallet
370 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
371 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
372 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
375 // WalletModel::UnlockContext implementation
376 WalletModel::UnlockContext WalletModel::requestUnlock()
378 bool was_locked = getEncryptionStatus() == Locked;
380 if ((!was_locked) && fWalletUnlockMintOnly)
382 setWalletLocked(true);
383 was_locked = getEncryptionStatus() == Locked;
388 // Request UI to unlock wallet
389 emit requireUnlock();
391 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
392 bool valid = getEncryptionStatus() != Locked;
394 return UnlockContext(this, valid, was_locked && !fWalletUnlockMintOnly);
397 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
404 WalletModel::UnlockContext::~UnlockContext()
408 wallet->setWalletLocked(true);
412 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
414 // Transfer context; old object no longer relocks wallet
419 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
421 return wallet->GetPubKey(address, vchPubKeyOut);
424 // returns a list of COutputs from COutPoints
425 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
427 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
429 if (!wallet->mapWallet.count(outpoint.hash)) continue;
430 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain());
431 vOutputs.push_back(out);
435 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
436 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
438 std::vector<COutput> vCoins;
439 wallet->AvailableCoins(vCoins);
440 std::vector<COutPoint> vLockedCoins;
443 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
445 if (!wallet->mapWallet.count(outpoint.hash)) continue;
446 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain());
447 vCoins.push_back(out);
450 BOOST_FOREACH(const COutput& out, vCoins)
454 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
456 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
457 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0);
460 CTxDestination address;
461 if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue;
462 mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
466 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
471 void WalletModel::lockCoin(COutPoint& output)
476 void WalletModel::unlockCoin(COutPoint& output)
481 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)