1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
17 extern int nStakeMaxAge;
19 //////////////////////////////////////////////////////////////////////////////
24 struct CompareValueOnly
26 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
29 return t1.first < t2.first;
33 CPubKey CWallet::GenerateNewKey()
35 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
39 key.MakeNewKey(fCompressed);
41 // Compressed public keys were introduced in version 0.6.0
43 SetMinVersion(FEATURE_COMPRPUBKEY);
45 CPubKey pubkey = key.GetPubKey();
47 // Create new metadata
48 int64 nCreationTime = GetTime();
49 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51 nTimeFirstKey = nCreationTime;
54 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55 return key.GetPubKey();
58 bool CWallet::AddKey(const CKey& key)
60 CPubKey pubkey = key.GetPubKey();
62 if (!CCryptoKeyStore::AddKey(key))
67 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
73 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 if (pwalletdbEncryption)
80 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
82 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
89 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90 nTimeFirstKey = meta.nCreateTime;
92 mapKeyMetadata[pubkey.GetID()] = meta;
96 bool CWallet::AddCScript(const CScript& redeemScript)
98 if (!CCryptoKeyStore::AddCScript(redeemScript))
102 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
105 // ppcoin: optional setting to unlock wallet for block minting only;
106 // serves to disable the trivial sendmoney when OS account compromised
107 bool fWalletUnlockMintOnly = false;
109 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
115 CKeyingMaterial vMasterKey;
119 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
121 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
123 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
125 if (CCryptoKeyStore::Unlock(vMasterKey))
132 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
134 bool fWasLocked = IsLocked();
141 CKeyingMaterial vMasterKey;
142 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
144 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
146 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
148 if (CCryptoKeyStore::Unlock(vMasterKey))
150 int64 nStartTime = GetTimeMillis();
151 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
152 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
154 nStartTime = GetTimeMillis();
155 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
156 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
158 if (pMasterKey.second.nDeriveIterations < 25000)
159 pMasterKey.second.nDeriveIterations = 25000;
161 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
163 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
165 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
167 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
178 void CWallet::SetBestChain(const CBlockLocator& loc)
180 CWalletDB walletdb(strWalletFile);
181 walletdb.WriteBestBlock(loc);
184 // This class implements an addrIncoming entry that causes pre-0.4
185 // clients to crash on startup if reading a private-key-encrypted wallet.
186 class CCorruptAddress
191 if (nType & SER_DISK)
196 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
198 if (nWalletVersion >= nVersion)
201 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
202 if (fExplicit && nVersion > nWalletMaxVersion)
203 nVersion = FEATURE_LATEST;
205 nWalletVersion = nVersion;
207 if (nVersion > nWalletMaxVersion)
208 nWalletMaxVersion = nVersion;
212 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
213 if (nWalletVersion >= 40000)
215 // Versions prior to 0.4.0 did not support the "minversion" record.
216 // Use a CCorruptAddress to make them crash instead.
217 CCorruptAddress corruptAddress;
218 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
220 if (nWalletVersion > 40000)
221 pwalletdb->WriteMinVersion(nWalletVersion);
229 bool CWallet::SetMaxVersion(int nVersion)
231 // cannot downgrade below current version
232 if (nWalletVersion > nVersion)
235 nWalletMaxVersion = nVersion;
240 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
245 CKeyingMaterial vMasterKey;
246 RandAddSeedPerfmon();
248 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
249 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
251 CMasterKey kMasterKey(nDerivationMethodIndex);
253 RandAddSeedPerfmon();
254 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
255 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
258 int64 nStartTime = GetTimeMillis();
259 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
260 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
262 nStartTime = GetTimeMillis();
263 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
264 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
266 if (kMasterKey.nDeriveIterations < 25000)
267 kMasterKey.nDeriveIterations = 25000;
269 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
271 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
273 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
278 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
281 pwalletdbEncryption = new CWalletDB(strWalletFile);
282 if (!pwalletdbEncryption->TxnBegin())
284 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
287 if (!EncryptKeys(vMasterKey))
290 pwalletdbEncryption->TxnAbort();
291 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.
294 // Encryption was introduced in version 0.4.0
295 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
299 if (!pwalletdbEncryption->TxnCommit())
300 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.
302 delete pwalletdbEncryption;
303 pwalletdbEncryption = NULL;
307 Unlock(strWalletPassphrase);
311 // Need to completely rewrite the wallet file; if we don't, bdb might keep
312 // bits of the unencrypted private key in slack space in the database file.
313 CDB::Rewrite(strWalletFile);
316 NotifyStatusChanged(this);
321 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
323 int64 nRet = nOrderPosNext++;
325 pwalletdb->WriteOrderPosNext(nOrderPosNext);
327 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
332 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
334 CWalletDB walletdb(strWalletFile);
336 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
339 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
340 // would make this much faster for applications that do this a lot.
341 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
343 CWalletTx* wtx = &((*it).second);
344 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
347 walletdb.ListAccountCreditDebit(strAccount, acentries);
348 BOOST_FOREACH(CAccountingEntry& entry, acentries)
350 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
356 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
358 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
359 // Update the wallet spent flag if it doesn't know due to wallet.dat being
360 // restored from backup or the user making copies of wallet.dat.
363 BOOST_FOREACH(const CTxIn& txin, tx.vin)
365 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
366 if (mi != mapWallet.end())
368 CWalletTx& wtx = (*mi).second;
369 if (txin.prevout.n >= wtx.vout.size())
370 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
371 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
373 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
374 wtx.MarkSpent(txin.prevout.n);
376 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
383 uint256 hash = tx.GetHash();
384 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
385 CWalletTx& wtx = (*mi).second;
387 BOOST_FOREACH(const CTxOut& txout, tx.vout)
391 wtx.MarkUnspent(&txout - &tx.vout[0]);
393 NotifyTransactionChanged(this, hash, CT_UPDATED);
401 void CWallet::MarkDirty()
405 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
406 item.second.MarkDirty();
410 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
412 uint256 hash = wtxIn.GetHash();
415 // Inserts only if not already there, returns tx inserted or tx found
416 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
417 CWalletTx& wtx = (*ret.first).second;
418 wtx.BindWallet(this);
419 bool fInsertedNew = ret.second;
422 wtx.nTimeReceived = GetAdjustedTime();
423 wtx.nOrderPos = IncOrderPosNext();
425 wtx.nTimeSmart = wtx.nTimeReceived;
426 if (wtxIn.hashBlock != 0)
428 if (mapBlockIndex.count(wtxIn.hashBlock))
430 unsigned int latestNow = wtx.nTimeReceived;
431 unsigned int latestEntry = 0;
433 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
434 int64 latestTolerated = latestNow + 300;
435 std::list<CAccountingEntry> acentries;
436 TxItems txOrdered = OrderedTxItems(acentries);
437 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
439 CWalletTx *const pwtx = (*it).second.first;
442 CAccountingEntry *const pacentry = (*it).second.second;
446 nSmartTime = pwtx->nTimeSmart;
448 nSmartTime = pwtx->nTimeReceived;
451 nSmartTime = pacentry->nTime;
452 if (nSmartTime <= latestTolerated)
454 latestEntry = nSmartTime;
455 if (nSmartTime > latestNow)
456 latestNow = nSmartTime;
462 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
463 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
466 printf("AddToWallet() : found %s in block %s not in index\n",
467 wtxIn.GetHash().ToString().substr(0,10).c_str(),
468 wtxIn.hashBlock.ToString().c_str());
472 bool fUpdated = false;
476 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
478 wtx.hashBlock = wtxIn.hashBlock;
481 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
483 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
484 wtx.nIndex = wtxIn.nIndex;
487 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
489 wtx.fFromMe = wtxIn.fFromMe;
492 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
496 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
499 if (fInsertedNew || fUpdated)
500 if (!wtx.WriteToDisk())
503 // If default receiving address gets used, replace it with a new one
504 CScript scriptDefaultKey;
505 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
506 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
508 if (txout.scriptPubKey == scriptDefaultKey)
510 CPubKey newDefaultKey;
511 if (GetKeyFromPool(newDefaultKey, false))
513 SetDefaultKey(newDefaultKey);
514 SetAddressBookName(vchDefaultKey.GetID(), "");
519 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
520 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
522 // Notify UI of new or updated transaction
523 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
525 // notify an external script when a wallet transaction comes in or is updated
526 std::string strCmd = GetArg("-walletnotify", "");
528 if ( !strCmd.empty())
530 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
531 boost::thread t(runCommand, strCmd); // thread runs free
538 // Add a transaction to the wallet, or update it.
539 // pblock is optional, but should be provided if the transaction is known to be in a block.
540 // If fUpdate is true, existing transactions will be updated.
541 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
543 uint256 hash = tx.GetHash();
546 bool fExisted = mapWallet.count(hash);
547 if (fExisted && !fUpdate) return false;
548 if (fExisted || IsMine(tx) || IsFromMe(tx))
550 CWalletTx wtx(this,tx);
551 // Get merkle branch if transaction was found in a block
553 wtx.SetMerkleBranch(pblock);
554 return AddToWallet(wtx);
557 WalletUpdateSpent(tx);
562 bool CWallet::EraseFromWallet(uint256 hash)
568 if (mapWallet.erase(hash))
569 CWalletDB(strWalletFile).EraseTx(hash);
575 bool CWallet::IsMine(const CTxIn &txin) const
579 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
580 if (mi != mapWallet.end())
582 const CWalletTx& prev = (*mi).second;
583 if (txin.prevout.n < prev.vout.size())
584 if (IsMine(prev.vout[txin.prevout.n]))
591 int64 CWallet::GetDebit(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 if (IsMine(prev.vout[txin.prevout.n]))
601 return prev.vout[txin.prevout.n].nValue;
607 bool CWallet::IsChange(const CTxOut& txout) const
609 CTxDestination address;
611 // TODO: fix handling of 'change' outputs. The assumption is that any
612 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
613 // is change. That assumption is likely to break when we implement multisignature
614 // wallets that return change back into a multi-signature-protected address;
615 // a better way of identifying which outputs are 'the send' and which are
616 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
617 // which output, if any, was change).
618 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
621 if (!mapAddressBook.count(address))
627 int64 CWalletTx::GetTxTime() const
629 int64 n = nTimeSmart;
630 return n ? n : nTimeReceived;
633 int CWalletTx::GetRequestCount() const
635 // Returns -1 if it wasn't being tracked
638 LOCK(pwallet->cs_wallet);
639 if (IsCoinBase() || IsCoinStake())
644 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
645 if (mi != pwallet->mapRequestCount.end())
646 nRequests = (*mi).second;
651 // Did anyone request this transaction?
652 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
653 if (mi != pwallet->mapRequestCount.end())
655 nRequests = (*mi).second;
657 // How about the block it's in?
658 if (nRequests == 0 && hashBlock != 0)
660 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
661 if (mi != pwallet->mapRequestCount.end())
662 nRequests = (*mi).second;
664 nRequests = 1; // If it's in someone else's block it must have got out
672 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
673 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
675 nGeneratedImmature = nGeneratedMature = nFee = 0;
676 listReceived.clear();
678 strSentAccount = strFromAccount;
680 if (IsCoinBase() || IsCoinStake())
682 if (GetBlocksToMaturity() > 0)
683 nGeneratedImmature = pwallet->GetCredit(*this);
685 nGeneratedMature = GetCredit();
690 int64 nDebit = GetDebit();
691 if (nDebit > 0) // debit>0 means we signed/sent this transaction
693 int64 nValueOut = GetValueOut();
694 nFee = nDebit - nValueOut;
698 BOOST_FOREACH(const CTxOut& txout, vout)
701 // Only need to handle txouts if AT LEAST one of these is true:
702 // 1) they debit from us (sent)
703 // 2) the output is to us (received)
706 // Don't report 'change' txouts
707 if (pwallet->IsChange(txout))
709 fIsMine = pwallet->IsMine(txout);
711 else if (!(fIsMine = pwallet->IsMine(txout)))
714 // In either case, we need to get the destination address
715 CTxDestination address;
716 if (!ExtractDestination(txout.scriptPubKey, address))
718 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
719 this->GetHash().ToString().c_str());
720 address = CNoDestination();
723 // If we are debited by the transaction, add the output as a "sent" entry
725 listSent.push_back(make_pair(address, txout.nValue));
727 // If we are receiving the output, add it as a "received" entry
729 listReceived.push_back(make_pair(address, txout.nValue));
734 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
735 int64& nSent, int64& nFee) const
737 nGenerated = nReceived = nSent = nFee = 0;
739 int64 allGeneratedImmature, allGeneratedMature, allFee;
740 allGeneratedImmature = allGeneratedMature = allFee = 0;
741 string strSentAccount;
742 list<pair<CTxDestination, int64> > listReceived;
743 list<pair<CTxDestination, int64> > listSent;
744 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
746 if (strAccount == "")
747 nGenerated = allGeneratedMature;
748 if (strAccount == strSentAccount)
750 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
755 LOCK(pwallet->cs_wallet);
756 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
758 if (pwallet->mapAddressBook.count(r.first))
760 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
761 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
762 nReceived += r.second;
764 else if (strAccount.empty())
766 nReceived += r.second;
772 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
776 const int COPY_DEPTH = 3;
777 if (SetMerkleBranch() < COPY_DEPTH)
779 vector<uint256> vWorkQueue;
780 BOOST_FOREACH(const CTxIn& txin, vin)
781 vWorkQueue.push_back(txin.prevout.hash);
783 // This critsect is OK because txdb is already open
785 LOCK(pwallet->cs_wallet);
786 map<uint256, const CMerkleTx*> mapWalletPrev;
787 set<uint256> setAlreadyDone;
788 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
790 uint256 hash = vWorkQueue[i];
791 if (setAlreadyDone.count(hash))
793 setAlreadyDone.insert(hash);
796 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
797 if (mi != pwallet->mapWallet.end())
800 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
801 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
803 else if (mapWalletPrev.count(hash))
805 tx = *mapWalletPrev[hash];
807 else if (!fClient && txdb.ReadDiskTx(hash, tx))
813 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
817 int nDepth = tx.SetMerkleBranch();
818 vtxPrev.push_back(tx);
820 if (nDepth < COPY_DEPTH)
822 BOOST_FOREACH(const CTxIn& txin, tx.vin)
823 vWorkQueue.push_back(txin.prevout.hash);
829 reverse(vtxPrev.begin(), vtxPrev.end());
832 bool CWalletTx::WriteToDisk()
834 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
837 // Scan the block chain (starting in pindexStart) for transactions
838 // from or to us. If fUpdate is true, found transactions that already
839 // exist in the wallet will be updated.
840 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
844 CBlockIndex* pindex = pindexStart;
850 block.ReadFromDisk(pindex, true);
851 BOOST_FOREACH(CTransaction& tx, block.vtx)
853 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
856 pindex = pindex->pnext;
862 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
865 tx.ReadFromDisk(COutPoint(hashTx, 0));
866 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
871 void CWallet::ReacceptWalletTransactions()
879 vector<CDiskTxPos> vMissingTx;
880 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
882 CWalletTx& wtx = item.second;
883 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
887 bool fUpdated = false;
888 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
890 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
891 if (txindex.vSpent.size() != wtx.vout.size())
893 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
896 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
900 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
904 vMissingTx.push_back(txindex.vSpent[i]);
909 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
916 // Re-accept any txes of ours that aren't already in a block
917 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
918 wtx.AcceptWalletTransaction(txdb, false);
921 if (!vMissingTx.empty())
923 // TODO: optimize this to scan just part of the block chain?
924 if (ScanForWalletTransactions(pindexGenesisBlock))
925 fRepeat = true; // Found missing transactions: re-do re-accept.
930 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
932 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
934 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
936 uint256 hash = tx.GetHash();
937 if (!txdb.ContainsTx(hash))
938 RelayTransaction((CTransaction)tx, hash);
941 if (!(IsCoinBase() || IsCoinStake()))
943 uint256 hash = GetHash();
944 if (!txdb.ContainsTx(hash))
946 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
947 RelayTransaction((CTransaction)*this, hash);
952 void CWalletTx::RelayWalletTransaction()
955 RelayWalletTransaction(txdb);
958 void CWallet::ResendWalletTransactions()
960 // Do this infrequently and randomly to avoid giving away
961 // that these are our transactions.
962 static int64 nNextTime;
963 if (GetTime() < nNextTime)
965 bool fFirst = (nNextTime == 0);
966 nNextTime = GetTime() + GetRand(30 * 60);
970 // Only do it if there's been a new block since last time
971 static int64 nLastTime;
972 if (nTimeBestReceived < nLastTime)
974 nLastTime = GetTime();
976 // Rebroadcast any of our txes that aren't in a block yet
977 printf("ResendWalletTransactions()\n");
981 // Sort them in chronological order
982 multimap<unsigned int, CWalletTx*> mapSorted;
983 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
985 CWalletTx& wtx = item.second;
986 // Don't rebroadcast until it's had plenty of time that
987 // it should have gotten in already by now.
988 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
989 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
991 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
993 CWalletTx& wtx = *item.second;
994 if (wtx.CheckTransaction())
995 wtx.RelayWalletTransaction(txdb);
997 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1007 //////////////////////////////////////////////////////////////////////////////
1013 int64 CWallet::GetBalance() const
1018 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1020 const CWalletTx* pcoin = &(*it).second;
1021 if (pcoin->IsTrusted())
1022 nTotal += pcoin->GetAvailableCredit();
1029 int64 CWallet::GetUnconfirmedBalance() const
1034 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1036 const CWalletTx* pcoin = &(*it).second;
1037 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1038 nTotal += pcoin->GetAvailableCredit();
1044 int64 CWallet::GetImmatureBalance() const
1049 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1051 const CWalletTx& pcoin = (*it).second;
1052 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1053 nTotal += GetCredit(pcoin);
1059 // populate vCoins with vector of spendable COutputs
1060 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1066 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1068 const CWalletTx* pcoin = &(*it).second;
1070 if (!pcoin->IsFinal())
1073 if (fOnlyConfirmed && !pcoin->IsTrusted())
1076 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1079 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1082 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1083 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1084 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1085 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1091 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1097 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1099 const CWalletTx* pcoin = &(*it).second;
1101 if (!pcoin->IsFinal())
1104 if(pcoin->GetDepthInMainChain() < nConf)
1107 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1108 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1109 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1114 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1115 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1117 vector<char> vfIncluded;
1119 vfBest.assign(vValue.size(), true);
1120 nBest = nTotalLower;
1122 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1124 vfIncluded.assign(vValue.size(), false);
1126 bool fReachedTarget = false;
1127 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1129 for (unsigned int i = 0; i < vValue.size(); i++)
1131 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1133 nTotal += vValue[i].first;
1134 vfIncluded[i] = true;
1135 if (nTotal >= nTargetValue)
1137 fReachedTarget = true;
1141 vfBest = vfIncluded;
1143 nTotal -= vValue[i].first;
1144 vfIncluded[i] = false;
1152 // ppcoin: total coins staked (non-spendable until maturity)
1153 int64 CWallet::GetStake() const
1157 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1159 const CWalletTx* pcoin = &(*it).second;
1160 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1161 nTotal += CWallet::GetCredit(*pcoin);
1166 int64 CWallet::GetNewMint() const
1170 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1172 const CWalletTx* pcoin = &(*it).second;
1173 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1174 nTotal += CWallet::GetCredit(*pcoin);
1179 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
1181 setCoinsRet.clear();
1184 // List of values less than target
1185 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1186 coinLowestLarger.first = std::numeric_limits<int64>::max();
1187 coinLowestLarger.second.first = NULL;
1188 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1189 int64 nTotalLower = 0;
1191 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1193 BOOST_FOREACH(COutput output, vCoins)
1195 const CWalletTx *pcoin = output.tx;
1197 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1202 // Follow the timestamp rules
1203 if (pcoin->nTime > nSpendTime)
1206 int64 n = pcoin->vout[i].nValue;
1208 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1210 if (n == nTargetValue)
1212 setCoinsRet.insert(coin.second);
1213 nValueRet += coin.first;
1216 else if (n < nTargetValue + CENT)
1218 vValue.push_back(coin);
1221 else if (n < coinLowestLarger.first)
1223 coinLowestLarger = coin;
1227 if (nTotalLower == nTargetValue)
1229 for (unsigned int i = 0; i < vValue.size(); ++i)
1231 setCoinsRet.insert(vValue[i].second);
1232 nValueRet += vValue[i].first;
1237 if (nTotalLower < nTargetValue)
1239 if (coinLowestLarger.second.first == NULL)
1241 setCoinsRet.insert(coinLowestLarger.second);
1242 nValueRet += coinLowestLarger.first;
1246 // Solve subset sum by stochastic approximation
1247 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1248 vector<char> vfBest;
1251 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1252 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1253 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1255 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1256 // or the next bigger coin is closer), return the bigger coin
1257 if (coinLowestLarger.second.first &&
1258 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1260 setCoinsRet.insert(coinLowestLarger.second);
1261 nValueRet += coinLowestLarger.first;
1264 for (unsigned int i = 0; i < vValue.size(); i++)
1267 setCoinsRet.insert(vValue[i].second);
1268 nValueRet += vValue[i].first;
1271 if (fDebug && GetBoolArg("-printpriority"))
1274 printf("SelectCoins() best subset: ");
1275 for (unsigned int i = 0; i < vValue.size(); i++)
1277 printf("%s ", FormatMoney(vValue[i].first).c_str());
1278 printf("total %s\n", FormatMoney(nBest).c_str());
1285 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1287 vector<COutput> vCoins;
1288 AvailableCoins(vCoins, true, coinControl);
1290 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1291 if (coinControl && coinControl->HasSelected())
1293 BOOST_FOREACH(const COutput& out, vCoins)
1295 nValueRet += out.tx->vout[out.i].nValue;
1296 setCoinsRet.insert(make_pair(out.tx, out.i));
1298 return (nValueRet >= nTargetValue);
1301 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1302 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1303 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1306 // Select some coins without random shuffle or best subset approximation
1307 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1309 vector<COutput> vCoins;
1310 AvailableCoinsMinConf(vCoins, nMinConf);
1312 setCoinsRet.clear();
1315 BOOST_FOREACH(COutput output, vCoins)
1317 const CWalletTx *pcoin = output.tx;
1320 // Stop if we've chosen enough inputs
1321 if (nValueRet >= nTargetValue)
1324 // Follow the timestamp rules
1325 if (pcoin->nTime > nSpendTime)
1328 int64 n = pcoin->vout[i].nValue;
1330 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1332 if (n >= nTargetValue)
1334 // If input value is greater or equal to target then simply insert
1335 // it into the current subset and exit
1336 setCoinsRet.insert(coin.second);
1337 nValueRet += coin.first;
1340 else if (n < nTargetValue + CENT)
1342 setCoinsRet.insert(coin.second);
1343 nValueRet += coin.first;
1350 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1353 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1359 if (vecSend.empty() || nValue < 0)
1362 wtxNew.BindWallet(this);
1365 LOCK2(cs_main, cs_wallet);
1366 // txdb must be opened before the mapWallet lock
1369 nFeeRet = nTransactionFee;
1373 wtxNew.vout.clear();
1374 wtxNew.fFromMe = true;
1376 int64 nTotalValue = nValue + nFeeRet;
1377 double dPriority = 0;
1378 // vouts to the payees
1379 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1380 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1382 // Choose coins to use
1383 set<pair<const CWalletTx*,unsigned int> > setCoins;
1385 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1387 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1389 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1390 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1393 int64 nChange = nValueIn - nValue - nFeeRet;
1394 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1395 // or until nChange becomes zero
1396 // NOTE: this depends on the exact behaviour of GetMinFee
1397 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1399 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1400 nChange -= nMoveToFee;
1401 nFeeRet += nMoveToFee;
1404 // ppcoin: sub-cent change is moved to fee
1405 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1413 // Fill a vout to ourself
1414 // TODO: pass in scriptChange instead of reservekey so
1415 // change transaction isn't always pay-to-bitcoin-address
1416 CScript scriptChange;
1418 // coin control: send change to custom address
1419 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1420 scriptChange.SetDestination(coinControl->destChange);
1422 // no coin control: send change to newly generated address
1425 // Note: We use a new key here to keep it from being obvious which side is the change.
1426 // The drawback is that by not reusing a previous key, the change may be lost if a
1427 // backup is restored, if the backup doesn't have the new private key for the change.
1428 // If we reused the old key, it would be possible to add code to look for and
1429 // rediscover unknown transactions that were written with keys of ours to recover
1430 // post-backup change.
1432 // Reserve a new key pair from key pool
1433 CPubKey vchPubKey = reservekey.GetReservedKey();
1435 scriptChange.SetDestination(vchPubKey.GetID());
1438 // Insert change txn at random position:
1439 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1440 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1443 reservekey.ReturnKey();
1446 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1447 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1451 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1452 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1456 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1457 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1459 dPriority /= nBytes;
1461 // Check that enough fee is included
1462 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1463 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND, nBytes);
1465 if (nFeeRet < max(nPayFee, nMinFee))
1467 nFeeRet = max(nPayFee, nMinFee);
1471 // Fill vtxPrev by copying from previous transactions vtxPrev
1472 wtxNew.AddSupportingTransactions(txdb);
1473 wtxNew.fTimeReceivedIsTxTime = true;
1482 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1484 vector< pair<CScript, int64> > vecSend;
1485 vecSend.push_back(make_pair(scriptPubKey, nValue));
1486 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1489 // NovaCoin: get current stake weight
1490 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1492 // Choose coins to use
1493 int64 nBalance = GetBalance();
1494 int64 nReserveBalance = 0;
1496 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1498 error("GetStakeWeight : invalid reserve balance amount");
1502 if (nBalance <= nReserveBalance)
1505 vector<const CWalletTx*> vwtxPrev;
1508 * TODO: performance comparison
1510 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1511 static uint256 hashPrevBlock;
1512 static int64 nValueIn = 0;
1514 // Cache outputs unless best block changed
1515 if (hashPrevBlock != pindexBest->GetBlockHash())
1517 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1520 if (setCoins.empty())
1523 hashPrevBlock == pindexBest->GetBlockHash();
1527 set<pair<const CWalletTx*,unsigned int> > setCoins;
1530 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1533 if (setCoins.empty())
1537 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1541 LOCK2(cs_main, cs_wallet);
1542 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1546 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1547 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1549 // Weight is greater than zero
1550 if (nTimeWeight > 0)
1552 nWeight += bnCoinDayWeight.getuint64();
1555 // Weight is greater than zero, but the maximum value isn't reached yet
1556 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1558 nMinWeight += bnCoinDayWeight.getuint64();
1561 // Maximum weight was reached
1562 if (nTimeWeight == nStakeMaxAge)
1564 nMaxWeight += bnCoinDayWeight.getuint64();
1571 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1573 // The following combine threshold is important to security
1574 // Should not be adjusted if you don't understand the consequences
1575 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1577 CBigNum bnTargetPerCoinDay;
1578 bnTargetPerCoinDay.SetCompact(nBits);
1583 // Mark coin stake transaction
1584 CScript scriptEmpty;
1585 scriptEmpty.clear();
1586 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1588 // Choose coins to use
1589 int64 nBalance = GetBalance();
1590 int64 nReserveBalance = 0;
1592 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1593 return error("CreateCoinStake : invalid reserve balance amount");
1595 if (nBalance <= nReserveBalance)
1598 vector<const CWalletTx*> vwtxPrev;
1601 * TODO: performance comparison
1603 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1604 static uint256 hashPrevBlock;
1605 static int64 nValueIn = 0;
1607 // Cache outputs unless best block changed
1608 if (hashPrevBlock != pindexBest->GetBlockHash())
1610 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1613 if (setCoins.empty())
1616 hashPrevBlock == pindexBest->GetBlockHash();
1620 set<pair<const CWalletTx*,unsigned int> > setCoins;
1623 // Select coins with suitable depth
1624 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1627 if (setCoins.empty())
1631 CScript scriptPubKeyKernel;
1633 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1637 LOCK2(cs_main, cs_wallet);
1638 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1642 // Read block header
1645 LOCK2(cs_main, cs_wallet);
1646 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1650 static int nMaxStakeSearchInterval = 60;
1651 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1652 continue; // only count coins meeting min age requirement
1654 bool fKernelFound = false;
1655 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1657 // Search backward in time from the given txNew timestamp
1658 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1659 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1660 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1661 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1664 if (fDebug && GetBoolArg("-printcoinstake"))
1665 printf("CreateCoinStake : kernel found\n");
1666 vector<valtype> vSolutions;
1667 txnouttype whichType;
1668 CScript scriptPubKeyOut;
1669 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1670 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1672 if (fDebug && GetBoolArg("-printcoinstake"))
1673 printf("CreateCoinStake : failed to parse kernel\n");
1676 if (fDebug && GetBoolArg("-printcoinstake"))
1677 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1678 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1680 if (fDebug && GetBoolArg("-printcoinstake"))
1681 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1682 break; // only support pay to public key and pay to address
1684 if (whichType == TX_PUBKEYHASH) // pay to address type
1686 // convert to pay to public key type
1687 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1689 if (fDebug && GetBoolArg("-printcoinstake"))
1690 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1691 break; // unable to find corresponding public key
1693 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1695 if (whichType == TX_PUBKEY)
1697 valtype& vchPubKey = vSolutions[0];
1698 if (!keystore.GetKey(Hash160(vchPubKey), key))
1700 if (fDebug && GetBoolArg("-printcoinstake"))
1701 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1702 break; // unable to find corresponding public key
1705 if (key.GetPubKey() != vchPubKey)
1707 if (fDebug && GetBoolArg("-printcoinstake"))
1708 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1709 break; // keys mismatch
1712 scriptPubKeyOut = scriptPubKeyKernel;
1716 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1717 nCredit += pcoin.first->vout[pcoin.second].nValue;
1718 vwtxPrev.push_back(pcoin.first);
1719 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1721 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1722 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1723 if (fDebug && GetBoolArg("-printcoinstake"))
1724 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1725 fKernelFound = true;
1730 if (fKernelFound || fShutdown)
1731 break; // if kernel is found stop searching
1734 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1737 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1739 // Attempt to add more inputs
1740 // Only add coins of the same key/address as kernel
1741 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1742 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1744 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1746 // Stop adding more inputs if already too many inputs
1747 if (txNew.vin.size() >= 100)
1749 // Stop adding more inputs if value is already pretty significant
1750 if (nCredit > nCombineThreshold)
1752 // Stop adding inputs if reached reserve limit
1753 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1755 // Do not add additional significant input
1756 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1758 // Do not add input that is still too young
1759 if (nTimeWeight < nStakeMaxAge)
1762 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1763 nCredit += pcoin.first->vout[pcoin.second].nValue;
1764 vwtxPrev.push_back(pcoin.first);
1768 // Calculate coin age reward
1772 if (!txNew.GetCoinAge(txdb, nCoinAge))
1773 return error("CreateCoinStake : failed to calculate coin age");
1774 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1780 // Set output amount
1781 if (txNew.vout.size() == 3)
1783 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1784 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1787 txNew.vout[1].nValue = nCredit - nMinFee;
1791 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1793 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1794 return error("CreateCoinStake : failed to sign coinstake");
1798 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1799 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1800 return error("CreateCoinStake : exceeded coinstake size limit");
1802 // Check enough fee is paid
1803 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1805 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1806 continue; // try signing again
1810 if (fDebug && GetBoolArg("-printfee"))
1811 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1816 // Successfully generated coinstake
1821 // Call after CreateTransaction unless you want to abort
1822 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1825 LOCK2(cs_main, cs_wallet);
1826 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1828 // This is only to keep the database open to defeat the auto-flush for the
1829 // duration of this scope. This is the only place where this optimization
1830 // maybe makes sense; please don't do it anywhere else.
1831 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1833 // Take key pair from key pool so it won't be used again
1834 reservekey.KeepKey();
1836 // Add tx to wallet, because if it has change it's also ours,
1837 // otherwise just for transaction history.
1838 AddToWallet(wtxNew);
1840 // Mark old coins as spent
1841 set<CWalletTx*> setCoins;
1842 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1844 CWalletTx &coin = mapWallet[txin.prevout.hash];
1845 coin.BindWallet(this);
1846 coin.MarkSpent(txin.prevout.n);
1848 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1855 // Track how many getdata requests our transaction gets
1856 mapRequestCount[wtxNew.GetHash()] = 0;
1859 if (!wtxNew.AcceptToMemoryPool())
1861 // This must not fail. The transaction has already been signed and recorded.
1862 printf("CommitTransaction() : Error: Transaction not valid");
1865 wtxNew.RelayWalletTransaction();
1873 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1875 CReserveKey reservekey(this);
1880 string strError = _("Error: Wallet locked, unable to create transaction ");
1881 printf("SendMoney() : %s", strError.c_str());
1884 if (fWalletUnlockMintOnly)
1886 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1887 printf("SendMoney() : %s", strError.c_str());
1890 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1893 if (nValue + nFeeRequired > GetBalance())
1894 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());
1896 strError = _("Error: Transaction creation failed ");
1897 printf("SendMoney() : %s", strError.c_str());
1901 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1904 if (!CommitTransaction(wtxNew, reservekey))
1905 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.");
1912 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1916 return _("Invalid amount");
1917 if (nValue + nTransactionFee > GetBalance())
1918 return _("Insufficient funds");
1920 // Parse Bitcoin address
1921 CScript scriptPubKey;
1922 scriptPubKey.SetDestination(address);
1924 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1930 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1934 fFirstRunRet = false;
1935 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1936 if (nLoadWalletRet == DB_NEED_REWRITE)
1938 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1941 // Note: can't top-up keypool here, because wallet is locked.
1942 // User will be prompted to unlock wallet the next operation
1943 // the requires a new key.
1947 if (nLoadWalletRet != DB_LOAD_OK)
1948 return nLoadWalletRet;
1949 fFirstRunRet = !vchDefaultKey.IsValid();
1951 NewThread(ThreadFlushWalletDB, &strWalletFile);
1956 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1958 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1959 mapAddressBook[address] = strName;
1960 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1963 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1966 bool CWallet::DelAddressBookName(const CTxDestination& address)
1968 mapAddressBook.erase(address);
1969 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1972 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1976 void CWallet::PrintWallet(const CBlock& block)
1980 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1982 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1983 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1985 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1987 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1988 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1995 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1999 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2000 if (mi != mapWallet.end())
2009 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2013 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2016 vchDefaultKey = vchPubKey;
2020 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2022 if (!pwallet->fFileBacked)
2024 strWalletFileOut = pwallet->strWalletFile;
2029 // Mark old keypool keys as used,
2030 // and generate all new keys
2032 bool CWallet::NewKeyPool()
2036 CWalletDB walletdb(strWalletFile);
2037 BOOST_FOREACH(int64 nIndex, setKeyPool)
2038 walletdb.ErasePool(nIndex);
2044 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2045 for (int i = 0; i < nKeys; i++)
2048 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2049 setKeyPool.insert(nIndex);
2051 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2056 bool CWallet::TopUpKeyPool(unsigned int nSize)
2064 CWalletDB walletdb(strWalletFile);
2067 unsigned int nTargetSize;
2069 nTargetSize = nSize;
2071 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2073 while (setKeyPool.size() < (nTargetSize + 1))
2076 if (!setKeyPool.empty())
2077 nEnd = *(--setKeyPool.end()) + 1;
2078 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2079 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2080 setKeyPool.insert(nEnd);
2081 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2087 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2090 keypool.vchPubKey = CPubKey();
2097 // Get the oldest key
2098 if(setKeyPool.empty())
2101 CWalletDB walletdb(strWalletFile);
2103 nIndex = *(setKeyPool.begin());
2104 setKeyPool.erase(setKeyPool.begin());
2105 if (!walletdb.ReadPool(nIndex, keypool))
2106 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2107 if (!HaveKey(keypool.vchPubKey.GetID()))
2108 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2109 assert(keypool.vchPubKey.IsValid());
2110 if (fDebug && GetBoolArg("-printkeypool"))
2111 printf("keypool reserve %"PRI64d"\n", nIndex);
2115 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2118 LOCK2(cs_main, cs_wallet);
2119 CWalletDB walletdb(strWalletFile);
2121 int64 nIndex = 1 + *(--setKeyPool.end());
2122 if (!walletdb.WritePool(nIndex, keypool))
2123 throw runtime_error("AddReserveKey() : writing added key failed");
2124 setKeyPool.insert(nIndex);
2130 void CWallet::KeepKey(int64 nIndex)
2132 // Remove from key pool
2135 CWalletDB walletdb(strWalletFile);
2136 walletdb.ErasePool(nIndex);
2139 printf("keypool keep %"PRI64d"\n", nIndex);
2142 void CWallet::ReturnKey(int64 nIndex)
2144 // Return to key pool
2147 setKeyPool.insert(nIndex);
2150 printf("keypool return %"PRI64d"\n", nIndex);
2153 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2159 ReserveKeyFromKeyPool(nIndex, keypool);
2162 if (fAllowReuse && vchDefaultKey.IsValid())
2164 result = vchDefaultKey;
2167 if (IsLocked()) return false;
2168 result = GenerateNewKey();
2172 result = keypool.vchPubKey;
2177 int64 CWallet::GetOldestKeyPoolTime()
2181 ReserveKeyFromKeyPool(nIndex, keypool);
2185 return keypool.nTime;
2188 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2190 map<CTxDestination, int64> balances;
2194 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2196 CWalletTx *pcoin = &walletEntry.second;
2198 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2201 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2204 int nDepth = pcoin->GetDepthInMainChain();
2205 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2208 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2210 CTxDestination addr;
2211 if (!IsMine(pcoin->vout[i]))
2213 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2216 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2218 if (!balances.count(addr))
2220 balances[addr] += n;
2228 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2230 set< set<CTxDestination> > groupings;
2231 set<CTxDestination> grouping;
2233 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2235 CWalletTx *pcoin = &walletEntry.second;
2237 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2239 // group all input addresses with each other
2240 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2242 CTxDestination address;
2243 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2245 grouping.insert(address);
2248 // group change with input addresses
2249 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2250 if (IsChange(txout))
2252 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2253 CTxDestination txoutAddr;
2254 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2256 grouping.insert(txoutAddr);
2258 groupings.insert(grouping);
2262 // group lone addrs by themselves
2263 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2264 if (IsMine(pcoin->vout[i]))
2266 CTxDestination address;
2267 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2269 grouping.insert(address);
2270 groupings.insert(grouping);
2275 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2276 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2277 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2279 // make a set of all the groups hit by this new group
2280 set< set<CTxDestination>* > hits;
2281 map< CTxDestination, set<CTxDestination>* >::iterator it;
2282 BOOST_FOREACH(CTxDestination address, grouping)
2283 if ((it = setmap.find(address)) != setmap.end())
2284 hits.insert((*it).second);
2286 // merge all hit groups into a new single group and delete old groups
2287 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2288 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2290 merged->insert(hit->begin(), hit->end());
2291 uniqueGroupings.erase(hit);
2294 uniqueGroupings.insert(merged);
2297 BOOST_FOREACH(CTxDestination element, *merged)
2298 setmap[element] = merged;
2301 set< set<CTxDestination> > ret;
2302 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2304 ret.insert(*uniqueGrouping);
2305 delete uniqueGrouping;
2311 // ppcoin: check 'spent' consistency between wallet and txindex
2312 // ppcoin: fix wallet spent state according to txindex
2313 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2316 nBalanceInQuestion = 0;
2319 vector<CWalletTx*> vCoins;
2320 vCoins.reserve(mapWallet.size());
2321 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2322 vCoins.push_back(&(*it).second);
2325 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2327 // Find the corresponding transaction index
2329 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2331 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2333 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2335 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2336 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2338 nBalanceInQuestion += pcoin->vout[n].nValue;
2341 pcoin->MarkUnspent(n);
2342 pcoin->WriteToDisk();
2345 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2347 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2348 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2350 nBalanceInQuestion += pcoin->vout[n].nValue;
2353 pcoin->MarkSpent(n);
2354 pcoin->WriteToDisk();
2361 // ppcoin: disable transaction (only for coinstake)
2362 void CWallet::DisableTransaction(const CTransaction &tx)
2364 if (!tx.IsCoinStake() || !IsFromMe(tx))
2365 return; // only disconnecting coinstake requires marking input unspent
2368 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2370 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2371 if (mi != mapWallet.end())
2373 CWalletTx& prev = (*mi).second;
2374 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2376 prev.MarkUnspent(txin.prevout.n);
2383 CPubKey CReserveKey::GetReservedKey()
2388 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2390 vchPubKey = keypool.vchPubKey;
2393 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2394 vchPubKey = pwallet->vchDefaultKey;
2397 assert(vchPubKey.IsValid());
2401 void CReserveKey::KeepKey()
2404 pwallet->KeepKey(nIndex);
2406 vchPubKey = CPubKey();
2409 void CReserveKey::ReturnKey()
2412 pwallet->ReturnKey(nIndex);
2414 vchPubKey = CPubKey();
2417 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2421 CWalletDB walletdb(strWalletFile);
2423 LOCK2(cs_main, cs_wallet);
2424 BOOST_FOREACH(const int64& id, setKeyPool)
2427 if (!walletdb.ReadPool(id, keypool))
2428 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2429 assert(keypool.vchPubKey.IsValid());
2430 CKeyID keyID = keypool.vchPubKey.GetID();
2431 if (!HaveKey(keyID))
2432 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2433 setAddress.insert(keyID);
2437 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2441 // Only notify UI if this transaction is in this wallet
2442 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2443 if (mi != mapWallet.end())
2444 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2448 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2449 mapKeyBirth.clear();
2451 // get birth times for keys with metadata
2452 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2453 if (it->second.nCreateTime)
2454 mapKeyBirth[it->first] = it->second.nCreateTime;
2456 // map in which we'll infer heights of other keys
2457 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2458 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2459 std::set<CKeyID> setKeys;
2461 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2462 if (mapKeyBirth.count(keyid) == 0)
2463 mapKeyFirstBlock[keyid] = pindexMax;
2467 // if there are no such keys, we're done
2468 if (mapKeyFirstBlock.empty())
2471 // find first block that affects those keys, if there are any left
2472 std::vector<CKeyID> vAffected;
2473 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2474 // iterate over all wallet transactions...
2475 const CWalletTx &wtx = (*it).second;
2476 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2477 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2478 // ... which are already in a block
2479 int nHeight = blit->second->nHeight;
2480 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2481 // iterate over all their outputs
2482 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2483 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2484 // ... and all their affected keys
2485 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2486 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2487 rit->second = blit->second;
2494 // Extract block timestamps for those keys
2495 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2496 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off