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 CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
484 uint256 hash = tx.GetHash();
487 bool fExisted = mapWallet.count(hash);
488 if (fExisted && !fUpdate) return false;
489 if (fExisted || IsMine(tx) || IsFromMe(tx))
491 CWalletTx wtx(this,tx);
492 // Get merkle branch if transaction was found in a block
494 wtx.SetMerkleBranch(pblock);
495 return AddToWallet(wtx);
498 WalletUpdateSpent(tx);
503 bool CWallet::EraseFromWallet(uint256 hash)
509 if (mapWallet.erase(hash))
510 CWalletDB(strWalletFile).EraseTx(hash);
516 bool CWallet::IsMine(const CTxIn &txin) const
520 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
521 if (mi != mapWallet.end())
523 const CWalletTx& prev = (*mi).second;
524 if (txin.prevout.n < prev.vout.size())
525 if (IsMine(prev.vout[txin.prevout.n]))
532 int64 CWallet::GetDebit(const CTxIn &txin) const
536 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
537 if (mi != mapWallet.end())
539 const CWalletTx& prev = (*mi).second;
540 if (txin.prevout.n < prev.vout.size())
541 if (IsMine(prev.vout[txin.prevout.n]))
542 return prev.vout[txin.prevout.n].nValue;
548 bool CWallet::IsChange(const CTxOut& txout) const
550 CTxDestination address;
552 // TODO: fix handling of 'change' outputs. The assumption is that any
553 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
554 // is change. That assumption is likely to break when we implement multisignature
555 // wallets that return change back into a multi-signature-protected address;
556 // a better way of identifying which outputs are 'the send' and which are
557 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
558 // which output, if any, was change).
559 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
562 if (!mapAddressBook.count(address))
568 int64 CWalletTx::GetTxTime() const
570 int64 n = nTimeSmart;
571 return n ? n : nTimeReceived;
574 int CWalletTx::GetRequestCount() const
576 // Returns -1 if it wasn't being tracked
579 LOCK(pwallet->cs_wallet);
585 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
586 if (mi != pwallet->mapRequestCount.end())
587 nRequests = (*mi).second;
592 // Did anyone request this transaction?
593 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
594 if (mi != pwallet->mapRequestCount.end())
596 nRequests = (*mi).second;
598 // How about the block it's in?
599 if (nRequests == 0 && hashBlock != 0)
601 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
602 if (mi != pwallet->mapRequestCount.end())
603 nRequests = (*mi).second;
605 nRequests = 1; // If it's in someone else's block it must have got out
613 void CWalletTx::GetAmounts(list<pair<CTxDestination, int64> >& listReceived,
614 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
617 listReceived.clear();
619 strSentAccount = strFromAccount;
622 int64 nDebit = GetDebit();
623 if (nDebit > 0) // debit>0 means we signed/sent this transaction
625 int64 nValueOut = GetValueOut();
626 nFee = nDebit - nValueOut;
630 BOOST_FOREACH(const CTxOut& txout, vout)
632 CTxDestination address;
633 vector<unsigned char> vchPubKey;
634 if (!ExtractDestination(txout.scriptPubKey, address))
636 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
637 this->GetHash().ToString().c_str());
640 // Don't report 'change' txouts
641 if (nDebit > 0 && pwallet->IsChange(txout))
645 listSent.push_back(make_pair(address, txout.nValue));
647 if (pwallet->IsMine(txout))
648 listReceived.push_back(make_pair(address, txout.nValue));
653 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nReceived,
654 int64& nSent, int64& nFee) const
656 nReceived = nSent = nFee = 0;
659 string strSentAccount;
660 list<pair<CTxDestination, int64> > listReceived;
661 list<pair<CTxDestination, int64> > listSent;
662 GetAmounts(listReceived, listSent, allFee, strSentAccount);
664 if (strAccount == strSentAccount)
666 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
671 LOCK(pwallet->cs_wallet);
672 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
674 if (pwallet->mapAddressBook.count(r.first))
676 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
677 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
678 nReceived += r.second;
680 else if (strAccount.empty())
682 nReceived += r.second;
688 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
692 const int COPY_DEPTH = 3;
693 if (SetMerkleBranch() < COPY_DEPTH)
695 vector<uint256> vWorkQueue;
696 BOOST_FOREACH(const CTxIn& txin, vin)
697 vWorkQueue.push_back(txin.prevout.hash);
699 // This critsect is OK because txdb is already open
701 LOCK(pwallet->cs_wallet);
702 map<uint256, const CMerkleTx*> mapWalletPrev;
703 set<uint256> setAlreadyDone;
704 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
706 uint256 hash = vWorkQueue[i];
707 if (setAlreadyDone.count(hash))
709 setAlreadyDone.insert(hash);
712 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
713 if (mi != pwallet->mapWallet.end())
716 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
717 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
719 else if (mapWalletPrev.count(hash))
721 tx = *mapWalletPrev[hash];
723 else if (!fClient && txdb.ReadDiskTx(hash, tx))
729 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
733 int nDepth = tx.SetMerkleBranch();
734 vtxPrev.push_back(tx);
736 if (nDepth < COPY_DEPTH)
738 BOOST_FOREACH(const CTxIn& txin, tx.vin)
739 vWorkQueue.push_back(txin.prevout.hash);
745 reverse(vtxPrev.begin(), vtxPrev.end());
748 bool CWalletTx::WriteToDisk()
750 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
753 // Scan the block chain (starting in pindexStart) for transactions
754 // from or to us. If fUpdate is true, found transactions that already
755 // exist in the wallet will be updated.
756 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
760 CBlockIndex* pindex = pindexStart;
766 block.ReadFromDisk(pindex, true);
767 BOOST_FOREACH(CTransaction& tx, block.vtx)
769 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
772 pindex = pindex->pnext;
778 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
781 tx.ReadFromDisk(COutPoint(hashTx, 0));
782 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
787 void CWallet::ReacceptWalletTransactions()
795 vector<CDiskTxPos> vMissingTx;
796 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
798 CWalletTx& wtx = item.second;
799 if (wtx.IsCoinBase() && wtx.IsSpent(0))
803 bool fUpdated = false;
804 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
806 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
807 if (txindex.vSpent.size() != wtx.vout.size())
809 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
812 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
816 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
820 vMissingTx.push_back(txindex.vSpent[i]);
825 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
832 // Re-accept any txes of ours that aren't already in a block
833 if (!wtx.IsCoinBase())
834 wtx.AcceptWalletTransaction(txdb, false);
837 if (!vMissingTx.empty())
839 // TODO: optimize this to scan just part of the block chain?
840 if (ScanForWalletTransactions(pindexGenesisBlock))
841 fRepeat = true; // Found missing transactions: re-do re-accept.
846 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
848 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
850 if (!tx.IsCoinBase())
852 uint256 hash = tx.GetHash();
853 if (!txdb.ContainsTx(hash))
854 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
859 uint256 hash = GetHash();
860 if (!txdb.ContainsTx(hash))
862 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
863 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
868 void CWalletTx::RelayWalletTransaction()
871 RelayWalletTransaction(txdb);
874 void CWallet::ResendWalletTransactions()
876 // Do this infrequently and randomly to avoid giving away
877 // that these are our transactions.
878 static int64 nNextTime;
879 if (GetTime() < nNextTime)
881 bool fFirst = (nNextTime == 0);
882 nNextTime = GetTime() + GetRand(30 * 60);
886 // Only do it if there's been a new block since last time
887 static int64 nLastTime;
888 if (nTimeBestReceived < nLastTime)
890 nLastTime = GetTime();
892 // Rebroadcast any of our txes that aren't in a block yet
893 printf("ResendWalletTransactions()\n");
897 // Sort them in chronological order
898 multimap<unsigned int, CWalletTx*> mapSorted;
899 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
901 CWalletTx& wtx = item.second;
902 // Don't rebroadcast until it's had plenty of time that
903 // it should have gotten in already by now.
904 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
905 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
907 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
909 CWalletTx& wtx = *item.second;
910 wtx.RelayWalletTransaction(txdb);
920 //////////////////////////////////////////////////////////////////////////////
926 int64 CWallet::GetBalance() const
931 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
933 const CWalletTx* pcoin = &(*it).second;
934 if (pcoin->IsFinal() && pcoin->IsConfirmed())
935 nTotal += pcoin->GetAvailableCredit();
942 int64 CWallet::GetUnconfirmedBalance() const
947 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
949 const CWalletTx* pcoin = &(*it).second;
950 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
951 nTotal += pcoin->GetAvailableCredit();
957 int64 CWallet::GetImmatureBalance() const
962 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
964 const CWalletTx& pcoin = (*it).second;
965 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
966 nTotal += GetCredit(pcoin);
972 // populate vCoins with vector of spendable COutputs
973 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
979 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
981 const CWalletTx* pcoin = &(*it).second;
983 if (!pcoin->IsFinal())
986 if (fOnlyConfirmed && !pcoin->IsConfirmed())
989 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
992 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
993 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue > 0)
994 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
999 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1000 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1002 vector<char> vfIncluded;
1004 vfBest.assign(vValue.size(), true);
1005 nBest = nTotalLower;
1007 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1009 vfIncluded.assign(vValue.size(), false);
1011 bool fReachedTarget = false;
1012 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1014 for (unsigned int i = 0; i < vValue.size(); i++)
1016 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1018 nTotal += vValue[i].first;
1019 vfIncluded[i] = true;
1020 if (nTotal >= nTargetValue)
1022 fReachedTarget = true;
1026 vfBest = vfIncluded;
1028 nTotal -= vValue[i].first;
1029 vfIncluded[i] = false;
1037 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1038 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1040 setCoinsRet.clear();
1043 // List of values less than target
1044 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1045 coinLowestLarger.first = std::numeric_limits<int64>::max();
1046 coinLowestLarger.second.first = NULL;
1047 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1048 int64 nTotalLower = 0;
1050 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1052 BOOST_FOREACH(COutput output, vCoins)
1054 const CWalletTx *pcoin = output.tx;
1056 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1060 int64 n = pcoin->vout[i].nValue;
1062 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1064 if (n == nTargetValue)
1066 setCoinsRet.insert(coin.second);
1067 nValueRet += coin.first;
1070 else if (n < nTargetValue + CENT)
1072 vValue.push_back(coin);
1075 else if (n < coinLowestLarger.first)
1077 coinLowestLarger = coin;
1081 if (nTotalLower == nTargetValue)
1083 for (unsigned int i = 0; i < vValue.size(); ++i)
1085 setCoinsRet.insert(vValue[i].second);
1086 nValueRet += vValue[i].first;
1091 if (nTotalLower < nTargetValue)
1093 if (coinLowestLarger.second.first == NULL)
1095 setCoinsRet.insert(coinLowestLarger.second);
1096 nValueRet += coinLowestLarger.first;
1100 // Solve subset sum by stochastic approximation
1101 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1102 vector<char> vfBest;
1105 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1106 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1107 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1109 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1110 // or the next bigger coin is closer), return the bigger coin
1111 if (coinLowestLarger.second.first &&
1112 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1114 setCoinsRet.insert(coinLowestLarger.second);
1115 nValueRet += coinLowestLarger.first;
1118 for (unsigned int i = 0; i < vValue.size(); i++)
1121 setCoinsRet.insert(vValue[i].second);
1122 nValueRet += vValue[i].first;
1126 printf("SelectCoins() best subset: ");
1127 for (unsigned int i = 0; i < vValue.size(); i++)
1129 printf("%s ", FormatMoney(vValue[i].first).c_str());
1130 printf("total %s\n", FormatMoney(nBest).c_str());
1136 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1138 vector<COutput> vCoins;
1139 AvailableCoins(vCoins);
1141 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1142 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1143 SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet));
1149 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1152 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1158 if (vecSend.empty() || nValue < 0)
1161 wtxNew.BindWallet(this);
1164 LOCK2(cs_main, cs_wallet);
1165 // txdb must be opened before the mapWallet lock
1168 nFeeRet = nTransactionFee;
1172 wtxNew.vout.clear();
1173 wtxNew.fFromMe = true;
1175 int64 nTotalValue = nValue + nFeeRet;
1176 double dPriority = 0;
1177 // vouts to the payees
1178 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1179 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1181 // Choose coins to use
1182 set<pair<const CWalletTx*,unsigned int> > setCoins;
1184 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1186 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1188 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1189 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1192 int64 nChange = nValueIn - nValue - nFeeRet;
1193 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1194 // or until nChange becomes zero
1195 // NOTE: this depends on the exact behaviour of GetMinFee
1196 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1198 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1199 nChange -= nMoveToFee;
1200 nFeeRet += nMoveToFee;
1205 // Note: We use a new key here to keep it from being obvious which side is the change.
1206 // The drawback is that by not reusing a previous key, the change may be lost if a
1207 // backup is restored, if the backup doesn't have the new private key for the change.
1208 // If we reused the old key, it would be possible to add code to look for and
1209 // rediscover unknown transactions that were written with keys of ours to recover
1210 // post-backup change.
1212 // Reserve a new key pair from key pool
1213 CPubKey vchPubKey = reservekey.GetReservedKey();
1214 // assert(mapKeys.count(vchPubKey));
1216 // Fill a vout to ourself
1217 // TODO: pass in scriptChange instead of reservekey so
1218 // change transaction isn't always pay-to-bitcoin-address
1219 CScript scriptChange;
1220 scriptChange.SetDestination(vchPubKey.GetID());
1222 // Insert change txn at random position:
1223 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1224 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1227 reservekey.ReturnKey();
1230 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1231 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1235 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1236 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1240 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1241 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1243 dPriority /= nBytes;
1245 // Check that enough fee is included
1246 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1247 bool fAllowFree = CTransaction::AllowFree(dPriority);
1248 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1249 if (nFeeRet < max(nPayFee, nMinFee))
1251 nFeeRet = max(nPayFee, nMinFee);
1255 // Fill vtxPrev by copying from previous transactions vtxPrev
1256 wtxNew.AddSupportingTransactions(txdb);
1257 wtxNew.fTimeReceivedIsTxTime = true;
1266 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1268 vector< pair<CScript, int64> > vecSend;
1269 vecSend.push_back(make_pair(scriptPubKey, nValue));
1270 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1273 // Call after CreateTransaction unless you want to abort
1274 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1277 LOCK2(cs_main, cs_wallet);
1278 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1280 // This is only to keep the database open to defeat the auto-flush for the
1281 // duration of this scope. This is the only place where this optimization
1282 // maybe makes sense; please don't do it anywhere else.
1283 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1285 // Take key pair from key pool so it won't be used again
1286 reservekey.KeepKey();
1288 // Add tx to wallet, because if it has change it's also ours,
1289 // otherwise just for transaction history.
1290 AddToWallet(wtxNew);
1292 // Mark old coins as spent
1293 set<CWalletTx*> setCoins;
1294 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1296 CWalletTx &coin = mapWallet[txin.prevout.hash];
1297 coin.BindWallet(this);
1298 coin.MarkSpent(txin.prevout.n);
1300 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1307 // Track how many getdata requests our transaction gets
1308 mapRequestCount[wtxNew.GetHash()] = 0;
1311 if (!wtxNew.AcceptToMemoryPool())
1313 // This must not fail. The transaction has already been signed and recorded.
1314 printf("CommitTransaction() : Error: Transaction not valid");
1317 wtxNew.RelayWalletTransaction();
1325 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1327 CReserveKey reservekey(this);
1332 string strError = _("Error: Wallet locked, unable to create transaction ");
1333 printf("SendMoney() : %s", strError.c_str());
1336 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1339 if (nValue + nFeeRequired > GetBalance())
1340 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());
1342 strError = _("Error: Transaction creation failed ");
1343 printf("SendMoney() : %s", strError.c_str());
1347 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1350 if (!CommitTransaction(wtxNew, reservekey))
1351 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.");
1358 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1362 return _("Invalid amount");
1363 if (nValue + nTransactionFee > GetBalance())
1364 return _("Insufficient funds");
1366 // Parse Bitcoin address
1367 CScript scriptPubKey;
1368 scriptPubKey.SetDestination(address);
1370 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1376 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1380 fFirstRunRet = false;
1381 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1382 if (nLoadWalletRet == DB_NEED_REWRITE)
1384 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1387 // Note: can't top-up keypool here, because wallet is locked.
1388 // User will be prompted to unlock wallet the next operation
1389 // the requires a new key.
1393 if (nLoadWalletRet != DB_LOAD_OK)
1394 return nLoadWalletRet;
1395 fFirstRunRet = !vchDefaultKey.IsValid();
1397 NewThread(ThreadFlushWalletDB, &strWalletFile);
1402 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1404 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1405 mapAddressBook[address] = strName;
1406 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1409 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1412 bool CWallet::DelAddressBookName(const CTxDestination& address)
1414 mapAddressBook.erase(address);
1415 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1418 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1422 void CWallet::PrintWallet(const CBlock& block)
1426 if (mapWallet.count(block.vtx[0].GetHash()))
1428 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1429 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1435 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1439 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1440 if (mi != mapWallet.end())
1449 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1453 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1456 vchDefaultKey = vchPubKey;
1460 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1462 if (!pwallet->fFileBacked)
1464 strWalletFileOut = pwallet->strWalletFile;
1469 // Mark old keypool keys as used,
1470 // and generate all new keys
1472 bool CWallet::NewKeyPool()
1476 CWalletDB walletdb(strWalletFile);
1477 BOOST_FOREACH(int64 nIndex, setKeyPool)
1478 walletdb.ErasePool(nIndex);
1484 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1485 for (int i = 0; i < nKeys; i++)
1488 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1489 setKeyPool.insert(nIndex);
1491 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1496 bool CWallet::TopUpKeyPool()
1504 CWalletDB walletdb(strWalletFile);
1507 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1508 while (setKeyPool.size() < (nTargetSize + 1))
1511 if (!setKeyPool.empty())
1512 nEnd = *(--setKeyPool.end()) + 1;
1513 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1514 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1515 setKeyPool.insert(nEnd);
1516 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1522 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1525 keypool.vchPubKey = CPubKey();
1532 // Get the oldest key
1533 if(setKeyPool.empty())
1536 CWalletDB walletdb(strWalletFile);
1538 nIndex = *(setKeyPool.begin());
1539 setKeyPool.erase(setKeyPool.begin());
1540 if (!walletdb.ReadPool(nIndex, keypool))
1541 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1542 if (!HaveKey(keypool.vchPubKey.GetID()))
1543 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1544 assert(keypool.vchPubKey.IsValid());
1545 printf("keypool reserve %"PRI64d"\n", nIndex);
1549 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1552 LOCK2(cs_main, cs_wallet);
1553 CWalletDB walletdb(strWalletFile);
1555 int64 nIndex = 1 + *(--setKeyPool.end());
1556 if (!walletdb.WritePool(nIndex, keypool))
1557 throw runtime_error("AddReserveKey() : writing added key failed");
1558 setKeyPool.insert(nIndex);
1564 void CWallet::KeepKey(int64 nIndex)
1566 // Remove from key pool
1569 CWalletDB walletdb(strWalletFile);
1570 walletdb.ErasePool(nIndex);
1572 printf("keypool keep %"PRI64d"\n", nIndex);
1575 void CWallet::ReturnKey(int64 nIndex)
1577 // Return to key pool
1580 setKeyPool.insert(nIndex);
1582 printf("keypool return %"PRI64d"\n", nIndex);
1585 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
1591 ReserveKeyFromKeyPool(nIndex, keypool);
1594 if (fAllowReuse && vchDefaultKey.IsValid())
1596 result = vchDefaultKey;
1599 if (IsLocked()) return false;
1600 result = GenerateNewKey();
1604 result = keypool.vchPubKey;
1609 int64 CWallet::GetOldestKeyPoolTime()
1613 ReserveKeyFromKeyPool(nIndex, keypool);
1617 return keypool.nTime;
1620 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
1622 map<CTxDestination, int64> balances;
1626 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1628 CWalletTx *pcoin = &walletEntry.second;
1630 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
1633 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1636 int nDepth = pcoin->GetDepthInMainChain();
1637 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
1640 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1642 CTxDestination addr;
1643 if (!IsMine(pcoin->vout[i]))
1645 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1648 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
1650 if (!balances.count(addr))
1652 balances[addr] += n;
1660 set< set<CTxDestination> > CWallet::GetAddressGroupings()
1662 set< set<CTxDestination> > groupings;
1663 set<CTxDestination> grouping;
1665 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1667 CWalletTx *pcoin = &walletEntry.second;
1669 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
1671 // group all input addresses with each other
1672 BOOST_FOREACH(CTxIn txin, pcoin->vin)
1674 CTxDestination address;
1675 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1677 grouping.insert(address);
1680 // group change with input addresses
1681 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1682 if (IsChange(txout))
1684 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
1685 CTxDestination txoutAddr;
1686 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1688 grouping.insert(txoutAddr);
1690 groupings.insert(grouping);
1694 // group lone addrs by themselves
1695 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1696 if (IsMine(pcoin->vout[i]))
1698 CTxDestination address;
1699 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1701 grouping.insert(address);
1702 groupings.insert(grouping);
1707 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1708 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1709 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
1711 // make a set of all the groups hit by this new group
1712 set< set<CTxDestination>* > hits;
1713 map< CTxDestination, set<CTxDestination>* >::iterator it;
1714 BOOST_FOREACH(CTxDestination address, grouping)
1715 if ((it = setmap.find(address)) != setmap.end())
1716 hits.insert((*it).second);
1718 // merge all hit groups into a new single group and delete old groups
1719 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
1720 BOOST_FOREACH(set<CTxDestination>* hit, hits)
1722 merged->insert(hit->begin(), hit->end());
1723 uniqueGroupings.erase(hit);
1726 uniqueGroupings.insert(merged);
1729 BOOST_FOREACH(CTxDestination element, *merged)
1730 setmap[element] = merged;
1733 set< set<CTxDestination> > ret;
1734 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
1736 ret.insert(*uniqueGrouping);
1737 delete uniqueGrouping;
1743 CPubKey CReserveKey::GetReservedKey()
1748 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1750 vchPubKey = keypool.vchPubKey;
1753 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
1754 vchPubKey = pwallet->vchDefaultKey;
1757 assert(vchPubKey.IsValid());
1761 void CReserveKey::KeepKey()
1764 pwallet->KeepKey(nIndex);
1766 vchPubKey = CPubKey();
1769 void CReserveKey::ReturnKey()
1772 pwallet->ReturnKey(nIndex);
1774 vchPubKey = CPubKey();
1777 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
1781 CWalletDB walletdb(strWalletFile);
1783 LOCK2(cs_main, cs_wallet);
1784 BOOST_FOREACH(const int64& id, setKeyPool)
1787 if (!walletdb.ReadPool(id, keypool))
1788 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1789 assert(keypool.vchPubKey.IsValid());
1790 CKeyID keyID = keypool.vchPubKey.GetID();
1791 if (!HaveKey(keyID))
1792 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1793 setAddress.insert(keyID);
1797 void CWallet::UpdatedTransaction(const uint256 &hashTx)
1801 // Only notify UI if this transaction is in this wallet
1802 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
1803 if (mi != mapWallet.end())
1804 NotifyTransactionChanged(this, hashTx, CT_UPDATED);