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.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
17 extern int nStakeMaxAge;
19 //////////////////////////////////////////////////////////////////////////////
24 struct CompareValueOnly
26 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
29 return t1.first < t2.first;
33 CPubKey CWallet::GenerateNewKey()
35 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
39 key.MakeNewKey(fCompressed);
41 // Compressed public keys were introduced in version 0.6.0
43 SetMinVersion(FEATURE_COMPRPUBKEY);
45 CPubKey pubkey = key.GetPubKey();
47 // Create new metadata
48 int64 nCreationTime = GetTime();
49 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51 nTimeFirstKey = nCreationTime;
54 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55 return key.GetPubKey();
58 bool CWallet::AddKey(const CKey& key)
60 CPubKey pubkey = key.GetPubKey();
62 if (!CCryptoKeyStore::AddKey(key))
67 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
73 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 if (pwalletdbEncryption)
80 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
82 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
89 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90 nTimeFirstKey = meta.nCreateTime;
92 mapKeyMetadata[pubkey.GetID()] = meta;
96 bool CWallet::AddCScript(const CScript& redeemScript)
98 if (!CCryptoKeyStore::AddCScript(redeemScript))
102 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
105 // ppcoin: optional setting to unlock wallet for block minting only;
106 // serves to disable the trivial sendmoney when OS account compromised
107 bool fWalletUnlockMintOnly = false;
109 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
115 CKeyingMaterial vMasterKey;
119 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
121 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
123 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
125 if (CCryptoKeyStore::Unlock(vMasterKey))
132 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
134 bool fWasLocked = IsLocked();
141 CKeyingMaterial vMasterKey;
142 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
144 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
146 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
148 if (CCryptoKeyStore::Unlock(vMasterKey))
150 int64 nStartTime = GetTimeMillis();
151 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
152 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
154 nStartTime = GetTimeMillis();
155 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
156 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
158 if (pMasterKey.second.nDeriveIterations < 25000)
159 pMasterKey.second.nDeriveIterations = 25000;
161 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
163 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
165 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
167 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
178 void CWallet::SetBestChain(const CBlockLocator& loc)
180 CWalletDB walletdb(strWalletFile);
181 walletdb.WriteBestBlock(loc);
184 // This class implements an addrIncoming entry that causes pre-0.4
185 // clients to crash on startup if reading a private-key-encrypted wallet.
186 class CCorruptAddress
191 if (nType & SER_DISK)
196 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
198 if (nWalletVersion >= nVersion)
201 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
202 if (fExplicit && nVersion > nWalletMaxVersion)
203 nVersion = FEATURE_LATEST;
205 nWalletVersion = nVersion;
207 if (nVersion > nWalletMaxVersion)
208 nWalletMaxVersion = nVersion;
212 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
213 if (nWalletVersion >= 40000)
215 // Versions prior to 0.4.0 did not support the "minversion" record.
216 // Use a CCorruptAddress to make them crash instead.
217 CCorruptAddress corruptAddress;
218 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
220 if (nWalletVersion > 40000)
221 pwalletdb->WriteMinVersion(nWalletVersion);
229 bool CWallet::SetMaxVersion(int nVersion)
231 // cannot downgrade below current version
232 if (nWalletVersion > nVersion)
235 nWalletMaxVersion = nVersion;
240 set<uint256> CWallet::GetConflicts(const uint256& txid) const
245 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
246 if (it == mapWallet.end())
248 const CWalletTx& wtx = it->second;
250 std::pair<TxConflicts::const_iterator, TxConflicts::const_iterator> range;
252 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
254 range = mapTxConflicts.equal_range(txin.prevout);
255 for (TxConflicts::const_iterator it = range.first; it != range.second; ++it)
256 result.insert(it->second);
261 void CWallet::SyncMetaData(pair<TxConflicts::iterator, TxConflicts::iterator> range)
263 // We want all the wallet transactions in range to have the same metadata as
264 // the oldest (smallest nOrderPos).
265 // So: find smallest nOrderPos:
267 int nMinOrderPos = std::numeric_limits<int>::max();
268 const CWalletTx* copyFrom = NULL;
269 for (TxConflicts::iterator it = range.first; it != range.second; ++it)
271 const uint256& hash = it->second;
272 int n = mapWallet[hash].nOrderPos;
273 if (n < nMinOrderPos)
276 copyFrom = &mapWallet[hash];
279 // Now copy data from copyFrom to rest:
280 for (TxConflicts::iterator it = range.first; it != range.second; ++it)
282 const uint256& hash = it->second;
283 CWalletTx* copyTo = &mapWallet[hash];
284 if (copyFrom == copyTo) continue;
285 copyTo->mapValue = copyFrom->mapValue;
286 copyTo->vOrderForm = copyFrom->vOrderForm;
287 // fTimeReceivedIsTxTime not copied on purpose
288 // nTimeReceived not copied on purpose
289 copyTo->nTimeSmart = copyFrom->nTimeSmart;
290 copyTo->fFromMe = copyFrom->fFromMe;
291 copyTo->strFromAccount = copyFrom->strFromAccount;
292 // vfSpent not copied on purpose
293 // nOrderPos not copied on purpose
294 // cached members not copied on purpose
298 void CWallet::AddToConflicts(const uint256& wtxhash)
300 assert(mapWallet.count(wtxhash));
301 CWalletTx& thisTx = mapWallet[wtxhash];
302 if (thisTx.IsCoinBase())
305 BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
307 mapTxConflicts.insert(make_pair(txin.prevout, wtxhash));
309 pair<TxConflicts::iterator, TxConflicts::iterator> range;
310 range = mapTxConflicts.equal_range(txin.prevout);
311 if (range.first != range.second)
316 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
321 CKeyingMaterial vMasterKey;
322 RandAddSeedPerfmon();
324 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
325 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
327 CMasterKey kMasterKey(nDerivationMethodIndex);
329 RandAddSeedPerfmon();
330 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
331 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
334 int64 nStartTime = GetTimeMillis();
335 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
336 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
338 nStartTime = GetTimeMillis();
339 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
340 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
342 if (kMasterKey.nDeriveIterations < 25000)
343 kMasterKey.nDeriveIterations = 25000;
345 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
347 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
349 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
354 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
357 pwalletdbEncryption = new CWalletDB(strWalletFile);
358 if (!pwalletdbEncryption->TxnBegin())
360 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
363 if (!EncryptKeys(vMasterKey))
366 pwalletdbEncryption->TxnAbort();
367 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.
370 // Encryption was introduced in version 0.4.0
371 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
375 if (!pwalletdbEncryption->TxnCommit())
376 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.
378 delete pwalletdbEncryption;
379 pwalletdbEncryption = NULL;
383 Unlock(strWalletPassphrase);
387 // Need to completely rewrite the wallet file; if we don't, bdb might keep
388 // bits of the unencrypted private key in slack space in the database file.
389 CDB::Rewrite(strWalletFile);
392 NotifyStatusChanged(this);
397 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
399 int64 nRet = nOrderPosNext++;
401 pwalletdb->WriteOrderPosNext(nOrderPosNext);
403 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
408 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
410 CWalletDB walletdb(strWalletFile);
412 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
415 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
416 // would make this much faster for applications that do this a lot.
417 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
419 CWalletTx* wtx = &((*it).second);
420 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
423 walletdb.ListAccountCreditDebit(strAccount, acentries);
424 BOOST_FOREACH(CAccountingEntry& entry, acentries)
426 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
432 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
434 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
435 // Update the wallet spent flag if it doesn't know due to wallet.dat being
436 // restored from backup or the user making copies of wallet.dat.
439 BOOST_FOREACH(const CTxIn& txin, tx.vin)
441 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
442 if (mi != mapWallet.end())
444 CWalletTx& wtx = (*mi).second;
445 if (txin.prevout.n >= wtx.vout.size())
446 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
447 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
449 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
450 wtx.MarkSpent(txin.prevout.n);
452 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
459 uint256 hash = tx.GetHash();
460 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
461 CWalletTx& wtx = (*mi).second;
463 BOOST_FOREACH(const CTxOut& txout, tx.vout)
467 wtx.MarkUnspent(&txout - &tx.vout[0]);
469 NotifyTransactionChanged(this, hash, CT_UPDATED);
476 void CWallet::MarkDirty()
480 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
481 item.second.MarkDirty();
485 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
487 uint256 hash = wtxIn.GetHash();
490 mapWallet[hash] = wtxIn;
491 AddToConflicts(hash);
496 // Inserts only if not already there, returns tx inserted or tx found
497 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
498 CWalletTx& wtx = (*ret.first).second;
499 wtx.BindWallet(this);
500 bool fInsertedNew = ret.second;
503 wtx.nTimeReceived = GetAdjustedTime();
504 wtx.nOrderPos = IncOrderPosNext();
506 wtx.nTimeSmart = wtx.nTimeReceived;
507 if (wtxIn.hashBlock != 0)
509 if (mapBlockIndex.count(wtxIn.hashBlock))
511 unsigned int latestNow = wtx.nTimeReceived;
512 unsigned int latestEntry = 0;
514 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
515 int64 latestTolerated = latestNow + 300;
516 std::list<CAccountingEntry> acentries;
517 TxItems txOrdered = OrderedTxItems(acentries);
518 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
520 CWalletTx *const pwtx = (*it).second.first;
523 CAccountingEntry *const pacentry = (*it).second.second;
527 nSmartTime = pwtx->nTimeSmart;
529 nSmartTime = pwtx->nTimeReceived;
532 nSmartTime = pacentry->nTime;
533 if (nSmartTime <= latestTolerated)
535 latestEntry = nSmartTime;
536 if (nSmartTime > latestNow)
537 latestNow = nSmartTime;
543 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
544 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
547 printf("AddToWallet() : found %s in block %s not in index\n",
548 hash.ToString().c_str(),
549 wtxIn.hashBlock.ToString().c_str());
551 AddToConflicts(hash);
554 bool fUpdated = false;
558 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
560 wtx.hashBlock = wtxIn.hashBlock;
563 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
565 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
566 wtx.nIndex = wtxIn.nIndex;
569 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
571 wtx.fFromMe = wtxIn.fFromMe;
574 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
578 printf("AddToWallet %s %s%s\n", hash.ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
581 if (fInsertedNew || fUpdated)
582 if (!wtx.WriteToDisk())
585 // If default receiving address gets used, replace it with a new one
586 CScript scriptDefaultKey;
587 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
588 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
590 if (txout.scriptPubKey == scriptDefaultKey)
592 CPubKey newDefaultKey;
593 if (GetKeyFromPool(newDefaultKey, false))
595 SetDefaultKey(newDefaultKey);
596 SetAddressBookName(vchDefaultKey.GetID(), "");
601 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
602 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
604 // Notify UI of new or updated transaction
605 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
607 // notify an external script when a wallet transaction comes in or is updated
608 std::string strCmd = GetArg("-walletnotify", "");
610 if ( !strCmd.empty())
612 boost::replace_all(strCmd, "%s", hash.GetHex());
613 boost::thread t(runCommand, strCmd); // thread runs free
620 // Add a transaction to the wallet, or update it.
621 // pblock is optional, but should be provided if the transaction is known to be in a block.
622 // If fUpdate is true, existing transactions will be updated.
623 bool CWallet::AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
627 bool fExisted = mapWallet.count(hash);
628 if (fExisted && !fUpdate) return false;
629 if (fExisted || IsMine(tx) || IsFromMe(tx))
631 CWalletTx wtx(this,tx);
632 // Get merkle branch if transaction was found in a block
634 wtx.SetMerkleBranch(pblock);
635 return AddToWallet(wtx);
638 WalletUpdateSpent(tx);
643 bool CWallet::EraseFromWallet(uint256 hash)
649 if (mapWallet.erase(hash))
650 CWalletDB(strWalletFile).EraseTx(hash);
656 bool CWallet::IsMine(const CTxIn &txin) const
660 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
661 if (mi != mapWallet.end())
663 const CWalletTx& prev = (*mi).second;
664 if (txin.prevout.n < prev.vout.size())
665 if (IsMine(prev.vout[txin.prevout.n]))
672 int64 CWallet::GetDebit(const CTxIn &txin) const
676 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
677 if (mi != mapWallet.end())
679 const CWalletTx& prev = (*mi).second;
680 if (txin.prevout.n < prev.vout.size())
681 if (IsMine(prev.vout[txin.prevout.n]))
682 return prev.vout[txin.prevout.n].nValue;
688 bool CWallet::IsChange(const CTxOut& txout) const
690 CTxDestination address;
692 // TODO: fix handling of 'change' outputs. The assumption is that any
693 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
694 // is change. That assumption is likely to break when we implement multisignature
695 // wallets that return change back into a multi-signature-protected address;
696 // a better way of identifying which outputs are 'the send' and which are
697 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
698 // which output, if any, was change).
699 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
702 if (!mapAddressBook.count(address))
708 int64 CWalletTx::GetTxTime() const
710 int64 n = nTimeSmart;
711 return n ? n : nTimeReceived;
714 int CWalletTx::GetRequestCount() const
716 // Returns -1 if it wasn't being tracked
719 LOCK(pwallet->cs_wallet);
720 if (IsCoinBase() || IsCoinStake())
725 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
726 if (mi != pwallet->mapRequestCount.end())
727 nRequests = (*mi).second;
732 // Did anyone request this transaction?
733 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
734 if (mi != pwallet->mapRequestCount.end())
736 nRequests = (*mi).second;
738 // How about the block it's in?
739 if (nRequests == 0 && hashBlock != 0)
741 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
742 if (mi != pwallet->mapRequestCount.end())
743 nRequests = (*mi).second;
745 nRequests = 1; // If it's in someone else's block it must have got out
753 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
754 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
756 nGeneratedImmature = nGeneratedMature = nFee = 0;
757 listReceived.clear();
759 strSentAccount = strFromAccount;
761 if (IsCoinBase() || IsCoinStake())
763 if (GetBlocksToMaturity() > 0)
764 nGeneratedImmature = pwallet->GetCredit(*this);
766 nGeneratedMature = GetCredit();
771 int64 nDebit = GetDebit();
772 if (nDebit > 0) // debit>0 means we signed/sent this transaction
774 int64 nValueOut = GetValueOut();
775 nFee = nDebit - nValueOut;
779 BOOST_FOREACH(const CTxOut& txout, vout)
782 // Only need to handle txouts if AT LEAST one of these is true:
783 // 1) they debit from us (sent)
784 // 2) the output is to us (received)
787 // Don't report 'change' txouts
788 if (pwallet->IsChange(txout))
790 fIsMine = pwallet->IsMine(txout);
792 else if (!(fIsMine = pwallet->IsMine(txout)))
795 // In either case, we need to get the destination address
796 CTxDestination address;
797 if (!ExtractDestination(txout.scriptPubKey, address))
799 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
800 this->GetHash().ToString().c_str());
801 address = CNoDestination();
804 // If we are debited by the transaction, add the output as a "sent" entry
806 listSent.push_back(make_pair(address, txout.nValue));
808 // If we are receiving the output, add it as a "received" entry
810 listReceived.push_back(make_pair(address, txout.nValue));
815 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
816 int64& nSent, int64& nFee) const
818 nGenerated = nReceived = nSent = nFee = 0;
820 int64 allGeneratedImmature, allGeneratedMature, allFee;
821 allGeneratedImmature = allGeneratedMature = allFee = 0;
822 string strSentAccount;
823 list<pair<CTxDestination, int64> > listReceived;
824 list<pair<CTxDestination, int64> > listSent;
825 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
827 if (strAccount == "")
828 nGenerated = allGeneratedMature;
829 if (strAccount == strSentAccount)
831 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
836 LOCK(pwallet->cs_wallet);
837 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
839 if (pwallet->mapAddressBook.count(r.first))
841 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
842 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
843 nReceived += r.second;
845 else if (strAccount.empty())
847 nReceived += r.second;
853 void CWalletTx::AddSupportingTransactions()
857 const int COPY_DEPTH = 3;
858 if (SetMerkleBranch() < COPY_DEPTH)
860 vector<uint256> vWorkQueue;
861 BOOST_FOREACH(const CTxIn& txin, vin)
862 vWorkQueue.push_back(txin.prevout.hash);
865 LOCK(pwallet->cs_wallet);
866 map<uint256, const CMerkleTx*> mapWalletPrev;
867 set<uint256> setAlreadyDone;
868 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
870 uint256 hash = vWorkQueue[i];
871 if (setAlreadyDone.count(hash))
873 setAlreadyDone.insert(hash);
876 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
877 if (mi != pwallet->mapWallet.end())
880 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
881 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
883 else if (mapWalletPrev.count(hash))
885 tx = *mapWalletPrev[hash];
888 int nDepth = tx.SetMerkleBranch();
889 vtxPrev.push_back(tx);
891 if (nDepth < COPY_DEPTH)
893 BOOST_FOREACH(const CTxIn& txin, tx.vin)
894 vWorkQueue.push_back(txin.prevout.hash);
900 reverse(vtxPrev.begin(), vtxPrev.end());
903 bool CWalletTx::WriteToDisk()
905 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
908 // Scan the block chain (starting in pindexStart) for transactions
909 // from or to us. If fUpdate is true, found transactions that already
910 // exist in the wallet will be updated.
911 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
915 CBlockIndex* pindex = pindexStart;
921 block.ReadFromDisk(pindex, true);
922 BOOST_FOREACH(CTransaction& tx, block.vtx)
924 if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate))
927 pindex = pindex->pnext;
933 void CWallet::ReacceptWalletTransactions()
940 bool fMissing = false;
941 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
943 CWalletTx& wtx = item.second;
944 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
948 bool fUpdated = false;
949 bool fNotFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);
950 if (!fNotFound || wtx.GetDepthInMainChain() > 0)
952 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
953 for (unsigned int i = 0; i < wtx.vout.size(); i++)
957 if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))
966 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
973 // Re-accept any txes of ours that aren't already in a block
974 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
975 wtx.AcceptWalletTransaction(false);
980 // TODO: optimize this to scan just part of the block chain?
981 if (ScanForWalletTransactions(pindexGenesisBlock))
982 fRepeat = true; // Found missing transactions: re-do re-accept.
987 set<uint256> CWalletTx::GetConflicts() const
992 uint256 myHash = GetHash();
993 result = pwallet->GetConflicts(myHash);
994 result.erase(myHash);
999 void CWalletTx::RelayWalletTransaction()
1001 CCoinsViewCache& coins = *pcoinsTip;
1002 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1004 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1006 uint256 hash = tx.GetHash();
1007 if (!coins.HaveCoins(hash))
1008 RelayTransaction((CTransaction)tx, hash);
1011 if (!(IsCoinBase() || IsCoinStake()))
1013 uint256 hash = GetHash();
1014 if (!coins.HaveCoins(hash))
1016 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1017 RelayTransaction((CTransaction)*this, hash);
1022 void CWallet::ResendWalletTransactions(bool fForce)
1026 // Do this infrequently and randomly to avoid giving away
1027 // that these are our transactions.
1028 static int64 nNextTime;
1029 if (GetTime() < nNextTime)
1031 bool fFirst = (nNextTime == 0);
1032 nNextTime = GetTime() + GetRand(30 * 60);
1036 // Only do it if there's been a new block since last time
1037 static int64 nLastTime;
1038 if (nTimeBestReceived < nLastTime)
1040 nLastTime = GetTime();
1043 // Rebroadcast any of our txes that aren't in a block yet
1044 printf("ResendWalletTransactions()\n");
1047 // Sort them in chronological order
1048 multimap<unsigned int, CWalletTx*> mapSorted;
1049 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1051 CWalletTx& wtx = item.second;
1052 // Don't rebroadcast until it's had plenty of time that
1053 // it should have gotten in already by now.
1054 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1055 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1057 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1059 CWalletTx& wtx = *item.second;
1060 wtx.RelayWalletTransaction();
1070 //////////////////////////////////////////////////////////////////////////////
1076 int64 CWallet::GetBalance() const
1081 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1083 const CWalletTx* pcoin = &(*it).second;
1084 if (pcoin->IsTrusted())
1085 nTotal += pcoin->GetAvailableCredit();
1092 int64 CWallet::GetUnconfirmedBalance() const
1097 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1099 const CWalletTx* pcoin = &(*it).second;
1100 if (!pcoin->IsFinal() || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1101 nTotal += pcoin->GetAvailableCredit();
1107 int64 CWallet::GetImmatureBalance() const
1112 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1114 const CWalletTx& pcoin = (*it).second;
1115 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1116 nTotal += GetCredit(pcoin);
1122 // populate vCoins with vector of spendable COutputs
1123 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1129 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1131 const CWalletTx* pcoin = &(*it).second;
1133 if (!pcoin->IsFinal()) {
1137 if (fOnlyConfirmed && !pcoin->IsTrusted()) {
1141 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) {
1145 int nDepth = pcoin->GetDepthInMainChain();
1150 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) {
1154 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1155 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1156 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1157 vCoins.push_back(COutput(pcoin, i, nDepth));
1163 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1168 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1170 const CWalletTx* pcoin = &(*it).second;
1172 if (!pcoin->IsFinal())
1175 if(pcoin->GetDepthInMainChain() < nConf)
1178 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1179 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1180 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1185 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1186 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1188 vector<char> vfIncluded;
1190 vfBest.assign(vValue.size(), true);
1191 nBest = nTotalLower;
1193 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1195 vfIncluded.assign(vValue.size(), false);
1197 bool fReachedTarget = false;
1198 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1200 for (unsigned int i = 0; i < vValue.size(); i++)
1202 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1204 nTotal += vValue[i].first;
1205 vfIncluded[i] = true;
1206 if (nTotal >= nTargetValue)
1208 fReachedTarget = true;
1212 vfBest = vfIncluded;
1214 nTotal -= vValue[i].first;
1215 vfIncluded[i] = false;
1223 // ppcoin: total coins staked (non-spendable until maturity)
1224 int64 CWallet::GetStake() const
1228 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1230 const CWalletTx* pcoin = &(*it).second;
1231 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1232 nTotal += CWallet::GetCredit(*pcoin);
1237 int64 CWallet::GetNewMint() const
1241 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1243 const CWalletTx* pcoin = &(*it).second;
1244 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1245 nTotal += CWallet::GetCredit(*pcoin);
1250 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1252 setCoinsRet.clear();
1255 // List of values less than target
1256 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1257 coinLowestLarger.first = std::numeric_limits<int64>::max();
1258 coinLowestLarger.second.first = NULL;
1259 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1260 int64 nTotalLower = 0;
1262 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1264 BOOST_FOREACH(COutput output, vCoins)
1266 const CWalletTx *pcoin = output.tx;
1268 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1273 // Follow the timestamp rules
1274 if (pcoin->nTime > nSpendTime)
1277 int64 n = pcoin->vout[i].nValue;
1279 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1281 if (n == nTargetValue)
1283 setCoinsRet.insert(coin.second);
1284 nValueRet += coin.first;
1287 else if (n < nTargetValue + CENT)
1289 vValue.push_back(coin);
1292 else if (n < coinLowestLarger.first)
1294 coinLowestLarger = coin;
1298 if (nTotalLower == nTargetValue)
1300 for (unsigned int i = 0; i < vValue.size(); ++i)
1302 setCoinsRet.insert(vValue[i].second);
1303 nValueRet += vValue[i].first;
1308 if (nTotalLower < nTargetValue)
1310 if (coinLowestLarger.second.first == NULL)
1312 setCoinsRet.insert(coinLowestLarger.second);
1313 nValueRet += coinLowestLarger.first;
1317 // Solve subset sum by stochastic approximation
1318 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1319 vector<char> vfBest;
1322 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1323 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1324 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1326 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1327 // or the next bigger coin is closer), return the bigger coin
1328 if (coinLowestLarger.second.first &&
1329 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1331 setCoinsRet.insert(coinLowestLarger.second);
1332 nValueRet += coinLowestLarger.first;
1335 for (unsigned int i = 0; i < vValue.size(); i++)
1338 setCoinsRet.insert(vValue[i].second);
1339 nValueRet += vValue[i].first;
1342 if (fDebug && GetBoolArg("-printpriority"))
1345 printf("SelectCoins() best subset: ");
1346 for (unsigned int i = 0; i < vValue.size(); i++)
1348 printf("%s ", FormatMoney(vValue[i].first).c_str());
1349 printf("total %s\n", FormatMoney(nBest).c_str());
1356 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1358 vector<COutput> vCoins;
1359 AvailableCoins(vCoins, true, coinControl);
1361 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1362 if (coinControl && coinControl->HasSelected())
1364 BOOST_FOREACH(const COutput& out, vCoins)
1366 nValueRet += out.tx->vout[out.i].nValue;
1367 setCoinsRet.insert(make_pair(out.tx, out.i));
1369 return (nValueRet >= nTargetValue);
1372 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1373 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1374 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1377 // Select some coins without random shuffle or best subset approximation
1378 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1380 vector<COutput> vCoins;
1381 AvailableCoinsMinConf(vCoins, nMinConf);
1383 setCoinsRet.clear();
1386 BOOST_FOREACH(COutput output, vCoins)
1388 const CWalletTx *pcoin = output.tx;
1391 // Stop if we've chosen enough inputs
1392 if (nValueRet >= nTargetValue)
1395 // Follow the timestamp rules
1396 if (pcoin->nTime > nSpendTime)
1399 int64 n = pcoin->vout[i].nValue;
1401 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1403 if (n >= nTargetValue)
1405 // If input value is greater or equal to target then simply insert
1406 // it into the current subset and exit
1407 setCoinsRet.insert(coin.second);
1408 nValueRet += coin.first;
1411 else if (n < nTargetValue + CENT)
1413 setCoinsRet.insert(coin.second);
1414 nValueRet += coin.first;
1421 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1424 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1430 if (vecSend.empty() || nValue < 0)
1433 wtxNew.BindWallet(this);
1436 LOCK2(cs_main, cs_wallet);
1438 nFeeRet = nTransactionFee;
1442 wtxNew.vout.clear();
1443 wtxNew.fFromMe = true;
1445 int64 nTotalValue = nValue + nFeeRet;
1446 double dPriority = 0;
1447 // vouts to the payees
1448 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1449 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1451 // Choose coins to use
1452 set<pair<const CWalletTx*,unsigned int> > setCoins;
1454 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1456 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1458 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1459 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1462 int64 nChange = nValueIn - nValue - nFeeRet;
1464 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1465 // or until nChange becomes zero
1466 // NOTE: this depends on the exact behaviour of GetMinFee
1467 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1469 if (nFeeRet < CENT && nChange > 0 && nChange < CENT)
1471 int64 nMoveToFee = min(nChange, CENT - nFeeRet);
1472 nChange -= nMoveToFee;
1473 nFeeRet += nMoveToFee;
1476 // sub-cent change is moved to fee
1477 if (nChange > 0 && nChange < CENT)
1486 // Fill a vout to ourself
1487 // TODO: pass in scriptChange instead of reservekey so
1488 // change transaction isn't always pay-to-bitcoin-address
1489 CScript scriptChange;
1491 // coin control: send change to custom address
1492 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1493 scriptChange.SetDestination(coinControl->destChange);
1495 // no coin control: send change to newly generated address
1498 // Note: We use a new key here to keep it from being obvious which side is the change.
1499 // The drawback is that by not reusing a previous key, the change may be lost if a
1500 // backup is restored, if the backup doesn't have the new private key for the change.
1501 // If we reused the old key, it would be possible to add code to look for and
1502 // rediscover unknown transactions that were written with keys of ours to recover
1503 // post-backup change.
1505 // Reserve a new key pair from key pool
1506 CPubKey vchPubKey = reservekey.GetReservedKey();
1508 scriptChange.SetDestination(vchPubKey.GetID());
1511 // Insert change txn at random position:
1512 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1513 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1516 reservekey.ReturnKey();
1519 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1520 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1524 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1525 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1529 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1530 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1532 dPriority /= nBytes;
1534 // Check that enough fee is included
1535 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1536 bool fAllowFree = CTransaction::AllowFree(dPriority);
1538 // Disable free transactions until 1 July 2014
1539 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1544 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1545 if (nFeeRet < max(nPayFee, nMinFee))
1547 nFeeRet = max(nPayFee, nMinFee);
1551 // Fill vtxPrev by copying from previous transactions vtxPrev
1552 wtxNew.AddSupportingTransactions();
1553 wtxNew.fTimeReceivedIsTxTime = true;
1562 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1564 vector< pair<CScript, int64> > vecSend;
1565 vecSend.push_back(make_pair(scriptPubKey, nValue));
1566 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1569 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1571 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1573 // If time weight is lower or equal to zero then weight is zero.
1574 if (nTimeWeight <= 0)
1580 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1581 nWeight = bnCoinDayWeight.getuint64();
1585 // NovaCoin: get current stake weight
1586 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1588 // Choose coins to use
1589 int64 nBalance = GetBalance();
1590 int64 nReserveBalance = 0;
1592 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1594 error("GetStakeWeight : invalid reserve balance amount");
1598 if (nBalance <= nReserveBalance)
1601 vector<const CWalletTx*> vwtxPrev;
1602 set<pair<const CWalletTx*,unsigned int> > setCoins;
1605 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1608 if (setCoins.empty())
1611 CCoinsViewCache &view = *pcoinsTip;
1612 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1616 LOCK2(cs_main, cs_wallet);
1617 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1621 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1622 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1624 // Weight is greater than zero
1625 if (nTimeWeight > 0)
1627 nWeight += bnCoinDayWeight.getuint64();
1630 // Weight is greater than zero, but the maximum value isn't reached yet
1631 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1633 nMinWeight += bnCoinDayWeight.getuint64();
1636 // Maximum weight was reached
1637 if (nTimeWeight == nStakeMaxAge)
1639 nMaxWeight += bnCoinDayWeight.getuint64();
1646 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1648 // The following combine threshold is important to security
1649 // Should not be adjusted if you don't understand the consequences
1650 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1651 CBlockIndex* pindexPrev = pindexBest;
1652 CBigNum bnTargetPerCoinDay;
1653 bnTargetPerCoinDay.SetCompact(nBits);
1658 // Mark coin stake transaction
1659 CScript scriptEmpty;
1660 scriptEmpty.clear();
1661 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1663 // Choose coins to use
1664 int64 nBalance = GetBalance();
1665 int64 nReserveBalance = 0;
1667 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1668 return error("CreateCoinStake : invalid reserve balance amount");
1670 if (nBalance <= nReserveBalance)
1673 vector<const CWalletTx*> vwtxPrev;
1674 set<pair<const CWalletTx*,unsigned int> > setCoins;
1677 // Select coins with suitable depth
1678 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1681 if (setCoins.empty())
1685 CScript scriptPubKeyKernel;
1687 CCoinsViewCache &view = *pcoinsTip;
1688 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1692 LOCK2(cs_main, cs_wallet);
1693 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1697 static int nMaxStakeSearchInterval = 60;
1698 if (coins.nBlockTime + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1699 continue; // only count coins meeting min age requirement
1701 // Read block header
1703 unsigned int nTxPos = 0;
1705 LOCK2(cs_main, cs_wallet);
1706 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
1708 if (!block.ReadFromDisk(pindex))
1711 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1712 if (tx.GetHash() == pcoin.first->GetHash()) {
1715 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
1717 nTxPos += GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
1721 bool fFatal = false;
1722 bool fKernelFound = false;
1723 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown && pindexPrev == pindexBest; n++)
1725 // Search backward in time from the given txNew timestamp
1726 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1727 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1728 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1729 if (CheckStakeKernelHash(nBits, block, nTxPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fFatal, true))
1732 if (fDebug && GetBoolArg("-printcoinstake"))
1733 printf("CreateCoinStake : kernel found\n");
1734 vector<valtype> vSolutions;
1735 txnouttype whichType;
1736 CScript scriptPubKeyOut;
1737 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1738 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1740 if (fDebug && GetBoolArg("-printcoinstake"))
1741 printf("CreateCoinStake : failed to parse kernel\n");
1744 if (fDebug && GetBoolArg("-printcoinstake"))
1745 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1746 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1748 if (fDebug && GetBoolArg("-printcoinstake"))
1749 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1750 break; // only support pay to public key and pay to address
1752 if (whichType == TX_PUBKEYHASH) // pay to address type
1754 // convert to pay to public key type
1755 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1757 if (fDebug && GetBoolArg("-printcoinstake"))
1758 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1759 break; // unable to find corresponding public key
1761 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1763 if (whichType == TX_PUBKEY)
1765 valtype& vchPubKey = vSolutions[0];
1766 if (!keystore.GetKey(Hash160(vchPubKey), key))
1768 if (fDebug && GetBoolArg("-printcoinstake"))
1769 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1770 break; // unable to find corresponding public key
1773 if (key.GetPubKey() != vchPubKey)
1775 if (fDebug && GetBoolArg("-printcoinstake"))
1776 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1777 break; // keys mismatch
1780 scriptPubKeyOut = scriptPubKeyKernel;
1784 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1785 nCredit += pcoin.first->vout[pcoin.second].nValue;
1786 vwtxPrev.push_back(pcoin.first);
1787 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1789 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1790 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1791 if (fDebug && GetBoolArg("-printcoinstake"))
1792 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1793 fKernelFound = true;
1798 if (fKernelFound || fShutdown)
1799 break; // if kernel is found stop searching
1802 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1805 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1807 // Attempt to add more inputs
1808 // Only add coins of the same key/address as kernel
1809 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1810 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1812 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1814 // Stop adding more inputs if already too many inputs
1815 if (txNew.vin.size() >= 100)
1817 // Stop adding more inputs if value is already pretty significant
1818 if (nCredit > nCombineThreshold)
1820 // Stop adding inputs if reached reserve limit
1821 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1823 // Do not add additional significant input
1824 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1826 // Do not add input that is still too young
1827 if (nTimeWeight < nStakeMaxAge)
1830 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1831 nCredit += pcoin.first->vout[pcoin.second].nValue;
1832 vwtxPrev.push_back(pcoin.first);
1836 // Calculate coin age reward
1840 if (!txNew.GetCoinAge(nCoinAge))
1841 return error("CreateCoinStake : failed to calculate coin age");
1842 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1848 // Set output amount
1849 if (txNew.vout.size() == 3)
1851 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1852 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1855 txNew.vout[1].nValue = nCredit - nMinFee;
1859 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1861 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1862 return error("CreateCoinStake : failed to sign coinstake");
1866 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1867 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1868 return error("CreateCoinStake : exceeded coinstake size limit");
1870 // Check enough fee is paid
1871 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes, CENT) - CENT)
1873 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes, CENT) - CENT;
1874 continue; // try signing again
1878 if (fDebug && GetBoolArg("-printfee"))
1879 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1884 // Successfully generated coinstake
1889 // Call after CreateTransaction unless you want to abort
1890 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1893 LOCK2(cs_main, cs_wallet);
1894 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1896 // This is only to keep the database open to defeat the auto-flush for the
1897 // duration of this scope. This is the only place where this optimization
1898 // maybe makes sense; please don't do it anywhere else.
1899 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1901 // Take key pair from key pool so it won't be used again
1902 reservekey.KeepKey();
1904 // Add tx to wallet, because if it has change it's also ours,
1905 // otherwise just for transaction history.
1906 AddToWallet(wtxNew);
1908 // Mark old coins as spent
1909 set<CWalletTx*> setCoins;
1910 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1912 CWalletTx &coin = mapWallet[txin.prevout.hash];
1913 coin.BindWallet(this);
1914 coin.MarkSpent(txin.prevout.n);
1916 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1923 // Track how many getdata requests our transaction gets
1924 mapRequestCount[wtxNew.GetHash()] = 0;
1927 if (!wtxNew.AcceptToMemoryPool())
1929 // This must not fail. The transaction has already been signed and recorded.
1930 printf("CommitTransaction() : Error: Transaction not valid");
1933 wtxNew.RelayWalletTransaction();
1941 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1943 CReserveKey reservekey(this);
1948 string strError = _("Error: Wallet locked, unable to create transaction ");
1949 printf("SendMoney() : %s", strError.c_str());
1952 if (fWalletUnlockMintOnly)
1954 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1955 printf("SendMoney() : %s", strError.c_str());
1958 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1961 if (nValue + nFeeRequired > GetBalance())
1962 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());
1964 strError = _("Error: Transaction creation failed ");
1965 printf("SendMoney() : %s", strError.c_str());
1969 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1972 if (!CommitTransaction(wtxNew, reservekey))
1973 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.");
1980 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1984 return _("Invalid amount");
1985 if (nValue + nTransactionFee > GetBalance())
1986 return _("Insufficient funds");
1988 // Parse Bitcoin address
1989 CScript scriptPubKey;
1990 scriptPubKey.SetDestination(address);
1992 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1998 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2002 fFirstRunRet = false;
2003 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2004 if (nLoadWalletRet == DB_NEED_REWRITE)
2006 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2009 // Note: can't top-up keypool here, because wallet is locked.
2010 // User will be prompted to unlock wallet the next operation
2011 // the requires a new key.
2015 if (nLoadWalletRet != DB_LOAD_OK)
2016 return nLoadWalletRet;
2017 fFirstRunRet = !vchDefaultKey.IsValid();
2019 NewThread(ThreadFlushWalletDB, &strWalletFile);
2023 DBErrors CWallet::ZapWalletTx()
2027 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2028 if (nZapWalletTxRet == DB_NEED_REWRITE)
2030 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2034 // Note: can't top-up keypool here, because wallet is locked.
2035 // User will be prompted to unlock wallet the next operation
2036 // the requires a new key.
2040 if (nZapWalletTxRet != DB_LOAD_OK)
2041 return nZapWalletTxRet;
2046 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2048 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2049 mapAddressBook[address] = strName;
2050 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2053 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2056 bool CWallet::DelAddressBookName(const CTxDestination& address)
2058 mapAddressBook.erase(address);
2059 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2062 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2066 void CWallet::PrintWallet(const CBlock& block)
2070 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2072 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2073 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2075 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2077 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2078 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2085 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2089 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2090 if (mi != mapWallet.end())
2099 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2103 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2106 vchDefaultKey = vchPubKey;
2110 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2112 if (!pwallet->fFileBacked)
2114 strWalletFileOut = pwallet->strWalletFile;
2119 // Mark old keypool keys as used,
2120 // and generate all new keys
2122 bool CWallet::NewKeyPool()
2126 CWalletDB walletdb(strWalletFile);
2127 BOOST_FOREACH(int64 nIndex, setKeyPool)
2128 walletdb.ErasePool(nIndex);
2134 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2135 for (int i = 0; i < nKeys; i++)
2138 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2139 setKeyPool.insert(nIndex);
2141 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2146 bool CWallet::TopUpKeyPool(unsigned int nSize)
2154 CWalletDB walletdb(strWalletFile);
2157 unsigned int nTargetSize;
2159 nTargetSize = nSize;
2161 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2163 while (setKeyPool.size() < (nTargetSize + 1))
2166 if (!setKeyPool.empty())
2167 nEnd = *(--setKeyPool.end()) + 1;
2168 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2169 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2170 setKeyPool.insert(nEnd);
2171 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2177 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2180 keypool.vchPubKey = CPubKey();
2187 // Get the oldest key
2188 if(setKeyPool.empty())
2191 CWalletDB walletdb(strWalletFile);
2193 nIndex = *(setKeyPool.begin());
2194 setKeyPool.erase(setKeyPool.begin());
2195 if (!walletdb.ReadPool(nIndex, keypool))
2196 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2197 if (!HaveKey(keypool.vchPubKey.GetID()))
2198 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2199 assert(keypool.vchPubKey.IsValid());
2200 if (fDebug && GetBoolArg("-printkeypool"))
2201 printf("keypool reserve %"PRI64d"\n", nIndex);
2205 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2208 LOCK2(cs_main, cs_wallet);
2209 CWalletDB walletdb(strWalletFile);
2211 int64 nIndex = 1 + *(--setKeyPool.end());
2212 if (!walletdb.WritePool(nIndex, keypool))
2213 throw runtime_error("AddReserveKey() : writing added key failed");
2214 setKeyPool.insert(nIndex);
2220 void CWallet::KeepKey(int64 nIndex)
2222 // Remove from key pool
2225 CWalletDB walletdb(strWalletFile);
2226 walletdb.ErasePool(nIndex);
2229 printf("keypool keep %"PRI64d"\n", nIndex);
2232 void CWallet::ReturnKey(int64 nIndex)
2234 // Return to key pool
2237 setKeyPool.insert(nIndex);
2240 printf("keypool return %"PRI64d"\n", nIndex);
2243 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2249 ReserveKeyFromKeyPool(nIndex, keypool);
2252 if (fAllowReuse && vchDefaultKey.IsValid())
2254 result = vchDefaultKey;
2257 if (IsLocked()) return false;
2258 result = GenerateNewKey();
2262 result = keypool.vchPubKey;
2267 int64 CWallet::GetOldestKeyPoolTime()
2271 ReserveKeyFromKeyPool(nIndex, keypool);
2275 return keypool.nTime;
2278 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2280 map<CTxDestination, int64> balances;
2284 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2286 CWalletTx *pcoin = &walletEntry.second;
2288 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2291 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2294 int nDepth = pcoin->GetDepthInMainChain();
2295 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2298 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2300 CTxDestination addr;
2301 if (!IsMine(pcoin->vout[i]))
2303 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2306 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2308 if (!balances.count(addr))
2310 balances[addr] += n;
2318 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2320 set< set<CTxDestination> > groupings;
2321 set<CTxDestination> grouping;
2323 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2325 CWalletTx *pcoin = &walletEntry.second;
2327 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2329 // group all input addresses with each other
2330 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2332 CTxDestination address;
2333 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2335 grouping.insert(address);
2338 // group change with input addresses
2339 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2340 if (IsChange(txout))
2342 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2343 CTxDestination txoutAddr;
2344 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2346 grouping.insert(txoutAddr);
2348 groupings.insert(grouping);
2352 // group lone addrs by themselves
2353 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2354 if (IsMine(pcoin->vout[i]))
2356 CTxDestination address;
2357 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2359 grouping.insert(address);
2360 groupings.insert(grouping);
2365 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2366 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2367 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2369 // make a set of all the groups hit by this new group
2370 set< set<CTxDestination>* > hits;
2371 map< CTxDestination, set<CTxDestination>* >::iterator it;
2372 BOOST_FOREACH(CTxDestination address, grouping)
2373 if ((it = setmap.find(address)) != setmap.end())
2374 hits.insert((*it).second);
2376 // merge all hit groups into a new single group and delete old groups
2377 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2378 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2380 merged->insert(hit->begin(), hit->end());
2381 uniqueGroupings.erase(hit);
2384 uniqueGroupings.insert(merged);
2387 BOOST_FOREACH(CTxDestination element, *merged)
2388 setmap[element] = merged;
2391 set< set<CTxDestination> > ret;
2392 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2394 ret.insert(*uniqueGrouping);
2395 delete uniqueGrouping;
2401 // 1. check 'spent' consistency between wallet and coins database
2402 // 2. fix wallet spent state according to coins database
2403 // 3. remove orphaned coinstakes and coinbases from wallet
2404 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2407 nBalanceInQuestion = 0;
2410 vector<CWalletTx*> vCoins;
2411 vCoins.reserve(mapWallet.size());
2412 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2413 vCoins.push_back(&(*it).second);
2415 CCoinsViewCache &view = *pcoinsTip;
2416 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2418 uint256 hash = pcoin->GetHash();
2419 if(!view.HaveCoins(hash))
2422 // Find the corresponding transaction index
2423 CCoins &coins = view.GetCoins(hash);
2425 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2427 bool fUpdated = false;
2428 if (IsMine(pcoin->vout[n]))
2430 if (pcoin->IsSpent(n) && coins.IsAvailable(n))
2432 printf("FixSpentCoins found lost coin %snvc %s[%d], %s\n",
2433 FormatMoney(pcoin->vout[n].nValue).c_str(), hash.ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2435 nBalanceInQuestion += pcoin->vout[n].nValue;
2439 pcoin->MarkUnspent(n);
2440 pcoin->WriteToDisk();
2443 else if (!pcoin->IsSpent(n) && !coins.IsAvailable(n))
2445 printf("FixSpentCoins found spent coin %snvc %s[%d], %s\n",
2446 FormatMoney(pcoin->vout[n].nValue).c_str(), hash.ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2448 nBalanceInQuestion += pcoin->vout[n].nValue;
2452 pcoin->MarkSpent(n);
2453 pcoin->WriteToDisk();
2458 NotifyTransactionChanged(this, hash, CT_UPDATED);
2462 if((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2466 EraseFromWallet(hash);
2467 NotifyTransactionChanged(this, hash, CT_DELETED);
2470 printf("FixSpentCoins %s orphaned generation tx %s\n", fCheckOnly ? "found" : "removed", hash.ToString().c_str());
2475 // ppcoin: disable transaction (only for coinstake)
2476 void CWallet::DisableTransaction(const CTransaction &tx)
2478 if (!tx.IsCoinStake() || !IsFromMe(tx))
2479 return; // only disconnecting coinstake requires marking input unspent
2482 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2484 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2485 if (mi != mapWallet.end())
2487 CWalletTx& prev = (*mi).second;
2488 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2490 prev.MarkUnspent(txin.prevout.n);
2497 CPubKey CReserveKey::GetReservedKey()
2502 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2504 vchPubKey = keypool.vchPubKey;
2507 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2508 vchPubKey = pwallet->vchDefaultKey;
2511 assert(vchPubKey.IsValid());
2515 void CReserveKey::KeepKey()
2518 pwallet->KeepKey(nIndex);
2520 vchPubKey = CPubKey();
2523 void CReserveKey::ReturnKey()
2526 pwallet->ReturnKey(nIndex);
2528 vchPubKey = CPubKey();
2531 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2535 CWalletDB walletdb(strWalletFile);
2537 LOCK2(cs_main, cs_wallet);
2538 BOOST_FOREACH(const int64& id, setKeyPool)
2541 if (!walletdb.ReadPool(id, keypool))
2542 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2543 assert(keypool.vchPubKey.IsValid());
2544 CKeyID keyID = keypool.vchPubKey.GetID();
2545 if (!HaveKey(keyID))
2546 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2547 setAddress.insert(keyID);
2551 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2555 // Only notify UI if this transaction is in this wallet
2556 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2557 if (mi != mapWallet.end())
2558 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2562 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2563 mapKeyBirth.clear();
2565 // get birth times for keys with metadata
2566 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2567 if (it->second.nCreateTime)
2568 mapKeyBirth[it->first] = it->second.nCreateTime;
2570 // map in which we'll infer heights of other keys
2571 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2572 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2573 std::set<CKeyID> setKeys;
2575 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2576 if (mapKeyBirth.count(keyid) == 0)
2577 mapKeyFirstBlock[keyid] = pindexMax;
2581 // if there are no such keys, we're done
2582 if (mapKeyFirstBlock.empty())
2585 // find first block that affects those keys, if there are any left
2586 std::vector<CKeyID> vAffected;
2587 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2588 // iterate over all wallet transactions...
2589 const CWalletTx &wtx = (*it).second;
2590 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2591 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2592 // ... which are already in a block
2593 int nHeight = blit->second->nHeight;
2594 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2595 // iterate over all their outputs
2596 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2597 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2598 // ... and all their affected keys
2599 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2600 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2601 rit->second = blit->second;
2608 // Extract block timestamps for those keys
2609 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2610 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off