1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "ui_interface.h"
15 //////////////////////////////////////////////////////////////////////////////
20 struct CompareValueOnly
22 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
23 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
25 return t1.first < t2.first;
29 CPubKey CWallet::GenerateNewKey()
31 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
35 key.MakeNewKey(fCompressed);
37 // Compressed public keys were introduced in version 0.6.0
39 SetMinVersion(FEATURE_COMPRPUBKEY);
42 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
43 return key.GetPubKey();
46 bool CWallet::AddKey(const CKey& key)
48 if (!CCryptoKeyStore::AddKey(key))
53 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
57 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
59 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
65 if (pwalletdbEncryption)
66 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
68 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
73 bool CWallet::AddCScript(const CScript& redeemScript)
75 if (!CCryptoKeyStore::AddCScript(redeemScript))
79 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
82 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
88 CKeyingMaterial vMasterKey;
92 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
94 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
96 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
98 if (CCryptoKeyStore::Unlock(vMasterKey))
105 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
107 bool fWasLocked = IsLocked();
114 CKeyingMaterial vMasterKey;
115 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
117 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
119 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
121 if (CCryptoKeyStore::Unlock(vMasterKey))
123 int64 nStartTime = GetTimeMillis();
124 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
125 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
127 nStartTime = GetTimeMillis();
128 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
129 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
131 if (pMasterKey.second.nDeriveIterations < 25000)
132 pMasterKey.second.nDeriveIterations = 25000;
134 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
136 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
138 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
140 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
151 void CWallet::SetBestChain(const CBlockLocator& loc)
153 CWalletDB walletdb(strWalletFile);
154 walletdb.WriteBestBlock(loc);
157 // This class implements an addrIncoming entry that causes pre-0.4
158 // clients to crash on startup if reading a private-key-encrypted wallet.
159 class CCorruptAddress
164 if (nType & SER_DISK)
169 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
171 if (nWalletVersion >= nVersion)
174 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
175 if (fExplicit && nVersion > nWalletMaxVersion)
176 nVersion = FEATURE_LATEST;
178 nWalletVersion = nVersion;
180 if (nVersion > nWalletMaxVersion)
181 nWalletMaxVersion = nVersion;
185 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
186 if (nWalletVersion >= 40000)
188 // Versions prior to 0.4.0 did not support the "minversion" record.
189 // Use a CCorruptAddress to make them crash instead.
190 CCorruptAddress corruptAddress;
191 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
193 if (nWalletVersion > 40000)
194 pwalletdb->WriteMinVersion(nWalletVersion);
202 bool CWallet::SetMaxVersion(int nVersion)
204 // cannot downgrade below current version
205 if (nWalletVersion > nVersion)
208 nWalletMaxVersion = nVersion;
213 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
218 CKeyingMaterial vMasterKey;
219 RandAddSeedPerfmon();
221 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
222 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
224 CMasterKey kMasterKey;
226 RandAddSeedPerfmon();
227 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
228 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
231 int64 nStartTime = GetTimeMillis();
232 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
233 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
235 nStartTime = GetTimeMillis();
236 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
237 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
239 if (kMasterKey.nDeriveIterations < 25000)
240 kMasterKey.nDeriveIterations = 25000;
242 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
244 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
246 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
251 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
254 pwalletdbEncryption = new CWalletDB(strWalletFile);
255 if (!pwalletdbEncryption->TxnBegin())
257 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
260 if (!EncryptKeys(vMasterKey))
263 pwalletdbEncryption->TxnAbort();
264 exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
267 // Encryption was introduced in version 0.4.0
268 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
272 if (!pwalletdbEncryption->TxnCommit())
273 exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
275 delete pwalletdbEncryption;
276 pwalletdbEncryption = NULL;
280 Unlock(strWalletPassphrase);
284 // Need to completely rewrite the wallet file; if we don't, bdb might keep
285 // bits of the unencrypted private key in slack space in the database file.
286 CDB::Rewrite(strWalletFile);
289 NotifyStatusChanged(this);
294 int64 CWallet::IncOrderPosNext()
296 int64 nRet = nOrderPosNext;
297 CWalletDB(strWalletFile).WriteOrderPosNext(++nOrderPosNext);
301 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
303 CWalletDB walletdb(strWalletFile);
305 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
308 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
309 // would make this much faster for applications that do this a lot.
310 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
312 CWalletTx* wtx = &((*it).second);
313 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
316 walletdb.ListAccountCreditDebit(strAccount, acentries);
317 BOOST_FOREACH(CAccountingEntry& entry, acentries)
319 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
325 void CWallet::WalletUpdateSpent(const CTransaction &tx)
327 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
328 // Update the wallet spent flag if it doesn't know due to wallet.dat being
329 // restored from backup or the user making copies of wallet.dat.
332 BOOST_FOREACH(const CTxIn& txin, tx.vin)
334 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
335 if (mi != mapWallet.end())
337 CWalletTx& wtx = (*mi).second;
338 if (txin.prevout.n >= wtx.vout.size())
339 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
340 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
342 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
343 wtx.MarkSpent(txin.prevout.n);
345 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
352 void CWallet::MarkDirty()
356 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
357 item.second.MarkDirty();
361 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
363 uint256 hash = wtxIn.GetHash();
366 // Inserts only if not already there, returns tx inserted or tx found
367 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
368 CWalletTx& wtx = (*ret.first).second;
369 wtx.BindWallet(this);
370 bool fInsertedNew = ret.second;
373 wtx.nTimeReceived = GetAdjustedTime();
374 wtx.nOrderPos = IncOrderPosNext();
376 wtx.nTimeSmart = wtx.nTimeReceived;
377 if (wtxIn.hashBlock != 0)
379 if (mapBlockIndex.count(wtxIn.hashBlock))
381 unsigned int latestNow = wtx.nTimeReceived;
382 unsigned int latestEntry = 0;
384 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
385 int64 latestTolerated = latestNow + 300;
386 std::list<CAccountingEntry> acentries;
387 TxItems txOrdered = OrderedTxItems(acentries);
388 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
390 CWalletTx *const pwtx = (*it).second.first;
393 CAccountingEntry *const pacentry = (*it).second.second;
397 nSmartTime = pwtx->nTimeSmart;
399 nSmartTime = pwtx->nTimeReceived;
402 nSmartTime = pacentry->nTime;
403 if (nSmartTime <= latestTolerated)
405 latestEntry = nSmartTime;
406 if (nSmartTime > latestNow)
407 latestNow = nSmartTime;
413 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
414 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
417 printf("AddToWallet() : found %s in block %s not in index\n",
418 wtxIn.GetHash().ToString().substr(0,10).c_str(),
419 wtxIn.hashBlock.ToString().c_str());
423 bool fUpdated = false;
427 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
429 wtx.hashBlock = wtxIn.hashBlock;
432 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
434 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
435 wtx.nIndex = wtxIn.nIndex;
438 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
440 wtx.fFromMe = wtxIn.fFromMe;
443 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
447 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
450 if (fInsertedNew || fUpdated)
451 if (!wtx.WriteToDisk())
454 // If default receiving address gets used, replace it with a new one
455 CScript scriptDefaultKey;
456 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
457 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
459 if (txout.scriptPubKey == scriptDefaultKey)
461 CPubKey newDefaultKey;
462 if (GetKeyFromPool(newDefaultKey, false))
464 SetDefaultKey(newDefaultKey);
465 SetAddressBookName(vchDefaultKey.GetID(), "");
470 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
471 WalletUpdateSpent(wtx);
473 // Notify UI of new or updated transaction
474 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
479 // Add a transaction to the wallet, or update it.
480 // pblock is optional, but should be provided if the transaction is known to be in a block.
481 // If fUpdate is true, existing transactions will be updated.
482 bool CWallet::AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
486 bool fExisted = mapWallet.count(hash);
487 if (fExisted && !fUpdate) return false;
488 if (fExisted || IsMine(tx) || IsFromMe(tx))
490 CWalletTx wtx(this,tx);
491 // Get merkle branch if transaction was found in a block
493 wtx.SetMerkleBranch(pblock);
494 return AddToWallet(wtx);
497 WalletUpdateSpent(tx);
502 bool CWallet::EraseFromWallet(uint256 hash)
508 if (mapWallet.erase(hash))
509 CWalletDB(strWalletFile).EraseTx(hash);
515 bool CWallet::IsMine(const CTxIn &txin) const
519 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
520 if (mi != mapWallet.end())
522 const CWalletTx& prev = (*mi).second;
523 if (txin.prevout.n < prev.vout.size())
524 if (IsMine(prev.vout[txin.prevout.n]))
531 int64 CWallet::GetDebit(const CTxIn &txin) const
535 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
536 if (mi != mapWallet.end())
538 const CWalletTx& prev = (*mi).second;
539 if (txin.prevout.n < prev.vout.size())
540 if (IsMine(prev.vout[txin.prevout.n]))
541 return prev.vout[txin.prevout.n].nValue;
547 bool CWallet::IsChange(const CTxOut& txout) const
549 CTxDestination address;
551 // TODO: fix handling of 'change' outputs. The assumption is that any
552 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
553 // is change. That assumption is likely to break when we implement multisignature
554 // wallets that return change back into a multi-signature-protected address;
555 // a better way of identifying which outputs are 'the send' and which are
556 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
557 // which output, if any, was change).
558 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
561 if (!mapAddressBook.count(address))
567 int64 CWalletTx::GetTxTime() const
569 int64 n = nTimeSmart;
570 return n ? n : nTimeReceived;
573 int CWalletTx::GetRequestCount() const
575 // Returns -1 if it wasn't being tracked
578 LOCK(pwallet->cs_wallet);
584 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
585 if (mi != pwallet->mapRequestCount.end())
586 nRequests = (*mi).second;
591 // Did anyone request this transaction?
592 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
593 if (mi != pwallet->mapRequestCount.end())
595 nRequests = (*mi).second;
597 // How about the block it's in?
598 if (nRequests == 0 && hashBlock != 0)
600 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
601 if (mi != pwallet->mapRequestCount.end())
602 nRequests = (*mi).second;
604 nRequests = 1; // If it's in someone else's block it must have got out
612 void CWalletTx::GetAmounts(list<pair<CTxDestination, int64> >& listReceived,
613 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
616 listReceived.clear();
618 strSentAccount = strFromAccount;
621 int64 nDebit = GetDebit();
622 if (nDebit > 0) // debit>0 means we signed/sent this transaction
624 int64 nValueOut = GetValueOut();
625 nFee = nDebit - nValueOut;
629 BOOST_FOREACH(const CTxOut& txout, vout)
631 CTxDestination address;
632 vector<unsigned char> vchPubKey;
633 if (!ExtractDestination(txout.scriptPubKey, address))
635 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
636 this->GetHash().ToString().c_str());
639 // Don't report 'change' txouts
640 if (nDebit > 0 && pwallet->IsChange(txout))
644 listSent.push_back(make_pair(address, txout.nValue));
646 if (pwallet->IsMine(txout))
647 listReceived.push_back(make_pair(address, txout.nValue));
652 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nReceived,
653 int64& nSent, int64& nFee) const
655 nReceived = nSent = nFee = 0;
658 string strSentAccount;
659 list<pair<CTxDestination, int64> > listReceived;
660 list<pair<CTxDestination, int64> > listSent;
661 GetAmounts(listReceived, listSent, allFee, strSentAccount);
663 if (strAccount == strSentAccount)
665 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
670 LOCK(pwallet->cs_wallet);
671 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
673 if (pwallet->mapAddressBook.count(r.first))
675 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
676 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
677 nReceived += r.second;
679 else if (strAccount.empty())
681 nReceived += r.second;
687 void CWalletTx::AddSupportingTransactions()
691 const int COPY_DEPTH = 3;
692 if (SetMerkleBranch() < COPY_DEPTH)
694 vector<uint256> vWorkQueue;
695 BOOST_FOREACH(const CTxIn& txin, vin)
696 vWorkQueue.push_back(txin.prevout.hash);
699 LOCK(pwallet->cs_wallet);
700 map<uint256, const CMerkleTx*> mapWalletPrev;
701 set<uint256> setAlreadyDone;
702 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
704 uint256 hash = vWorkQueue[i];
705 if (setAlreadyDone.count(hash))
707 setAlreadyDone.insert(hash);
710 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
711 if (mi != pwallet->mapWallet.end())
714 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
715 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
717 else if (mapWalletPrev.count(hash))
719 tx = *mapWalletPrev[hash];
722 int nDepth = tx.SetMerkleBranch();
723 vtxPrev.push_back(tx);
725 if (nDepth < COPY_DEPTH)
727 BOOST_FOREACH(const CTxIn& txin, tx.vin)
728 vWorkQueue.push_back(txin.prevout.hash);
734 reverse(vtxPrev.begin(), vtxPrev.end());
737 bool CWalletTx::WriteToDisk()
739 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
742 // Scan the block chain (starting in pindexStart) for transactions
743 // from or to us. If fUpdate is true, found transactions that already
744 // exist in the wallet will be updated.
745 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
749 CBlockIndex* pindex = pindexStart;
755 block.ReadFromDisk(pindex, true);
756 BOOST_FOREACH(CTransaction& tx, block.vtx)
758 if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate))
761 pindex = pindex->pnext;
767 void CWallet::ReacceptWalletTransactions()
774 bool fMissing = false;
775 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
777 CWalletTx& wtx = item.second;
778 if (wtx.IsCoinBase() && wtx.IsSpent(0))
782 bool fUpdated = false;
783 bool fFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);
784 if (fFound || wtx.GetDepthInMainChain() > 0)
786 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
787 for (unsigned int i = 0; i < wtx.vout.size(); i++)
791 if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))
800 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
807 // Re-accept any txes of ours that aren't already in a block
808 if (!wtx.IsCoinBase())
809 wtx.AcceptWalletTransaction(false);
814 // TODO: optimize this to scan just part of the block chain?
815 if (ScanForWalletTransactions(pindexGenesisBlock))
816 fRepeat = true; // Found missing transactions: re-do re-accept.
821 void CWalletTx::RelayWalletTransaction()
823 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
825 if (!tx.IsCoinBase()) {
826 if (tx.GetDepthInMainChain() == 0)
827 RelayMessage(CInv(MSG_TX, tx.GetHash()), (CTransaction)tx);
832 if (GetDepthInMainChain() == 0) {
833 uint256 hash = GetHash();
834 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
835 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
840 void CWallet::ResendWalletTransactions()
842 // Do this infrequently and randomly to avoid giving away
843 // that these are our transactions.
844 static int64 nNextTime;
845 if (GetTime() < nNextTime)
847 bool fFirst = (nNextTime == 0);
848 nNextTime = GetTime() + GetRand(30 * 60);
852 // Only do it if there's been a new block since last time
853 static int64 nLastTime;
854 if (nTimeBestReceived < nLastTime)
856 nLastTime = GetTime();
858 // Rebroadcast any of our txes that aren't in a block yet
859 printf("ResendWalletTransactions()\n");
862 // Sort them in chronological order
863 multimap<unsigned int, CWalletTx*> mapSorted;
864 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
866 CWalletTx& wtx = item.second;
867 // Don't rebroadcast until it's had plenty of time that
868 // it should have gotten in already by now.
869 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
870 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
872 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
874 CWalletTx& wtx = *item.second;
875 wtx.RelayWalletTransaction();
885 //////////////////////////////////////////////////////////////////////////////
891 int64 CWallet::GetBalance() const
896 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
898 const CWalletTx* pcoin = &(*it).second;
899 if (pcoin->IsFinal() && pcoin->IsConfirmed())
900 nTotal += pcoin->GetAvailableCredit();
907 int64 CWallet::GetUnconfirmedBalance() const
912 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
914 const CWalletTx* pcoin = &(*it).second;
915 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
916 nTotal += pcoin->GetAvailableCredit();
922 int64 CWallet::GetImmatureBalance() const
927 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
929 const CWalletTx& pcoin = (*it).second;
930 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
931 nTotal += GetCredit(pcoin);
937 // populate vCoins with vector of spendable COutputs
938 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
944 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
946 const CWalletTx* pcoin = &(*it).second;
948 if (!pcoin->IsFinal())
951 if (fOnlyConfirmed && !pcoin->IsConfirmed())
954 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
957 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
958 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue > 0)
959 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
964 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
965 vector<char>& vfBest, int64& nBest, int iterations = 1000)
967 vector<char> vfIncluded;
969 vfBest.assign(vValue.size(), true);
972 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
974 vfIncluded.assign(vValue.size(), false);
976 bool fReachedTarget = false;
977 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
979 for (unsigned int i = 0; i < vValue.size(); i++)
981 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
983 nTotal += vValue[i].first;
984 vfIncluded[i] = true;
985 if (nTotal >= nTargetValue)
987 fReachedTarget = true;
993 nTotal -= vValue[i].first;
994 vfIncluded[i] = false;
1002 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1003 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1005 setCoinsRet.clear();
1008 // List of values less than target
1009 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1010 coinLowestLarger.first = std::numeric_limits<int64>::max();
1011 coinLowestLarger.second.first = NULL;
1012 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1013 int64 nTotalLower = 0;
1015 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1017 BOOST_FOREACH(COutput output, vCoins)
1019 const CWalletTx *pcoin = output.tx;
1021 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1025 int64 n = pcoin->vout[i].nValue;
1027 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1029 if (n == nTargetValue)
1031 setCoinsRet.insert(coin.second);
1032 nValueRet += coin.first;
1035 else if (n < nTargetValue + CENT)
1037 vValue.push_back(coin);
1040 else if (n < coinLowestLarger.first)
1042 coinLowestLarger = coin;
1046 if (nTotalLower == nTargetValue)
1048 for (unsigned int i = 0; i < vValue.size(); ++i)
1050 setCoinsRet.insert(vValue[i].second);
1051 nValueRet += vValue[i].first;
1056 if (nTotalLower < nTargetValue)
1058 if (coinLowestLarger.second.first == NULL)
1060 setCoinsRet.insert(coinLowestLarger.second);
1061 nValueRet += coinLowestLarger.first;
1065 // Solve subset sum by stochastic approximation
1066 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1067 vector<char> vfBest;
1070 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1071 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1072 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1074 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1075 // or the next bigger coin is closer), return the bigger coin
1076 if (coinLowestLarger.second.first &&
1077 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1079 setCoinsRet.insert(coinLowestLarger.second);
1080 nValueRet += coinLowestLarger.first;
1083 for (unsigned int i = 0; i < vValue.size(); i++)
1086 setCoinsRet.insert(vValue[i].second);
1087 nValueRet += vValue[i].first;
1091 printf("SelectCoins() best subset: ");
1092 for (unsigned int i = 0; i < vValue.size(); i++)
1094 printf("%s ", FormatMoney(vValue[i].first).c_str());
1095 printf("total %s\n", FormatMoney(nBest).c_str());
1101 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1103 vector<COutput> vCoins;
1104 AvailableCoins(vCoins);
1106 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1107 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1108 SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet));
1114 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1117 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1123 if (vecSend.empty() || nValue < 0)
1126 wtxNew.BindWallet(this);
1129 LOCK2(cs_main, cs_wallet);
1131 nFeeRet = nTransactionFee;
1135 wtxNew.vout.clear();
1136 wtxNew.fFromMe = true;
1138 int64 nTotalValue = nValue + nFeeRet;
1139 double dPriority = 0;
1140 // vouts to the payees
1141 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1142 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1144 // Choose coins to use
1145 set<pair<const CWalletTx*,unsigned int> > setCoins;
1147 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1149 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1151 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1152 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1155 int64 nChange = nValueIn - nValue - nFeeRet;
1156 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1157 // or until nChange becomes zero
1158 // NOTE: this depends on the exact behaviour of GetMinFee
1159 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1161 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1162 nChange -= nMoveToFee;
1163 nFeeRet += nMoveToFee;
1168 // Note: We use a new key here to keep it from being obvious which side is the change.
1169 // The drawback is that by not reusing a previous key, the change may be lost if a
1170 // backup is restored, if the backup doesn't have the new private key for the change.
1171 // If we reused the old key, it would be possible to add code to look for and
1172 // rediscover unknown transactions that were written with keys of ours to recover
1173 // post-backup change.
1175 // Reserve a new key pair from key pool
1176 CPubKey vchPubKey = reservekey.GetReservedKey();
1177 // assert(mapKeys.count(vchPubKey));
1179 // Fill a vout to ourself
1180 // TODO: pass in scriptChange instead of reservekey so
1181 // change transaction isn't always pay-to-bitcoin-address
1182 CScript scriptChange;
1183 scriptChange.SetDestination(vchPubKey.GetID());
1185 // Insert change txn at random position:
1186 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1187 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1190 reservekey.ReturnKey();
1193 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1194 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1198 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1199 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1203 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1204 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1206 dPriority /= nBytes;
1208 // Check that enough fee is included
1209 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1210 bool fAllowFree = CTransaction::AllowFree(dPriority);
1211 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1212 if (nFeeRet < max(nPayFee, nMinFee))
1214 nFeeRet = max(nPayFee, nMinFee);
1218 // Fill vtxPrev by copying from previous transactions vtxPrev
1219 wtxNew.AddSupportingTransactions();
1220 wtxNew.fTimeReceivedIsTxTime = true;
1229 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1231 vector< pair<CScript, int64> > vecSend;
1232 vecSend.push_back(make_pair(scriptPubKey, nValue));
1233 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1236 // Call after CreateTransaction unless you want to abort
1237 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1240 LOCK2(cs_main, cs_wallet);
1241 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1243 // This is only to keep the database open to defeat the auto-flush for the
1244 // duration of this scope. This is the only place where this optimization
1245 // maybe makes sense; please don't do it anywhere else.
1246 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1248 // Take key pair from key pool so it won't be used again
1249 reservekey.KeepKey();
1251 // Add tx to wallet, because if it has change it's also ours,
1252 // otherwise just for transaction history.
1253 AddToWallet(wtxNew);
1255 // Mark old coins as spent
1256 set<CWalletTx*> setCoins;
1257 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1259 CWalletTx &coin = mapWallet[txin.prevout.hash];
1260 coin.BindWallet(this);
1261 coin.MarkSpent(txin.prevout.n);
1263 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1270 // Track how many getdata requests our transaction gets
1271 mapRequestCount[wtxNew.GetHash()] = 0;
1274 if (!wtxNew.AcceptToMemoryPool())
1276 // This must not fail. The transaction has already been signed and recorded.
1277 printf("CommitTransaction() : Error: Transaction not valid");
1280 wtxNew.RelayWalletTransaction();
1288 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1290 CReserveKey reservekey(this);
1295 string strError = _("Error: Wallet locked, unable to create transaction ");
1296 printf("SendMoney() : %s", strError.c_str());
1299 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1302 if (nValue + nFeeRequired > GetBalance())
1303 strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
1305 strError = _("Error: Transaction creation failed ");
1306 printf("SendMoney() : %s", strError.c_str());
1310 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1313 if (!CommitTransaction(wtxNew, reservekey))
1314 return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
1321 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1325 return _("Invalid amount");
1326 if (nValue + nTransactionFee > GetBalance())
1327 return _("Insufficient funds");
1329 // Parse Bitcoin address
1330 CScript scriptPubKey;
1331 scriptPubKey.SetDestination(address);
1333 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1339 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1343 fFirstRunRet = false;
1344 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1345 if (nLoadWalletRet == DB_NEED_REWRITE)
1347 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1350 // Note: can't top-up keypool here, because wallet is locked.
1351 // User will be prompted to unlock wallet the next operation
1352 // the requires a new key.
1356 if (nLoadWalletRet != DB_LOAD_OK)
1357 return nLoadWalletRet;
1358 fFirstRunRet = !vchDefaultKey.IsValid();
1360 NewThread(ThreadFlushWalletDB, &strWalletFile);
1365 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1367 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1368 mapAddressBook[address] = strName;
1369 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1372 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1375 bool CWallet::DelAddressBookName(const CTxDestination& address)
1377 mapAddressBook.erase(address);
1378 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1381 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1385 void CWallet::PrintWallet(const CBlock& block)
1389 if (mapWallet.count(block.vtx[0].GetHash()))
1391 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1392 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1398 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1402 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1403 if (mi != mapWallet.end())
1412 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1416 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1419 vchDefaultKey = vchPubKey;
1423 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1425 if (!pwallet->fFileBacked)
1427 strWalletFileOut = pwallet->strWalletFile;
1432 // Mark old keypool keys as used,
1433 // and generate all new keys
1435 bool CWallet::NewKeyPool()
1439 CWalletDB walletdb(strWalletFile);
1440 BOOST_FOREACH(int64 nIndex, setKeyPool)
1441 walletdb.ErasePool(nIndex);
1447 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1448 for (int i = 0; i < nKeys; i++)
1451 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1452 setKeyPool.insert(nIndex);
1454 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1459 bool CWallet::TopUpKeyPool()
1467 CWalletDB walletdb(strWalletFile);
1470 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1471 while (setKeyPool.size() < (nTargetSize + 1))
1474 if (!setKeyPool.empty())
1475 nEnd = *(--setKeyPool.end()) + 1;
1476 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1477 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1478 setKeyPool.insert(nEnd);
1479 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1485 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1488 keypool.vchPubKey = CPubKey();
1495 // Get the oldest key
1496 if(setKeyPool.empty())
1499 CWalletDB walletdb(strWalletFile);
1501 nIndex = *(setKeyPool.begin());
1502 setKeyPool.erase(setKeyPool.begin());
1503 if (!walletdb.ReadPool(nIndex, keypool))
1504 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1505 if (!HaveKey(keypool.vchPubKey.GetID()))
1506 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1507 assert(keypool.vchPubKey.IsValid());
1508 printf("keypool reserve %"PRI64d"\n", nIndex);
1512 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1515 LOCK2(cs_main, cs_wallet);
1516 CWalletDB walletdb(strWalletFile);
1518 int64 nIndex = 1 + *(--setKeyPool.end());
1519 if (!walletdb.WritePool(nIndex, keypool))
1520 throw runtime_error("AddReserveKey() : writing added key failed");
1521 setKeyPool.insert(nIndex);
1527 void CWallet::KeepKey(int64 nIndex)
1529 // Remove from key pool
1532 CWalletDB walletdb(strWalletFile);
1533 walletdb.ErasePool(nIndex);
1535 printf("keypool keep %"PRI64d"\n", nIndex);
1538 void CWallet::ReturnKey(int64 nIndex)
1540 // Return to key pool
1543 setKeyPool.insert(nIndex);
1545 printf("keypool return %"PRI64d"\n", nIndex);
1548 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
1554 ReserveKeyFromKeyPool(nIndex, keypool);
1557 if (fAllowReuse && vchDefaultKey.IsValid())
1559 result = vchDefaultKey;
1562 if (IsLocked()) return false;
1563 result = GenerateNewKey();
1567 result = keypool.vchPubKey;
1572 int64 CWallet::GetOldestKeyPoolTime()
1576 ReserveKeyFromKeyPool(nIndex, keypool);
1580 return keypool.nTime;
1583 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
1585 map<CTxDestination, int64> balances;
1589 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1591 CWalletTx *pcoin = &walletEntry.second;
1593 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
1596 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1599 int nDepth = pcoin->GetDepthInMainChain();
1600 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
1603 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1605 CTxDestination addr;
1606 if (!IsMine(pcoin->vout[i]))
1608 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1611 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
1613 if (!balances.count(addr))
1615 balances[addr] += n;
1623 set< set<CTxDestination> > CWallet::GetAddressGroupings()
1625 set< set<CTxDestination> > groupings;
1626 set<CTxDestination> grouping;
1628 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1630 CWalletTx *pcoin = &walletEntry.second;
1632 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
1634 // group all input addresses with each other
1635 BOOST_FOREACH(CTxIn txin, pcoin->vin)
1637 CTxDestination address;
1638 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1640 grouping.insert(address);
1643 // group change with input addresses
1644 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1645 if (IsChange(txout))
1647 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
1648 CTxDestination txoutAddr;
1649 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1651 grouping.insert(txoutAddr);
1653 groupings.insert(grouping);
1657 // group lone addrs by themselves
1658 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1659 if (IsMine(pcoin->vout[i]))
1661 CTxDestination address;
1662 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1664 grouping.insert(address);
1665 groupings.insert(grouping);
1670 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1671 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1672 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
1674 // make a set of all the groups hit by this new group
1675 set< set<CTxDestination>* > hits;
1676 map< CTxDestination, set<CTxDestination>* >::iterator it;
1677 BOOST_FOREACH(CTxDestination address, grouping)
1678 if ((it = setmap.find(address)) != setmap.end())
1679 hits.insert((*it).second);
1681 // merge all hit groups into a new single group and delete old groups
1682 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
1683 BOOST_FOREACH(set<CTxDestination>* hit, hits)
1685 merged->insert(hit->begin(), hit->end());
1686 uniqueGroupings.erase(hit);
1689 uniqueGroupings.insert(merged);
1692 BOOST_FOREACH(CTxDestination element, *merged)
1693 setmap[element] = merged;
1696 set< set<CTxDestination> > ret;
1697 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
1699 ret.insert(*uniqueGrouping);
1700 delete uniqueGrouping;
1706 CPubKey CReserveKey::GetReservedKey()
1711 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1713 vchPubKey = keypool.vchPubKey;
1716 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
1717 vchPubKey = pwallet->vchDefaultKey;
1720 assert(vchPubKey.IsValid());
1724 void CReserveKey::KeepKey()
1727 pwallet->KeepKey(nIndex);
1729 vchPubKey = CPubKey();
1732 void CReserveKey::ReturnKey()
1735 pwallet->ReturnKey(nIndex);
1737 vchPubKey = CPubKey();
1740 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
1744 CWalletDB walletdb(strWalletFile);
1746 LOCK2(cs_main, cs_wallet);
1747 BOOST_FOREACH(const int64& id, setKeyPool)
1750 if (!walletdb.ReadPool(id, keypool))
1751 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1752 assert(keypool.vchPubKey.IsValid());
1753 CKeyID keyID = keypool.vchPubKey.GetID();
1754 if (!HaveKey(keyID))
1755 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1756 setAddress.insert(keyID);
1760 void CWallet::UpdatedTransaction(const uint256 &hashTx)
1764 // Only notify UI if this transaction is in this wallet
1765 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
1766 if (mi != mapWallet.end())
1767 NotifyTransactionChanged(this, hashTx, CT_UPDATED);