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 bool CWallet::AddWatchOnly(const CTxDestination &dest)
107 if (!CCryptoKeyStore::AddWatchOnly(dest))
109 nTimeFirstKey = 1; // No birthday information for watch-only keys.
112 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
115 bool CWallet::LoadWatchOnly(const CTxDestination &dest)
117 printf("Loaded %s!\n", CBitcoinAddress(dest).ToString().c_str());
118 return CCryptoKeyStore::AddWatchOnly(dest);
121 // ppcoin: optional setting to unlock wallet for block minting only;
122 // serves to disable the trivial sendmoney when OS account compromised
123 bool fWalletUnlockMintOnly = false;
125 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
131 CKeyingMaterial vMasterKey;
135 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
137 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
139 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
141 if (CCryptoKeyStore::Unlock(vMasterKey))
148 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
150 bool fWasLocked = IsLocked();
157 CKeyingMaterial vMasterKey;
158 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
160 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
162 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
164 if (CCryptoKeyStore::Unlock(vMasterKey))
166 int64 nStartTime = GetTimeMillis();
167 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
168 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
170 nStartTime = GetTimeMillis();
171 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
172 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
174 if (pMasterKey.second.nDeriveIterations < 25000)
175 pMasterKey.second.nDeriveIterations = 25000;
177 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
179 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
181 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
183 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
194 void CWallet::SetBestChain(const CBlockLocator& loc)
196 CWalletDB walletdb(strWalletFile);
197 walletdb.WriteBestBlock(loc);
200 // This class implements an addrIncoming entry that causes pre-0.4
201 // clients to crash on startup if reading a private-key-encrypted wallet.
202 class CCorruptAddress
207 if (nType & SER_DISK)
212 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
214 if (nWalletVersion >= nVersion)
217 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
218 if (fExplicit && nVersion > nWalletMaxVersion)
219 nVersion = FEATURE_LATEST;
221 nWalletVersion = nVersion;
223 if (nVersion > nWalletMaxVersion)
224 nWalletMaxVersion = nVersion;
228 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
229 if (nWalletVersion >= 40000)
231 // Versions prior to 0.4.0 did not support the "minversion" record.
232 // Use a CCorruptAddress to make them crash instead.
233 CCorruptAddress corruptAddress;
234 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
236 if (nWalletVersion > 40000)
237 pwalletdb->WriteMinVersion(nWalletVersion);
245 bool CWallet::SetMaxVersion(int nVersion)
247 // cannot downgrade below current version
248 if (nWalletVersion > nVersion)
251 nWalletMaxVersion = nVersion;
256 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
261 CKeyingMaterial vMasterKey;
262 RandAddSeedPerfmon();
264 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
265 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
267 CMasterKey kMasterKey(nDerivationMethodIndex);
269 RandAddSeedPerfmon();
270 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
271 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
274 int64 nStartTime = GetTimeMillis();
275 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
276 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
278 nStartTime = GetTimeMillis();
279 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
280 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
282 if (kMasterKey.nDeriveIterations < 25000)
283 kMasterKey.nDeriveIterations = 25000;
285 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
287 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
289 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
294 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
297 pwalletdbEncryption = new CWalletDB(strWalletFile);
298 if (!pwalletdbEncryption->TxnBegin())
300 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
303 if (!EncryptKeys(vMasterKey))
306 pwalletdbEncryption->TxnAbort();
307 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.
310 // Encryption was introduced in version 0.4.0
311 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
315 if (!pwalletdbEncryption->TxnCommit())
316 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.
318 delete pwalletdbEncryption;
319 pwalletdbEncryption = NULL;
323 Unlock(strWalletPassphrase);
327 // Need to completely rewrite the wallet file; if we don't, bdb might keep
328 // bits of the unencrypted private key in slack space in the database file.
329 CDB::Rewrite(strWalletFile);
332 NotifyStatusChanged(this);
337 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
339 int64 nRet = nOrderPosNext++;
341 pwalletdb->WriteOrderPosNext(nOrderPosNext);
343 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
348 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
350 CWalletDB walletdb(strWalletFile);
352 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
355 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
356 // would make this much faster for applications that do this a lot.
357 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
359 CWalletTx* wtx = &((*it).second);
360 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
363 walletdb.ListAccountCreditDebit(strAccount, acentries);
364 BOOST_FOREACH(CAccountingEntry& entry, acentries)
366 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
372 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
374 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
375 // Update the wallet spent flag if it doesn't know due to wallet.dat being
376 // restored from backup or the user making copies of wallet.dat.
379 BOOST_FOREACH(const CTxIn& txin, tx.vin)
381 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
382 if (mi != mapWallet.end())
384 CWalletTx& wtx = (*mi).second;
385 if (txin.prevout.n >= wtx.vout.size())
386 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
387 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
389 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(false)).c_str(), wtx.GetHash().ToString().c_str());
390 wtx.MarkSpent(txin.prevout.n);
392 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
399 uint256 hash = tx.GetHash();
400 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
401 CWalletTx& wtx = (*mi).second;
403 BOOST_FOREACH(const CTxOut& txout, tx.vout)
407 wtx.MarkUnspent(&txout - &tx.vout[0]);
409 NotifyTransactionChanged(this, hash, CT_UPDATED);
417 void CWallet::MarkDirty()
421 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
422 item.second.MarkDirty();
426 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
428 uint256 hash = wtxIn.GetHash();
431 // Inserts only if not already there, returns tx inserted or tx found
432 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
433 CWalletTx& wtx = (*ret.first).second;
434 wtx.BindWallet(this);
435 bool fInsertedNew = ret.second;
438 wtx.nTimeReceived = GetAdjustedTime();
439 wtx.nOrderPos = IncOrderPosNext();
441 wtx.nTimeSmart = wtx.nTimeReceived;
442 if (wtxIn.hashBlock != 0)
444 if (mapBlockIndex.count(wtxIn.hashBlock))
446 unsigned int latestNow = wtx.nTimeReceived;
447 unsigned int latestEntry = 0;
449 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
450 int64 latestTolerated = latestNow + 300;
451 std::list<CAccountingEntry> acentries;
452 TxItems txOrdered = OrderedTxItems(acentries);
453 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
455 CWalletTx *const pwtx = (*it).second.first;
458 CAccountingEntry *const pacentry = (*it).second.second;
462 nSmartTime = pwtx->nTimeSmart;
464 nSmartTime = pwtx->nTimeReceived;
467 nSmartTime = pacentry->nTime;
468 if (nSmartTime <= latestTolerated)
470 latestEntry = nSmartTime;
471 if (nSmartTime > latestNow)
472 latestNow = nSmartTime;
478 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
479 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
482 printf("AddToWallet() : found %s in block %s not in index\n",
483 wtxIn.GetHash().ToString().substr(0,10).c_str(),
484 wtxIn.hashBlock.ToString().c_str());
488 bool fUpdated = false;
492 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
494 wtx.hashBlock = wtxIn.hashBlock;
497 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
499 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
500 wtx.nIndex = wtxIn.nIndex;
503 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
505 wtx.fFromMe = wtxIn.fFromMe;
508 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
512 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
515 if (fInsertedNew || fUpdated)
516 if (!wtx.WriteToDisk())
519 // If default receiving address gets used, replace it with a new one
520 CScript scriptDefaultKey;
521 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
522 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
524 if (txout.scriptPubKey == scriptDefaultKey)
526 CPubKey newDefaultKey;
527 if (GetKeyFromPool(newDefaultKey, false))
529 SetDefaultKey(newDefaultKey);
530 SetAddressBookName(vchDefaultKey.GetID(), "");
535 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
536 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
538 // Notify UI of new or updated transaction
539 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
541 // notify an external script when a wallet transaction comes in or is updated
542 std::string strCmd = GetArg("-walletnotify", "");
544 if ( !strCmd.empty())
546 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
547 boost::thread t(runCommand, strCmd); // thread runs free
554 // Add a transaction to the wallet, or update it.
555 // pblock is optional, but should be provided if the transaction is known to be in a block.
556 // If fUpdate is true, existing transactions will be updated.
557 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
559 uint256 hash = tx.GetHash();
562 bool fExisted = mapWallet.count(hash);
563 if (fExisted && !fUpdate) return false;
564 if (fExisted || IsMine(tx) || IsFromMe(tx))
566 CWalletTx wtx(this,tx);
567 // Get merkle branch if transaction was found in a block
569 wtx.SetMerkleBranch(pblock);
570 return AddToWallet(wtx);
573 WalletUpdateSpent(tx);
578 bool CWallet::EraseFromWallet(uint256 hash)
584 if (mapWallet.erase(hash))
585 CWalletDB(strWalletFile).EraseTx(hash);
591 isminetype CWallet::IsMine(const CTxIn &txin) const
595 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
596 if (mi != mapWallet.end())
598 const CWalletTx& prev = (*mi).second;
599 if (txin.prevout.n < prev.vout.size())
600 return IsMine(prev.vout[txin.prevout.n]);
606 int64 CWallet::GetDebit(const CTxIn &txin) const
610 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
611 if (mi != mapWallet.end())
613 const CWalletTx& prev = (*mi).second;
614 if (txin.prevout.n < prev.vout.size())
615 if (IsMine(prev.vout[txin.prevout.n]))
616 return prev.vout[txin.prevout.n].nValue;
622 bool CWallet::IsChange(const CTxOut& txout) const
624 CTxDestination address;
626 // TODO: fix handling of 'change' outputs. The assumption is that any
627 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
628 // is change. That assumption is likely to break when we implement multisignature
629 // wallets that return change back into a multi-signature-protected address;
630 // a better way of identifying which outputs are 'the send' and which are
631 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
632 // which output, if any, was change).
633 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
636 if (!mapAddressBook.count(address))
642 int64 CWalletTx::GetTxTime() const
644 int64 n = nTimeSmart;
645 return n ? n : nTimeReceived;
648 int CWalletTx::GetRequestCount() const
650 // Returns -1 if it wasn't being tracked
653 LOCK(pwallet->cs_wallet);
654 if (IsCoinBase() || IsCoinStake())
659 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
660 if (mi != pwallet->mapRequestCount.end())
661 nRequests = (*mi).second;
666 // Did anyone request this transaction?
667 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
668 if (mi != pwallet->mapRequestCount.end())
670 nRequests = (*mi).second;
672 // How about the block it's in?
673 if (nRequests == 0 && hashBlock != 0)
675 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
676 if (mi != pwallet->mapRequestCount.end())
677 nRequests = (*mi).second;
679 nRequests = 1; // If it's in someone else's block it must have got out
687 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
688 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
690 nGeneratedImmature = nGeneratedMature = nFee = 0;
691 listReceived.clear();
693 strSentAccount = strFromAccount;
695 if (IsCoinBase() || IsCoinStake())
697 if (GetBlocksToMaturity() > 0)
698 nGeneratedImmature = pwallet->GetCredit(*this);
700 nGeneratedMature = GetCredit(false);
705 int64 nDebit = GetDebit();
706 if (nDebit > 0) // debit>0 means we signed/sent this transaction
708 int64 nValueOut = GetValueOut();
709 nFee = nDebit - nValueOut;
713 BOOST_FOREACH(const CTxOut& txout, vout)
716 // Only need to handle txouts if AT LEAST one of these is true:
717 // 1) they debit from us (sent)
718 // 2) the output is to us (received)
721 // Don't report 'change' txouts
722 if (pwallet->IsChange(txout))
724 fIsMine = pwallet->IsMine(txout);
726 else if (!(fIsMine = pwallet->IsMine(txout)))
729 // In either case, we need to get the destination address
730 CTxDestination address;
731 if (!ExtractDestination(txout.scriptPubKey, address))
733 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
734 this->GetHash().ToString().c_str());
735 address = CNoDestination();
738 // If we are debited by the transaction, add the output as a "sent" entry
740 listSent.push_back(make_pair(address, txout.nValue));
742 // If we are receiving the output, add it as a "received" entry
744 listReceived.push_back(make_pair(address, txout.nValue));
749 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
750 int64& nSent, int64& nFee) const
752 nGenerated = nReceived = nSent = nFee = 0;
754 int64 allGeneratedImmature, allGeneratedMature, allFee;
755 allGeneratedImmature = allGeneratedMature = allFee = 0;
756 string strSentAccount;
757 list<pair<CTxDestination, int64> > listReceived;
758 list<pair<CTxDestination, int64> > listSent;
759 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
761 if (strAccount == "")
762 nGenerated = allGeneratedMature;
763 if (strAccount == strSentAccount)
765 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
770 LOCK(pwallet->cs_wallet);
771 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
773 if (pwallet->mapAddressBook.count(r.first))
775 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
776 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
777 nReceived += r.second;
779 else if (strAccount.empty())
781 nReceived += r.second;
787 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
791 const int COPY_DEPTH = 3;
792 if (SetMerkleBranch() < COPY_DEPTH)
794 vector<uint256> vWorkQueue;
795 BOOST_FOREACH(const CTxIn& txin, vin)
796 vWorkQueue.push_back(txin.prevout.hash);
798 // This critsect is OK because txdb is already open
800 LOCK(pwallet->cs_wallet);
801 map<uint256, const CMerkleTx*> mapWalletPrev;
802 set<uint256> setAlreadyDone;
803 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
805 uint256 hash = vWorkQueue[i];
806 if (setAlreadyDone.count(hash))
808 setAlreadyDone.insert(hash);
811 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
812 if (mi != pwallet->mapWallet.end())
815 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
816 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
818 else if (mapWalletPrev.count(hash))
820 tx = *mapWalletPrev[hash];
822 else if (!fClient && txdb.ReadDiskTx(hash, tx))
828 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
832 int nDepth = tx.SetMerkleBranch();
833 vtxPrev.push_back(tx);
835 if (nDepth < COPY_DEPTH)
837 BOOST_FOREACH(const CTxIn& txin, tx.vin)
838 vWorkQueue.push_back(txin.prevout.hash);
844 reverse(vtxPrev.begin(), vtxPrev.end());
847 bool CWalletTx::WriteToDisk()
849 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
852 // Scan the block chain (starting in pindexStart) for transactions
853 // from or to us. If fUpdate is true, found transactions that already
854 // exist in the wallet will be updated.
855 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
859 CBlockIndex* pindex = pindexStart;
865 block.ReadFromDisk(pindex, true);
866 BOOST_FOREACH(CTransaction& tx, block.vtx)
868 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
871 pindex = pindex->pnext;
877 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
880 tx.ReadFromDisk(COutPoint(hashTx, 0));
881 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
886 void CWallet::ReacceptWalletTransactions()
894 vector<CDiskTxPos> vMissingTx;
895 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
897 CWalletTx& wtx = item.second;
898 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
902 bool fUpdated = false;
903 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
905 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
906 if (txindex.vSpent.size() != wtx.vout.size())
908 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
911 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
915 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
919 vMissingTx.push_back(txindex.vSpent[i]);
924 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(false)).c_str(), wtx.GetHash().ToString().c_str());
931 // Re-accept any txes of ours that aren't already in a block
932 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
933 wtx.AcceptWalletTransaction(txdb, false);
936 if (!vMissingTx.empty())
938 // TODO: optimize this to scan just part of the block chain?
939 if (ScanForWalletTransactions(pindexGenesisBlock))
940 fRepeat = true; // Found missing transactions: re-do re-accept.
945 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
947 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
949 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
951 uint256 hash = tx.GetHash();
952 if (!txdb.ContainsTx(hash))
953 RelayTransaction((CTransaction)tx, hash);
956 if (!(IsCoinBase() || IsCoinStake()))
958 uint256 hash = GetHash();
959 if (!txdb.ContainsTx(hash))
961 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
962 RelayTransaction((CTransaction)*this, hash);
967 void CWalletTx::RelayWalletTransaction()
970 RelayWalletTransaction(txdb);
973 void CWallet::ResendWalletTransactions()
975 // Do this infrequently and randomly to avoid giving away
976 // that these are our transactions.
977 static int64 nNextTime;
978 if (GetTime() < nNextTime)
980 bool fFirst = (nNextTime == 0);
981 nNextTime = GetTime() + GetRand(30 * 60);
985 // Only do it if there's been a new block since last time
986 static int64 nLastTime;
987 if (nTimeBestReceived < nLastTime)
989 nLastTime = GetTime();
991 // Rebroadcast any of our txes that aren't in a block yet
992 printf("ResendWalletTransactions()\n");
996 // Sort them in chronological order
997 multimap<unsigned int, CWalletTx*> mapSorted;
998 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1000 CWalletTx& wtx = item.second;
1001 // Don't rebroadcast until it's had plenty of time that
1002 // it should have gotten in already by now.
1003 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1004 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1006 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1008 CWalletTx& wtx = *item.second;
1009 if (wtx.CheckTransaction())
1010 wtx.RelayWalletTransaction(txdb);
1012 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1022 //////////////////////////////////////////////////////////////////////////////
1028 int64 CWallet::GetBalance() const
1033 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1035 const CWalletTx* pcoin = &(*it).second;
1036 if (pcoin->IsTrusted())
1037 nTotal += pcoin->GetAvailableCredit(false);
1044 void CWallet::GetBalance(int64 &nTotal, int64 &nWatchOnly) const
1048 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1050 const CWalletTx* pcoin = &(*it).second;
1051 if (pcoin->IsTrusted()) {
1052 nWatchOnly += pcoin->GetAvailableCredit(true);
1053 nTotal += pcoin->GetAvailableCredit(false);
1059 int64 CWallet::GetUnconfirmedBalance() const
1064 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1066 const CWalletTx* pcoin = &(*it).second;
1067 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1068 nTotal += pcoin->GetAvailableCredit(false);
1074 int64 CWallet::GetImmatureBalance() const
1079 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1081 const CWalletTx& pcoin = (*it).second;
1082 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1083 nTotal += GetCredit(pcoin);
1089 // populate vCoins with vector of spendable COutputs
1090 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1096 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1098 const CWalletTx* pcoin = &(*it).second;
1100 if (!pcoin->IsFinal())
1103 if (fOnlyConfirmed && !pcoin->IsTrusted())
1106 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1109 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1112 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1113 isminetype mine = IsMine(pcoin->vout[i]);
1114 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1115 pcoin->vout[i].nValue >= nMinimumInputValue &&
1116 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1118 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1125 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1131 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1133 const CWalletTx* pcoin = &(*it).second;
1135 if (!pcoin->IsFinal())
1138 if(pcoin->GetDepthInMainChain() < nConf)
1141 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1142 isminetype mine = IsMine(pcoin->vout[i]);
1144 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1145 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1151 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1152 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1154 vector<char> vfIncluded;
1156 vfBest.assign(vValue.size(), true);
1157 nBest = nTotalLower;
1159 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1161 vfIncluded.assign(vValue.size(), false);
1163 bool fReachedTarget = false;
1164 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1166 for (unsigned int i = 0; i < vValue.size(); i++)
1168 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1170 nTotal += vValue[i].first;
1171 vfIncluded[i] = true;
1172 if (nTotal >= nTargetValue)
1174 fReachedTarget = true;
1178 vfBest = vfIncluded;
1180 nTotal -= vValue[i].first;
1181 vfIncluded[i] = false;
1189 // ppcoin: total coins staked (non-spendable until maturity)
1190 int64 CWallet::GetStake() const
1194 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1196 const CWalletTx* pcoin = &(*it).second;
1197 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1198 nTotal += CWallet::GetCredit(*pcoin);
1203 int64 CWallet::GetNewMint() const
1207 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1209 const CWalletTx* pcoin = &(*it).second;
1210 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1211 nTotal += CWallet::GetCredit(*pcoin);
1216 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
1218 setCoinsRet.clear();
1221 // List of values less than target
1222 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1223 coinLowestLarger.first = std::numeric_limits<int64>::max();
1224 coinLowestLarger.second.first = NULL;
1225 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1226 int64 nTotalLower = 0;
1228 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1230 BOOST_FOREACH(const COutput &output, vCoins)
1232 if (!output.fSpendable)
1235 const CWalletTx *pcoin = output.tx;
1237 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1242 // Follow the timestamp rules
1243 if (pcoin->nTime > nSpendTime)
1246 int64 n = pcoin->vout[i].nValue;
1248 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1250 if (n == nTargetValue)
1252 setCoinsRet.insert(coin.second);
1253 nValueRet += coin.first;
1256 else if (n < nTargetValue + CENT)
1258 vValue.push_back(coin);
1261 else if (n < coinLowestLarger.first)
1263 coinLowestLarger = coin;
1267 if (nTotalLower == nTargetValue)
1269 for (unsigned int i = 0; i < vValue.size(); ++i)
1271 setCoinsRet.insert(vValue[i].second);
1272 nValueRet += vValue[i].first;
1277 if (nTotalLower < nTargetValue)
1279 if (coinLowestLarger.second.first == NULL)
1281 setCoinsRet.insert(coinLowestLarger.second);
1282 nValueRet += coinLowestLarger.first;
1286 // Solve subset sum by stochastic approximation
1287 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1288 vector<char> vfBest;
1291 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1292 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1293 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1295 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1296 // or the next bigger coin is closer), return the bigger coin
1297 if (coinLowestLarger.second.first &&
1298 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1300 setCoinsRet.insert(coinLowestLarger.second);
1301 nValueRet += coinLowestLarger.first;
1304 for (unsigned int i = 0; i < vValue.size(); i++)
1307 setCoinsRet.insert(vValue[i].second);
1308 nValueRet += vValue[i].first;
1311 if (fDebug && GetBoolArg("-printpriority"))
1314 printf("SelectCoins() best subset: ");
1315 for (unsigned int i = 0; i < vValue.size(); i++)
1317 printf("%s ", FormatMoney(vValue[i].first).c_str());
1318 printf("total %s\n", FormatMoney(nBest).c_str());
1325 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1327 vector<COutput> vCoins;
1328 AvailableCoins(vCoins, true, coinControl);
1330 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1331 if (coinControl && coinControl->HasSelected())
1333 BOOST_FOREACH(const COutput& out, vCoins)
1337 nValueRet += out.tx->vout[out.i].nValue;
1338 setCoinsRet.insert(make_pair(out.tx, out.i));
1340 return (nValueRet >= nTargetValue);
1343 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1344 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1345 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1348 // Select some coins without random shuffle or best subset approximation
1349 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1351 vector<COutput> vCoins;
1352 AvailableCoinsMinConf(vCoins, nMinConf);
1354 setCoinsRet.clear();
1357 BOOST_FOREACH(COutput output, vCoins)
1359 if(!output.fSpendable)
1361 const CWalletTx *pcoin = output.tx;
1364 // Stop if we've chosen enough inputs
1365 if (nValueRet >= nTargetValue)
1368 // Follow the timestamp rules
1369 if (pcoin->nTime > nSpendTime)
1372 int64 n = pcoin->vout[i].nValue;
1374 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1376 if (n >= nTargetValue)
1378 // If input value is greater or equal to target then simply insert
1379 // it into the current subset and exit
1380 setCoinsRet.insert(coin.second);
1381 nValueRet += coin.first;
1384 else if (n < nTargetValue + CENT)
1386 setCoinsRet.insert(coin.second);
1387 nValueRet += coin.first;
1394 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1397 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1403 if (vecSend.empty() || nValue < 0)
1406 wtxNew.BindWallet(this);
1409 LOCK2(cs_main, cs_wallet);
1410 // txdb must be opened before the mapWallet lock
1413 nFeeRet = nTransactionFee;
1417 wtxNew.vout.clear();
1418 wtxNew.fFromMe = true;
1420 int64 nTotalValue = nValue + nFeeRet;
1421 double dPriority = 0;
1422 // vouts to the payees
1423 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1424 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1426 // Choose coins to use
1427 set<pair<const CWalletTx*,unsigned int> > setCoins;
1429 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1431 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1433 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1434 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1437 int64 nChange = nValueIn - nValue - nFeeRet;
1438 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1439 // or until nChange becomes zero
1440 // NOTE: this depends on the exact behaviour of GetMinFee
1441 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1443 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1445 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1446 nChange -= nMoveToFee;
1447 nFeeRet += nMoveToFee;
1450 // sub-cent change is moved to fee
1451 if (nChange > 0 && nChange < CENT)
1460 // Fill a vout to ourself
1461 // TODO: pass in scriptChange instead of reservekey so
1462 // change transaction isn't always pay-to-bitcoin-address
1463 CScript scriptChange;
1465 // coin control: send change to custom address
1466 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1467 scriptChange.SetDestination(coinControl->destChange);
1469 // no coin control: send change to newly generated address
1472 // Note: We use a new key here to keep it from being obvious which side is the change.
1473 // The drawback is that by not reusing a previous key, the change may be lost if a
1474 // backup is restored, if the backup doesn't have the new private key for the change.
1475 // If we reused the old key, it would be possible to add code to look for and
1476 // rediscover unknown transactions that were written with keys of ours to recover
1477 // post-backup change.
1479 // Reserve a new key pair from key pool
1480 CPubKey vchPubKey = reservekey.GetReservedKey();
1482 scriptChange.SetDestination(vchPubKey.GetID());
1485 // Insert change txn at random position:
1486 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1487 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1490 reservekey.ReturnKey();
1493 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1494 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1498 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1499 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1503 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1504 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1506 dPriority /= nBytes;
1508 // Check that enough fee is included
1509 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1510 bool fAllowFree = CTransaction::AllowFree(dPriority);
1512 // Disable free transactions until 1 July 2014
1513 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1518 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1520 if (nFeeRet < max(nPayFee, nMinFee))
1522 nFeeRet = max(nPayFee, nMinFee);
1526 // Fill vtxPrev by copying from previous transactions vtxPrev
1527 wtxNew.AddSupportingTransactions(txdb);
1528 wtxNew.fTimeReceivedIsTxTime = true;
1537 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1539 vector< pair<CScript, int64> > vecSend;
1540 vecSend.push_back(make_pair(scriptPubKey, nValue));
1541 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1544 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1546 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1548 // If time weight is lower or equal to zero then weight is zero.
1549 if (nTimeWeight <= 0)
1555 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1556 nWeight = bnCoinDayWeight.getuint64();
1560 // NovaCoin: get current stake weight
1561 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1563 // Choose coins to use
1564 int64 nBalance = GetBalance();
1565 int64 nReserveBalance = 0;
1567 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1569 error("GetStakeWeight : invalid reserve balance amount");
1573 if (nBalance <= nReserveBalance)
1576 vector<const CWalletTx*> vwtxPrev;
1579 * TODO: performance comparison
1581 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1582 static uint256 hashPrevBlock;
1583 static int64 nValueIn = 0;
1585 // Cache outputs unless best block changed
1586 if (hashPrevBlock != pindexBest->GetBlockHash())
1588 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1591 if (setCoins.empty())
1594 hashPrevBlock == pindexBest->GetBlockHash();
1598 set<pair<const CWalletTx*,unsigned int> > setCoins;
1601 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1604 if (setCoins.empty())
1608 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1612 LOCK2(cs_main, cs_wallet);
1613 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1617 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1618 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1620 // Weight is greater than zero
1621 if (nTimeWeight > 0)
1623 nWeight += bnCoinDayWeight.getuint64();
1626 // Weight is greater than zero, but the maximum value isn't reached yet
1627 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1629 nMinWeight += bnCoinDayWeight.getuint64();
1632 // Maximum weight was reached
1633 if (nTimeWeight == nStakeMaxAge)
1635 nMaxWeight += bnCoinDayWeight.getuint64();
1642 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1644 // The following combine threshold is important to security
1645 // Should not be adjusted if you don't understand the consequences
1646 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1648 CBigNum bnTargetPerCoinDay;
1649 bnTargetPerCoinDay.SetCompact(nBits);
1654 // Mark coin stake transaction
1655 CScript scriptEmpty;
1656 scriptEmpty.clear();
1657 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1659 // Choose coins to use
1660 int64 nBalance = GetBalance();
1661 int64 nReserveBalance = 0;
1663 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1664 return error("CreateCoinStake : invalid reserve balance amount");
1666 if (nBalance <= nReserveBalance)
1669 vector<const CWalletTx*> vwtxPrev;
1672 * TODO: performance comparison
1674 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1675 static uint256 hashPrevBlock;
1676 static int64 nValueIn = 0;
1678 // Cache outputs unless best block changed
1679 if (hashPrevBlock != pindexBest->GetBlockHash())
1681 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1684 if (setCoins.empty())
1687 hashPrevBlock == pindexBest->GetBlockHash();
1691 set<pair<const CWalletTx*,unsigned int> > setCoins;
1694 // Select coins with suitable depth
1695 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1698 if (setCoins.empty())
1702 CScript scriptPubKeyKernel;
1704 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1708 LOCK2(cs_main, cs_wallet);
1709 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1713 // Read block header
1716 LOCK2(cs_main, cs_wallet);
1717 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1721 static int nMaxStakeSearchInterval = 60;
1722 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1723 continue; // only count coins meeting min age requirement
1725 bool fKernelFound = false;
1726 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1728 // Search backward in time from the given txNew timestamp
1729 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1730 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1731 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1732 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1735 if (fDebug && GetBoolArg("-printcoinstake"))
1736 printf("CreateCoinStake : kernel found\n");
1737 vector<valtype> vSolutions;
1738 txnouttype whichType;
1739 CScript scriptPubKeyOut;
1740 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1741 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1743 if (fDebug && GetBoolArg("-printcoinstake"))
1744 printf("CreateCoinStake : failed to parse kernel\n");
1747 if (fDebug && GetBoolArg("-printcoinstake"))
1748 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1749 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1751 if (fDebug && GetBoolArg("-printcoinstake"))
1752 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1753 break; // only support pay to public key and pay to address
1755 if (whichType == TX_PUBKEYHASH) // pay to address type
1757 // convert to pay to public key type
1758 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1760 if (fDebug && GetBoolArg("-printcoinstake"))
1761 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1762 break; // unable to find corresponding public key
1764 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1766 if (whichType == TX_PUBKEY)
1768 valtype& vchPubKey = vSolutions[0];
1769 if (!keystore.GetKey(Hash160(vchPubKey), key))
1771 if (fDebug && GetBoolArg("-printcoinstake"))
1772 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1773 break; // unable to find corresponding public key
1776 if (key.GetPubKey() != vchPubKey)
1778 if (fDebug && GetBoolArg("-printcoinstake"))
1779 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1780 break; // keys mismatch
1783 scriptPubKeyOut = scriptPubKeyKernel;
1787 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1788 nCredit += pcoin.first->vout[pcoin.second].nValue;
1789 vwtxPrev.push_back(pcoin.first);
1790 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1792 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1793 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1794 if (fDebug && GetBoolArg("-printcoinstake"))
1795 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1796 fKernelFound = true;
1801 if (fKernelFound || fShutdown)
1802 break; // if kernel is found stop searching
1805 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1808 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1810 // Attempt to add more inputs
1811 // Only add coins of the same key/address as kernel
1812 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1813 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1815 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1817 // Stop adding more inputs if already too many inputs
1818 if (txNew.vin.size() >= 100)
1820 // Stop adding more inputs if value is already pretty significant
1821 if (nCredit > nCombineThreshold)
1823 // Stop adding inputs if reached reserve limit
1824 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1826 // Do not add additional significant input
1827 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1829 // Do not add input that is still too young
1830 if (nTimeWeight < nStakeMaxAge)
1833 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1834 nCredit += pcoin.first->vout[pcoin.second].nValue;
1835 vwtxPrev.push_back(pcoin.first);
1839 // Calculate coin age reward
1843 if (!txNew.GetCoinAge(txdb, nCoinAge))
1844 return error("CreateCoinStake : failed to calculate coin age");
1845 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1851 // Set output amount
1852 if (txNew.vout.size() == 3)
1854 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1855 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1858 txNew.vout[1].nValue = nCredit - nMinFee;
1862 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1864 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1865 return error("CreateCoinStake : failed to sign coinstake");
1869 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1870 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1871 return error("CreateCoinStake : exceeded coinstake size limit");
1873 // Check enough fee is paid
1874 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1876 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1877 continue; // try signing again
1881 if (fDebug && GetBoolArg("-printfee"))
1882 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1887 // Successfully generated coinstake
1892 // Call after CreateTransaction unless you want to abort
1893 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1896 LOCK2(cs_main, cs_wallet);
1897 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1899 // This is only to keep the database open to defeat the auto-flush for the
1900 // duration of this scope. This is the only place where this optimization
1901 // maybe makes sense; please don't do it anywhere else.
1902 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1904 // Take key pair from key pool so it won't be used again
1905 reservekey.KeepKey();
1907 // Add tx to wallet, because if it has change it's also ours,
1908 // otherwise just for transaction history.
1909 AddToWallet(wtxNew);
1911 // Mark old coins as spent
1912 set<CWalletTx*> setCoins;
1913 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1915 CWalletTx &coin = mapWallet[txin.prevout.hash];
1916 coin.BindWallet(this);
1917 coin.MarkSpent(txin.prevout.n);
1919 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1926 // Track how many getdata requests our transaction gets
1927 mapRequestCount[wtxNew.GetHash()] = 0;
1930 if (!wtxNew.AcceptToMemoryPool())
1932 // This must not fail. The transaction has already been signed and recorded.
1933 printf("CommitTransaction() : Error: Transaction not valid");
1936 wtxNew.RelayWalletTransaction();
1944 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1946 CReserveKey reservekey(this);
1951 string strError = _("Error: Wallet locked, unable to create transaction ");
1952 printf("SendMoney() : %s", strError.c_str());
1955 if (fWalletUnlockMintOnly)
1957 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1958 printf("SendMoney() : %s", strError.c_str());
1961 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1964 if (nValue + nFeeRequired > GetBalance())
1965 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());
1967 strError = _("Error: Transaction creation failed ");
1968 printf("SendMoney() : %s", strError.c_str());
1972 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1975 if (!CommitTransaction(wtxNew, reservekey))
1976 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.");
1983 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1987 return _("Invalid amount");
1988 if (nValue + nTransactionFee > GetBalance())
1989 return _("Insufficient funds");
1991 // Parse Bitcoin address
1992 CScript scriptPubKey;
1993 scriptPubKey.SetDestination(address);
1995 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2001 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2005 fFirstRunRet = false;
2006 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2007 if (nLoadWalletRet == DB_NEED_REWRITE)
2009 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2012 // Note: can't top-up keypool here, because wallet is locked.
2013 // User will be prompted to unlock wallet the next operation
2014 // the requires a new key.
2018 if (nLoadWalletRet != DB_LOAD_OK)
2019 return nLoadWalletRet;
2020 fFirstRunRet = !vchDefaultKey.IsValid();
2022 NewThread(ThreadFlushWalletDB, &strWalletFile);
2027 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2029 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2030 mapAddressBook[address] = strName;
2031 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2034 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2037 bool CWallet::DelAddressBookName(const CTxDestination& address)
2039 mapAddressBook.erase(address);
2040 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2043 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2047 void CWallet::PrintWallet(const CBlock& block)
2051 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2053 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2054 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(false));
2056 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2058 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2059 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(false));
2066 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2070 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2071 if (mi != mapWallet.end())
2080 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2084 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2087 vchDefaultKey = vchPubKey;
2091 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2093 if (!pwallet->fFileBacked)
2095 strWalletFileOut = pwallet->strWalletFile;
2100 // Mark old keypool keys as used,
2101 // and generate all new keys
2103 bool CWallet::NewKeyPool()
2107 CWalletDB walletdb(strWalletFile);
2108 BOOST_FOREACH(int64 nIndex, setKeyPool)
2109 walletdb.ErasePool(nIndex);
2115 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2116 for (int i = 0; i < nKeys; i++)
2119 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2120 setKeyPool.insert(nIndex);
2122 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2127 bool CWallet::TopUpKeyPool(unsigned int nSize)
2135 CWalletDB walletdb(strWalletFile);
2138 unsigned int nTargetSize;
2140 nTargetSize = nSize;
2142 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2144 while (setKeyPool.size() < (nTargetSize + 1))
2147 if (!setKeyPool.empty())
2148 nEnd = *(--setKeyPool.end()) + 1;
2149 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2150 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2151 setKeyPool.insert(nEnd);
2152 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2158 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2161 keypool.vchPubKey = CPubKey();
2168 // Get the oldest key
2169 if(setKeyPool.empty())
2172 CWalletDB walletdb(strWalletFile);
2174 nIndex = *(setKeyPool.begin());
2175 setKeyPool.erase(setKeyPool.begin());
2176 if (!walletdb.ReadPool(nIndex, keypool))
2177 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2178 if (!HaveKey(keypool.vchPubKey.GetID()))
2179 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2180 assert(keypool.vchPubKey.IsValid());
2181 if (fDebug && GetBoolArg("-printkeypool"))
2182 printf("keypool reserve %"PRI64d"\n", nIndex);
2186 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2189 LOCK2(cs_main, cs_wallet);
2190 CWalletDB walletdb(strWalletFile);
2192 int64 nIndex = 1 + *(--setKeyPool.end());
2193 if (!walletdb.WritePool(nIndex, keypool))
2194 throw runtime_error("AddReserveKey() : writing added key failed");
2195 setKeyPool.insert(nIndex);
2201 void CWallet::KeepKey(int64 nIndex)
2203 // Remove from key pool
2206 CWalletDB walletdb(strWalletFile);
2207 walletdb.ErasePool(nIndex);
2210 printf("keypool keep %"PRI64d"\n", nIndex);
2213 void CWallet::ReturnKey(int64 nIndex)
2215 // Return to key pool
2218 setKeyPool.insert(nIndex);
2221 printf("keypool return %"PRI64d"\n", nIndex);
2224 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2230 ReserveKeyFromKeyPool(nIndex, keypool);
2233 if (fAllowReuse && vchDefaultKey.IsValid())
2235 result = vchDefaultKey;
2238 if (IsLocked()) return false;
2239 result = GenerateNewKey();
2243 result = keypool.vchPubKey;
2248 int64 CWallet::GetOldestKeyPoolTime()
2252 ReserveKeyFromKeyPool(nIndex, keypool);
2256 return keypool.nTime;
2259 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2261 map<CTxDestination, int64> balances;
2265 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2267 CWalletTx *pcoin = &walletEntry.second;
2269 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2272 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2275 int nDepth = pcoin->GetDepthInMainChain();
2276 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2279 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2281 CTxDestination addr;
2282 if (!IsMine(pcoin->vout[i]))
2284 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2287 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2289 if (!balances.count(addr))
2291 balances[addr] += n;
2299 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2301 set< set<CTxDestination> > groupings;
2302 set<CTxDestination> grouping;
2304 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2306 CWalletTx *pcoin = &walletEntry.second;
2308 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2310 // group all input addresses with each other
2311 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2313 CTxDestination address;
2314 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2316 grouping.insert(address);
2319 // group change with input addresses
2320 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2321 if (IsChange(txout))
2323 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2324 CTxDestination txoutAddr;
2325 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2327 grouping.insert(txoutAddr);
2329 groupings.insert(grouping);
2333 // group lone addrs by themselves
2334 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2335 if (IsMine(pcoin->vout[i]))
2337 CTxDestination address;
2338 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2340 grouping.insert(address);
2341 groupings.insert(grouping);
2346 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2347 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2348 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2350 // make a set of all the groups hit by this new group
2351 set< set<CTxDestination>* > hits;
2352 map< CTxDestination, set<CTxDestination>* >::iterator it;
2353 BOOST_FOREACH(CTxDestination address, grouping)
2354 if ((it = setmap.find(address)) != setmap.end())
2355 hits.insert((*it).second);
2357 // merge all hit groups into a new single group and delete old groups
2358 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2359 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2361 merged->insert(hit->begin(), hit->end());
2362 uniqueGroupings.erase(hit);
2365 uniqueGroupings.insert(merged);
2368 BOOST_FOREACH(CTxDestination element, *merged)
2369 setmap[element] = merged;
2372 set< set<CTxDestination> > ret;
2373 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2375 ret.insert(*uniqueGrouping);
2376 delete uniqueGrouping;
2382 // ppcoin: check 'spent' consistency between wallet and txindex
2383 // ppcoin: fix wallet spent state according to txindex
2384 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2387 nBalanceInQuestion = 0;
2390 vector<CWalletTx*> vCoins;
2391 vCoins.reserve(mapWallet.size());
2392 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2393 vCoins.push_back(&(*it).second);
2396 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2398 // Find the corresponding transaction index
2400 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2402 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2404 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2406 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2407 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2409 nBalanceInQuestion += pcoin->vout[n].nValue;
2412 pcoin->MarkUnspent(n);
2413 pcoin->WriteToDisk();
2416 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2418 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2419 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2421 nBalanceInQuestion += pcoin->vout[n].nValue;
2424 pcoin->MarkSpent(n);
2425 pcoin->WriteToDisk();
2431 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2433 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2436 EraseFromWallet(pcoin->GetHash());
2442 // ppcoin: disable transaction (only for coinstake)
2443 void CWallet::DisableTransaction(const CTransaction &tx)
2445 if (!tx.IsCoinStake() || !IsFromMe(tx))
2446 return; // only disconnecting coinstake requires marking input unspent
2449 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2451 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2452 if (mi != mapWallet.end())
2454 CWalletTx& prev = (*mi).second;
2455 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2457 prev.MarkUnspent(txin.prevout.n);
2464 CPubKey CReserveKey::GetReservedKey()
2469 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2471 vchPubKey = keypool.vchPubKey;
2474 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2475 vchPubKey = pwallet->vchDefaultKey;
2478 assert(vchPubKey.IsValid());
2482 void CReserveKey::KeepKey()
2485 pwallet->KeepKey(nIndex);
2487 vchPubKey = CPubKey();
2490 void CReserveKey::ReturnKey()
2493 pwallet->ReturnKey(nIndex);
2495 vchPubKey = CPubKey();
2498 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2502 CWalletDB walletdb(strWalletFile);
2504 LOCK2(cs_main, cs_wallet);
2505 BOOST_FOREACH(const int64& id, setKeyPool)
2508 if (!walletdb.ReadPool(id, keypool))
2509 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2510 assert(keypool.vchPubKey.IsValid());
2511 CKeyID keyID = keypool.vchPubKey.GetID();
2512 if (!HaveKey(keyID))
2513 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2514 setAddress.insert(keyID);
2518 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2522 // Only notify UI if this transaction is in this wallet
2523 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2524 if (mi != mapWallet.end())
2525 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2529 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2530 mapKeyBirth.clear();
2532 // get birth times for keys with metadata
2533 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2534 if (it->second.nCreateTime)
2535 mapKeyBirth[it->first] = it->second.nCreateTime;
2537 // map in which we'll infer heights of other keys
2538 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2539 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2540 std::set<CKeyID> setKeys;
2542 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2543 if (mapKeyBirth.count(keyid) == 0)
2544 mapKeyFirstBlock[keyid] = pindexMax;
2548 // if there are no such keys, we're done
2549 if (mapKeyFirstBlock.empty())
2552 // find first block that affects those keys, if there are any left
2553 std::vector<CKeyID> vAffected;
2554 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2555 // iterate over all wallet transactions...
2556 const CWalletTx &wtx = (*it).second;
2557 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2558 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2559 // ... which are already in a block
2560 int nHeight = blit->second->nHeight;
2561 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2562 // iterate over all their outputs
2563 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2564 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2565 // ... and all their affected keys
2566 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2567 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2568 rit->second = blit->second;
2575 // Extract block timestamps for those keys
2576 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2577 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off