1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
17 extern int nStakeMaxAge;
19 //////////////////////////////////////////////////////////////////////////////
24 struct CompareValueOnly
26 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
29 return t1.first < t2.first;
33 CPubKey CWallet::GenerateNewKey()
35 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
39 key.MakeNewKey(fCompressed);
41 // Compressed public keys were introduced in version 0.6.0
43 SetMinVersion(FEATURE_COMPRPUBKEY);
45 CPubKey pubkey = key.GetPubKey();
47 // Create new metadata
48 int64 nCreationTime = GetTime();
49 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51 nTimeFirstKey = nCreationTime;
54 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55 return key.GetPubKey();
58 bool CWallet::AddKey(const CKey& key)
60 CPubKey pubkey = key.GetPubKey();
62 if (!CCryptoKeyStore::AddKey(key))
67 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
73 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 if (pwalletdbEncryption)
80 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
82 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
89 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90 nTimeFirstKey = meta.nCreateTime;
92 mapKeyMetadata[pubkey.GetID()] = meta;
96 bool CWallet::AddCScript(const CScript& redeemScript)
98 if (!CCryptoKeyStore::AddCScript(redeemScript))
102 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
105 bool CWallet::AddWatchOnly(const CScript &dest)
107 if (!CCryptoKeyStore::AddWatchOnly(dest))
109 nTimeFirstKey = 1; // No birthday information for watch-only keys.
112 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
115 bool CWallet::LoadWatchOnly(const CScript &dest)
117 return CCryptoKeyStore::AddWatchOnly(dest);
120 // ppcoin: optional setting to unlock wallet for block minting only;
121 // serves to disable the trivial sendmoney when OS account compromised
122 bool fWalletUnlockMintOnly = false;
124 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
130 CKeyingMaterial vMasterKey;
134 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
136 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
138 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
140 if (CCryptoKeyStore::Unlock(vMasterKey))
147 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
149 bool fWasLocked = IsLocked();
156 CKeyingMaterial vMasterKey;
157 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
159 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
161 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
163 if (CCryptoKeyStore::Unlock(vMasterKey))
165 int64 nStartTime = GetTimeMillis();
166 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
167 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
169 nStartTime = GetTimeMillis();
170 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
171 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
173 if (pMasterKey.second.nDeriveIterations < 25000)
174 pMasterKey.second.nDeriveIterations = 25000;
176 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
178 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
180 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
182 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
193 void CWallet::SetBestChain(const CBlockLocator& loc)
195 CWalletDB walletdb(strWalletFile);
196 walletdb.WriteBestBlock(loc);
199 // This class implements an addrIncoming entry that causes pre-0.4
200 // clients to crash on startup if reading a private-key-encrypted wallet.
201 class CCorruptAddress
206 if (nType & SER_DISK)
211 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
213 if (nWalletVersion >= nVersion)
216 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
217 if (fExplicit && nVersion > nWalletMaxVersion)
218 nVersion = FEATURE_LATEST;
220 nWalletVersion = nVersion;
222 if (nVersion > nWalletMaxVersion)
223 nWalletMaxVersion = nVersion;
227 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
228 if (nWalletVersion >= 40000)
230 // Versions prior to 0.4.0 did not support the "minversion" record.
231 // Use a CCorruptAddress to make them crash instead.
232 CCorruptAddress corruptAddress;
233 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
235 if (nWalletVersion > 40000)
236 pwalletdb->WriteMinVersion(nWalletVersion);
244 bool CWallet::SetMaxVersion(int nVersion)
246 // cannot downgrade below current version
247 if (nWalletVersion > nVersion)
250 nWalletMaxVersion = nVersion;
255 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
260 CKeyingMaterial vMasterKey;
261 RandAddSeedPerfmon();
263 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
264 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
266 CMasterKey kMasterKey(nDerivationMethodIndex);
268 RandAddSeedPerfmon();
269 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
270 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
273 int64 nStartTime = GetTimeMillis();
274 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
275 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
277 nStartTime = GetTimeMillis();
278 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
279 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
281 if (kMasterKey.nDeriveIterations < 25000)
282 kMasterKey.nDeriveIterations = 25000;
284 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
286 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
288 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
293 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
296 pwalletdbEncryption = new CWalletDB(strWalletFile);
297 if (!pwalletdbEncryption->TxnBegin())
299 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
302 if (!EncryptKeys(vMasterKey))
305 pwalletdbEncryption->TxnAbort();
306 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.
309 // Encryption was introduced in version 0.4.0
310 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
314 if (!pwalletdbEncryption->TxnCommit())
315 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.
317 delete pwalletdbEncryption;
318 pwalletdbEncryption = NULL;
322 Unlock(strWalletPassphrase);
326 // Need to completely rewrite the wallet file; if we don't, bdb might keep
327 // bits of the unencrypted private key in slack space in the database file.
328 CDB::Rewrite(strWalletFile);
331 NotifyStatusChanged(this);
336 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
338 int64 nRet = nOrderPosNext++;
340 pwalletdb->WriteOrderPosNext(nOrderPosNext);
342 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
347 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
349 CWalletDB walletdb(strWalletFile);
351 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
354 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
355 // would make this much faster for applications that do this a lot.
356 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
358 CWalletTx* wtx = &((*it).second);
359 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
362 walletdb.ListAccountCreditDebit(strAccount, acentries);
363 BOOST_FOREACH(CAccountingEntry& entry, acentries)
365 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
371 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
373 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
374 // Update the wallet spent flag if it doesn't know due to wallet.dat being
375 // restored from backup or the user making copies of wallet.dat.
378 BOOST_FOREACH(const CTxIn& txin, tx.vin)
380 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
381 if (mi != mapWallet.end())
383 CWalletTx& wtx = (*mi).second;
384 if (txin.prevout.n >= wtx.vout.size())
385 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
386 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
388 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
389 wtx.MarkSpent(txin.prevout.n);
391 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
398 uint256 hash = tx.GetHash();
399 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
400 CWalletTx& wtx = (*mi).second;
402 BOOST_FOREACH(const CTxOut& txout, tx.vout)
406 wtx.MarkUnspent(&txout - &tx.vout[0]);
408 NotifyTransactionChanged(this, hash, CT_UPDATED);
416 void CWallet::MarkDirty()
420 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
421 item.second.MarkDirty();
425 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
427 uint256 hash = wtxIn.GetHash();
430 // Inserts only if not already there, returns tx inserted or tx found
431 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
432 CWalletTx& wtx = (*ret.first).second;
433 wtx.BindWallet(this);
434 bool fInsertedNew = ret.second;
437 wtx.nTimeReceived = GetAdjustedTime();
438 wtx.nOrderPos = IncOrderPosNext();
440 wtx.nTimeSmart = wtx.nTimeReceived;
441 if (wtxIn.hashBlock != 0)
443 if (mapBlockIndex.count(wtxIn.hashBlock))
445 unsigned int latestNow = wtx.nTimeReceived;
446 unsigned int latestEntry = 0;
448 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
449 int64 latestTolerated = latestNow + 300;
450 std::list<CAccountingEntry> acentries;
451 TxItems txOrdered = OrderedTxItems(acentries);
452 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
454 CWalletTx *const pwtx = (*it).second.first;
457 CAccountingEntry *const pacentry = (*it).second.second;
461 nSmartTime = pwtx->nTimeSmart;
463 nSmartTime = pwtx->nTimeReceived;
466 nSmartTime = pacentry->nTime;
467 if (nSmartTime <= latestTolerated)
469 latestEntry = nSmartTime;
470 if (nSmartTime > latestNow)
471 latestNow = nSmartTime;
477 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
478 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
481 printf("AddToWallet() : found %s in block %s not in index\n",
482 wtxIn.GetHash().ToString().substr(0,10).c_str(),
483 wtxIn.hashBlock.ToString().c_str());
487 bool fUpdated = false;
491 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
493 wtx.hashBlock = wtxIn.hashBlock;
496 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
498 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
499 wtx.nIndex = wtxIn.nIndex;
502 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
504 wtx.fFromMe = wtxIn.fFromMe;
507 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
511 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
514 if (fInsertedNew || fUpdated)
515 if (!wtx.WriteToDisk())
518 // If default receiving address gets used, replace it with a new one
519 CScript scriptDefaultKey;
520 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
521 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
523 if (txout.scriptPubKey == scriptDefaultKey)
525 CPubKey newDefaultKey;
526 if (GetKeyFromPool(newDefaultKey, false))
528 SetDefaultKey(newDefaultKey);
529 SetAddressBookName(vchDefaultKey.GetID(), "");
534 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
535 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
537 // Notify UI of new or updated transaction
538 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
540 // notify an external script when a wallet transaction comes in or is updated
541 std::string strCmd = GetArg("-walletnotify", "");
543 if ( !strCmd.empty())
545 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
546 boost::thread t(runCommand, strCmd); // thread runs free
553 // Add a transaction to the wallet, or update it.
554 // pblock is optional, but should be provided if the transaction is known to be in a block.
555 // If fUpdate is true, existing transactions will be updated.
556 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
558 uint256 hash = tx.GetHash();
561 bool fExisted = mapWallet.count(hash);
562 if (fExisted && !fUpdate) return false;
563 if (fExisted || IsMine(tx) || IsFromMe(tx))
565 CWalletTx wtx(this,tx);
566 // Get merkle branch if transaction was found in a block
568 wtx.SetMerkleBranch(pblock);
569 return AddToWallet(wtx);
572 WalletUpdateSpent(tx);
577 bool CWallet::EraseFromWallet(uint256 hash)
583 if (mapWallet.erase(hash))
584 CWalletDB(strWalletFile).EraseTx(hash);
590 isminetype CWallet::IsMine(const CTxIn &txin) const
594 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
595 if (mi != mapWallet.end())
597 const CWalletTx& prev = (*mi).second;
598 if (txin.prevout.n < prev.vout.size())
599 return IsMine(prev.vout[txin.prevout.n]);
605 int64 CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
609 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
610 if (mi != mapWallet.end())
612 const CWalletTx& prev = (*mi).second;
613 if (txin.prevout.n < prev.vout.size())
614 if (IsMine(prev.vout[txin.prevout.n]) & filter)
615 return prev.vout[txin.prevout.n].nValue;
621 bool CWallet::IsChange(const CTxOut& txout) const
623 // TODO: fix handling of 'change' outputs. The assumption is that any
624 // payment to a script that is ours, but isn't in the address book
625 // is change. That assumption is likely to break when we implement multisignature
626 // wallets that return change back into a multi-signature-protected address;
627 // a better way of identifying which outputs are 'the send' and which are
628 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
629 // which output, if any, was change).
630 if (::IsMine(*this, txout.scriptPubKey))
632 CTxDestination address;
633 if (!ExtractDestination(txout.scriptPubKey, address))
637 if (!mapAddressBook.count(address))
643 int64 CWalletTx::GetTxTime() const
645 int64 n = nTimeSmart;
646 return n ? n : nTimeReceived;
649 int CWalletTx::GetRequestCount() const
651 // Returns -1 if it wasn't being tracked
654 LOCK(pwallet->cs_wallet);
655 if (IsCoinBase() || IsCoinStake())
660 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
661 if (mi != pwallet->mapRequestCount.end())
662 nRequests = (*mi).second;
667 // Did anyone request this transaction?
668 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
669 if (mi != pwallet->mapRequestCount.end())
671 nRequests = (*mi).second;
673 // How about the block it's in?
674 if (nRequests == 0 && hashBlock != 0)
676 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
677 if (mi != pwallet->mapRequestCount.end())
678 nRequests = (*mi).second;
680 nRequests = 1; // If it's in someone else's block it must have got out
688 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
689 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount, const isminefilter& filter) const
691 nGeneratedImmature = nGeneratedMature = nFee = 0;
692 listReceived.clear();
694 strSentAccount = strFromAccount;
696 if (IsCoinBase() || IsCoinStake())
698 if (GetBlocksToMaturity() > 0)
699 nGeneratedImmature = pwallet->GetCredit(*this, filter);
701 nGeneratedMature = GetCredit(filter);
706 int64 nDebit = GetDebit(filter);
707 if (nDebit > 0) // debit>0 means we signed/sent this transaction
709 int64 nValueOut = GetValueOut();
710 nFee = nDebit - nValueOut;
714 BOOST_FOREACH(const CTxOut& txout, vout)
716 isminetype fIsMine = pwallet->IsMine(txout);
717 // Only need to handle txouts if AT LEAST one of these is true:
718 // 1) they debit from us (sent)
719 // 2) the output is to us (received)
722 // Don't report 'change' txouts
723 if (pwallet->IsChange(txout))
726 else if (!(fIsMine & filter))
729 // In either case, we need to get the destination address
730 CTxDestination address;
731 if (!ExtractDestination(txout.scriptPubKey, address))
733 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
734 this->GetHash().ToString().c_str());
735 address = CNoDestination();
738 // If we are debited by the transaction, add the output as a "sent" entry
740 listSent.push_back(make_pair(address, txout.nValue));
742 // If we are receiving the output, add it as a "received" entry
743 if (fIsMine & filter)
744 listReceived.push_back(make_pair(address, txout.nValue));
749 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
750 int64& nSent, int64& nFee, const isminefilter& filter) const
752 nGenerated = nReceived = nSent = nFee = 0;
754 int64 allGeneratedImmature, allGeneratedMature, allFee;
755 allGeneratedImmature = allGeneratedMature = allFee = 0;
756 string strSentAccount;
757 list<pair<CTxDestination, int64> > listReceived;
758 list<pair<CTxDestination, int64> > listSent;
759 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
761 if (strAccount == "")
762 nGenerated = allGeneratedMature;
763 if (strAccount == strSentAccount)
765 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
770 LOCK(pwallet->cs_wallet);
771 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
773 if (pwallet->mapAddressBook.count(r.first))
775 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
776 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
777 nReceived += r.second;
779 else if (strAccount.empty())
781 nReceived += r.second;
787 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
791 const int COPY_DEPTH = 3;
792 if (SetMerkleBranch() < COPY_DEPTH)
794 vector<uint256> vWorkQueue;
795 BOOST_FOREACH(const CTxIn& txin, vin)
796 vWorkQueue.push_back(txin.prevout.hash);
798 // This critsect is OK because txdb is already open
800 LOCK(pwallet->cs_wallet);
801 map<uint256, const CMerkleTx*> mapWalletPrev;
802 set<uint256> setAlreadyDone;
803 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
805 uint256 hash = vWorkQueue[i];
806 if (setAlreadyDone.count(hash))
808 setAlreadyDone.insert(hash);
811 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
812 if (mi != pwallet->mapWallet.end())
815 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
816 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
818 else if (mapWalletPrev.count(hash))
820 tx = *mapWalletPrev[hash];
822 else if (!fClient && txdb.ReadDiskTx(hash, tx))
828 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
832 int nDepth = tx.SetMerkleBranch();
833 vtxPrev.push_back(tx);
835 if (nDepth < COPY_DEPTH)
837 BOOST_FOREACH(const CTxIn& txin, tx.vin)
838 vWorkQueue.push_back(txin.prevout.hash);
844 reverse(vtxPrev.begin(), vtxPrev.end());
847 bool CWalletTx::WriteToDisk()
849 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
852 // Scan the block chain (starting in pindexStart) for transactions
853 // from or to us. If fUpdate is true, found transactions that already
854 // exist in the wallet will be updated.
855 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
859 CBlockIndex* pindex = pindexStart;
865 block.ReadFromDisk(pindex, true);
866 BOOST_FOREACH(CTransaction& tx, block.vtx)
868 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
871 pindex = pindex->pnext;
877 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
880 tx.ReadFromDisk(COutPoint(hashTx, 0));
881 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
886 void CWallet::ReacceptWalletTransactions()
894 vector<CDiskTxPos> vMissingTx;
895 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
897 CWalletTx& wtx = item.second;
898 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
902 bool fUpdated = false;
903 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
905 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
906 if (txindex.vSpent.size() != wtx.vout.size())
908 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
911 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
915 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
919 vMissingTx.push_back(txindex.vSpent[i]);
924 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
931 // Re-accept any txes of ours that aren't already in a block
932 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
933 wtx.AcceptWalletTransaction(txdb, false);
936 if (!vMissingTx.empty())
938 // TODO: optimize this to scan just part of the block chain?
939 if (ScanForWalletTransactions(pindexGenesisBlock))
940 fRepeat = true; // Found missing transactions: re-do re-accept.
945 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
947 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
949 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
951 uint256 hash = tx.GetHash();
952 if (!txdb.ContainsTx(hash))
953 RelayTransaction((CTransaction)tx, hash);
956 if (!(IsCoinBase() || IsCoinStake()))
958 uint256 hash = GetHash();
959 if (!txdb.ContainsTx(hash))
961 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
962 RelayTransaction((CTransaction)*this, hash);
967 void CWalletTx::RelayWalletTransaction()
970 RelayWalletTransaction(txdb);
973 void CWallet::ResendWalletTransactions()
975 // Do this infrequently and randomly to avoid giving away
976 // that these are our transactions.
977 static int64 nNextTime;
978 if (GetTime() < nNextTime)
980 bool fFirst = (nNextTime == 0);
981 nNextTime = GetTime() + GetRand(30 * 60);
985 // Only do it if there's been a new block since last time
986 static int64 nLastTime;
987 if (nTimeBestReceived < nLastTime)
989 nLastTime = GetTime();
991 // Rebroadcast any of our txes that aren't in a block yet
992 printf("ResendWalletTransactions()\n");
996 // Sort them in chronological order
997 multimap<unsigned int, CWalletTx*> mapSorted;
998 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1000 CWalletTx& wtx = item.second;
1001 // Don't rebroadcast until it's had plenty of time that
1002 // it should have gotten in already by now.
1003 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1004 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1006 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1008 CWalletTx& wtx = *item.second;
1009 if (wtx.CheckTransaction())
1010 wtx.RelayWalletTransaction(txdb);
1012 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1022 //////////////////////////////////////////////////////////////////////////////
1028 int64 CWallet::GetBalance() const
1033 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1035 const CWalletTx* pcoin = &(*it).second;
1036 if (pcoin->IsTrusted())
1037 nTotal += pcoin->GetAvailableCredit();
1044 int64 CWallet::GetWatchOnlyBalance() const
1049 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1051 const CWalletTx* pcoin = &(*it).second;
1052 if (pcoin->IsTrusted())
1053 nTotal += pcoin->GetAvailableWatchCredit();
1060 int64 CWallet::GetUnconfirmedBalance() const
1065 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1067 const CWalletTx* pcoin = &(*it).second;
1068 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1069 nTotal += pcoin->GetAvailableCredit();
1075 int64 CWallet::GetUnconfirmedWatchOnlyBalance() const
1080 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1082 const CWalletTx* pcoin = &(*it).second;
1083 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1084 nTotal += pcoin->GetAvailableWatchCredit();
1090 int64 CWallet::GetImmatureBalance() const
1095 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1097 const CWalletTx* pcoin = &(*it).second;
1098 nTotal += pcoin->GetImmatureCredit();
1104 int64 CWallet::GetImmatureWatchOnlyBalance() const
1109 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1111 const CWalletTx* pcoin = &(*it).second;
1112 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1118 // populate vCoins with vector of spendable COutputs
1119 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1125 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1127 const CWalletTx* pcoin = &(*it).second;
1129 if (!pcoin->IsFinal())
1132 if (fOnlyConfirmed && !pcoin->IsTrusted())
1135 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1138 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1141 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1142 isminetype mine = IsMine(pcoin->vout[i]);
1143 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1144 pcoin->vout[i].nValue >= nMinimumInputValue &&
1145 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1147 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1154 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1160 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1162 const CWalletTx* pcoin = &(*it).second;
1164 if (!pcoin->IsFinal())
1167 if(pcoin->GetDepthInMainChain() < nConf)
1170 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1171 isminetype mine = IsMine(pcoin->vout[i]);
1173 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1174 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1180 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1181 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1183 vector<char> vfIncluded;
1185 vfBest.assign(vValue.size(), true);
1186 nBest = nTotalLower;
1188 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1190 vfIncluded.assign(vValue.size(), false);
1192 bool fReachedTarget = false;
1193 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1195 for (unsigned int i = 0; i < vValue.size(); i++)
1197 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1199 nTotal += vValue[i].first;
1200 vfIncluded[i] = true;
1201 if (nTotal >= nTargetValue)
1203 fReachedTarget = true;
1207 vfBest = vfIncluded;
1209 nTotal -= vValue[i].first;
1210 vfIncluded[i] = false;
1218 int64 CWallet::GetStake() const
1222 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1224 const CWalletTx* pcoin = &(*it).second;
1225 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1226 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1231 int64 CWallet::GetWatchOnlyStake() const
1235 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1237 const CWalletTx* pcoin = &(*it).second;
1238 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1239 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1244 int64 CWallet::GetNewMint() const
1248 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1250 const CWalletTx* pcoin = &(*it).second;
1251 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1252 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1257 int64 CWallet::GetWatchOnlyNewMint() const
1261 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1263 const CWalletTx* pcoin = &(*it).second;
1264 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1265 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1270 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
1272 setCoinsRet.clear();
1275 // List of values less than target
1276 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1277 coinLowestLarger.first = std::numeric_limits<int64>::max();
1278 coinLowestLarger.second.first = NULL;
1279 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1280 int64 nTotalLower = 0;
1282 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1284 BOOST_FOREACH(const COutput &output, vCoins)
1286 if (!output.fSpendable)
1289 const CWalletTx *pcoin = output.tx;
1291 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1296 // Follow the timestamp rules
1297 if (pcoin->nTime > nSpendTime)
1300 int64 n = pcoin->vout[i].nValue;
1302 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1304 if (n == nTargetValue)
1306 setCoinsRet.insert(coin.second);
1307 nValueRet += coin.first;
1310 else if (n < nTargetValue + CENT)
1312 vValue.push_back(coin);
1315 else if (n < coinLowestLarger.first)
1317 coinLowestLarger = coin;
1321 if (nTotalLower == nTargetValue)
1323 for (unsigned int i = 0; i < vValue.size(); ++i)
1325 setCoinsRet.insert(vValue[i].second);
1326 nValueRet += vValue[i].first;
1331 if (nTotalLower < nTargetValue)
1333 if (coinLowestLarger.second.first == NULL)
1335 setCoinsRet.insert(coinLowestLarger.second);
1336 nValueRet += coinLowestLarger.first;
1340 // Solve subset sum by stochastic approximation
1341 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1342 vector<char> vfBest;
1345 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1346 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1347 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1349 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1350 // or the next bigger coin is closer), return the bigger coin
1351 if (coinLowestLarger.second.first &&
1352 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1354 setCoinsRet.insert(coinLowestLarger.second);
1355 nValueRet += coinLowestLarger.first;
1358 for (unsigned int i = 0; i < vValue.size(); i++)
1361 setCoinsRet.insert(vValue[i].second);
1362 nValueRet += vValue[i].first;
1365 if (fDebug && GetBoolArg("-printpriority"))
1368 printf("SelectCoins() best subset: ");
1369 for (unsigned int i = 0; i < vValue.size(); i++)
1371 printf("%s ", FormatMoney(vValue[i].first).c_str());
1372 printf("total %s\n", FormatMoney(nBest).c_str());
1379 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1381 vector<COutput> vCoins;
1382 AvailableCoins(vCoins, true, coinControl);
1384 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1385 if (coinControl && coinControl->HasSelected())
1387 BOOST_FOREACH(const COutput& out, vCoins)
1391 nValueRet += out.tx->vout[out.i].nValue;
1392 setCoinsRet.insert(make_pair(out.tx, out.i));
1394 return (nValueRet >= nTargetValue);
1397 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1398 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1399 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1402 // Select some coins without random shuffle or best subset approximation
1403 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1405 vector<COutput> vCoins;
1406 AvailableCoinsMinConf(vCoins, nMinConf);
1408 setCoinsRet.clear();
1411 BOOST_FOREACH(COutput output, vCoins)
1413 if(!output.fSpendable)
1415 const CWalletTx *pcoin = output.tx;
1418 // Stop if we've chosen enough inputs
1419 if (nValueRet >= nTargetValue)
1422 // Follow the timestamp rules
1423 if (pcoin->nTime > nSpendTime)
1426 int64 n = pcoin->vout[i].nValue;
1428 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1430 if (n >= nTargetValue)
1432 // If input value is greater or equal to target then simply insert
1433 // it into the current subset and exit
1434 setCoinsRet.insert(coin.second);
1435 nValueRet += coin.first;
1438 else if (n < nTargetValue + CENT)
1440 setCoinsRet.insert(coin.second);
1441 nValueRet += coin.first;
1448 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1451 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1457 if (vecSend.empty() || nValue < 0)
1460 wtxNew.BindWallet(this);
1463 LOCK2(cs_main, cs_wallet);
1464 // txdb must be opened before the mapWallet lock
1467 nFeeRet = nTransactionFee;
1471 wtxNew.vout.clear();
1472 wtxNew.fFromMe = true;
1474 int64 nTotalValue = nValue + nFeeRet;
1475 double dPriority = 0;
1476 // vouts to the payees
1477 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1478 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1480 // Choose coins to use
1481 set<pair<const CWalletTx*,unsigned int> > setCoins;
1483 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1485 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1487 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1488 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1491 int64 nChange = nValueIn - nValue - nFeeRet;
1492 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1493 // or until nChange becomes zero
1494 // NOTE: this depends on the exact behaviour of GetMinFee
1495 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1497 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1499 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1500 nChange -= nMoveToFee;
1501 nFeeRet += nMoveToFee;
1504 // sub-cent change is moved to fee
1505 if (nChange > 0 && nChange < CENT)
1514 // Fill a vout to ourself
1515 // TODO: pass in scriptChange instead of reservekey so
1516 // change transaction isn't always pay-to-bitcoin-address
1517 CScript scriptChange;
1519 // coin control: send change to custom address
1520 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1521 scriptChange.SetDestination(coinControl->destChange);
1523 // no coin control: send change to newly generated address
1526 // Note: We use a new key here to keep it from being obvious which side is the change.
1527 // The drawback is that by not reusing a previous key, the change may be lost if a
1528 // backup is restored, if the backup doesn't have the new private key for the change.
1529 // If we reused the old key, it would be possible to add code to look for and
1530 // rediscover unknown transactions that were written with keys of ours to recover
1531 // post-backup change.
1533 // Reserve a new key pair from key pool
1534 CPubKey vchPubKey = reservekey.GetReservedKey();
1536 scriptChange.SetDestination(vchPubKey.GetID());
1539 // Insert change txn at random position:
1540 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1541 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1544 reservekey.ReturnKey();
1547 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1548 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1552 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1553 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1557 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1558 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1560 dPriority /= nBytes;
1562 // Check that enough fee is included
1563 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1564 bool fAllowFree = CTransaction::AllowFree(dPriority);
1566 // Disable free transactions until 1 July 2014
1567 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1572 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1574 if (nFeeRet < max(nPayFee, nMinFee))
1576 nFeeRet = max(nPayFee, nMinFee);
1580 // Fill vtxPrev by copying from previous transactions vtxPrev
1581 wtxNew.AddSupportingTransactions(txdb);
1582 wtxNew.fTimeReceivedIsTxTime = true;
1591 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1593 vector< pair<CScript, int64> > vecSend;
1594 vecSend.push_back(make_pair(scriptPubKey, nValue));
1595 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1598 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1600 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1602 // If time weight is lower or equal to zero then weight is zero.
1603 if (nTimeWeight <= 0)
1609 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1610 nWeight = bnCoinDayWeight.getuint64();
1614 // NovaCoin: get current stake weight
1615 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1617 // Choose coins to use
1618 int64 nBalance = GetBalance();
1619 int64 nReserveBalance = 0;
1621 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1623 error("GetStakeWeight : invalid reserve balance amount");
1627 if (nBalance <= nReserveBalance)
1630 vector<const CWalletTx*> vwtxPrev;
1633 * TODO: performance comparison
1635 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1636 static uint256 hashPrevBlock;
1637 static int64 nValueIn = 0;
1639 // Cache outputs unless best block changed
1640 if (hashPrevBlock != pindexBest->GetBlockHash())
1642 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1645 if (setCoins.empty())
1648 hashPrevBlock == pindexBest->GetBlockHash();
1652 set<pair<const CWalletTx*,unsigned int> > setCoins;
1655 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1658 if (setCoins.empty())
1662 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1666 LOCK2(cs_main, cs_wallet);
1667 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1671 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1672 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1674 // Weight is greater than zero
1675 if (nTimeWeight > 0)
1677 nWeight += bnCoinDayWeight.getuint64();
1680 // Weight is greater than zero, but the maximum value isn't reached yet
1681 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1683 nMinWeight += bnCoinDayWeight.getuint64();
1686 // Maximum weight was reached
1687 if (nTimeWeight == nStakeMaxAge)
1689 nMaxWeight += bnCoinDayWeight.getuint64();
1696 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1698 // The following combine threshold is important to security
1699 // Should not be adjusted if you don't understand the consequences
1700 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1702 CBigNum bnTargetPerCoinDay;
1703 bnTargetPerCoinDay.SetCompact(nBits);
1708 // Mark coin stake transaction
1709 CScript scriptEmpty;
1710 scriptEmpty.clear();
1711 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1713 // Choose coins to use
1714 int64 nBalance = GetBalance();
1715 int64 nReserveBalance = 0;
1717 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1718 return error("CreateCoinStake : invalid reserve balance amount");
1720 if (nBalance <= nReserveBalance)
1723 vector<const CWalletTx*> vwtxPrev;
1726 * TODO: performance comparison
1728 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1729 static uint256 hashPrevBlock;
1730 static int64 nValueIn = 0;
1732 // Cache outputs unless best block changed
1733 if (hashPrevBlock != pindexBest->GetBlockHash())
1735 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1738 if (setCoins.empty())
1741 hashPrevBlock == pindexBest->GetBlockHash();
1745 set<pair<const CWalletTx*,unsigned int> > setCoins;
1748 // Select coins with suitable depth
1749 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1752 if (setCoins.empty())
1756 CScript scriptPubKeyKernel;
1758 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1762 LOCK2(cs_main, cs_wallet);
1763 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1767 // Read block header
1770 LOCK2(cs_main, cs_wallet);
1771 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1775 static int nMaxStakeSearchInterval = 60;
1776 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1777 continue; // only count coins meeting min age requirement
1779 bool fKernelFound = false;
1780 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1782 // Search backward in time from the given txNew timestamp
1783 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1784 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1785 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1786 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1789 if (fDebug && GetBoolArg("-printcoinstake"))
1790 printf("CreateCoinStake : kernel found\n");
1791 vector<valtype> vSolutions;
1792 txnouttype whichType;
1793 CScript scriptPubKeyOut;
1794 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1795 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1797 if (fDebug && GetBoolArg("-printcoinstake"))
1798 printf("CreateCoinStake : failed to parse kernel\n");
1801 if (fDebug && GetBoolArg("-printcoinstake"))
1802 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1803 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1805 if (fDebug && GetBoolArg("-printcoinstake"))
1806 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1807 break; // only support pay to public key and pay to address
1809 if (whichType == TX_PUBKEYHASH) // pay to address type
1811 // convert to pay to public key type
1812 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1814 if (fDebug && GetBoolArg("-printcoinstake"))
1815 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1816 break; // unable to find corresponding public key
1818 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1820 if (whichType == TX_PUBKEY)
1822 valtype& vchPubKey = vSolutions[0];
1823 if (!keystore.GetKey(Hash160(vchPubKey), key))
1825 if (fDebug && GetBoolArg("-printcoinstake"))
1826 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1827 break; // unable to find corresponding public key
1830 if (key.GetPubKey() != vchPubKey)
1832 if (fDebug && GetBoolArg("-printcoinstake"))
1833 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1834 break; // keys mismatch
1837 scriptPubKeyOut = scriptPubKeyKernel;
1841 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1842 nCredit += pcoin.first->vout[pcoin.second].nValue;
1843 vwtxPrev.push_back(pcoin.first);
1844 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1846 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1847 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1848 if (fDebug && GetBoolArg("-printcoinstake"))
1849 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1850 fKernelFound = true;
1855 if (fKernelFound || fShutdown)
1856 break; // if kernel is found stop searching
1859 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1862 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1864 // Attempt to add more inputs
1865 // Only add coins of the same key/address as kernel
1866 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1867 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1869 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1871 // Stop adding more inputs if already too many inputs
1872 if (txNew.vin.size() >= 100)
1874 // Stop adding more inputs if value is already pretty significant
1875 if (nCredit > nCombineThreshold)
1877 // Stop adding inputs if reached reserve limit
1878 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1880 // Do not add additional significant input
1881 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1883 // Do not add input that is still too young
1884 if (nTimeWeight < nStakeMaxAge)
1887 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1888 nCredit += pcoin.first->vout[pcoin.second].nValue;
1889 vwtxPrev.push_back(pcoin.first);
1893 // Calculate coin age reward
1897 if (!txNew.GetCoinAge(txdb, nCoinAge))
1898 return error("CreateCoinStake : failed to calculate coin age");
1899 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1905 // Set output amount
1906 if (txNew.vout.size() == 3)
1908 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1909 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1912 txNew.vout[1].nValue = nCredit - nMinFee;
1916 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1918 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1919 return error("CreateCoinStake : failed to sign coinstake");
1923 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1924 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1925 return error("CreateCoinStake : exceeded coinstake size limit");
1927 // Check enough fee is paid
1928 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1930 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1931 continue; // try signing again
1935 if (fDebug && GetBoolArg("-printfee"))
1936 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1941 // Successfully generated coinstake
1946 // Call after CreateTransaction unless you want to abort
1947 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1950 LOCK2(cs_main, cs_wallet);
1951 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1953 // This is only to keep the database open to defeat the auto-flush for the
1954 // duration of this scope. This is the only place where this optimization
1955 // maybe makes sense; please don't do it anywhere else.
1956 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1958 // Take key pair from key pool so it won't be used again
1959 reservekey.KeepKey();
1961 // Add tx to wallet, because if it has change it's also ours,
1962 // otherwise just for transaction history.
1963 AddToWallet(wtxNew);
1965 // Mark old coins as spent
1966 set<CWalletTx*> setCoins;
1967 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1969 CWalletTx &coin = mapWallet[txin.prevout.hash];
1970 coin.BindWallet(this);
1971 coin.MarkSpent(txin.prevout.n);
1973 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1980 // Track how many getdata requests our transaction gets
1981 mapRequestCount[wtxNew.GetHash()] = 0;
1984 if (!wtxNew.AcceptToMemoryPool())
1986 // This must not fail. The transaction has already been signed and recorded.
1987 printf("CommitTransaction() : Error: Transaction not valid");
1990 wtxNew.RelayWalletTransaction();
1998 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2000 CReserveKey reservekey(this);
2005 string strError = _("Error: Wallet locked, unable to create transaction ");
2006 printf("SendMoney() : %s", strError.c_str());
2009 if (fWalletUnlockMintOnly)
2011 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2012 printf("SendMoney() : %s", strError.c_str());
2015 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2018 if (nValue + nFeeRequired > GetBalance())
2019 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());
2021 strError = _("Error: Transaction creation failed ");
2022 printf("SendMoney() : %s", strError.c_str());
2026 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2029 if (!CommitTransaction(wtxNew, reservekey))
2030 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.");
2037 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2041 return _("Invalid amount");
2042 if (nValue + nTransactionFee > GetBalance())
2043 return _("Insufficient funds");
2045 // Parse Bitcoin address
2046 CScript scriptPubKey;
2047 scriptPubKey.SetDestination(address);
2049 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2055 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2059 fFirstRunRet = false;
2060 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2061 if (nLoadWalletRet == DB_NEED_REWRITE)
2063 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2066 // Note: can't top-up keypool here, because wallet is locked.
2067 // User will be prompted to unlock wallet the next operation
2068 // the requires a new key.
2072 if (nLoadWalletRet != DB_LOAD_OK)
2073 return nLoadWalletRet;
2074 fFirstRunRet = !vchDefaultKey.IsValid();
2076 NewThread(ThreadFlushWalletDB, &strWalletFile);
2081 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2083 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2084 mapAddressBook[address] = strName;
2085 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2088 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2091 bool CWallet::DelAddressBookName(const CTxDestination& address)
2093 mapAddressBook.erase(address);
2094 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2097 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2101 void CWallet::PrintWallet(const CBlock& block)
2105 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2107 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2108 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2110 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2112 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2113 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2120 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2124 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2125 if (mi != mapWallet.end())
2134 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2138 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2141 vchDefaultKey = vchPubKey;
2145 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2147 if (!pwallet->fFileBacked)
2149 strWalletFileOut = pwallet->strWalletFile;
2154 // Mark old keypool keys as used,
2155 // and generate all new keys
2157 bool CWallet::NewKeyPool()
2161 CWalletDB walletdb(strWalletFile);
2162 BOOST_FOREACH(int64 nIndex, setKeyPool)
2163 walletdb.ErasePool(nIndex);
2169 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2170 for (int i = 0; i < nKeys; i++)
2173 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2174 setKeyPool.insert(nIndex);
2176 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2181 bool CWallet::TopUpKeyPool(unsigned int nSize)
2189 CWalletDB walletdb(strWalletFile);
2192 unsigned int nTargetSize;
2194 nTargetSize = nSize;
2196 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2198 while (setKeyPool.size() < (nTargetSize + 1))
2201 if (!setKeyPool.empty())
2202 nEnd = *(--setKeyPool.end()) + 1;
2203 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2204 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2205 setKeyPool.insert(nEnd);
2206 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2212 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2215 keypool.vchPubKey = CPubKey();
2222 // Get the oldest key
2223 if(setKeyPool.empty())
2226 CWalletDB walletdb(strWalletFile);
2228 nIndex = *(setKeyPool.begin());
2229 setKeyPool.erase(setKeyPool.begin());
2230 if (!walletdb.ReadPool(nIndex, keypool))
2231 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2232 if (!HaveKey(keypool.vchPubKey.GetID()))
2233 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2234 assert(keypool.vchPubKey.IsValid());
2235 if (fDebug && GetBoolArg("-printkeypool"))
2236 printf("keypool reserve %"PRI64d"\n", nIndex);
2240 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2243 LOCK2(cs_main, cs_wallet);
2244 CWalletDB walletdb(strWalletFile);
2246 int64 nIndex = 1 + *(--setKeyPool.end());
2247 if (!walletdb.WritePool(nIndex, keypool))
2248 throw runtime_error("AddReserveKey() : writing added key failed");
2249 setKeyPool.insert(nIndex);
2255 void CWallet::KeepKey(int64 nIndex)
2257 // Remove from key pool
2260 CWalletDB walletdb(strWalletFile);
2261 walletdb.ErasePool(nIndex);
2264 printf("keypool keep %"PRI64d"\n", nIndex);
2267 void CWallet::ReturnKey(int64 nIndex)
2269 // Return to key pool
2272 setKeyPool.insert(nIndex);
2275 printf("keypool return %"PRI64d"\n", nIndex);
2278 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2284 ReserveKeyFromKeyPool(nIndex, keypool);
2287 if (fAllowReuse && vchDefaultKey.IsValid())
2289 result = vchDefaultKey;
2292 if (IsLocked()) return false;
2293 result = GenerateNewKey();
2297 result = keypool.vchPubKey;
2302 int64 CWallet::GetOldestKeyPoolTime()
2306 ReserveKeyFromKeyPool(nIndex, keypool);
2310 return keypool.nTime;
2313 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2315 map<CTxDestination, int64> balances;
2319 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2321 CWalletTx *pcoin = &walletEntry.second;
2323 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2326 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2329 int nDepth = pcoin->GetDepthInMainChain();
2330 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2333 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2335 CTxDestination addr;
2336 if (!IsMine(pcoin->vout[i]))
2338 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2341 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2343 if (!balances.count(addr))
2345 balances[addr] += n;
2353 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2355 set< set<CTxDestination> > groupings;
2356 set<CTxDestination> grouping;
2358 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2360 CWalletTx *pcoin = &walletEntry.second;
2362 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2364 // group all input addresses with each other
2365 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2367 CTxDestination address;
2368 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2370 grouping.insert(address);
2373 // group change with input addresses
2374 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2375 if (IsChange(txout))
2377 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2378 CTxDestination txoutAddr;
2379 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2381 grouping.insert(txoutAddr);
2383 groupings.insert(grouping);
2387 // group lone addrs by themselves
2388 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2389 if (IsMine(pcoin->vout[i]))
2391 CTxDestination address;
2392 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2394 grouping.insert(address);
2395 groupings.insert(grouping);
2400 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2401 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2402 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2404 // make a set of all the groups hit by this new group
2405 set< set<CTxDestination>* > hits;
2406 map< CTxDestination, set<CTxDestination>* >::iterator it;
2407 BOOST_FOREACH(CTxDestination address, grouping)
2408 if ((it = setmap.find(address)) != setmap.end())
2409 hits.insert((*it).second);
2411 // merge all hit groups into a new single group and delete old groups
2412 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2413 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2415 merged->insert(hit->begin(), hit->end());
2416 uniqueGroupings.erase(hit);
2419 uniqueGroupings.insert(merged);
2422 BOOST_FOREACH(CTxDestination element, *merged)
2423 setmap[element] = merged;
2426 set< set<CTxDestination> > ret;
2427 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2429 ret.insert(*uniqueGrouping);
2430 delete uniqueGrouping;
2436 // ppcoin: check 'spent' consistency between wallet and txindex
2437 // ppcoin: fix wallet spent state according to txindex
2438 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2441 nBalanceInQuestion = 0;
2444 vector<CWalletTx*> vCoins;
2445 vCoins.reserve(mapWallet.size());
2446 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2447 vCoins.push_back(&(*it).second);
2450 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2452 // Find the corresponding transaction index
2454 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2456 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2458 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2460 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2461 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2463 nBalanceInQuestion += pcoin->vout[n].nValue;
2466 pcoin->MarkUnspent(n);
2467 pcoin->WriteToDisk();
2470 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2472 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2473 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2475 nBalanceInQuestion += pcoin->vout[n].nValue;
2478 pcoin->MarkSpent(n);
2479 pcoin->WriteToDisk();
2485 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2487 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2490 EraseFromWallet(pcoin->GetHash());
2496 // ppcoin: disable transaction (only for coinstake)
2497 void CWallet::DisableTransaction(const CTransaction &tx)
2499 if (!tx.IsCoinStake() || !IsFromMe(tx))
2500 return; // only disconnecting coinstake requires marking input unspent
2503 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2505 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2506 if (mi != mapWallet.end())
2508 CWalletTx& prev = (*mi).second;
2509 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2511 prev.MarkUnspent(txin.prevout.n);
2518 CPubKey CReserveKey::GetReservedKey()
2523 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2525 vchPubKey = keypool.vchPubKey;
2528 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2529 vchPubKey = pwallet->vchDefaultKey;
2532 assert(vchPubKey.IsValid());
2536 void CReserveKey::KeepKey()
2539 pwallet->KeepKey(nIndex);
2541 vchPubKey = CPubKey();
2544 void CReserveKey::ReturnKey()
2547 pwallet->ReturnKey(nIndex);
2549 vchPubKey = CPubKey();
2552 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2556 CWalletDB walletdb(strWalletFile);
2558 LOCK2(cs_main, cs_wallet);
2559 BOOST_FOREACH(const int64& id, setKeyPool)
2562 if (!walletdb.ReadPool(id, keypool))
2563 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2564 assert(keypool.vchPubKey.IsValid());
2565 CKeyID keyID = keypool.vchPubKey.GetID();
2566 if (!HaveKey(keyID))
2567 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2568 setAddress.insert(keyID);
2572 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2576 // Only notify UI if this transaction is in this wallet
2577 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2578 if (mi != mapWallet.end())
2579 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2583 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2584 mapKeyBirth.clear();
2586 // get birth times for keys with metadata
2587 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2588 if (it->second.nCreateTime)
2589 mapKeyBirth[it->first] = it->second.nCreateTime;
2591 // map in which we'll infer heights of other keys
2592 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2593 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2594 std::set<CKeyID> setKeys;
2596 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2597 if (mapKeyBirth.count(keyid) == 0)
2598 mapKeyFirstBlock[keyid] = pindexMax;
2602 // if there are no such keys, we're done
2603 if (mapKeyFirstBlock.empty())
2606 // find first block that affects those keys, if there are any left
2607 std::vector<CKeyID> vAffected;
2608 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2609 // iterate over all wallet transactions...
2610 const CWalletTx &wtx = (*it).second;
2611 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2612 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2613 // ... which are already in a block
2614 int nHeight = blit->second->nHeight;
2615 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2616 // iterate over all their outputs
2617 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2618 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2619 // ... and all their affected keys
2620 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2621 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2622 rit->second = blit->second;
2629 // Extract block timestamps for those keys
2630 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2631 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off