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 (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1399 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1401 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1402 nChange -= nMoveToFee;
1403 nFeeRet += nMoveToFee;
1406 // sub-cent change is moved to fee
1407 if (nChange > 0 && nChange < CENT)
1416 // Fill a vout to ourself
1417 // TODO: pass in scriptChange instead of reservekey so
1418 // change transaction isn't always pay-to-bitcoin-address
1419 CScript scriptChange;
1421 // coin control: send change to custom address
1422 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1423 scriptChange.SetDestination(coinControl->destChange);
1425 // no coin control: send change to newly generated address
1428 // Note: We use a new key here to keep it from being obvious which side is the change.
1429 // The drawback is that by not reusing a previous key, the change may be lost if a
1430 // backup is restored, if the backup doesn't have the new private key for the change.
1431 // If we reused the old key, it would be possible to add code to look for and
1432 // rediscover unknown transactions that were written with keys of ours to recover
1433 // post-backup change.
1435 // Reserve a new key pair from key pool
1436 CPubKey vchPubKey = reservekey.GetReservedKey();
1438 scriptChange.SetDestination(vchPubKey.GetID());
1441 // Insert change txn at random position:
1442 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1443 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1446 reservekey.ReturnKey();
1449 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1450 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1454 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1455 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1459 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1460 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1462 dPriority /= nBytes;
1464 // Check that enough fee is included
1465 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1466 bool fAllowFree = CTransaction::AllowFree(dPriority);
1468 // Disable free transactions until 1 July 2014
1469 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1474 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1476 if (nFeeRet < max(nPayFee, nMinFee))
1478 nFeeRet = max(nPayFee, nMinFee);
1482 // Fill vtxPrev by copying from previous transactions vtxPrev
1483 wtxNew.AddSupportingTransactions(txdb);
1484 wtxNew.fTimeReceivedIsTxTime = true;
1493 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1495 vector< pair<CScript, int64> > vecSend;
1496 vecSend.push_back(make_pair(scriptPubKey, nValue));
1497 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1500 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1502 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1504 // If time weight is lower or equal to zero then weight is zero.
1505 if (nTimeWeight <= 0)
1511 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1512 nWeight = bnCoinDayWeight.getuint64();
1516 // NovaCoin: get current stake weight
1517 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1519 // Choose coins to use
1520 int64 nBalance = GetBalance();
1521 int64 nReserveBalance = 0;
1523 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1525 error("GetStakeWeight : invalid reserve balance amount");
1529 if (nBalance <= nReserveBalance)
1532 vector<const CWalletTx*> vwtxPrev;
1535 * TODO: performance comparison
1537 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1538 static uint256 hashPrevBlock;
1539 static int64 nValueIn = 0;
1541 // Cache outputs unless best block changed
1542 if (hashPrevBlock != pindexBest->GetBlockHash())
1544 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1547 if (setCoins.empty())
1550 hashPrevBlock == pindexBest->GetBlockHash();
1554 set<pair<const CWalletTx*,unsigned int> > setCoins;
1557 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1560 if (setCoins.empty())
1564 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1568 LOCK2(cs_main, cs_wallet);
1569 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1573 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1574 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1576 // Weight is greater than zero
1577 if (nTimeWeight > 0)
1579 nWeight += bnCoinDayWeight.getuint64();
1582 // Weight is greater than zero, but the maximum value isn't reached yet
1583 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1585 nMinWeight += bnCoinDayWeight.getuint64();
1588 // Maximum weight was reached
1589 if (nTimeWeight == nStakeMaxAge)
1591 nMaxWeight += bnCoinDayWeight.getuint64();
1598 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1600 // The following combine threshold is important to security
1601 // Should not be adjusted if you don't understand the consequences
1602 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1604 CBigNum bnTargetPerCoinDay;
1605 bnTargetPerCoinDay.SetCompact(nBits);
1610 // Mark coin stake transaction
1611 CScript scriptEmpty;
1612 scriptEmpty.clear();
1613 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1615 // Choose coins to use
1616 int64 nBalance = GetBalance();
1617 int64 nReserveBalance = 0;
1619 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1620 return error("CreateCoinStake : invalid reserve balance amount");
1622 if (nBalance <= nReserveBalance)
1625 vector<const CWalletTx*> vwtxPrev;
1628 * TODO: performance comparison
1630 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1631 static uint256 hashPrevBlock;
1632 static int64 nValueIn = 0;
1634 // Cache outputs unless best block changed
1635 if (hashPrevBlock != pindexBest->GetBlockHash())
1637 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1640 if (setCoins.empty())
1643 hashPrevBlock == pindexBest->GetBlockHash();
1647 set<pair<const CWalletTx*,unsigned int> > setCoins;
1650 // Select coins with suitable depth
1651 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1654 if (setCoins.empty())
1658 CScript scriptPubKeyKernel;
1660 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1664 LOCK2(cs_main, cs_wallet);
1665 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1669 // Read block header
1672 LOCK2(cs_main, cs_wallet);
1673 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1677 static int nMaxStakeSearchInterval = 60;
1678 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1679 continue; // only count coins meeting min age requirement
1681 bool fKernelFound = false;
1682 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1684 // Search backward in time from the given txNew timestamp
1685 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1686 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1687 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1688 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1691 if (fDebug && GetBoolArg("-printcoinstake"))
1692 printf("CreateCoinStake : kernel found\n");
1693 vector<valtype> vSolutions;
1694 txnouttype whichType;
1695 CScript scriptPubKeyOut;
1696 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1697 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1699 if (fDebug && GetBoolArg("-printcoinstake"))
1700 printf("CreateCoinStake : failed to parse kernel\n");
1703 if (fDebug && GetBoolArg("-printcoinstake"))
1704 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1705 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1707 if (fDebug && GetBoolArg("-printcoinstake"))
1708 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1709 break; // only support pay to public key and pay to address
1711 if (whichType == TX_PUBKEYHASH) // pay to address type
1713 // convert to pay to public key type
1714 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1716 if (fDebug && GetBoolArg("-printcoinstake"))
1717 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1718 break; // unable to find corresponding public key
1720 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1722 if (whichType == TX_PUBKEY)
1724 valtype& vchPubKey = vSolutions[0];
1725 if (!keystore.GetKey(Hash160(vchPubKey), key))
1727 if (fDebug && GetBoolArg("-printcoinstake"))
1728 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1729 break; // unable to find corresponding public key
1732 if (key.GetPubKey() != vchPubKey)
1734 if (fDebug && GetBoolArg("-printcoinstake"))
1735 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1736 break; // keys mismatch
1739 scriptPubKeyOut = scriptPubKeyKernel;
1743 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1744 nCredit += pcoin.first->vout[pcoin.second].nValue;
1745 vwtxPrev.push_back(pcoin.first);
1746 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1748 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1749 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1750 if (fDebug && GetBoolArg("-printcoinstake"))
1751 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1752 fKernelFound = true;
1757 if (fKernelFound || fShutdown)
1758 break; // if kernel is found stop searching
1761 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1764 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1766 // Attempt to add more inputs
1767 // Only add coins of the same key/address as kernel
1768 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1769 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1771 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1773 // Stop adding more inputs if already too many inputs
1774 if (txNew.vin.size() >= 100)
1776 // Stop adding more inputs if value is already pretty significant
1777 if (nCredit > nCombineThreshold)
1779 // Stop adding inputs if reached reserve limit
1780 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1782 // Do not add additional significant input
1783 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1785 // Do not add input that is still too young
1786 if (nTimeWeight < nStakeMaxAge)
1789 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1790 nCredit += pcoin.first->vout[pcoin.second].nValue;
1791 vwtxPrev.push_back(pcoin.first);
1795 // Calculate coin age reward
1799 if (!txNew.GetCoinAge(txdb, nCoinAge))
1800 return error("CreateCoinStake : failed to calculate coin age");
1801 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1807 // Set output amount
1808 if (txNew.vout.size() == 3)
1810 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1811 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1814 txNew.vout[1].nValue = nCredit - nMinFee;
1818 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1820 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1821 return error("CreateCoinStake : failed to sign coinstake");
1825 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1826 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1827 return error("CreateCoinStake : exceeded coinstake size limit");
1829 // Check enough fee is paid
1830 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1832 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1833 continue; // try signing again
1837 if (fDebug && GetBoolArg("-printfee"))
1838 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1843 // Successfully generated coinstake
1848 // Call after CreateTransaction unless you want to abort
1849 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1852 LOCK2(cs_main, cs_wallet);
1853 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1855 // This is only to keep the database open to defeat the auto-flush for the
1856 // duration of this scope. This is the only place where this optimization
1857 // maybe makes sense; please don't do it anywhere else.
1858 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1860 // Take key pair from key pool so it won't be used again
1861 reservekey.KeepKey();
1863 // Add tx to wallet, because if it has change it's also ours,
1864 // otherwise just for transaction history.
1865 AddToWallet(wtxNew);
1867 // Mark old coins as spent
1868 set<CWalletTx*> setCoins;
1869 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1871 CWalletTx &coin = mapWallet[txin.prevout.hash];
1872 coin.BindWallet(this);
1873 coin.MarkSpent(txin.prevout.n);
1875 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1882 // Track how many getdata requests our transaction gets
1883 mapRequestCount[wtxNew.GetHash()] = 0;
1886 if (!wtxNew.AcceptToMemoryPool())
1888 // This must not fail. The transaction has already been signed and recorded.
1889 printf("CommitTransaction() : Error: Transaction not valid");
1892 wtxNew.RelayWalletTransaction();
1900 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1902 CReserveKey reservekey(this);
1907 string strError = _("Error: Wallet locked, unable to create transaction ");
1908 printf("SendMoney() : %s", strError.c_str());
1911 if (fWalletUnlockMintOnly)
1913 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1914 printf("SendMoney() : %s", strError.c_str());
1917 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1920 if (nValue + nFeeRequired > GetBalance())
1921 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());
1923 strError = _("Error: Transaction creation failed ");
1924 printf("SendMoney() : %s", strError.c_str());
1928 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1931 if (!CommitTransaction(wtxNew, reservekey))
1932 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.");
1939 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1943 return _("Invalid amount");
1944 if (nValue + nTransactionFee > GetBalance())
1945 return _("Insufficient funds");
1947 // Parse Bitcoin address
1948 CScript scriptPubKey;
1949 scriptPubKey.SetDestination(address);
1951 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1957 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1961 fFirstRunRet = false;
1962 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1963 if (nLoadWalletRet == DB_NEED_REWRITE)
1965 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1968 // Note: can't top-up keypool here, because wallet is locked.
1969 // User will be prompted to unlock wallet the next operation
1970 // the requires a new key.
1974 if (nLoadWalletRet != DB_LOAD_OK)
1975 return nLoadWalletRet;
1976 fFirstRunRet = !vchDefaultKey.IsValid();
1978 NewThread(ThreadFlushWalletDB, &strWalletFile);
1983 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1985 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1986 mapAddressBook[address] = strName;
1987 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1990 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1993 bool CWallet::DelAddressBookName(const CTxDestination& address)
1995 mapAddressBook.erase(address);
1996 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1999 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2003 void CWallet::PrintWallet(const CBlock& block)
2007 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2009 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2010 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2012 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2014 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2015 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2022 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2026 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2027 if (mi != mapWallet.end())
2036 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2040 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2043 vchDefaultKey = vchPubKey;
2047 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2049 if (!pwallet->fFileBacked)
2051 strWalletFileOut = pwallet->strWalletFile;
2056 // Mark old keypool keys as used,
2057 // and generate all new keys
2059 bool CWallet::NewKeyPool()
2063 CWalletDB walletdb(strWalletFile);
2064 BOOST_FOREACH(int64 nIndex, setKeyPool)
2065 walletdb.ErasePool(nIndex);
2071 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2072 for (int i = 0; i < nKeys; i++)
2075 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2076 setKeyPool.insert(nIndex);
2078 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2083 bool CWallet::TopUpKeyPool(unsigned int nSize)
2091 CWalletDB walletdb(strWalletFile);
2094 unsigned int nTargetSize;
2096 nTargetSize = nSize;
2098 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2100 while (setKeyPool.size() < (nTargetSize + 1))
2103 if (!setKeyPool.empty())
2104 nEnd = *(--setKeyPool.end()) + 1;
2105 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2106 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2107 setKeyPool.insert(nEnd);
2108 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2114 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2117 keypool.vchPubKey = CPubKey();
2124 // Get the oldest key
2125 if(setKeyPool.empty())
2128 CWalletDB walletdb(strWalletFile);
2130 nIndex = *(setKeyPool.begin());
2131 setKeyPool.erase(setKeyPool.begin());
2132 if (!walletdb.ReadPool(nIndex, keypool))
2133 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2134 if (!HaveKey(keypool.vchPubKey.GetID()))
2135 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2136 assert(keypool.vchPubKey.IsValid());
2137 if (fDebug && GetBoolArg("-printkeypool"))
2138 printf("keypool reserve %"PRI64d"\n", nIndex);
2142 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2145 LOCK2(cs_main, cs_wallet);
2146 CWalletDB walletdb(strWalletFile);
2148 int64 nIndex = 1 + *(--setKeyPool.end());
2149 if (!walletdb.WritePool(nIndex, keypool))
2150 throw runtime_error("AddReserveKey() : writing added key failed");
2151 setKeyPool.insert(nIndex);
2157 void CWallet::KeepKey(int64 nIndex)
2159 // Remove from key pool
2162 CWalletDB walletdb(strWalletFile);
2163 walletdb.ErasePool(nIndex);
2166 printf("keypool keep %"PRI64d"\n", nIndex);
2169 void CWallet::ReturnKey(int64 nIndex)
2171 // Return to key pool
2174 setKeyPool.insert(nIndex);
2177 printf("keypool return %"PRI64d"\n", nIndex);
2180 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2186 ReserveKeyFromKeyPool(nIndex, keypool);
2189 if (fAllowReuse && vchDefaultKey.IsValid())
2191 result = vchDefaultKey;
2194 if (IsLocked()) return false;
2195 result = GenerateNewKey();
2199 result = keypool.vchPubKey;
2204 int64 CWallet::GetOldestKeyPoolTime()
2208 ReserveKeyFromKeyPool(nIndex, keypool);
2212 return keypool.nTime;
2215 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2217 map<CTxDestination, int64> balances;
2221 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2223 CWalletTx *pcoin = &walletEntry.second;
2225 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2228 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2231 int nDepth = pcoin->GetDepthInMainChain();
2232 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2235 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2237 CTxDestination addr;
2238 if (!IsMine(pcoin->vout[i]))
2240 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2243 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2245 if (!balances.count(addr))
2247 balances[addr] += n;
2255 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2257 set< set<CTxDestination> > groupings;
2258 set<CTxDestination> grouping;
2260 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2262 CWalletTx *pcoin = &walletEntry.second;
2264 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2266 // group all input addresses with each other
2267 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2269 CTxDestination address;
2270 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2272 grouping.insert(address);
2275 // group change with input addresses
2276 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2277 if (IsChange(txout))
2279 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2280 CTxDestination txoutAddr;
2281 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2283 grouping.insert(txoutAddr);
2285 groupings.insert(grouping);
2289 // group lone addrs by themselves
2290 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2291 if (IsMine(pcoin->vout[i]))
2293 CTxDestination address;
2294 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2296 grouping.insert(address);
2297 groupings.insert(grouping);
2302 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2303 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2304 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2306 // make a set of all the groups hit by this new group
2307 set< set<CTxDestination>* > hits;
2308 map< CTxDestination, set<CTxDestination>* >::iterator it;
2309 BOOST_FOREACH(CTxDestination address, grouping)
2310 if ((it = setmap.find(address)) != setmap.end())
2311 hits.insert((*it).second);
2313 // merge all hit groups into a new single group and delete old groups
2314 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2315 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2317 merged->insert(hit->begin(), hit->end());
2318 uniqueGroupings.erase(hit);
2321 uniqueGroupings.insert(merged);
2324 BOOST_FOREACH(CTxDestination element, *merged)
2325 setmap[element] = merged;
2328 set< set<CTxDestination> > ret;
2329 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2331 ret.insert(*uniqueGrouping);
2332 delete uniqueGrouping;
2338 // ppcoin: check 'spent' consistency between wallet and txindex
2339 // ppcoin: fix wallet spent state according to txindex
2340 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2343 nBalanceInQuestion = 0;
2346 vector<CWalletTx*> vCoins;
2347 vCoins.reserve(mapWallet.size());
2348 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2349 vCoins.push_back(&(*it).second);
2352 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2354 // Find the corresponding transaction index
2356 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2358 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2360 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2362 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2363 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2365 nBalanceInQuestion += pcoin->vout[n].nValue;
2368 pcoin->MarkUnspent(n);
2369 pcoin->WriteToDisk();
2372 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2374 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2375 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2377 nBalanceInQuestion += pcoin->vout[n].nValue;
2380 pcoin->MarkSpent(n);
2381 pcoin->WriteToDisk();
2387 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2389 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2392 EraseFromWallet(pcoin->GetHash());
2398 // ppcoin: disable transaction (only for coinstake)
2399 void CWallet::DisableTransaction(const CTransaction &tx)
2401 if (!tx.IsCoinStake() || !IsFromMe(tx))
2402 return; // only disconnecting coinstake requires marking input unspent
2405 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2407 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2408 if (mi != mapWallet.end())
2410 CWalletTx& prev = (*mi).second;
2411 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2413 prev.MarkUnspent(txin.prevout.n);
2420 CPubKey CReserveKey::GetReservedKey()
2425 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2427 vchPubKey = keypool.vchPubKey;
2430 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2431 vchPubKey = pwallet->vchDefaultKey;
2434 assert(vchPubKey.IsValid());
2438 void CReserveKey::KeepKey()
2441 pwallet->KeepKey(nIndex);
2443 vchPubKey = CPubKey();
2446 void CReserveKey::ReturnKey()
2449 pwallet->ReturnKey(nIndex);
2451 vchPubKey = CPubKey();
2454 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2458 CWalletDB walletdb(strWalletFile);
2460 LOCK2(cs_main, cs_wallet);
2461 BOOST_FOREACH(const int64& id, setKeyPool)
2464 if (!walletdb.ReadPool(id, keypool))
2465 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2466 assert(keypool.vchPubKey.IsValid());
2467 CKeyID keyID = keypool.vchPubKey.GetID();
2468 if (!HaveKey(keyID))
2469 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2470 setAddress.insert(keyID);
2474 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2478 // Only notify UI if this transaction is in this wallet
2479 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2480 if (mi != mapWallet.end())
2481 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2485 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2486 mapKeyBirth.clear();
2488 // get birth times for keys with metadata
2489 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2490 if (it->second.nCreateTime)
2491 mapKeyBirth[it->first] = it->second.nCreateTime;
2493 // map in which we'll infer heights of other keys
2494 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2495 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2496 std::set<CKeyID> setKeys;
2498 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2499 if (mapKeyBirth.count(keyid) == 0)
2500 mapKeyFirstBlock[keyid] = pindexMax;
2504 // if there are no such keys, we're done
2505 if (mapKeyFirstBlock.empty())
2508 // find first block that affects those keys, if there are any left
2509 std::vector<CKeyID> vAffected;
2510 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2511 // iterate over all wallet transactions...
2512 const CWalletTx &wtx = (*it).second;
2513 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2514 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2515 // ... which are already in a block
2516 int nHeight = blit->second->nHeight;
2517 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2518 // iterate over all their outputs
2519 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2520 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2521 // ... and all their affected keys
2522 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2523 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2524 rit->second = blit->second;
2531 // Extract block timestamps for those keys
2532 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2533 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off