1 #include "walletmodel.h"
2 #include "guiconstants.h"
3 #include "optionsmodel.h"
4 #include "addresstablemodel.h"
5 #include "mintingtablemodel.h"
6 #include "transactiontablemodel.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.SetAddress(CBitcoinAddress(rcp.address.toStdString()));
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 CBitcoinAddress addr(strAddress);
243 std::string strLabel = rcp.label.toStdString();
245 LOCK(wallet->cs_wallet);
247 std::map<CBitcoinAddress, std::string>::iterator mi = wallet->mapAddressBook.find(addr);
249 // Check if we have a new address or an updated label
250 if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
252 wallet->SetAddressBookName(addr, 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::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
337 wallet->GetStakeWeightFromValue(nTime, nValue, nWeight);
340 bool WalletModel::dumpWallet(const QString &filename)
342 return DumpWallet(wallet, filename.toLocal8Bit().data());
345 bool WalletModel::importWallet(const QString &filename)
347 return ImportWallet(wallet, filename.toLocal8Bit().data());
350 bool WalletModel::backupWallet(const QString &filename)
352 return BackupWallet(*wallet, filename.toLocal8Bit().data());
355 // Handlers for core signals
356 static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
358 OutputDebugStringF("NotifyKeyStoreStatusChanged\n");
359 QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
362 static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)
364 OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", address.ToString().c_str(), label.c_str(), isMine, status);
365 QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
366 Q_ARG(QString, QString::fromStdString(address.ToString())),
367 Q_ARG(QString, QString::fromStdString(label)),
372 static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
374 OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status);
375 QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
376 Q_ARG(QString, QString::fromStdString(hash.GetHex())),
380 static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
382 QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection,
383 Q_ARG(bool, fHaveWatchonly));
386 void WalletModel::subscribeToCoreSignals()
388 // Connect signals to wallet
389 wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, boost::placeholders::_1));
390 wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3, boost::placeholders::_4, boost::placeholders::_5));
391 wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
392 wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, boost::placeholders::_1));
395 void WalletModel::unsubscribeFromCoreSignals()
397 // Disconnect signals from wallet
398 wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, boost::placeholders::_1));
399 wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3, boost::placeholders::_4, boost::placeholders::_5));
400 wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
401 wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, boost::placeholders::_1));
404 // WalletModel::UnlockContext implementation
405 WalletModel::UnlockContext WalletModel::requestUnlock()
407 bool was_locked = getEncryptionStatus() == Locked;
408 bool mintflag = fWalletUnlockMintOnly;
410 if ((!was_locked) && fWalletUnlockMintOnly)
412 setWalletLocked(true);
413 was_locked = getEncryptionStatus() == Locked;
417 // Request UI to unlock wallet
418 emit requireUnlock();
420 // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
421 bool valid = getEncryptionStatus() != Locked;
423 return UnlockContext(this, valid, was_locked, mintflag);
426 WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock, bool mintflag):
434 WalletModel::UnlockContext::~UnlockContext()
440 // Restore unlock minting flag
441 fWalletUnlockMintOnly = mintflag;
444 wallet->setWalletLocked(true);
449 void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
451 // Transfer context; old object no longer relocks wallet
456 bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
458 return wallet->GetPubKey(address, vchPubKeyOut);
461 // returns a list of COutputs from COutPoints
462 void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
464 BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
466 if (!wallet->mapWallet.count(outpoint.hash)) continue;
467 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
468 vOutputs.push_back(out);
472 // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
473 void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
475 std::vector<COutput> vCoins;
476 wallet->AvailableCoins(vCoins);
477 std::vector<COutPoint> vLockedCoins;
480 BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
482 if (!wallet->mapWallet.count(outpoint.hash)) continue;
483 COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain(), true);
484 if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == MINE_SPENDABLE)
485 vCoins.push_back(out);
488 BOOST_FOREACH(const COutput& out, vCoins)
492 while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
494 if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
495 cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
498 CBitcoinAddress addressRet;
499 if(!out.fSpendable || !ExtractAddress(*wallet, cout.tx->vout[cout.i].scriptPubKey, addressRet))
502 mapCoins[addressRet.ToString().c_str()].push_back(out);
506 bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
511 void WalletModel::lockCoin(COutPoint& output)
516 void WalletModel::unlockCoin(COutPoint& output)
521 void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
526 void WalletModel::clearOrphans()
528 wallet->ClearOrphans();
531 CWallet* WalletModel::getWallet()