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;
20 //////////////////////////////////////////////////////////////////////////////
25 struct CompareValueOnly
27 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
28 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
30 return t1.first < t2.first;
34 CPubKey CWallet::GenerateNewKey()
36 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
40 key.MakeNewKey(fCompressed);
42 // Compressed public keys were introduced in version 0.6.0
44 SetMinVersion(FEATURE_COMPRPUBKEY);
46 CPubKey pubkey = key.GetPubKey();
48 // Create new metadata
49 int64 nCreationTime = GetTime();
50 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
51 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
52 nTimeFirstKey = nCreationTime;
55 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
56 return key.GetPubKey();
59 bool CWallet::AddKey(const CKey& key)
61 CPubKey pubkey = key.GetPubKey();
63 if (!CCryptoKeyStore::AddKey(key))
68 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
72 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
74 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
80 if (pwalletdbEncryption)
81 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
83 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
88 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
90 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
91 nTimeFirstKey = meta.nCreateTime;
93 mapKeyMetadata[pubkey.GetID()] = meta;
97 bool CWallet::AddCScript(const CScript& redeemScript)
99 if (!CCryptoKeyStore::AddCScript(redeemScript))
103 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
106 // ppcoin: optional setting to unlock wallet for block minting only;
107 // serves to disable the trivial sendmoney when OS account compromised
108 bool fWalletUnlockMintOnly = false;
110 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
116 CKeyingMaterial vMasterKey;
120 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
122 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
124 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
126 if (CCryptoKeyStore::Unlock(vMasterKey))
133 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
135 bool fWasLocked = IsLocked();
142 CKeyingMaterial vMasterKey;
143 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
145 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
147 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
149 if (CCryptoKeyStore::Unlock(vMasterKey))
151 int64 nStartTime = GetTimeMillis();
152 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
153 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
155 nStartTime = GetTimeMillis();
156 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
157 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
159 if (pMasterKey.second.nDeriveIterations < 25000)
160 pMasterKey.second.nDeriveIterations = 25000;
162 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
164 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
166 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
168 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
179 void CWallet::SetBestChain(const CBlockLocator& loc)
181 CWalletDB walletdb(strWalletFile);
182 walletdb.WriteBestBlock(loc);
185 // This class implements an addrIncoming entry that causes pre-0.4
186 // clients to crash on startup if reading a private-key-encrypted wallet.
187 class CCorruptAddress
192 if (nType & SER_DISK)
197 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
199 if (nWalletVersion >= nVersion)
202 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
203 if (fExplicit && nVersion > nWalletMaxVersion)
204 nVersion = FEATURE_LATEST;
206 nWalletVersion = nVersion;
208 if (nVersion > nWalletMaxVersion)
209 nWalletMaxVersion = nVersion;
213 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
214 if (nWalletVersion >= 40000)
216 // Versions prior to 0.4.0 did not support the "minversion" record.
217 // Use a CCorruptAddress to make them crash instead.
218 CCorruptAddress corruptAddress;
219 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
221 if (nWalletVersion > 40000)
222 pwalletdb->WriteMinVersion(nWalletVersion);
230 bool CWallet::SetMaxVersion(int nVersion)
232 // cannot downgrade below current version
233 if (nWalletVersion > nVersion)
236 nWalletMaxVersion = nVersion;
241 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
246 CKeyingMaterial vMasterKey;
247 RandAddSeedPerfmon();
249 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
250 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
252 CMasterKey kMasterKey(nDerivationMethodIndex);
254 RandAddSeedPerfmon();
255 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
256 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
259 int64 nStartTime = GetTimeMillis();
260 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
261 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
263 nStartTime = GetTimeMillis();
264 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
265 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
267 if (kMasterKey.nDeriveIterations < 25000)
268 kMasterKey.nDeriveIterations = 25000;
270 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
272 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
274 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
279 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
282 pwalletdbEncryption = new CWalletDB(strWalletFile);
283 if (!pwalletdbEncryption->TxnBegin())
285 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
288 if (!EncryptKeys(vMasterKey))
291 pwalletdbEncryption->TxnAbort();
292 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.
295 // Encryption was introduced in version 0.4.0
296 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
300 if (!pwalletdbEncryption->TxnCommit())
301 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.
303 delete pwalletdbEncryption;
304 pwalletdbEncryption = NULL;
308 Unlock(strWalletPassphrase);
312 // Need to completely rewrite the wallet file; if we don't, bdb might keep
313 // bits of the unencrypted private key in slack space in the database file.
314 CDB::Rewrite(strWalletFile);
317 NotifyStatusChanged(this);
322 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
324 int64 nRet = nOrderPosNext++;
326 pwalletdb->WriteOrderPosNext(nOrderPosNext);
328 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
333 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
335 CWalletDB walletdb(strWalletFile);
337 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
340 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
341 // would make this much faster for applications that do this a lot.
342 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
344 CWalletTx* wtx = &((*it).second);
345 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
348 walletdb.ListAccountCreditDebit(strAccount, acentries);
349 BOOST_FOREACH(CAccountingEntry& entry, acentries)
351 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
357 void CWallet::WalletUpdateSpent(const CTransaction &tx)
359 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
360 // Update the wallet spent flag if it doesn't know due to wallet.dat being
361 // restored from backup or the user making copies of wallet.dat.
364 BOOST_FOREACH(const CTxIn& txin, tx.vin)
366 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
367 if (mi != mapWallet.end())
369 CWalletTx& wtx = (*mi).second;
370 if (txin.prevout.n >= wtx.vout.size())
371 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
372 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
374 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
375 wtx.MarkSpent(txin.prevout.n);
377 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
384 void CWallet::MarkDirty()
388 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
389 item.second.MarkDirty();
393 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
395 uint256 hash = wtxIn.GetHash();
398 // Inserts only if not already there, returns tx inserted or tx found
399 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
400 CWalletTx& wtx = (*ret.first).second;
401 wtx.BindWallet(this);
402 bool fInsertedNew = ret.second;
405 wtx.nTimeReceived = GetAdjustedTime();
406 wtx.nOrderPos = IncOrderPosNext();
408 wtx.nTimeSmart = wtx.nTimeReceived;
409 if (wtxIn.hashBlock != 0)
411 if (mapBlockIndex.count(wtxIn.hashBlock))
413 unsigned int latestNow = wtx.nTimeReceived;
414 unsigned int latestEntry = 0;
416 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
417 int64 latestTolerated = latestNow + 300;
418 std::list<CAccountingEntry> acentries;
419 TxItems txOrdered = OrderedTxItems(acentries);
420 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
422 CWalletTx *const pwtx = (*it).second.first;
425 CAccountingEntry *const pacentry = (*it).second.second;
429 nSmartTime = pwtx->nTimeSmart;
431 nSmartTime = pwtx->nTimeReceived;
434 nSmartTime = pacentry->nTime;
435 if (nSmartTime <= latestTolerated)
437 latestEntry = nSmartTime;
438 if (nSmartTime > latestNow)
439 latestNow = nSmartTime;
445 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
446 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
449 printf("AddToWallet() : found %s in block %s not in index\n",
450 wtxIn.GetHash().ToString().substr(0,10).c_str(),
451 wtxIn.hashBlock.ToString().c_str());
455 bool fUpdated = false;
459 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
461 wtx.hashBlock = wtxIn.hashBlock;
464 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
466 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
467 wtx.nIndex = wtxIn.nIndex;
470 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
472 wtx.fFromMe = wtxIn.fFromMe;
475 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
479 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
482 if (fInsertedNew || fUpdated)
483 if (!wtx.WriteToDisk())
486 // If default receiving address gets used, replace it with a new one
487 CScript scriptDefaultKey;
488 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
489 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
491 if (txout.scriptPubKey == scriptDefaultKey)
493 CPubKey newDefaultKey;
494 if (GetKeyFromPool(newDefaultKey, false))
496 SetDefaultKey(newDefaultKey);
497 SetAddressBookName(vchDefaultKey.GetID(), "");
502 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
503 WalletUpdateSpent(wtx);
505 // Notify UI of new or updated transaction
506 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
508 // notify an external script when a wallet transaction comes in or is updated
509 std::string strCmd = GetArg("-walletnotify", "");
511 if ( !strCmd.empty())
513 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
514 boost::thread t(runCommand, strCmd); // thread runs free
521 // Add a transaction to the wallet, or update it.
522 // pblock is optional, but should be provided if the transaction is known to be in a block.
523 // If fUpdate is true, existing transactions will be updated.
524 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
526 uint256 hash = tx.GetHash();
529 bool fExisted = mapWallet.count(hash);
530 if (fExisted && !fUpdate) return false;
531 if (fExisted || IsMine(tx) || IsFromMe(tx))
533 CWalletTx wtx(this,tx);
534 // Get merkle branch if transaction was found in a block
536 wtx.SetMerkleBranch(pblock);
537 return AddToWallet(wtx);
540 WalletUpdateSpent(tx);
545 bool CWallet::EraseFromWallet(uint256 hash)
551 if (mapWallet.erase(hash))
552 CWalletDB(strWalletFile).EraseTx(hash);
558 bool CWallet::IsMine(const CTxIn &txin) const
562 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
563 if (mi != mapWallet.end())
565 const CWalletTx& prev = (*mi).second;
566 if (txin.prevout.n < prev.vout.size())
567 if (IsMine(prev.vout[txin.prevout.n]))
574 int64 CWallet::GetDebit(const CTxIn &txin) const
578 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
579 if (mi != mapWallet.end())
581 const CWalletTx& prev = (*mi).second;
582 if (txin.prevout.n < prev.vout.size())
583 if (IsMine(prev.vout[txin.prevout.n]))
584 return prev.vout[txin.prevout.n].nValue;
590 bool CWallet::IsChange(const CTxOut& txout) const
592 CTxDestination address;
594 // TODO: fix handling of 'change' outputs. The assumption is that any
595 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
596 // is change. That assumption is likely to break when we implement multisignature
597 // wallets that return change back into a multi-signature-protected address;
598 // a better way of identifying which outputs are 'the send' and which are
599 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
600 // which output, if any, was change).
601 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
604 if (!mapAddressBook.count(address))
610 int64 CWalletTx::GetTxTime() const
612 int64 n = nTimeSmart;
613 return n ? n : nTimeReceived;
616 int CWalletTx::GetRequestCount() const
618 // Returns -1 if it wasn't being tracked
621 LOCK(pwallet->cs_wallet);
622 if (IsCoinBase() || IsCoinStake())
627 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
628 if (mi != pwallet->mapRequestCount.end())
629 nRequests = (*mi).second;
634 // Did anyone request this transaction?
635 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
636 if (mi != pwallet->mapRequestCount.end())
638 nRequests = (*mi).second;
640 // How about the block it's in?
641 if (nRequests == 0 && hashBlock != 0)
643 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
644 if (mi != pwallet->mapRequestCount.end())
645 nRequests = (*mi).second;
647 nRequests = 1; // If it's in someone else's block it must have got out
655 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
656 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
658 nGeneratedImmature = nGeneratedMature = nFee = 0;
659 listReceived.clear();
661 strSentAccount = strFromAccount;
663 if (IsCoinBase() || IsCoinStake())
665 if (GetBlocksToMaturity() > 0)
666 nGeneratedImmature = pwallet->GetCredit(*this);
668 nGeneratedMature = GetCredit();
673 int64 nDebit = GetDebit();
674 if (nDebit > 0) // debit>0 means we signed/sent this transaction
676 int64 nValueOut = GetValueOut();
677 nFee = nDebit - nValueOut;
681 BOOST_FOREACH(const CTxOut& txout, vout)
683 CTxDestination address;
684 vector<unsigned char> vchPubKey;
685 if (!ExtractDestination(txout.scriptPubKey, address))
687 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
688 this->GetHash().ToString().c_str());
691 // Don't report 'change' txouts
692 if (nDebit > 0 && pwallet->IsChange(txout))
696 listSent.push_back(make_pair(address, txout.nValue));
698 if (pwallet->IsMine(txout))
699 listReceived.push_back(make_pair(address, txout.nValue));
704 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
705 int64& nSent, int64& nFee) const
707 nGenerated = nReceived = nSent = nFee = 0;
709 int64 allGeneratedImmature, allGeneratedMature, allFee;
710 allGeneratedImmature = allGeneratedMature = allFee = 0;
711 string strSentAccount;
712 list<pair<CTxDestination, int64> > listReceived;
713 list<pair<CTxDestination, int64> > listSent;
714 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
716 if (strAccount == "")
717 nGenerated = allGeneratedMature;
718 if (strAccount == strSentAccount)
720 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
725 LOCK(pwallet->cs_wallet);
726 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
728 if (pwallet->mapAddressBook.count(r.first))
730 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
731 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
732 nReceived += r.second;
734 else if (strAccount.empty())
736 nReceived += r.second;
742 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
746 const int COPY_DEPTH = 3;
747 if (SetMerkleBranch() < COPY_DEPTH)
749 vector<uint256> vWorkQueue;
750 BOOST_FOREACH(const CTxIn& txin, vin)
751 vWorkQueue.push_back(txin.prevout.hash);
753 // This critsect is OK because txdb is already open
755 LOCK(pwallet->cs_wallet);
756 map<uint256, const CMerkleTx*> mapWalletPrev;
757 set<uint256> setAlreadyDone;
758 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
760 uint256 hash = vWorkQueue[i];
761 if (setAlreadyDone.count(hash))
763 setAlreadyDone.insert(hash);
766 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
767 if (mi != pwallet->mapWallet.end())
770 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
771 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
773 else if (mapWalletPrev.count(hash))
775 tx = *mapWalletPrev[hash];
777 else if (!fClient && txdb.ReadDiskTx(hash, tx))
783 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
787 int nDepth = tx.SetMerkleBranch();
788 vtxPrev.push_back(tx);
790 if (nDepth < COPY_DEPTH)
792 BOOST_FOREACH(const CTxIn& txin, tx.vin)
793 vWorkQueue.push_back(txin.prevout.hash);
799 reverse(vtxPrev.begin(), vtxPrev.end());
802 bool CWalletTx::WriteToDisk()
804 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
807 // Scan the block chain (starting in pindexStart) for transactions
808 // from or to us. If fUpdate is true, found transactions that already
809 // exist in the wallet will be updated.
810 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
814 CBlockIndex* pindex = pindexStart;
820 block.ReadFromDisk(pindex, true);
821 BOOST_FOREACH(CTransaction& tx, block.vtx)
823 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
826 pindex = pindex->pnext;
832 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
835 tx.ReadFromDisk(COutPoint(hashTx, 0));
836 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
841 void CWallet::ReacceptWalletTransactions()
849 vector<CDiskTxPos> vMissingTx;
850 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
852 CWalletTx& wtx = item.second;
853 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
857 bool fUpdated = false;
858 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
860 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
861 if (txindex.vSpent.size() != wtx.vout.size())
863 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
866 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
870 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
874 vMissingTx.push_back(txindex.vSpent[i]);
879 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
886 // Re-accept any txes of ours that aren't already in a block
887 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
888 wtx.AcceptWalletTransaction(txdb, false);
891 if (!vMissingTx.empty())
893 // TODO: optimize this to scan just part of the block chain?
894 if (ScanForWalletTransactions(pindexGenesisBlock))
895 fRepeat = true; // Found missing transactions: re-do re-accept.
900 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
902 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
904 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
906 uint256 hash = tx.GetHash();
907 if (!txdb.ContainsTx(hash))
908 RelayTransaction((CTransaction)tx, hash);
911 if (!(IsCoinBase() || IsCoinStake()))
913 uint256 hash = GetHash();
914 if (!txdb.ContainsTx(hash))
916 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
917 RelayTransaction((CTransaction)*this, hash);
922 void CWalletTx::RelayWalletTransaction()
925 RelayWalletTransaction(txdb);
928 void CWallet::ResendWalletTransactions()
930 // Do this infrequently and randomly to avoid giving away
931 // that these are our transactions.
932 static int64 nNextTime;
933 if (GetTime() < nNextTime)
935 bool fFirst = (nNextTime == 0);
936 nNextTime = GetTime() + GetRand(30 * 60);
940 // Only do it if there's been a new block since last time
941 static int64 nLastTime;
942 if (nTimeBestReceived < nLastTime)
944 nLastTime = GetTime();
946 // Rebroadcast any of our txes that aren't in a block yet
947 printf("ResendWalletTransactions()\n");
951 // Sort them in chronological order
952 multimap<unsigned int, CWalletTx*> mapSorted;
953 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
955 CWalletTx& wtx = item.second;
956 // Don't rebroadcast until it's had plenty of time that
957 // it should have gotten in already by now.
958 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
959 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
961 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
963 CWalletTx& wtx = *item.second;
964 if (wtx.CheckTransaction())
965 wtx.RelayWalletTransaction(txdb);
967 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
977 //////////////////////////////////////////////////////////////////////////////
983 int64 CWallet::GetBalance() const
988 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
990 const CWalletTx* pcoin = &(*it).second;
991 if (pcoin->IsConfirmed())
992 nTotal += pcoin->GetAvailableCredit();
999 int64 CWallet::GetUnconfirmedBalance() const
1004 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1006 const CWalletTx* pcoin = &(*it).second;
1007 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
1008 nTotal += pcoin->GetAvailableCredit();
1014 int64 CWallet::GetImmatureBalance() const
1019 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1021 const CWalletTx& pcoin = (*it).second;
1022 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1023 nTotal += GetCredit(pcoin);
1029 // populate vCoins with vector of spendable COutputs
1030 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1036 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1038 const CWalletTx* pcoin = &(*it).second;
1040 if (!pcoin->IsFinal())
1043 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1046 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1049 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1052 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1053 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1054 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1055 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1061 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1067 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1069 const CWalletTx* pcoin = &(*it).second;
1071 if (!pcoin->IsFinal())
1074 if(pcoin->GetDepthInMainChain() < nConf)
1077 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1078 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1079 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1084 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1085 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1087 vector<char> vfIncluded;
1089 vfBest.assign(vValue.size(), true);
1090 nBest = nTotalLower;
1092 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1094 vfIncluded.assign(vValue.size(), false);
1096 bool fReachedTarget = false;
1097 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1099 for (unsigned int i = 0; i < vValue.size(); i++)
1101 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1103 nTotal += vValue[i].first;
1104 vfIncluded[i] = true;
1105 if (nTotal >= nTargetValue)
1107 fReachedTarget = true;
1111 vfBest = vfIncluded;
1113 nTotal -= vValue[i].first;
1114 vfIncluded[i] = false;
1122 // ppcoin: total coins staked (non-spendable until maturity)
1123 int64 CWallet::GetStake() const
1127 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1129 const CWalletTx* pcoin = &(*it).second;
1130 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1131 nTotal += CWallet::GetCredit(*pcoin);
1136 int64 CWallet::GetNewMint() const
1140 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1142 const CWalletTx* pcoin = &(*it).second;
1143 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1144 nTotal += CWallet::GetCredit(*pcoin);
1149 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
1151 setCoinsRet.clear();
1154 // List of values less than target
1155 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1156 coinLowestLarger.first = std::numeric_limits<int64>::max();
1157 coinLowestLarger.second.first = NULL;
1158 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1159 int64 nTotalLower = 0;
1161 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1163 BOOST_FOREACH(COutput output, vCoins)
1165 const CWalletTx *pcoin = output.tx;
1167 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1172 // Follow the timestamp rules
1173 if (pcoin->nTime > nSpendTime)
1176 int64 n = pcoin->vout[i].nValue;
1178 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1180 if (n == nTargetValue)
1182 setCoinsRet.insert(coin.second);
1183 nValueRet += coin.first;
1186 else if (n < nTargetValue + CENT)
1188 vValue.push_back(coin);
1191 else if (n < coinLowestLarger.first)
1193 coinLowestLarger = coin;
1197 if (nTotalLower == nTargetValue)
1199 for (unsigned int i = 0; i < vValue.size(); ++i)
1201 setCoinsRet.insert(vValue[i].second);
1202 nValueRet += vValue[i].first;
1207 if (nTotalLower < nTargetValue)
1209 if (coinLowestLarger.second.first == NULL)
1211 setCoinsRet.insert(coinLowestLarger.second);
1212 nValueRet += coinLowestLarger.first;
1216 // Solve subset sum by stochastic approximation
1217 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1218 vector<char> vfBest;
1221 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1222 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1223 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1225 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1226 // or the next bigger coin is closer), return the bigger coin
1227 if (coinLowestLarger.second.first &&
1228 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1230 setCoinsRet.insert(coinLowestLarger.second);
1231 nValueRet += coinLowestLarger.first;
1234 for (unsigned int i = 0; i < vValue.size(); i++)
1237 setCoinsRet.insert(vValue[i].second);
1238 nValueRet += vValue[i].first;
1241 if (fDebug && GetBoolArg("-printpriority"))
1244 printf("SelectCoins() best subset: ");
1245 for (unsigned int i = 0; i < vValue.size(); i++)
1247 printf("%s ", FormatMoney(vValue[i].first).c_str());
1248 printf("total %s\n", FormatMoney(nBest).c_str());
1255 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1257 vector<COutput> vCoins;
1258 AvailableCoins(vCoins, true, coinControl);
1260 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1261 if (coinControl && coinControl->HasSelected())
1263 BOOST_FOREACH(const COutput& out, vCoins)
1265 nValueRet += out.tx->vout[out.i].nValue;
1266 setCoinsRet.insert(make_pair(out.tx, out.i));
1268 return (nValueRet >= nTargetValue);
1271 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1272 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1273 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1276 // Select some coins without random shuffle or best subset approximation
1277 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1279 vector<COutput> vCoins;
1280 AvailableCoinsMinConf(vCoins, nMinConf);
1282 setCoinsRet.clear();
1285 BOOST_FOREACH(COutput output, vCoins)
1287 const CWalletTx *pcoin = output.tx;
1290 // Stop if we've chosen enough inputs
1291 if (nValueRet >= nTargetValue)
1294 // Follow the timestamp rules
1295 if (pcoin->nTime > nSpendTime)
1298 int64 n = pcoin->vout[i].nValue;
1300 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1302 if (n >= nTargetValue)
1304 // If input value is greater or equal to target then simply insert
1305 // it into the current subset and exit
1306 setCoinsRet.insert(coin.second);
1307 nValueRet += coin.first;
1310 else if (n < nTargetValue + CENT)
1312 setCoinsRet.insert(coin.second);
1313 nValueRet += coin.first;
1320 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1323 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1329 if (vecSend.empty() || nValue < 0)
1332 wtxNew.BindWallet(this);
1335 LOCK2(cs_main, cs_wallet);
1336 // txdb must be opened before the mapWallet lock
1339 nFeeRet = nTransactionFee;
1343 wtxNew.vout.clear();
1344 wtxNew.fFromMe = true;
1346 int64 nTotalValue = nValue + nFeeRet;
1347 double dPriority = 0;
1348 // vouts to the payees
1349 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1350 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1352 // Choose coins to use
1353 set<pair<const CWalletTx*,unsigned int> > setCoins;
1355 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1357 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1359 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1360 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1363 int64 nChange = nValueIn - nValue - nFeeRet;
1364 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1365 // or until nChange becomes zero
1366 // NOTE: this depends on the exact behaviour of GetMinFee
1367 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1369 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1370 nChange -= nMoveToFee;
1371 nFeeRet += nMoveToFee;
1374 // ppcoin: sub-cent change is moved to fee
1375 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1383 // Fill a vout to ourself
1384 // TODO: pass in scriptChange instead of reservekey so
1385 // change transaction isn't always pay-to-bitcoin-address
1386 CScript scriptChange;
1388 // coin control: send change to custom address
1389 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1390 scriptChange.SetDestination(coinControl->destChange);
1392 // no coin control: send change to newly generated address
1395 // Note: We use a new key here to keep it from being obvious which side is the change.
1396 // The drawback is that by not reusing a previous key, the change may be lost if a
1397 // backup is restored, if the backup doesn't have the new private key for the change.
1398 // If we reused the old key, it would be possible to add code to look for and
1399 // rediscover unknown transactions that were written with keys of ours to recover
1400 // post-backup change.
1402 // Reserve a new key pair from key pool
1403 CPubKey vchPubKey = reservekey.GetReservedKey();
1405 scriptChange.SetDestination(vchPubKey.GetID());
1408 // Insert change txn at random position:
1409 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1410 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1413 reservekey.ReturnKey();
1416 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1417 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1421 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1422 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1426 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1427 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1429 dPriority /= nBytes;
1431 // Check that enough fee is included
1432 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1433 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND, nBytes);
1435 if (nFeeRet < max(nPayFee, nMinFee))
1437 nFeeRet = max(nPayFee, nMinFee);
1441 // Fill vtxPrev by copying from previous transactions vtxPrev
1442 wtxNew.AddSupportingTransactions(txdb);
1443 wtxNew.fTimeReceivedIsTxTime = true;
1452 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1454 vector< pair<CScript, int64> > vecSend;
1455 vecSend.push_back(make_pair(scriptPubKey, nValue));
1456 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1459 // NovaCoin: get current stake weight
1460 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1462 // Choose coins to use
1463 int64 nBalance = GetBalance();
1464 int64 nReserveBalance = 0;
1466 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1468 error("GetStakeWeight : invalid reserve balance amount");
1472 if (nBalance <= nReserveBalance)
1475 vector<const CWalletTx*> vwtxPrev;
1478 * TODO: performance comparison
1480 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1481 static uint256 hashPrevBlock;
1482 static int64 nValueIn = 0;
1484 // Cache outputs unless best block changed
1485 if (hashPrevBlock != pindexBest->GetBlockHash())
1487 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1490 if (setCoins.empty())
1493 hashPrevBlock == pindexBest->GetBlockHash();
1497 set<pair<const CWalletTx*,unsigned int> > setCoins;
1500 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1503 if (setCoins.empty())
1507 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1511 LOCK2(cs_main, cs_wallet);
1512 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1516 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1517 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1519 // Weight is greater than zero
1520 if (nTimeWeight > 0)
1522 nWeight += bnCoinDayWeight.getuint64();
1525 // Weight is greater than zero, but the maximum value isn't reached yet
1526 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1528 nMinWeight += bnCoinDayWeight.getuint64();
1531 // Maximum weight was reached
1532 if (nTimeWeight == nStakeMaxAge)
1534 nMaxWeight += bnCoinDayWeight.getuint64();
1541 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1543 // The following combine threshold is important to security
1544 // Should not be adjusted if you don't understand the consequences
1545 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1547 CBigNum bnTargetPerCoinDay;
1548 bnTargetPerCoinDay.SetCompact(nBits);
1553 // Mark coin stake transaction
1554 CScript scriptEmpty;
1555 scriptEmpty.clear();
1556 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1558 // Choose coins to use
1559 int64 nBalance = GetBalance();
1560 int64 nReserveBalance = 0;
1562 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1563 return error("CreateCoinStake : invalid reserve balance amount");
1565 if (nBalance <= nReserveBalance)
1568 vector<const CWalletTx*> vwtxPrev;
1571 * TODO: performance comparison
1573 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1574 static uint256 hashPrevBlock;
1575 static int64 nValueIn = 0;
1577 // Cache outputs unless best block changed
1578 if (hashPrevBlock != pindexBest->GetBlockHash())
1580 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1583 if (setCoins.empty())
1586 hashPrevBlock == pindexBest->GetBlockHash();
1590 set<pair<const CWalletTx*,unsigned int> > setCoins;
1593 // Select coins with suitable depth
1594 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1597 if (setCoins.empty())
1601 CScript scriptPubKeyKernel;
1603 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1607 LOCK2(cs_main, cs_wallet);
1608 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1612 // Read block header
1615 LOCK2(cs_main, cs_wallet);
1616 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1620 static int nMaxStakeSearchInterval = 60;
1621 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1622 continue; // only count coins meeting min age requirement
1624 bool fKernelFound = false;
1625 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1627 // Search backward in time from the given txNew timestamp
1628 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1629 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1630 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1631 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1634 if (fDebug && GetBoolArg("-printcoinstake"))
1635 printf("CreateCoinStake : kernel found\n");
1636 vector<valtype> vSolutions;
1637 txnouttype whichType;
1638 CScript scriptPubKeyOut;
1639 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1640 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1642 if (fDebug && GetBoolArg("-printcoinstake"))
1643 printf("CreateCoinStake : failed to parse kernel\n");
1646 if (fDebug && GetBoolArg("-printcoinstake"))
1647 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1648 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1650 if (fDebug && GetBoolArg("-printcoinstake"))
1651 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1652 break; // only support pay to public key and pay to address
1654 if (whichType == TX_PUBKEYHASH) // pay to address type
1656 // convert to pay to public key type
1657 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1659 if (fDebug && GetBoolArg("-printcoinstake"))
1660 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1661 break; // unable to find corresponding public key
1663 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1665 if (whichType == TX_PUBKEY)
1667 valtype& vchPubKey = vSolutions[0];
1668 if (!keystore.GetKey(Hash160(vchPubKey), key))
1670 if (fDebug && GetBoolArg("-printcoinstake"))
1671 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1672 break; // unable to find corresponding public key
1675 if (key.GetPubKey() != vchPubKey)
1677 if (fDebug && GetBoolArg("-printcoinstake"))
1678 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1679 break; // keys mismatch
1682 scriptPubKeyOut = scriptPubKeyKernel;
1686 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1687 nCredit += pcoin.first->vout[pcoin.second].nValue;
1688 vwtxPrev.push_back(pcoin.first);
1689 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1691 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1692 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1693 if (fDebug && GetBoolArg("-printcoinstake"))
1694 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1695 fKernelFound = true;
1700 if (fKernelFound || fShutdown)
1701 break; // if kernel is found stop searching
1704 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1707 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1709 // Attempt to add more inputs
1710 // Only add coins of the same key/address as kernel
1711 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1712 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1714 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1716 // Stop adding more inputs if already too many inputs
1717 if (txNew.vin.size() >= 100)
1719 // Stop adding more inputs if value is already pretty significant
1720 if (nCredit > nCombineThreshold)
1722 // Stop adding inputs if reached reserve limit
1723 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1725 // Do not add additional significant input
1726 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1728 // Do not add input that is still too young
1729 if (nTimeWeight < nStakeMaxAge)
1732 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1733 nCredit += pcoin.first->vout[pcoin.second].nValue;
1734 vwtxPrev.push_back(pcoin.first);
1738 // Calculate coin age reward
1742 if (!txNew.GetCoinAge(txdb, nCoinAge))
1743 return error("CreateCoinStake : failed to calculate coin age");
1744 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1750 // Set output amount
1751 if (txNew.vout.size() == 3)
1753 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1754 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1757 txNew.vout[1].nValue = nCredit - nMinFee;
1761 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1763 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1764 return error("CreateCoinStake : failed to sign coinstake");
1768 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1769 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1770 return error("CreateCoinStake : exceeded coinstake size limit");
1772 // Check enough fee is paid
1773 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1775 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1776 continue; // try signing again
1780 if (fDebug && GetBoolArg("-printfee"))
1781 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1786 // Successfully generated coinstake
1791 // Call after CreateTransaction unless you want to abort
1792 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1795 LOCK2(cs_main, cs_wallet);
1796 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1798 // This is only to keep the database open to defeat the auto-flush for the
1799 // duration of this scope. This is the only place where this optimization
1800 // maybe makes sense; please don't do it anywhere else.
1801 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1803 // Take key pair from key pool so it won't be used again
1804 reservekey.KeepKey();
1806 // Add tx to wallet, because if it has change it's also ours,
1807 // otherwise just for transaction history.
1808 AddToWallet(wtxNew);
1810 // Mark old coins as spent
1811 set<CWalletTx*> setCoins;
1812 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1814 CWalletTx &coin = mapWallet[txin.prevout.hash];
1815 coin.BindWallet(this);
1816 coin.MarkSpent(txin.prevout.n);
1818 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1825 // Track how many getdata requests our transaction gets
1826 mapRequestCount[wtxNew.GetHash()] = 0;
1829 if (!wtxNew.AcceptToMemoryPool())
1831 // This must not fail. The transaction has already been signed and recorded.
1832 printf("CommitTransaction() : Error: Transaction not valid");
1835 wtxNew.RelayWalletTransaction();
1843 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1845 CReserveKey reservekey(this);
1850 string strError = _("Error: Wallet locked, unable to create transaction ");
1851 printf("SendMoney() : %s", strError.c_str());
1854 if (fWalletUnlockMintOnly)
1856 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1857 printf("SendMoney() : %s", strError.c_str());
1860 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1863 if (nValue + nFeeRequired > GetBalance())
1864 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());
1866 strError = _("Error: Transaction creation failed ");
1867 printf("SendMoney() : %s", strError.c_str());
1871 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1874 if (!CommitTransaction(wtxNew, reservekey))
1875 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.");
1882 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1886 return _("Invalid amount");
1887 if (nValue + nTransactionFee > GetBalance())
1888 return _("Insufficient funds");
1890 // Parse Bitcoin address
1891 CScript scriptPubKey;
1892 scriptPubKey.SetDestination(address);
1894 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1900 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1904 fFirstRunRet = false;
1905 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1906 if (nLoadWalletRet == DB_NEED_REWRITE)
1908 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1911 // Note: can't top-up keypool here, because wallet is locked.
1912 // User will be prompted to unlock wallet the next operation
1913 // the requires a new key.
1917 if (nLoadWalletRet != DB_LOAD_OK)
1918 return nLoadWalletRet;
1919 fFirstRunRet = !vchDefaultKey.IsValid();
1921 NewThread(ThreadFlushWalletDB, &strWalletFile);
1926 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1928 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1929 mapAddressBook[address] = strName;
1930 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1933 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1936 bool CWallet::DelAddressBookName(const CTxDestination& address)
1938 mapAddressBook.erase(address);
1939 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1942 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1946 void CWallet::PrintWallet(const CBlock& block)
1950 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1952 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1953 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1955 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1957 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1958 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1965 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1969 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1970 if (mi != mapWallet.end())
1979 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1983 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1986 vchDefaultKey = vchPubKey;
1990 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1992 if (!pwallet->fFileBacked)
1994 strWalletFileOut = pwallet->strWalletFile;
1999 // Mark old keypool keys as used,
2000 // and generate all new keys
2002 bool CWallet::NewKeyPool()
2006 CWalletDB walletdb(strWalletFile);
2007 BOOST_FOREACH(int64 nIndex, setKeyPool)
2008 walletdb.ErasePool(nIndex);
2014 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2015 for (int i = 0; i < nKeys; i++)
2018 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2019 setKeyPool.insert(nIndex);
2021 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2026 bool CWallet::TopUpKeyPool(unsigned int nSize)
2034 CWalletDB walletdb(strWalletFile);
2037 unsigned int nTargetSize;
2039 nTargetSize = nSize;
2041 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2043 while (setKeyPool.size() < (nTargetSize + 1))
2046 if (!setKeyPool.empty())
2047 nEnd = *(--setKeyPool.end()) + 1;
2048 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2049 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2050 setKeyPool.insert(nEnd);
2051 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2057 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2060 keypool.vchPubKey = CPubKey();
2067 // Get the oldest key
2068 if(setKeyPool.empty())
2071 CWalletDB walletdb(strWalletFile);
2073 nIndex = *(setKeyPool.begin());
2074 setKeyPool.erase(setKeyPool.begin());
2075 if (!walletdb.ReadPool(nIndex, keypool))
2076 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2077 if (!HaveKey(keypool.vchPubKey.GetID()))
2078 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2079 assert(keypool.vchPubKey.IsValid());
2080 if (fDebug && GetBoolArg("-printkeypool"))
2081 printf("keypool reserve %"PRI64d"\n", nIndex);
2085 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2088 LOCK2(cs_main, cs_wallet);
2089 CWalletDB walletdb(strWalletFile);
2091 int64 nIndex = 1 + *(--setKeyPool.end());
2092 if (!walletdb.WritePool(nIndex, keypool))
2093 throw runtime_error("AddReserveKey() : writing added key failed");
2094 setKeyPool.insert(nIndex);
2100 void CWallet::KeepKey(int64 nIndex)
2102 // Remove from key pool
2105 CWalletDB walletdb(strWalletFile);
2106 walletdb.ErasePool(nIndex);
2109 printf("keypool keep %"PRI64d"\n", nIndex);
2112 void CWallet::ReturnKey(int64 nIndex)
2114 // Return to key pool
2117 setKeyPool.insert(nIndex);
2120 printf("keypool return %"PRI64d"\n", nIndex);
2123 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2129 ReserveKeyFromKeyPool(nIndex, keypool);
2132 if (fAllowReuse && vchDefaultKey.IsValid())
2134 result = vchDefaultKey;
2137 if (IsLocked()) return false;
2138 result = GenerateNewKey();
2142 result = keypool.vchPubKey;
2147 int64 CWallet::GetOldestKeyPoolTime()
2151 ReserveKeyFromKeyPool(nIndex, keypool);
2155 return keypool.nTime;
2158 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2160 map<CTxDestination, int64> balances;
2164 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2166 CWalletTx *pcoin = &walletEntry.second;
2168 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2171 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2174 int nDepth = pcoin->GetDepthInMainChain();
2175 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2178 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2180 CTxDestination addr;
2181 if (!IsMine(pcoin->vout[i]))
2183 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2186 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2188 if (!balances.count(addr))
2190 balances[addr] += n;
2198 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2200 set< set<CTxDestination> > groupings;
2201 set<CTxDestination> grouping;
2203 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2205 CWalletTx *pcoin = &walletEntry.second;
2207 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2209 // group all input addresses with each other
2210 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2212 CTxDestination address;
2213 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2215 grouping.insert(address);
2218 // group change with input addresses
2219 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2220 if (IsChange(txout))
2222 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2223 CTxDestination txoutAddr;
2224 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2226 grouping.insert(txoutAddr);
2228 groupings.insert(grouping);
2232 // group lone addrs by themselves
2233 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2234 if (IsMine(pcoin->vout[i]))
2236 CTxDestination address;
2237 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2239 grouping.insert(address);
2240 groupings.insert(grouping);
2245 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2246 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2247 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2249 // make a set of all the groups hit by this new group
2250 set< set<CTxDestination>* > hits;
2251 map< CTxDestination, set<CTxDestination>* >::iterator it;
2252 BOOST_FOREACH(CTxDestination address, grouping)
2253 if ((it = setmap.find(address)) != setmap.end())
2254 hits.insert((*it).second);
2256 // merge all hit groups into a new single group and delete old groups
2257 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2258 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2260 merged->insert(hit->begin(), hit->end());
2261 uniqueGroupings.erase(hit);
2264 uniqueGroupings.insert(merged);
2267 BOOST_FOREACH(CTxDestination element, *merged)
2268 setmap[element] = merged;
2271 set< set<CTxDestination> > ret;
2272 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2274 ret.insert(*uniqueGrouping);
2275 delete uniqueGrouping;
2281 // ppcoin: check 'spent' consistency between wallet and txindex
2282 // ppcoin: fix wallet spent state according to txindex
2283 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2286 nBalanceInQuestion = 0;
2289 vector<CWalletTx*> vCoins;
2290 vCoins.reserve(mapWallet.size());
2291 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2292 vCoins.push_back(&(*it).second);
2295 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2297 // Find the corresponding transaction index
2299 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2301 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2303 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2305 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2306 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2308 nBalanceInQuestion += pcoin->vout[n].nValue;
2311 pcoin->MarkUnspent(n);
2312 pcoin->WriteToDisk();
2315 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2317 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2318 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2320 nBalanceInQuestion += pcoin->vout[n].nValue;
2323 pcoin->MarkSpent(n);
2324 pcoin->WriteToDisk();
2331 // ppcoin: disable transaction (only for coinstake)
2332 void CWallet::DisableTransaction(const CTransaction &tx)
2334 if (!tx.IsCoinStake() || !IsFromMe(tx))
2335 return; // only disconnecting coinstake requires marking input unspent
2338 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2340 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2341 if (mi != mapWallet.end())
2343 CWalletTx& prev = (*mi).second;
2344 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2346 prev.MarkUnspent(txin.prevout.n);
2353 CPubKey CReserveKey::GetReservedKey()
2358 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2360 vchPubKey = keypool.vchPubKey;
2363 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2364 vchPubKey = pwallet->vchDefaultKey;
2367 assert(vchPubKey.IsValid());
2371 void CReserveKey::KeepKey()
2374 pwallet->KeepKey(nIndex);
2376 vchPubKey = CPubKey();
2379 void CReserveKey::ReturnKey()
2382 pwallet->ReturnKey(nIndex);
2384 vchPubKey = CPubKey();
2387 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2391 CWalletDB walletdb(strWalletFile);
2393 LOCK2(cs_main, cs_wallet);
2394 BOOST_FOREACH(const int64& id, setKeyPool)
2397 if (!walletdb.ReadPool(id, keypool))
2398 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2399 assert(keypool.vchPubKey.IsValid());
2400 CKeyID keyID = keypool.vchPubKey.GetID();
2401 if (!HaveKey(keyID))
2402 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2403 setAddress.insert(keyID);
2407 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2411 // Only notify UI if this transaction is in this wallet
2412 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2413 if (mi != mapWallet.end())
2414 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2418 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2419 mapKeyBirth.clear();
2421 // get birth times for keys with metadata
2422 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2423 if (it->second.nCreateTime)
2424 mapKeyBirth[it->first] = it->second.nCreateTime;
2426 // map in which we'll infer heights of other keys
2427 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2428 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2429 std::set<CKeyID> setKeys;
2431 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2432 if (mapKeyBirth.count(keyid) == 0)
2433 mapKeyFirstBlock[keyid] = pindexMax;
2437 // if there are no such keys, we're done
2438 if (mapKeyFirstBlock.empty())
2441 // find first block that affects those keys, if there are any left
2442 std::vector<CKeyID> vAffected;
2443 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2444 // iterate over all wallet transactions...
2445 const CWalletTx &wtx = (*it).second;
2446 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2447 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2448 // ... which are already in a block
2449 int nHeight = blit->second->nHeight;
2450 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2451 // iterate over all their outputs
2452 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2453 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2454 // ... and all their affected keys
2455 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2456 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2457 rit->second = blit->second;
2464 // Extract block timestamps for those keys
2465 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2466 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off