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::MergeCoins(const int64& nAmount, const int64& nMaxValue, const int64& nOutputValue, list<uint256>& listMerged)
1698 int64 nBalance = GetBalance();
1700 if (nAmount > nBalance)
1705 set<pair<const CWalletTx*,unsigned int> > setCoins;
1707 // Simple coins selection - no randomization
1708 if (!SelectCoinsSimple(nAmount, GetTime(), 1, setCoins, nValueIn))
1711 if (setCoins.empty())
1715 vector<const CWalletTx*> vwtxPrev;
1717 // Reserve a new key pair from key pool
1718 CReserveKey reservekey(this);
1719 CPubKey vchPubKey = reservekey.GetReservedKey();
1722 CScript scriptOutput;
1723 scriptOutput.SetDestination(vchPubKey.GetID());
1726 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1730 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1732 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1734 // Ignore coin if credit is too high
1735 if (nCredit >= nMaxValue)
1738 // Ignore immature coins
1739 if (pcoin.first->GetBlocksToMaturity() > 0)
1742 // Add current coin to inputs list and add its credit to transaction output
1743 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1744 wtxNew.vout[0].nValue += nCredit;
1745 vwtxPrev.push_back(pcoin.first);
1747 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1748 const CWalletTx *txin = vwtxPrev[i];
1750 // Sign scripts to get actual transaction size for fee calculation
1751 if (!SignSignature(*this, *txin, wtxNew, i))
1755 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1756 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1758 double dFinalPriority = dWeight /= nBytes;
1759 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1761 // Get actual transaction fee according to its size and priority
1762 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1764 // Prepare transaction for commit if sum is enough ot its size is too big
1765 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || (wtxNew.vout[0].nValue >= nOutputValue && wtxNew.vout.size() > 1))
1767 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1769 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1770 const CWalletTx *txin = vwtxPrev[i];
1772 // Sign all scripts again
1773 if (!SignSignature(*this, *txin, wtxNew, i))
1777 // Try to commit, return false on failure
1778 if (!CommitTransaction(wtxNew, reservekey))
1781 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1783 dWeight = 0; // Reset all temporary values
1786 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1790 // Create transactions if there are some unhandled coins left
1791 if (wtxNew.vout[0].nValue > 0) {
1792 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1794 double dFinalPriority = dWeight /= nBytes;
1795 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1797 // Get actual transaction fee according to its size and priority
1798 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1800 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1802 if (wtxNew.vout[0].nValue <= 0)
1805 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1806 const CWalletTx *txin = vwtxPrev[i];
1808 // Sign all scripts again
1809 if (!SignSignature(*this, *txin, wtxNew, i))
1813 // Try to commit, return false on failure
1814 if (!CommitTransaction(wtxNew, reservekey))
1817 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1824 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1826 // The following combine threshold is important to security
1827 // Should not be adjusted if you don't understand the consequences
1828 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1830 CBigNum bnTargetPerCoinDay;
1831 bnTargetPerCoinDay.SetCompact(nBits);
1836 // Mark coin stake transaction
1837 CScript scriptEmpty;
1838 scriptEmpty.clear();
1839 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1841 // Choose coins to use
1842 int64 nBalance = GetBalance();
1843 int64 nReserveBalance = 0;
1845 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1846 return error("CreateCoinStake : invalid reserve balance amount");
1848 if (nBalance <= nReserveBalance)
1851 vector<const CWalletTx*> vwtxPrev;
1854 * TODO: performance comparison
1856 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1857 static uint256 hashPrevBlock;
1858 static int64 nValueIn = 0;
1860 // Cache outputs unless best block changed
1861 if (hashPrevBlock != pindexBest->GetBlockHash())
1863 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1866 if (setCoins.empty())
1869 hashPrevBlock == pindexBest->GetBlockHash();
1873 set<pair<const CWalletTx*,unsigned int> > setCoins;
1876 // Select coins with suitable depth
1877 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1880 if (setCoins.empty())
1884 CScript scriptPubKeyKernel;
1886 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1890 LOCK2(cs_main, cs_wallet);
1891 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1895 // Read block header
1898 LOCK2(cs_main, cs_wallet);
1899 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1903 static int nMaxStakeSearchInterval = 60;
1904 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1905 continue; // only count coins meeting min age requirement
1907 bool fKernelFound = false;
1908 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1910 // Search backward in time from the given txNew timestamp
1911 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1912 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1913 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1914 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1917 if (fDebug && GetBoolArg("-printcoinstake"))
1918 printf("CreateCoinStake : kernel found\n");
1919 vector<valtype> vSolutions;
1920 txnouttype whichType;
1921 CScript scriptPubKeyOut;
1922 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1923 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1925 if (fDebug && GetBoolArg("-printcoinstake"))
1926 printf("CreateCoinStake : failed to parse kernel\n");
1929 if (fDebug && GetBoolArg("-printcoinstake"))
1930 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1931 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1933 if (fDebug && GetBoolArg("-printcoinstake"))
1934 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1935 break; // only support pay to public key and pay to address
1937 if (whichType == TX_PUBKEYHASH) // pay to address type
1939 // convert to pay to public key type
1940 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1942 if (fDebug && GetBoolArg("-printcoinstake"))
1943 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1944 break; // unable to find corresponding public key
1946 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1948 if (whichType == TX_PUBKEY)
1950 valtype& vchPubKey = vSolutions[0];
1951 if (!keystore.GetKey(Hash160(vchPubKey), key))
1953 if (fDebug && GetBoolArg("-printcoinstake"))
1954 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1955 break; // unable to find corresponding public key
1958 if (key.GetPubKey() != vchPubKey)
1960 if (fDebug && GetBoolArg("-printcoinstake"))
1961 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1962 break; // keys mismatch
1965 scriptPubKeyOut = scriptPubKeyKernel;
1969 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1970 nCredit += pcoin.first->vout[pcoin.second].nValue;
1971 vwtxPrev.push_back(pcoin.first);
1972 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1974 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1975 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1976 if (fDebug && GetBoolArg("-printcoinstake"))
1977 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1978 fKernelFound = true;
1983 if (fKernelFound || fShutdown)
1984 break; // if kernel is found stop searching
1987 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1990 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1992 // Attempt to add more inputs
1993 // Only add coins of the same key/address as kernel
1994 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1995 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1997 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1999 // Stop adding more inputs if already too many inputs
2000 if (txNew.vin.size() >= 100)
2002 // Stop adding more inputs if value is already pretty significant
2003 if (nCredit > nCombineThreshold)
2005 // Stop adding inputs if reached reserve limit
2006 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2008 // Do not add additional significant input
2009 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2011 // Do not add input that is still too young
2012 if (nTimeWeight < nStakeMaxAge)
2015 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2016 nCredit += pcoin.first->vout[pcoin.second].nValue;
2017 vwtxPrev.push_back(pcoin.first);
2021 // Calculate coin age reward
2025 if (!txNew.GetCoinAge(txdb, nCoinAge))
2026 return error("CreateCoinStake : failed to calculate coin age");
2027 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2033 // Set output amount
2034 if (txNew.vout.size() == 3)
2036 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2037 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2040 txNew.vout[1].nValue = nCredit - nMinFee;
2044 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2046 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2047 return error("CreateCoinStake : failed to sign coinstake");
2051 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2052 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2053 return error("CreateCoinStake : exceeded coinstake size limit");
2055 // Check enough fee is paid
2056 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2058 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2059 continue; // try signing again
2063 if (fDebug && GetBoolArg("-printfee"))
2064 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2069 // Successfully generated coinstake
2074 // Call after CreateTransaction unless you want to abort
2075 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2078 LOCK2(cs_main, cs_wallet);
2079 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2081 // This is only to keep the database open to defeat the auto-flush for the
2082 // duration of this scope. This is the only place where this optimization
2083 // maybe makes sense; please don't do it anywhere else.
2084 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2086 // Take key pair from key pool so it won't be used again
2087 reservekey.KeepKey();
2089 // Add tx to wallet, because if it has change it's also ours,
2090 // otherwise just for transaction history.
2091 AddToWallet(wtxNew);
2093 // Mark old coins as spent
2094 set<CWalletTx*> setCoins;
2095 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2097 CWalletTx &coin = mapWallet[txin.prevout.hash];
2098 coin.BindWallet(this);
2099 coin.MarkSpent(txin.prevout.n);
2101 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2108 // Track how many getdata requests our transaction gets
2109 mapRequestCount[wtxNew.GetHash()] = 0;
2112 if (!wtxNew.AcceptToMemoryPool())
2114 // This must not fail. The transaction has already been signed and recorded.
2115 printf("CommitTransaction() : Error: Transaction not valid");
2118 wtxNew.RelayWalletTransaction();
2126 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2128 CReserveKey reservekey(this);
2133 string strError = _("Error: Wallet locked, unable to create transaction ");
2134 printf("SendMoney() : %s", strError.c_str());
2137 if (fWalletUnlockMintOnly)
2139 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2140 printf("SendMoney() : %s", strError.c_str());
2143 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2146 if (nValue + nFeeRequired > GetBalance())
2147 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());
2149 strError = _("Error: Transaction creation failed ");
2150 printf("SendMoney() : %s", strError.c_str());
2154 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2157 if (!CommitTransaction(wtxNew, reservekey))
2158 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.");
2165 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2169 return _("Invalid amount");
2170 if (nValue + nTransactionFee > GetBalance())
2171 return _("Insufficient funds");
2173 // Parse Bitcoin address
2174 CScript scriptPubKey;
2175 scriptPubKey.SetDestination(address);
2177 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2183 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2187 fFirstRunRet = false;
2188 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2189 if (nLoadWalletRet == DB_NEED_REWRITE)
2191 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2194 // Note: can't top-up keypool here, because wallet is locked.
2195 // User will be prompted to unlock wallet the next operation
2196 // the requires a new key.
2200 if (nLoadWalletRet != DB_LOAD_OK)
2201 return nLoadWalletRet;
2202 fFirstRunRet = !vchDefaultKey.IsValid();
2204 NewThread(ThreadFlushWalletDB, &strWalletFile);
2209 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2211 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2212 mapAddressBook[address] = strName;
2213 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2216 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2219 bool CWallet::DelAddressBookName(const CTxDestination& address)
2221 mapAddressBook.erase(address);
2222 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2225 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2229 void CWallet::PrintWallet(const CBlock& block)
2233 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2235 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2236 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2238 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2240 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2241 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2248 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2252 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2253 if (mi != mapWallet.end())
2262 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2266 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2269 vchDefaultKey = vchPubKey;
2273 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2275 if (!pwallet->fFileBacked)
2277 strWalletFileOut = pwallet->strWalletFile;
2282 // Mark old keypool keys as used,
2283 // and generate all new keys
2285 bool CWallet::NewKeyPool()
2289 CWalletDB walletdb(strWalletFile);
2290 BOOST_FOREACH(int64 nIndex, setKeyPool)
2291 walletdb.ErasePool(nIndex);
2297 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2298 for (int i = 0; i < nKeys; i++)
2301 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2302 setKeyPool.insert(nIndex);
2304 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2309 bool CWallet::TopUpKeyPool(unsigned int nSize)
2317 CWalletDB walletdb(strWalletFile);
2320 unsigned int nTargetSize;
2322 nTargetSize = nSize;
2324 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2326 while (setKeyPool.size() < (nTargetSize + 1))
2329 if (!setKeyPool.empty())
2330 nEnd = *(--setKeyPool.end()) + 1;
2331 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2332 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2333 setKeyPool.insert(nEnd);
2334 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2340 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2343 keypool.vchPubKey = CPubKey();
2350 // Get the oldest key
2351 if(setKeyPool.empty())
2354 CWalletDB walletdb(strWalletFile);
2356 nIndex = *(setKeyPool.begin());
2357 setKeyPool.erase(setKeyPool.begin());
2358 if (!walletdb.ReadPool(nIndex, keypool))
2359 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2360 if (!HaveKey(keypool.vchPubKey.GetID()))
2361 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2362 assert(keypool.vchPubKey.IsValid());
2363 if (fDebug && GetBoolArg("-printkeypool"))
2364 printf("keypool reserve %"PRI64d"\n", nIndex);
2368 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2371 LOCK2(cs_main, cs_wallet);
2372 CWalletDB walletdb(strWalletFile);
2374 int64 nIndex = 1 + *(--setKeyPool.end());
2375 if (!walletdb.WritePool(nIndex, keypool))
2376 throw runtime_error("AddReserveKey() : writing added key failed");
2377 setKeyPool.insert(nIndex);
2383 void CWallet::KeepKey(int64 nIndex)
2385 // Remove from key pool
2388 CWalletDB walletdb(strWalletFile);
2389 walletdb.ErasePool(nIndex);
2392 printf("keypool keep %"PRI64d"\n", nIndex);
2395 void CWallet::ReturnKey(int64 nIndex)
2397 // Return to key pool
2400 setKeyPool.insert(nIndex);
2403 printf("keypool return %"PRI64d"\n", nIndex);
2406 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2412 ReserveKeyFromKeyPool(nIndex, keypool);
2415 if (fAllowReuse && vchDefaultKey.IsValid())
2417 result = vchDefaultKey;
2420 if (IsLocked()) return false;
2421 result = GenerateNewKey();
2425 result = keypool.vchPubKey;
2430 int64 CWallet::GetOldestKeyPoolTime()
2434 ReserveKeyFromKeyPool(nIndex, keypool);
2438 return keypool.nTime;
2441 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2443 map<CTxDestination, int64> balances;
2447 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2449 CWalletTx *pcoin = &walletEntry.second;
2451 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2454 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2457 int nDepth = pcoin->GetDepthInMainChain();
2458 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2461 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2463 CTxDestination addr;
2464 if (!IsMine(pcoin->vout[i]))
2466 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2469 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2471 if (!balances.count(addr))
2473 balances[addr] += n;
2481 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2483 set< set<CTxDestination> > groupings;
2484 set<CTxDestination> grouping;
2486 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2488 CWalletTx *pcoin = &walletEntry.second;
2490 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2492 // group all input addresses with each other
2493 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2495 CTxDestination address;
2496 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2498 grouping.insert(address);
2501 // group change with input addresses
2502 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2503 if (IsChange(txout))
2505 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2506 CTxDestination txoutAddr;
2507 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2509 grouping.insert(txoutAddr);
2511 groupings.insert(grouping);
2515 // group lone addrs by themselves
2516 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2517 if (IsMine(pcoin->vout[i]))
2519 CTxDestination address;
2520 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2522 grouping.insert(address);
2523 groupings.insert(grouping);
2528 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2529 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2530 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2532 // make a set of all the groups hit by this new group
2533 set< set<CTxDestination>* > hits;
2534 map< CTxDestination, set<CTxDestination>* >::iterator it;
2535 BOOST_FOREACH(CTxDestination address, grouping)
2536 if ((it = setmap.find(address)) != setmap.end())
2537 hits.insert((*it).second);
2539 // merge all hit groups into a new single group and delete old groups
2540 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2541 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2543 merged->insert(hit->begin(), hit->end());
2544 uniqueGroupings.erase(hit);
2547 uniqueGroupings.insert(merged);
2550 BOOST_FOREACH(CTxDestination element, *merged)
2551 setmap[element] = merged;
2554 set< set<CTxDestination> > ret;
2555 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2557 ret.insert(*uniqueGrouping);
2558 delete uniqueGrouping;
2564 // ppcoin: check 'spent' consistency between wallet and txindex
2565 // ppcoin: fix wallet spent state according to txindex
2566 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2569 nBalanceInQuestion = 0;
2572 vector<CWalletTx*> vCoins;
2573 vCoins.reserve(mapWallet.size());
2574 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2575 vCoins.push_back(&(*it).second);
2578 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2580 // Find the corresponding transaction index
2582 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2584 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2586 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2588 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2589 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2591 nBalanceInQuestion += pcoin->vout[n].nValue;
2594 pcoin->MarkUnspent(n);
2595 pcoin->WriteToDisk();
2598 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2600 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2601 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2603 nBalanceInQuestion += pcoin->vout[n].nValue;
2606 pcoin->MarkSpent(n);
2607 pcoin->WriteToDisk();
2613 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2615 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2618 EraseFromWallet(pcoin->GetHash());
2624 // ppcoin: disable transaction (only for coinstake)
2625 void CWallet::DisableTransaction(const CTransaction &tx)
2627 if (!tx.IsCoinStake() || !IsFromMe(tx))
2628 return; // only disconnecting coinstake requires marking input unspent
2631 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2633 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2634 if (mi != mapWallet.end())
2636 CWalletTx& prev = (*mi).second;
2637 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2639 prev.MarkUnspent(txin.prevout.n);
2646 CPubKey CReserveKey::GetReservedKey()
2651 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2653 vchPubKey = keypool.vchPubKey;
2656 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2657 vchPubKey = pwallet->vchDefaultKey;
2660 assert(vchPubKey.IsValid());
2664 void CReserveKey::KeepKey()
2667 pwallet->KeepKey(nIndex);
2669 vchPubKey = CPubKey();
2672 void CReserveKey::ReturnKey()
2675 pwallet->ReturnKey(nIndex);
2677 vchPubKey = CPubKey();
2680 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2684 CWalletDB walletdb(strWalletFile);
2686 LOCK2(cs_main, cs_wallet);
2687 BOOST_FOREACH(const int64& id, setKeyPool)
2690 if (!walletdb.ReadPool(id, keypool))
2691 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2692 assert(keypool.vchPubKey.IsValid());
2693 CKeyID keyID = keypool.vchPubKey.GetID();
2694 if (!HaveKey(keyID))
2695 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2696 setAddress.insert(keyID);
2700 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2704 // Only notify UI if this transaction is in this wallet
2705 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2706 if (mi != mapWallet.end())
2707 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2711 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2712 mapKeyBirth.clear();
2714 // get birth times for keys with metadata
2715 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2716 if (it->second.nCreateTime)
2717 mapKeyBirth[it->first] = it->second.nCreateTime;
2719 // map in which we'll infer heights of other keys
2720 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2721 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2722 std::set<CKeyID> setKeys;
2724 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2725 if (mapKeyBirth.count(keyid) == 0)
2726 mapKeyFirstBlock[keyid] = pindexMax;
2730 // if there are no such keys, we're done
2731 if (mapKeyFirstBlock.empty())
2734 // find first block that affects those keys, if there are any left
2735 std::vector<CKeyID> vAffected;
2736 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2737 // iterate over all wallet transactions...
2738 const CWalletTx &wtx = (*it).second;
2739 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2740 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2741 // ... which are already in a block
2742 int nHeight = blit->second->nHeight;
2743 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2744 // iterate over all their outputs
2745 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2746 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2747 // ... and all their affected keys
2748 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2749 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2750 rit->second = blit->second;
2757 // Extract block timestamps for those keys
2758 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2759 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off