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()).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();
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()).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();
1044 int64 CWallet::GetUnconfirmedBalance() const
1049 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1051 const CWalletTx* pcoin = &(*it).second;
1052 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1053 nTotal += pcoin->GetAvailableCredit();
1059 int64 CWallet::GetImmatureBalance() const
1064 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1066 const CWalletTx& pcoin = (*it).second;
1067 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1068 nTotal += GetCredit(pcoin);
1074 // populate vCoins with vector of spendable COutputs
1075 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1081 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1083 const CWalletTx* pcoin = &(*it).second;
1085 if (!pcoin->IsFinal())
1088 if (fOnlyConfirmed && !pcoin->IsTrusted())
1091 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1094 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1097 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1098 isminetype mine = IsMine(pcoin->vout[i]);
1099 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1100 pcoin->vout[i].nValue >= nMinimumInputValue &&
1101 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1103 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1110 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1116 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1118 const CWalletTx* pcoin = &(*it).second;
1120 if (!pcoin->IsFinal())
1123 if(pcoin->GetDepthInMainChain() < nConf)
1126 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1127 isminetype mine = IsMine(pcoin->vout[i]);
1129 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1130 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1136 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1137 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1139 vector<char> vfIncluded;
1141 vfBest.assign(vValue.size(), true);
1142 nBest = nTotalLower;
1144 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1146 vfIncluded.assign(vValue.size(), false);
1148 bool fReachedTarget = false;
1149 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1151 for (unsigned int i = 0; i < vValue.size(); i++)
1153 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1155 nTotal += vValue[i].first;
1156 vfIncluded[i] = true;
1157 if (nTotal >= nTargetValue)
1159 fReachedTarget = true;
1163 vfBest = vfIncluded;
1165 nTotal -= vValue[i].first;
1166 vfIncluded[i] = false;
1174 // ppcoin: total coins staked (non-spendable until maturity)
1175 int64 CWallet::GetStake() const
1179 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1181 const CWalletTx* pcoin = &(*it).second;
1182 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1183 nTotal += CWallet::GetCredit(*pcoin);
1188 int64 CWallet::GetNewMint() const
1192 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1194 const CWalletTx* pcoin = &(*it).second;
1195 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1196 nTotal += CWallet::GetCredit(*pcoin);
1201 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
1203 setCoinsRet.clear();
1206 // List of values less than target
1207 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1208 coinLowestLarger.first = std::numeric_limits<int64>::max();
1209 coinLowestLarger.second.first = NULL;
1210 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1211 int64 nTotalLower = 0;
1213 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1215 BOOST_FOREACH(const COutput &output, vCoins)
1217 if (!output.fSpendable)
1220 const CWalletTx *pcoin = output.tx;
1222 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1227 // Follow the timestamp rules
1228 if (pcoin->nTime > nSpendTime)
1231 int64 n = pcoin->vout[i].nValue;
1233 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1235 if (n == nTargetValue)
1237 setCoinsRet.insert(coin.second);
1238 nValueRet += coin.first;
1241 else if (n < nTargetValue + CENT)
1243 vValue.push_back(coin);
1246 else if (n < coinLowestLarger.first)
1248 coinLowestLarger = coin;
1252 if (nTotalLower == nTargetValue)
1254 for (unsigned int i = 0; i < vValue.size(); ++i)
1256 setCoinsRet.insert(vValue[i].second);
1257 nValueRet += vValue[i].first;
1262 if (nTotalLower < nTargetValue)
1264 if (coinLowestLarger.second.first == NULL)
1266 setCoinsRet.insert(coinLowestLarger.second);
1267 nValueRet += coinLowestLarger.first;
1271 // Solve subset sum by stochastic approximation
1272 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1273 vector<char> vfBest;
1276 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1277 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1278 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1280 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1281 // or the next bigger coin is closer), return the bigger coin
1282 if (coinLowestLarger.second.first &&
1283 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1285 setCoinsRet.insert(coinLowestLarger.second);
1286 nValueRet += coinLowestLarger.first;
1289 for (unsigned int i = 0; i < vValue.size(); i++)
1292 setCoinsRet.insert(vValue[i].second);
1293 nValueRet += vValue[i].first;
1296 if (fDebug && GetBoolArg("-printpriority"))
1299 printf("SelectCoins() best subset: ");
1300 for (unsigned int i = 0; i < vValue.size(); i++)
1302 printf("%s ", FormatMoney(vValue[i].first).c_str());
1303 printf("total %s\n", FormatMoney(nBest).c_str());
1310 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1312 vector<COutput> vCoins;
1313 AvailableCoins(vCoins, true, coinControl);
1315 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1316 if (coinControl && coinControl->HasSelected())
1318 BOOST_FOREACH(const COutput& out, vCoins)
1322 nValueRet += out.tx->vout[out.i].nValue;
1323 setCoinsRet.insert(make_pair(out.tx, out.i));
1325 return (nValueRet >= nTargetValue);
1328 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1329 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1330 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1333 // Select some coins without random shuffle or best subset approximation
1334 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1336 vector<COutput> vCoins;
1337 AvailableCoinsMinConf(vCoins, nMinConf);
1339 setCoinsRet.clear();
1342 BOOST_FOREACH(COutput output, vCoins)
1344 if(!output.fSpendable)
1346 const CWalletTx *pcoin = output.tx;
1349 // Stop if we've chosen enough inputs
1350 if (nValueRet >= nTargetValue)
1353 // Follow the timestamp rules
1354 if (pcoin->nTime > nSpendTime)
1357 int64 n = pcoin->vout[i].nValue;
1359 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1361 if (n >= nTargetValue)
1363 // If input value is greater or equal to target then simply insert
1364 // it into the current subset and exit
1365 setCoinsRet.insert(coin.second);
1366 nValueRet += coin.first;
1369 else if (n < nTargetValue + CENT)
1371 setCoinsRet.insert(coin.second);
1372 nValueRet += coin.first;
1379 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1382 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1388 if (vecSend.empty() || nValue < 0)
1391 wtxNew.BindWallet(this);
1394 LOCK2(cs_main, cs_wallet);
1395 // txdb must be opened before the mapWallet lock
1398 nFeeRet = nTransactionFee;
1402 wtxNew.vout.clear();
1403 wtxNew.fFromMe = true;
1405 int64 nTotalValue = nValue + nFeeRet;
1406 double dPriority = 0;
1407 // vouts to the payees
1408 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1409 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1411 // Choose coins to use
1412 set<pair<const CWalletTx*,unsigned int> > setCoins;
1414 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1416 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1418 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1419 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1422 int64 nChange = nValueIn - nValue - nFeeRet;
1423 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1424 // or until nChange becomes zero
1425 // NOTE: this depends on the exact behaviour of GetMinFee
1426 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1428 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1430 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1431 nChange -= nMoveToFee;
1432 nFeeRet += nMoveToFee;
1435 // sub-cent change is moved to fee
1436 if (nChange > 0 && nChange < CENT)
1445 // Fill a vout to ourself
1446 // TODO: pass in scriptChange instead of reservekey so
1447 // change transaction isn't always pay-to-bitcoin-address
1448 CScript scriptChange;
1450 // coin control: send change to custom address
1451 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1452 scriptChange.SetDestination(coinControl->destChange);
1454 // no coin control: send change to newly generated address
1457 // Note: We use a new key here to keep it from being obvious which side is the change.
1458 // The drawback is that by not reusing a previous key, the change may be lost if a
1459 // backup is restored, if the backup doesn't have the new private key for the change.
1460 // If we reused the old key, it would be possible to add code to look for and
1461 // rediscover unknown transactions that were written with keys of ours to recover
1462 // post-backup change.
1464 // Reserve a new key pair from key pool
1465 CPubKey vchPubKey = reservekey.GetReservedKey();
1467 scriptChange.SetDestination(vchPubKey.GetID());
1470 // Insert change txn at random position:
1471 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1472 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1475 reservekey.ReturnKey();
1478 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1479 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1483 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1484 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1488 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1489 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1491 dPriority /= nBytes;
1493 // Check that enough fee is included
1494 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1495 bool fAllowFree = CTransaction::AllowFree(dPriority);
1497 // Disable free transactions until 1 July 2014
1498 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1503 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1505 if (nFeeRet < max(nPayFee, nMinFee))
1507 nFeeRet = max(nPayFee, nMinFee);
1511 // Fill vtxPrev by copying from previous transactions vtxPrev
1512 wtxNew.AddSupportingTransactions(txdb);
1513 wtxNew.fTimeReceivedIsTxTime = true;
1522 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1524 vector< pair<CScript, int64> > vecSend;
1525 vecSend.push_back(make_pair(scriptPubKey, nValue));
1526 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1529 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1531 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1533 // If time weight is lower or equal to zero then weight is zero.
1534 if (nTimeWeight <= 0)
1540 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1541 nWeight = bnCoinDayWeight.getuint64();
1545 // NovaCoin: get current stake weight
1546 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1548 // Choose coins to use
1549 int64 nBalance = GetBalance();
1550 int64 nReserveBalance = 0;
1552 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1554 error("GetStakeWeight : invalid reserve balance amount");
1558 if (nBalance <= nReserveBalance)
1561 vector<const CWalletTx*> vwtxPrev;
1564 * TODO: performance comparison
1566 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1567 static uint256 hashPrevBlock;
1568 static int64 nValueIn = 0;
1570 // Cache outputs unless best block changed
1571 if (hashPrevBlock != pindexBest->GetBlockHash())
1573 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1576 if (setCoins.empty())
1579 hashPrevBlock == pindexBest->GetBlockHash();
1583 set<pair<const CWalletTx*,unsigned int> > setCoins;
1586 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1589 if (setCoins.empty())
1593 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1597 LOCK2(cs_main, cs_wallet);
1598 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1602 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1603 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1605 // Weight is greater than zero
1606 if (nTimeWeight > 0)
1608 nWeight += bnCoinDayWeight.getuint64();
1611 // Weight is greater than zero, but the maximum value isn't reached yet
1612 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1614 nMinWeight += bnCoinDayWeight.getuint64();
1617 // Maximum weight was reached
1618 if (nTimeWeight == nStakeMaxAge)
1620 nMaxWeight += bnCoinDayWeight.getuint64();
1627 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1629 // The following combine threshold is important to security
1630 // Should not be adjusted if you don't understand the consequences
1631 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1633 CBigNum bnTargetPerCoinDay;
1634 bnTargetPerCoinDay.SetCompact(nBits);
1639 // Mark coin stake transaction
1640 CScript scriptEmpty;
1641 scriptEmpty.clear();
1642 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1644 // Choose coins to use
1645 int64 nBalance = GetBalance();
1646 int64 nReserveBalance = 0;
1648 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1649 return error("CreateCoinStake : invalid reserve balance amount");
1651 if (nBalance <= nReserveBalance)
1654 vector<const CWalletTx*> vwtxPrev;
1657 * TODO: performance comparison
1659 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1660 static uint256 hashPrevBlock;
1661 static int64 nValueIn = 0;
1663 // Cache outputs unless best block changed
1664 if (hashPrevBlock != pindexBest->GetBlockHash())
1666 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1669 if (setCoins.empty())
1672 hashPrevBlock == pindexBest->GetBlockHash();
1676 set<pair<const CWalletTx*,unsigned int> > setCoins;
1679 // Select coins with suitable depth
1680 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1683 if (setCoins.empty())
1687 CScript scriptPubKeyKernel;
1689 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1693 LOCK2(cs_main, cs_wallet);
1694 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1698 // Read block header
1701 LOCK2(cs_main, cs_wallet);
1702 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1706 static int nMaxStakeSearchInterval = 60;
1707 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1708 continue; // only count coins meeting min age requirement
1710 bool fKernelFound = false;
1711 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1713 // Search backward in time from the given txNew timestamp
1714 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1715 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1716 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1717 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1720 if (fDebug && GetBoolArg("-printcoinstake"))
1721 printf("CreateCoinStake : kernel found\n");
1722 vector<valtype> vSolutions;
1723 txnouttype whichType;
1724 CScript scriptPubKeyOut;
1725 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1726 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1728 if (fDebug && GetBoolArg("-printcoinstake"))
1729 printf("CreateCoinStake : failed to parse kernel\n");
1732 if (fDebug && GetBoolArg("-printcoinstake"))
1733 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1734 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1736 if (fDebug && GetBoolArg("-printcoinstake"))
1737 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1738 break; // only support pay to public key and pay to address
1740 if (whichType == TX_PUBKEYHASH) // pay to address type
1742 // convert to pay to public key type
1743 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1745 if (fDebug && GetBoolArg("-printcoinstake"))
1746 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1747 break; // unable to find corresponding public key
1749 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1751 if (whichType == TX_PUBKEY)
1753 valtype& vchPubKey = vSolutions[0];
1754 if (!keystore.GetKey(Hash160(vchPubKey), key))
1756 if (fDebug && GetBoolArg("-printcoinstake"))
1757 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1758 break; // unable to find corresponding public key
1761 if (key.GetPubKey() != vchPubKey)
1763 if (fDebug && GetBoolArg("-printcoinstake"))
1764 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1765 break; // keys mismatch
1768 scriptPubKeyOut = scriptPubKeyKernel;
1772 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1773 nCredit += pcoin.first->vout[pcoin.second].nValue;
1774 vwtxPrev.push_back(pcoin.first);
1775 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1777 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1778 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1779 if (fDebug && GetBoolArg("-printcoinstake"))
1780 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1781 fKernelFound = true;
1786 if (fKernelFound || fShutdown)
1787 break; // if kernel is found stop searching
1790 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1793 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1795 // Attempt to add more inputs
1796 // Only add coins of the same key/address as kernel
1797 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1798 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1800 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1802 // Stop adding more inputs if already too many inputs
1803 if (txNew.vin.size() >= 100)
1805 // Stop adding more inputs if value is already pretty significant
1806 if (nCredit > nCombineThreshold)
1808 // Stop adding inputs if reached reserve limit
1809 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1811 // Do not add additional significant input
1812 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1814 // Do not add input that is still too young
1815 if (nTimeWeight < nStakeMaxAge)
1818 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1819 nCredit += pcoin.first->vout[pcoin.second].nValue;
1820 vwtxPrev.push_back(pcoin.first);
1824 // Calculate coin age reward
1828 if (!txNew.GetCoinAge(txdb, nCoinAge))
1829 return error("CreateCoinStake : failed to calculate coin age");
1830 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1836 // Set output amount
1837 if (txNew.vout.size() == 3)
1839 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1840 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1843 txNew.vout[1].nValue = nCredit - nMinFee;
1847 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1849 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1850 return error("CreateCoinStake : failed to sign coinstake");
1854 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1855 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1856 return error("CreateCoinStake : exceeded coinstake size limit");
1858 // Check enough fee is paid
1859 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1861 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1862 continue; // try signing again
1866 if (fDebug && GetBoolArg("-printfee"))
1867 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1872 // Successfully generated coinstake
1877 // Call after CreateTransaction unless you want to abort
1878 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1881 LOCK2(cs_main, cs_wallet);
1882 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1884 // This is only to keep the database open to defeat the auto-flush for the
1885 // duration of this scope. This is the only place where this optimization
1886 // maybe makes sense; please don't do it anywhere else.
1887 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1889 // Take key pair from key pool so it won't be used again
1890 reservekey.KeepKey();
1892 // Add tx to wallet, because if it has change it's also ours,
1893 // otherwise just for transaction history.
1894 AddToWallet(wtxNew);
1896 // Mark old coins as spent
1897 set<CWalletTx*> setCoins;
1898 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1900 CWalletTx &coin = mapWallet[txin.prevout.hash];
1901 coin.BindWallet(this);
1902 coin.MarkSpent(txin.prevout.n);
1904 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1911 // Track how many getdata requests our transaction gets
1912 mapRequestCount[wtxNew.GetHash()] = 0;
1915 if (!wtxNew.AcceptToMemoryPool())
1917 // This must not fail. The transaction has already been signed and recorded.
1918 printf("CommitTransaction() : Error: Transaction not valid");
1921 wtxNew.RelayWalletTransaction();
1929 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1931 CReserveKey reservekey(this);
1936 string strError = _("Error: Wallet locked, unable to create transaction ");
1937 printf("SendMoney() : %s", strError.c_str());
1940 if (fWalletUnlockMintOnly)
1942 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1943 printf("SendMoney() : %s", strError.c_str());
1946 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1949 if (nValue + nFeeRequired > GetBalance())
1950 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());
1952 strError = _("Error: Transaction creation failed ");
1953 printf("SendMoney() : %s", strError.c_str());
1957 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1960 if (!CommitTransaction(wtxNew, reservekey))
1961 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.");
1968 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1972 return _("Invalid amount");
1973 if (nValue + nTransactionFee > GetBalance())
1974 return _("Insufficient funds");
1976 // Parse Bitcoin address
1977 CScript scriptPubKey;
1978 scriptPubKey.SetDestination(address);
1980 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1986 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1990 fFirstRunRet = false;
1991 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1992 if (nLoadWalletRet == DB_NEED_REWRITE)
1994 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1997 // Note: can't top-up keypool here, because wallet is locked.
1998 // User will be prompted to unlock wallet the next operation
1999 // the requires a new key.
2003 if (nLoadWalletRet != DB_LOAD_OK)
2004 return nLoadWalletRet;
2005 fFirstRunRet = !vchDefaultKey.IsValid();
2007 NewThread(ThreadFlushWalletDB, &strWalletFile);
2012 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2014 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2015 mapAddressBook[address] = strName;
2016 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2019 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2022 bool CWallet::DelAddressBookName(const CTxDestination& address)
2024 mapAddressBook.erase(address);
2025 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2028 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2032 void CWallet::PrintWallet(const CBlock& block)
2036 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2038 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2039 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2041 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2043 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2044 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2051 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2055 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2056 if (mi != mapWallet.end())
2065 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2069 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2072 vchDefaultKey = vchPubKey;
2076 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2078 if (!pwallet->fFileBacked)
2080 strWalletFileOut = pwallet->strWalletFile;
2085 // Mark old keypool keys as used,
2086 // and generate all new keys
2088 bool CWallet::NewKeyPool()
2092 CWalletDB walletdb(strWalletFile);
2093 BOOST_FOREACH(int64 nIndex, setKeyPool)
2094 walletdb.ErasePool(nIndex);
2100 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2101 for (int i = 0; i < nKeys; i++)
2104 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2105 setKeyPool.insert(nIndex);
2107 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2112 bool CWallet::TopUpKeyPool(unsigned int nSize)
2120 CWalletDB walletdb(strWalletFile);
2123 unsigned int nTargetSize;
2125 nTargetSize = nSize;
2127 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2129 while (setKeyPool.size() < (nTargetSize + 1))
2132 if (!setKeyPool.empty())
2133 nEnd = *(--setKeyPool.end()) + 1;
2134 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2135 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2136 setKeyPool.insert(nEnd);
2137 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2143 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2146 keypool.vchPubKey = CPubKey();
2153 // Get the oldest key
2154 if(setKeyPool.empty())
2157 CWalletDB walletdb(strWalletFile);
2159 nIndex = *(setKeyPool.begin());
2160 setKeyPool.erase(setKeyPool.begin());
2161 if (!walletdb.ReadPool(nIndex, keypool))
2162 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2163 if (!HaveKey(keypool.vchPubKey.GetID()))
2164 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2165 assert(keypool.vchPubKey.IsValid());
2166 if (fDebug && GetBoolArg("-printkeypool"))
2167 printf("keypool reserve %"PRI64d"\n", nIndex);
2171 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2174 LOCK2(cs_main, cs_wallet);
2175 CWalletDB walletdb(strWalletFile);
2177 int64 nIndex = 1 + *(--setKeyPool.end());
2178 if (!walletdb.WritePool(nIndex, keypool))
2179 throw runtime_error("AddReserveKey() : writing added key failed");
2180 setKeyPool.insert(nIndex);
2186 void CWallet::KeepKey(int64 nIndex)
2188 // Remove from key pool
2191 CWalletDB walletdb(strWalletFile);
2192 walletdb.ErasePool(nIndex);
2195 printf("keypool keep %"PRI64d"\n", nIndex);
2198 void CWallet::ReturnKey(int64 nIndex)
2200 // Return to key pool
2203 setKeyPool.insert(nIndex);
2206 printf("keypool return %"PRI64d"\n", nIndex);
2209 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2215 ReserveKeyFromKeyPool(nIndex, keypool);
2218 if (fAllowReuse && vchDefaultKey.IsValid())
2220 result = vchDefaultKey;
2223 if (IsLocked()) return false;
2224 result = GenerateNewKey();
2228 result = keypool.vchPubKey;
2233 int64 CWallet::GetOldestKeyPoolTime()
2237 ReserveKeyFromKeyPool(nIndex, keypool);
2241 return keypool.nTime;
2244 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2246 map<CTxDestination, int64> balances;
2250 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2252 CWalletTx *pcoin = &walletEntry.second;
2254 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2257 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2260 int nDepth = pcoin->GetDepthInMainChain();
2261 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2264 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2266 CTxDestination addr;
2267 if (!IsMine(pcoin->vout[i]))
2269 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2272 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2274 if (!balances.count(addr))
2276 balances[addr] += n;
2284 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2286 set< set<CTxDestination> > groupings;
2287 set<CTxDestination> grouping;
2289 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2291 CWalletTx *pcoin = &walletEntry.second;
2293 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2295 // group all input addresses with each other
2296 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2298 CTxDestination address;
2299 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2301 grouping.insert(address);
2304 // group change with input addresses
2305 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2306 if (IsChange(txout))
2308 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2309 CTxDestination txoutAddr;
2310 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2312 grouping.insert(txoutAddr);
2314 groupings.insert(grouping);
2318 // group lone addrs by themselves
2319 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2320 if (IsMine(pcoin->vout[i]))
2322 CTxDestination address;
2323 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2325 grouping.insert(address);
2326 groupings.insert(grouping);
2331 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2332 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2333 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2335 // make a set of all the groups hit by this new group
2336 set< set<CTxDestination>* > hits;
2337 map< CTxDestination, set<CTxDestination>* >::iterator it;
2338 BOOST_FOREACH(CTxDestination address, grouping)
2339 if ((it = setmap.find(address)) != setmap.end())
2340 hits.insert((*it).second);
2342 // merge all hit groups into a new single group and delete old groups
2343 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2344 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2346 merged->insert(hit->begin(), hit->end());
2347 uniqueGroupings.erase(hit);
2350 uniqueGroupings.insert(merged);
2353 BOOST_FOREACH(CTxDestination element, *merged)
2354 setmap[element] = merged;
2357 set< set<CTxDestination> > ret;
2358 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2360 ret.insert(*uniqueGrouping);
2361 delete uniqueGrouping;
2367 // ppcoin: check 'spent' consistency between wallet and txindex
2368 // ppcoin: fix wallet spent state according to txindex
2369 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2372 nBalanceInQuestion = 0;
2375 vector<CWalletTx*> vCoins;
2376 vCoins.reserve(mapWallet.size());
2377 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2378 vCoins.push_back(&(*it).second);
2381 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2383 // Find the corresponding transaction index
2385 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2387 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2389 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2391 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2392 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2394 nBalanceInQuestion += pcoin->vout[n].nValue;
2397 pcoin->MarkUnspent(n);
2398 pcoin->WriteToDisk();
2401 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2403 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2404 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2406 nBalanceInQuestion += pcoin->vout[n].nValue;
2409 pcoin->MarkSpent(n);
2410 pcoin->WriteToDisk();
2416 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2418 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2421 EraseFromWallet(pcoin->GetHash());
2427 // ppcoin: disable transaction (only for coinstake)
2428 void CWallet::DisableTransaction(const CTransaction &tx)
2430 if (!tx.IsCoinStake() || !IsFromMe(tx))
2431 return; // only disconnecting coinstake requires marking input unspent
2434 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2436 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2437 if (mi != mapWallet.end())
2439 CWalletTx& prev = (*mi).second;
2440 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2442 prev.MarkUnspent(txin.prevout.n);
2449 CPubKey CReserveKey::GetReservedKey()
2454 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2456 vchPubKey = keypool.vchPubKey;
2459 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2460 vchPubKey = pwallet->vchDefaultKey;
2463 assert(vchPubKey.IsValid());
2467 void CReserveKey::KeepKey()
2470 pwallet->KeepKey(nIndex);
2472 vchPubKey = CPubKey();
2475 void CReserveKey::ReturnKey()
2478 pwallet->ReturnKey(nIndex);
2480 vchPubKey = CPubKey();
2483 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2487 CWalletDB walletdb(strWalletFile);
2489 LOCK2(cs_main, cs_wallet);
2490 BOOST_FOREACH(const int64& id, setKeyPool)
2493 if (!walletdb.ReadPool(id, keypool))
2494 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2495 assert(keypool.vchPubKey.IsValid());
2496 CKeyID keyID = keypool.vchPubKey.GetID();
2497 if (!HaveKey(keyID))
2498 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2499 setAddress.insert(keyID);
2503 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2507 // Only notify UI if this transaction is in this wallet
2508 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2509 if (mi != mapWallet.end())
2510 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2514 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2515 mapKeyBirth.clear();
2517 // get birth times for keys with metadata
2518 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2519 if (it->second.nCreateTime)
2520 mapKeyBirth[it->first] = it->second.nCreateTime;
2522 // map in which we'll infer heights of other keys
2523 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2524 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2525 std::set<CKeyID> setKeys;
2527 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2528 if (mapKeyBirth.count(keyid) == 0)
2529 mapKeyFirstBlock[keyid] = pindexMax;
2533 // if there are no such keys, we're done
2534 if (mapKeyFirstBlock.empty())
2537 // find first block that affects those keys, if there are any left
2538 std::vector<CKeyID> vAffected;
2539 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2540 // iterate over all wallet transactions...
2541 const CWalletTx &wtx = (*it).second;
2542 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2543 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2544 // ... which are already in a block
2545 int nHeight = blit->second->nHeight;
2546 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2547 // iterate over all their outputs
2548 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2549 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2550 // ... and all their affected keys
2551 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2552 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2553 rit->second = blit->second;
2560 // Extract block timestamps for those keys
2561 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2562 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off