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>
21 bool fCoinsDataActual;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 CPubKey CWallet::GenerateNewKey()
39 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
43 key.MakeNewKey(fCompressed);
45 // Compressed public keys were introduced in version 0.6.0
47 SetMinVersion(FEATURE_COMPRPUBKEY);
49 CPubKey pubkey = key.GetPubKey();
51 // Create new metadata
52 int64 nCreationTime = GetTime();
53 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
54 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
55 nTimeFirstKey = nCreationTime;
58 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
59 return key.GetPubKey();
62 bool CWallet::AddKey(const CKey& key)
64 CPubKey pubkey = key.GetPubKey();
66 if (!CCryptoKeyStore::AddKey(key))
71 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
75 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
77 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
83 if (pwalletdbEncryption)
84 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
86 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
91 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
93 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
94 nTimeFirstKey = meta.nCreateTime;
96 mapKeyMetadata[pubkey.GetID()] = meta;
100 bool CWallet::AddCScript(const CScript& redeemScript)
102 if (!CCryptoKeyStore::AddCScript(redeemScript))
106 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
109 bool CWallet::AddWatchOnly(const CScript &dest)
111 if (!CCryptoKeyStore::AddWatchOnly(dest))
113 nTimeFirstKey = 1; // No birthday information for watch-only keys.
116 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
119 bool CWallet::LoadWatchOnly(const CScript &dest)
121 return CCryptoKeyStore::AddWatchOnly(dest);
124 // ppcoin: optional setting to unlock wallet for block minting only;
125 // serves to disable the trivial sendmoney when OS account compromised
126 bool fWalletUnlockMintOnly = false;
128 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
134 CKeyingMaterial vMasterKey;
138 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
140 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
142 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
144 if (CCryptoKeyStore::Unlock(vMasterKey))
151 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
153 bool fWasLocked = IsLocked();
160 CKeyingMaterial vMasterKey;
161 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
163 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
165 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
167 if (CCryptoKeyStore::Unlock(vMasterKey))
169 int64 nStartTime = GetTimeMillis();
170 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
171 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
173 nStartTime = GetTimeMillis();
174 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
175 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
177 if (pMasterKey.second.nDeriveIterations < 25000)
178 pMasterKey.second.nDeriveIterations = 25000;
180 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
182 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
184 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
186 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
197 void CWallet::SetBestChain(const CBlockLocator& loc)
199 CWalletDB walletdb(strWalletFile);
200 walletdb.WriteBestBlock(loc);
203 // This class implements an addrIncoming entry that causes pre-0.4
204 // clients to crash on startup if reading a private-key-encrypted wallet.
205 class CCorruptAddress
210 if (nType & SER_DISK)
215 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
217 if (nWalletVersion >= nVersion)
220 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
221 if (fExplicit && nVersion > nWalletMaxVersion)
222 nVersion = FEATURE_LATEST;
224 nWalletVersion = nVersion;
226 if (nVersion > nWalletMaxVersion)
227 nWalletMaxVersion = nVersion;
231 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
232 if (nWalletVersion >= 40000)
234 // Versions prior to 0.4.0 did not support the "minversion" record.
235 // Use a CCorruptAddress to make them crash instead.
236 CCorruptAddress corruptAddress;
237 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
239 if (nWalletVersion > 40000)
240 pwalletdb->WriteMinVersion(nWalletVersion);
248 bool CWallet::SetMaxVersion(int nVersion)
250 // cannot downgrade below current version
251 if (nWalletVersion > nVersion)
254 nWalletMaxVersion = nVersion;
259 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
264 CKeyingMaterial vMasterKey;
265 RandAddSeedPerfmon();
267 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
268 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
270 CMasterKey kMasterKey(nDerivationMethodIndex);
272 RandAddSeedPerfmon();
273 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
274 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
277 int64 nStartTime = GetTimeMillis();
278 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
279 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
281 nStartTime = GetTimeMillis();
282 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
283 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
285 if (kMasterKey.nDeriveIterations < 25000)
286 kMasterKey.nDeriveIterations = 25000;
288 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
290 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
292 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
297 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
300 pwalletdbEncryption = new CWalletDB(strWalletFile);
301 if (!pwalletdbEncryption->TxnBegin())
303 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
306 if (!EncryptKeys(vMasterKey))
309 pwalletdbEncryption->TxnAbort();
310 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.
313 // Encryption was introduced in version 0.4.0
314 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
318 if (!pwalletdbEncryption->TxnCommit())
319 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.
321 delete pwalletdbEncryption;
322 pwalletdbEncryption = NULL;
326 Unlock(strWalletPassphrase);
330 // Need to completely rewrite the wallet file; if we don't, bdb might keep
331 // bits of the unencrypted private key in slack space in the database file.
332 CDB::Rewrite(strWalletFile);
335 NotifyStatusChanged(this);
340 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
342 int64 nRet = nOrderPosNext++;
344 pwalletdb->WriteOrderPosNext(nOrderPosNext);
346 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
351 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
353 CWalletDB walletdb(strWalletFile);
355 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
358 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
359 // would make this much faster for applications that do this a lot.
360 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
362 CWalletTx* wtx = &((*it).second);
363 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
366 walletdb.ListAccountCreditDebit(strAccount, acentries);
367 BOOST_FOREACH(CAccountingEntry& entry, acentries)
369 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
375 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
377 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
378 // Update the wallet spent flag if it doesn't know due to wallet.dat being
379 // restored from backup or the user making copies of wallet.dat.
382 BOOST_FOREACH(const CTxIn& txin, tx.vin)
384 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
385 if (mi != mapWallet.end())
387 CWalletTx& wtx = (*mi).second;
388 if (txin.prevout.n >= wtx.vout.size())
389 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
390 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
392 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
393 wtx.MarkSpent(txin.prevout.n);
395 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
396 vMintingWalletUpdated.push_back(txin.prevout.hash);
403 uint256 hash = tx.GetHash();
404 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
405 CWalletTx& wtx = (*mi).second;
407 BOOST_FOREACH(const CTxOut& txout, tx.vout)
411 wtx.MarkUnspent(&txout - &tx.vout[0]);
413 NotifyTransactionChanged(this, hash, CT_UPDATED);
414 vMintingWalletUpdated.push_back(hash);
422 void CWallet::MarkDirty()
426 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
427 item.second.MarkDirty();
431 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
433 uint256 hash = wtxIn.GetHash();
436 // Inserts only if not already there, returns tx inserted or tx found
437 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
438 CWalletTx& wtx = (*ret.first).second;
439 wtx.BindWallet(this);
440 bool fInsertedNew = ret.second;
443 wtx.nTimeReceived = GetAdjustedTime();
444 wtx.nOrderPos = IncOrderPosNext();
446 wtx.nTimeSmart = wtx.nTimeReceived;
447 if (wtxIn.hashBlock != 0)
449 if (mapBlockIndex.count(wtxIn.hashBlock))
451 unsigned int latestNow = wtx.nTimeReceived;
452 unsigned int latestEntry = 0;
454 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
455 int64 latestTolerated = latestNow + 300;
456 std::list<CAccountingEntry> acentries;
457 TxItems txOrdered = OrderedTxItems(acentries);
458 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
460 CWalletTx *const pwtx = (*it).second.first;
463 CAccountingEntry *const pacentry = (*it).second.second;
467 nSmartTime = pwtx->nTimeSmart;
469 nSmartTime = pwtx->nTimeReceived;
472 nSmartTime = pacentry->nTime;
473 if (nSmartTime <= latestTolerated)
475 latestEntry = nSmartTime;
476 if (nSmartTime > latestNow)
477 latestNow = nSmartTime;
483 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
484 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
487 printf("AddToWallet() : found %s in block %s not in index\n",
488 wtxIn.GetHash().ToString().substr(0,10).c_str(),
489 wtxIn.hashBlock.ToString().c_str());
493 bool fUpdated = false;
497 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
499 wtx.hashBlock = wtxIn.hashBlock;
502 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
504 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
505 wtx.nIndex = wtxIn.nIndex;
508 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
510 wtx.fFromMe = wtxIn.fFromMe;
513 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
517 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
520 if (fInsertedNew || fUpdated)
521 if (!wtx.WriteToDisk())
524 // If default receiving address gets used, replace it with a new one
525 CScript scriptDefaultKey;
526 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
527 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
529 if (txout.scriptPubKey == scriptDefaultKey)
531 CPubKey newDefaultKey;
532 if (GetKeyFromPool(newDefaultKey, false))
534 SetDefaultKey(newDefaultKey);
535 SetAddressBookName(vchDefaultKey.GetID(), "");
540 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
541 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
543 // Notify UI of new or updated transaction
544 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
545 vMintingWalletUpdated.push_back(hash);
546 // notify an external script when a wallet transaction comes in or is updated
547 std::string strCmd = GetArg("-walletnotify", "");
549 if ( !strCmd.empty())
551 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
552 boost::thread t(runCommand, strCmd); // thread runs free
559 // Add a transaction to the wallet, or update it.
560 // pblock is optional, but should be provided if the transaction is known to be in a block.
561 // If fUpdate is true, existing transactions will be updated.
562 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
564 uint256 hash = tx.GetHash();
567 bool fExisted = mapWallet.count(hash);
568 if (fExisted && !fUpdate) return false;
569 if (fExisted || IsMine(tx) || IsFromMe(tx))
571 CWalletTx wtx(this,tx);
572 // Get merkle branch if transaction was found in a block
574 wtx.SetMerkleBranch(pblock);
575 return AddToWallet(wtx);
578 WalletUpdateSpent(tx);
583 bool CWallet::EraseFromWallet(uint256 hash)
589 if (mapWallet.erase(hash))
590 CWalletDB(strWalletFile).EraseTx(hash);
596 isminetype CWallet::IsMine(const CTxIn &txin) const
600 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
601 if (mi != mapWallet.end())
603 const CWalletTx& prev = (*mi).second;
604 if (txin.prevout.n < prev.vout.size())
605 return IsMine(prev.vout[txin.prevout.n]);
611 int64 CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
615 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
616 if (mi != mapWallet.end())
618 const CWalletTx& prev = (*mi).second;
619 if (txin.prevout.n < prev.vout.size())
620 if (IsMine(prev.vout[txin.prevout.n]) & filter)
621 return prev.vout[txin.prevout.n].nValue;
627 bool CWallet::IsChange(const CTxOut& txout) const
629 // TODO: fix handling of 'change' outputs. The assumption is that any
630 // payment to a script that is ours, but isn't in the address book
631 // is change. That assumption is likely to break when we implement multisignature
632 // wallets that return change back into a multi-signature-protected address;
633 // a better way of identifying which outputs are 'the send' and which are
634 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
635 // which output, if any, was change).
636 if (::IsMine(*this, txout.scriptPubKey))
638 CTxDestination address;
639 if (!ExtractDestination(txout.scriptPubKey, address))
643 if (!mapAddressBook.count(address))
649 int64 CWalletTx::GetTxTime() const
651 int64 n = nTimeSmart;
652 return n ? n : nTimeReceived;
655 int CWalletTx::GetRequestCount() const
657 // Returns -1 if it wasn't being tracked
660 LOCK(pwallet->cs_wallet);
661 if (IsCoinBase() || IsCoinStake())
666 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
667 if (mi != pwallet->mapRequestCount.end())
668 nRequests = (*mi).second;
673 // Did anyone request this transaction?
674 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
675 if (mi != pwallet->mapRequestCount.end())
677 nRequests = (*mi).second;
679 // How about the block it's in?
680 if (nRequests == 0 && hashBlock != 0)
682 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
683 if (mi != pwallet->mapRequestCount.end())
684 nRequests = (*mi).second;
686 nRequests = 1; // If it's in someone else's block it must have got out
694 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
695 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount, const isminefilter& filter) const
697 nGeneratedImmature = nGeneratedMature = nFee = 0;
698 listReceived.clear();
700 strSentAccount = strFromAccount;
702 if (IsCoinBase() || IsCoinStake())
704 if (GetBlocksToMaturity() > 0)
705 nGeneratedImmature = pwallet->GetCredit(*this, filter);
707 nGeneratedMature = GetCredit(filter);
712 int64 nDebit = GetDebit(filter);
713 if (nDebit > 0) // debit>0 means we signed/sent this transaction
715 int64 nValueOut = GetValueOut();
716 nFee = nDebit - nValueOut;
720 BOOST_FOREACH(const CTxOut& txout, vout)
722 isminetype fIsMine = pwallet->IsMine(txout);
723 // Only need to handle txouts if AT LEAST one of these is true:
724 // 1) they debit from us (sent)
725 // 2) the output is to us (received)
728 // Don't report 'change' txouts
729 if (pwallet->IsChange(txout))
732 else if (!(fIsMine & filter))
735 // In either case, we need to get the destination address
736 CTxDestination address;
737 if (!ExtractDestination(txout.scriptPubKey, address))
739 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
740 this->GetHash().ToString().c_str());
741 address = CNoDestination();
744 // If we are debited by the transaction, add the output as a "sent" entry
746 listSent.push_back(make_pair(address, txout.nValue));
748 // If we are receiving the output, add it as a "received" entry
749 if (fIsMine & filter)
750 listReceived.push_back(make_pair(address, txout.nValue));
755 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
756 int64& nSent, int64& nFee, const isminefilter& filter) const
758 nGenerated = nReceived = nSent = nFee = 0;
760 int64 allGeneratedImmature, allGeneratedMature, allFee;
761 allGeneratedImmature = allGeneratedMature = allFee = 0;
762 string strSentAccount;
763 list<pair<CTxDestination, int64> > listReceived;
764 list<pair<CTxDestination, int64> > listSent;
765 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
767 if (strAccount == "")
768 nGenerated = allGeneratedMature;
769 if (strAccount == strSentAccount)
771 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
776 LOCK(pwallet->cs_wallet);
777 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
779 if (pwallet->mapAddressBook.count(r.first))
781 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
782 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
783 nReceived += r.second;
785 else if (strAccount.empty())
787 nReceived += r.second;
793 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
797 const int COPY_DEPTH = 3;
798 if (SetMerkleBranch() < COPY_DEPTH)
800 vector<uint256> vWorkQueue;
801 BOOST_FOREACH(const CTxIn& txin, vin)
802 vWorkQueue.push_back(txin.prevout.hash);
804 // This critsect is OK because txdb is already open
806 LOCK(pwallet->cs_wallet);
807 map<uint256, const CMerkleTx*> mapWalletPrev;
808 set<uint256> setAlreadyDone;
809 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
811 uint256 hash = vWorkQueue[i];
812 if (setAlreadyDone.count(hash))
814 setAlreadyDone.insert(hash);
817 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
818 if (mi != pwallet->mapWallet.end())
821 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
822 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
824 else if (mapWalletPrev.count(hash))
826 tx = *mapWalletPrev[hash];
828 else if (!fClient && txdb.ReadDiskTx(hash, tx))
834 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
838 int nDepth = tx.SetMerkleBranch();
839 vtxPrev.push_back(tx);
841 if (nDepth < COPY_DEPTH)
843 BOOST_FOREACH(const CTxIn& txin, tx.vin)
844 vWorkQueue.push_back(txin.prevout.hash);
850 reverse(vtxPrev.begin(), vtxPrev.end());
853 bool CWalletTx::WriteToDisk()
855 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
858 // Scan the block chain (starting in pindexStart) for transactions
859 // from or to us. If fUpdate is true, found transactions that already
860 // exist in the wallet will be updated.
861 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
865 CBlockIndex* pindex = pindexStart;
871 block.ReadFromDisk(pindex, true);
872 BOOST_FOREACH(CTransaction& tx, block.vtx)
874 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
877 pindex = pindex->pnext;
883 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
886 tx.ReadFromDisk(COutPoint(hashTx, 0));
887 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
892 void CWallet::ReacceptWalletTransactions()
900 vector<CDiskTxPos> vMissingTx;
901 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
903 CWalletTx& wtx = item.second;
904 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
908 bool fUpdated = false;
909 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
911 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
912 if (txindex.vSpent.size() != wtx.vout.size())
914 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
917 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
921 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
925 vMissingTx.push_back(txindex.vSpent[i]);
930 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
937 // Re-accept any txes of ours that aren't already in a block
938 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
939 wtx.AcceptWalletTransaction(txdb, false);
942 if (!vMissingTx.empty())
944 // TODO: optimize this to scan just part of the block chain?
945 if (ScanForWalletTransactions(pindexGenesisBlock))
946 fRepeat = true; // Found missing transactions: re-do re-accept.
951 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
953 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
955 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
957 uint256 hash = tx.GetHash();
958 if (!txdb.ContainsTx(hash))
959 RelayTransaction((CTransaction)tx, hash);
962 if (!(IsCoinBase() || IsCoinStake()))
964 uint256 hash = GetHash();
965 if (!txdb.ContainsTx(hash))
967 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
968 RelayTransaction((CTransaction)*this, hash);
973 void CWalletTx::RelayWalletTransaction()
976 RelayWalletTransaction(txdb);
979 void CWallet::ResendWalletTransactions()
981 // Do this infrequently and randomly to avoid giving away
982 // that these are our transactions.
983 static int64 nNextTime;
984 if (GetTime() < nNextTime)
986 bool fFirst = (nNextTime == 0);
987 nNextTime = GetTime() + GetRand(30 * 60);
991 // Only do it if there's been a new block since last time
992 static int64 nLastTime;
993 if (nTimeBestReceived < nLastTime)
995 nLastTime = GetTime();
997 // Rebroadcast any of our txes that aren't in a block yet
998 printf("ResendWalletTransactions()\n");
1002 // Sort them in chronological order
1003 multimap<unsigned int, CWalletTx*> mapSorted;
1004 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1006 CWalletTx& wtx = item.second;
1007 // Don't rebroadcast until it's had plenty of time that
1008 // it should have gotten in already by now.
1009 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1010 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1012 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1014 CWalletTx& wtx = *item.second;
1015 if (wtx.CheckTransaction())
1016 wtx.RelayWalletTransaction(txdb);
1018 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1028 //////////////////////////////////////////////////////////////////////////////
1034 int64 CWallet::GetBalance() const
1039 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1041 const CWalletTx* pcoin = &(*it).second;
1042 if (pcoin->IsTrusted())
1043 nTotal += pcoin->GetAvailableCredit();
1050 int64 CWallet::GetWatchOnlyBalance() const
1055 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1057 const CWalletTx* pcoin = &(*it).second;
1058 if (pcoin->IsTrusted())
1059 nTotal += pcoin->GetAvailableWatchCredit();
1066 int64 CWallet::GetUnconfirmedBalance() const
1071 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1073 const CWalletTx* pcoin = &(*it).second;
1074 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1075 nTotal += pcoin->GetAvailableCredit();
1081 int64 CWallet::GetUnconfirmedWatchOnlyBalance() const
1086 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1088 const CWalletTx* pcoin = &(*it).second;
1089 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1090 nTotal += pcoin->GetAvailableWatchCredit();
1096 int64 CWallet::GetImmatureBalance() const
1101 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1103 const CWalletTx* pcoin = &(*it).second;
1104 nTotal += pcoin->GetImmatureCredit();
1110 int64 CWallet::GetImmatureWatchOnlyBalance() const
1115 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1117 const CWalletTx* pcoin = &(*it).second;
1118 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1124 // populate vCoins with vector of spendable COutputs
1125 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1131 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1133 const CWalletTx* pcoin = &(*it).second;
1135 if (!pcoin->IsFinal())
1138 if (fOnlyConfirmed && !pcoin->IsTrusted())
1141 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1144 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1147 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1148 isminetype mine = IsMine(pcoin->vout[i]);
1149 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1150 pcoin->vout[i].nValue >= nMinimumInputValue &&
1151 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1153 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1160 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64 nMinValue, int64 nMaxValue) const
1166 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1168 const CWalletTx* pcoin = &(*it).second;
1170 if (!pcoin->IsFinal())
1173 if(pcoin->GetDepthInMainChain() < nConf)
1176 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1177 isminetype mine = IsMine(pcoin->vout[i]);
1179 // ignore coin if it was already spent or we don't own it
1180 if (pcoin->IsSpent(i) || mine == MINE_NO)
1183 // if coin value is between required limits then add new item to vector
1184 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1185 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1191 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1192 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1194 vector<char> vfIncluded;
1196 vfBest.assign(vValue.size(), true);
1197 nBest = nTotalLower;
1199 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1201 vfIncluded.assign(vValue.size(), false);
1203 bool fReachedTarget = false;
1204 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1206 for (unsigned int i = 0; i < vValue.size(); i++)
1208 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1210 nTotal += vValue[i].first;
1211 vfIncluded[i] = true;
1212 if (nTotal >= nTargetValue)
1214 fReachedTarget = true;
1218 vfBest = vfIncluded;
1220 nTotal -= vValue[i].first;
1221 vfIncluded[i] = false;
1229 int64 CWallet::GetStake() const
1233 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1235 const CWalletTx* pcoin = &(*it).second;
1236 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1237 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1242 int64 CWallet::GetWatchOnlyStake() const
1246 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1248 const CWalletTx* pcoin = &(*it).second;
1249 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1250 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1255 int64 CWallet::GetNewMint() const
1259 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1261 const CWalletTx* pcoin = &(*it).second;
1262 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1263 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1268 int64 CWallet::GetWatchOnlyNewMint() const
1272 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1274 const CWalletTx* pcoin = &(*it).second;
1275 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1276 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1281 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
1283 setCoinsRet.clear();
1286 // List of values less than target
1287 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1288 coinLowestLarger.first = std::numeric_limits<int64>::max();
1289 coinLowestLarger.second.first = NULL;
1290 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1291 int64 nTotalLower = 0;
1293 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1295 BOOST_FOREACH(const COutput &output, vCoins)
1297 if (!output.fSpendable)
1300 const CWalletTx *pcoin = output.tx;
1302 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1307 // Follow the timestamp rules
1308 if (pcoin->nTime > nSpendTime)
1311 int64 n = pcoin->vout[i].nValue;
1313 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1315 if (n == nTargetValue)
1317 setCoinsRet.insert(coin.second);
1318 nValueRet += coin.first;
1321 else if (n < nTargetValue + CENT)
1323 vValue.push_back(coin);
1326 else if (n < coinLowestLarger.first)
1328 coinLowestLarger = coin;
1332 if (nTotalLower == nTargetValue)
1334 for (unsigned int i = 0; i < vValue.size(); ++i)
1336 setCoinsRet.insert(vValue[i].second);
1337 nValueRet += vValue[i].first;
1342 if (nTotalLower < nTargetValue)
1344 if (coinLowestLarger.second.first == NULL)
1346 setCoinsRet.insert(coinLowestLarger.second);
1347 nValueRet += coinLowestLarger.first;
1351 // Solve subset sum by stochastic approximation
1352 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1353 vector<char> vfBest;
1356 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1357 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1358 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1360 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1361 // or the next bigger coin is closer), return the bigger coin
1362 if (coinLowestLarger.second.first &&
1363 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1365 setCoinsRet.insert(coinLowestLarger.second);
1366 nValueRet += coinLowestLarger.first;
1369 for (unsigned int i = 0; i < vValue.size(); i++)
1372 setCoinsRet.insert(vValue[i].second);
1373 nValueRet += vValue[i].first;
1376 if (fDebug && GetBoolArg("-printpriority"))
1379 printf("SelectCoins() best subset: ");
1380 for (unsigned int i = 0; i < vValue.size(); i++)
1382 printf("%s ", FormatMoney(vValue[i].first).c_str());
1383 printf("total %s\n", FormatMoney(nBest).c_str());
1390 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1392 vector<COutput> vCoins;
1393 AvailableCoins(vCoins, true, coinControl);
1395 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1396 if (coinControl && coinControl->HasSelected())
1398 BOOST_FOREACH(const COutput& out, vCoins)
1402 nValueRet += out.tx->vout[out.i].nValue;
1403 setCoinsRet.insert(make_pair(out.tx, out.i));
1405 return (nValueRet >= nTargetValue);
1408 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1409 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1410 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1413 // Select some coins without random shuffle or best subset approximation
1414 bool CWallet::SelectCoinsSimple(int64 nTargetValue, int64 nMinValue, int64 nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1416 vector<COutput> vCoins;
1417 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1419 setCoinsRet.clear();
1422 BOOST_FOREACH(COutput output, vCoins)
1424 if(!output.fSpendable)
1426 const CWalletTx *pcoin = output.tx;
1429 // Ignore immature coins
1430 if (pcoin->GetBlocksToMaturity() > 0)
1433 // Stop if we've chosen enough inputs
1434 if (nValueRet >= nTargetValue)
1437 // Follow the timestamp rules
1438 if (pcoin->nTime > nSpendTime)
1441 int64 n = pcoin->vout[i].nValue;
1443 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1445 if (n >= nTargetValue)
1447 // If input value is greater or equal to target then simply insert
1448 // it into the current subset and exit
1449 setCoinsRet.insert(coin.second);
1450 nValueRet += coin.first;
1453 else if (n < nTargetValue + CENT)
1455 setCoinsRet.insert(coin.second);
1456 nValueRet += coin.first;
1463 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1466 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1472 if (vecSend.empty() || nValue < 0)
1475 wtxNew.BindWallet(this);
1478 LOCK2(cs_main, cs_wallet);
1479 // txdb must be opened before the mapWallet lock
1482 nFeeRet = nTransactionFee;
1486 wtxNew.vout.clear();
1487 wtxNew.fFromMe = true;
1489 int64 nTotalValue = nValue + nFeeRet;
1490 double dPriority = 0;
1491 // vouts to the payees
1492 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1493 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1495 // Choose coins to use
1496 set<pair<const CWalletTx*,unsigned int> > setCoins;
1498 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1500 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1502 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1503 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1506 int64 nChange = nValueIn - nValue - nFeeRet;
1507 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1508 // or until nChange becomes zero
1509 // NOTE: this depends on the exact behaviour of GetMinFee
1510 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1512 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1514 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1515 nChange -= nMoveToFee;
1516 nFeeRet += nMoveToFee;
1519 // sub-cent change is moved to fee
1520 if (nChange > 0 && nChange < CENT)
1529 // Fill a vout to ourself
1530 // TODO: pass in scriptChange instead of reservekey so
1531 // change transaction isn't always pay-to-bitcoin-address
1532 CScript scriptChange;
1534 // coin control: send change to custom address
1535 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1536 scriptChange.SetDestination(coinControl->destChange);
1538 // no coin control: send change to newly generated address
1541 // Note: We use a new key here to keep it from being obvious which side is the change.
1542 // The drawback is that by not reusing a previous key, the change may be lost if a
1543 // backup is restored, if the backup doesn't have the new private key for the change.
1544 // If we reused the old key, it would be possible to add code to look for and
1545 // rediscover unknown transactions that were written with keys of ours to recover
1546 // post-backup change.
1548 // Reserve a new key pair from key pool
1549 CPubKey vchPubKey = reservekey.GetReservedKey();
1551 scriptChange.SetDestination(vchPubKey.GetID());
1554 // Insert change txn at random position:
1555 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1556 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1559 reservekey.ReturnKey();
1562 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1563 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1567 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1568 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1572 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1573 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1575 dPriority /= nBytes;
1577 // Check that enough fee is included
1578 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1579 bool fAllowFree = CTransaction::AllowFree(dPriority);
1581 // Disable free transactions until 1 July 2014
1582 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1587 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1589 if (nFeeRet < max(nPayFee, nMinFee))
1591 nFeeRet = max(nPayFee, nMinFee);
1595 // Fill vtxPrev by copying from previous transactions vtxPrev
1596 wtxNew.AddSupportingTransactions(txdb);
1597 wtxNew.fTimeReceivedIsTxTime = true;
1606 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1608 vector< pair<CScript, int64> > vecSend;
1609 vecSend.push_back(make_pair(scriptPubKey, nValue));
1610 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1613 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1615 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1617 // If time weight is lower or equal to zero then weight is zero.
1618 if (nTimeWeight <= 0)
1624 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1625 nWeight = bnCoinDayWeight.getuint64();
1629 // NovaCoin: get current stake miner statistics
1630 void CWallet::GetStakeStats(float &nKernelsRate, float &nCoinDaysRate)
1632 static uint64 nLastKernels = 0, nLastCoinDays = 0;
1633 static float nLastKernelsRate = 0, nLastCoinDaysRate = 0;
1634 static unsigned int nLastTime = GetTime();
1637 if (nKernelsTried < nLastKernels)
1642 nLastTime = GetTime();
1645 unsigned int nInterval = GetTime() - nLastTime;
1646 if (nKernelsTried > 1000 && nInterval > 5)
1648 nKernelsRate = nLastKernelsRate = ( nKernelsTried - nLastKernels ) / (float) nInterval;
1649 nCoinDaysRate = nLastCoinDaysRate = ( nCoinDaysTried - nLastCoinDays ) / (float) nInterval;
1651 nLastKernels = nKernelsTried;
1652 nLastCoinDays = nCoinDaysTried;
1653 nLastTime = GetTime();
1657 nKernelsRate = nLastKernelsRate;
1658 nCoinDaysRate = nLastCoinDaysRate;
1662 bool CWallet::MergeCoins(const int64& nAmount, const int64& nMinValue, const int64& nOutputValue, list<uint256>& listMerged)
1664 int64 nBalance = GetBalance();
1666 if (nAmount > nBalance)
1671 set<pair<const CWalletTx*,unsigned int> > setCoins;
1673 // Simple coins selection - no randomization
1674 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1677 if (setCoins.empty())
1681 vector<const CWalletTx*> vwtxPrev;
1683 // Reserve a new key pair from key pool
1684 CReserveKey reservekey(this);
1685 CPubKey vchPubKey = reservekey.GetReservedKey();
1688 CScript scriptOutput;
1689 scriptOutput.SetDestination(vchPubKey.GetID());
1692 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1695 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1697 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1699 // Add current coin to inputs list and add its credit to transaction output
1700 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1701 wtxNew.vout[0].nValue += nCredit;
1702 vwtxPrev.push_back(pcoin.first);
1705 // Replaced with estimation for performance purposes
1707 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1708 const CWalletTx *txin = vwtxPrev[i];
1710 // Sign scripts to get actual transaction size for fee calculation
1711 if (!SignSignature(*this, *txin, wtxNew, i))
1716 // Assuming that average scriptsig size is 110 bytes
1717 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1718 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1720 double dFinalPriority = dWeight /= nBytes;
1721 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1723 // Get actual transaction fee according to its estimated size and priority
1724 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1726 // Prepare transaction for commit if sum is enough ot its size is too big
1727 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1729 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1731 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1732 const CWalletTx *txin = vwtxPrev[i];
1735 if (!SignSignature(*this, *txin, wtxNew, i))
1739 // Try to commit, return false on failure
1740 if (!CommitTransaction(wtxNew, reservekey))
1743 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1745 dWeight = 0; // Reset all temporary values
1748 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1752 // Create transactions if there are some unhandled coins left
1753 if (wtxNew.vout[0].nValue > 0) {
1754 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1756 double dFinalPriority = dWeight /= nBytes;
1757 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1759 // Get actual transaction fee according to its size and priority
1760 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1762 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1764 if (wtxNew.vout[0].nValue <= 0)
1767 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1768 const CWalletTx *txin = vwtxPrev[i];
1770 // Sign all scripts again
1771 if (!SignSignature(*this, *txin, wtxNew, i))
1775 // Try to commit, return false on failure
1776 if (!CommitTransaction(wtxNew, reservekey))
1779 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1786 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1788 // The following combine threshold is important to security
1789 // Should not be adjusted if you don't understand the consequences
1790 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1792 CBigNum bnTargetPerCoinDay;
1793 bnTargetPerCoinDay.SetCompact(nBits);
1798 // Mark coin stake transaction
1799 CScript scriptEmpty;
1800 scriptEmpty.clear();
1801 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1803 // Choose coins to use
1804 int64 nBalance = GetBalance();
1805 int64 nReserveBalance = 0;
1807 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1808 return error("CreateCoinStake : invalid reserve balance amount");
1810 if (nBalance <= nReserveBalance)
1813 vector<const CWalletTx*> vwtxPrev;
1817 LOCK2(cs_main, cs_wallet);
1818 // Cache outputs unless best block or wallet transaction set changed
1819 if (!fCoinsDataActual)
1824 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1827 if (setCoins.empty())
1833 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1835 // Load transaction index item
1836 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1839 // Read block header
1840 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1843 uint64 nStakeModifier = 0;
1844 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1848 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1849 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1852 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1857 printf("Stake miner: %"PRIszu" meta items loaded for %"PRIszu" coins\n", mapMeta.size(), setCoins.size());
1859 fCoinsDataActual = true;
1866 CScript scriptPubKeyKernel;
1868 KernelSearchSettings settings;
1869 settings.nBits = nBits;
1870 settings.nTime = txNew.nTime;
1871 settings.nOffset = 0;
1872 settings.nLimit = mapMeta.size();
1873 settings.nSearchInterval = nSearchInterval;
1875 unsigned int nTimeTx, nBlockTime;
1876 COutPoint prevoutStake;
1877 CoinsSet::value_type kernelcoin;
1879 if (ScanForStakeKernelHash(mapMeta, settings, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1882 if (fDebug && GetBoolArg("-printcoinstake"))
1883 printf("CreateCoinStake : kernel found\n");
1884 vector<valtype> vSolutions;
1885 txnouttype whichType;
1886 CScript scriptPubKeyOut;
1887 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1888 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1890 if (fDebug && GetBoolArg("-printcoinstake"))
1891 printf("CreateCoinStake : failed to parse kernel\n");
1894 if (fDebug && GetBoolArg("-printcoinstake"))
1895 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1896 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1898 if (fDebug && GetBoolArg("-printcoinstake"))
1899 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1900 return false; // only support pay to public key and pay to address
1902 if (whichType == TX_PUBKEYHASH) // pay to address type
1904 // convert to pay to public key type
1905 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1907 if (fDebug && GetBoolArg("-printcoinstake"))
1908 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1909 return false; // unable to find corresponding public key
1911 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1913 if (whichType == TX_PUBKEY)
1915 valtype& vchPubKey = vSolutions[0];
1916 if (!keystore.GetKey(Hash160(vchPubKey), key))
1918 if (fDebug && GetBoolArg("-printcoinstake"))
1919 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1920 return false; // unable to find corresponding public key
1922 if (key.GetPubKey() != vchPubKey)
1924 if (fDebug && GetBoolArg("-printcoinstake"))
1925 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1926 return false; // keys mismatch
1929 scriptPubKeyOut = scriptPubKeyKernel;
1932 txNew.nTime = nTimeTx;
1933 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1934 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1935 vwtxPrev.push_back(kernelcoin.first);
1936 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1938 if (GetWeight((int64)nBlockTime, (int64)txNew.nTime) < nStakeMaxAge)
1939 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1940 if (fDebug && GetBoolArg("-printcoinstake"))
1941 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1944 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1947 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1948 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1951 CoinsSet::value_type pcoin = meta_item->second.first.second;
1953 // Attempt to add more inputs
1954 // Only add coins of the same key/address as kernel
1955 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1956 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1958 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1960 // Stop adding more inputs if already too many inputs
1961 if (txNew.vin.size() >= 100)
1963 // Stop adding more inputs if value is already pretty significant
1964 if (nCredit > nCombineThreshold)
1966 // Stop adding inputs if reached reserve limit
1967 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1969 // Do not add additional significant input
1970 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1972 // Do not add input that is still too young
1973 if (nTimeWeight < nStakeMaxAge)
1976 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1977 nCredit += pcoin.first->vout[pcoin.second].nValue;
1978 vwtxPrev.push_back(pcoin.first);
1982 // Calculate coin age reward
1986 if (!txNew.GetCoinAge(txdb, nCoinAge))
1987 return error("CreateCoinStake : failed to calculate coin age");
1989 int64 nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1990 // Refuse to create mint that has zero or negative reward
2000 // Set output amount
2001 if (txNew.vout.size() == 3)
2003 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2004 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2007 txNew.vout[1].nValue = nCredit - nMinFee;
2011 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2013 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2014 return error("CreateCoinStake : failed to sign coinstake");
2018 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2019 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2020 return error("CreateCoinStake : exceeded coinstake size limit");
2022 // Check enough fee is paid
2023 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2025 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2026 continue; // try signing again
2030 if (fDebug && GetBoolArg("-printfee"))
2031 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2036 // Successfully generated coinstake
2041 // Call after CreateTransaction unless you want to abort
2042 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2045 LOCK2(cs_main, cs_wallet);
2046 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2048 // This is only to keep the database open to defeat the auto-flush for the
2049 // duration of this scope. This is the only place where this optimization
2050 // maybe makes sense; please don't do it anywhere else.
2051 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2053 // Take key pair from key pool so it won't be used again
2054 reservekey.KeepKey();
2056 // Add tx to wallet, because if it has change it's also ours,
2057 // otherwise just for transaction history.
2058 AddToWallet(wtxNew);
2060 // Mark old coins as spent
2061 set<CWalletTx*> setCoins;
2062 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2064 CWalletTx &coin = mapWallet[txin.prevout.hash];
2065 coin.BindWallet(this);
2066 coin.MarkSpent(txin.prevout.n);
2068 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2069 vMintingWalletUpdated.push_back(coin.GetHash());
2076 // Track how many getdata requests our transaction gets
2077 mapRequestCount[wtxNew.GetHash()] = 0;
2080 if (!wtxNew.AcceptToMemoryPool())
2082 // This must not fail. The transaction has already been signed and recorded.
2083 printf("CommitTransaction() : Error: Transaction not valid");
2086 wtxNew.RelayWalletTransaction();
2094 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2096 CReserveKey reservekey(this);
2101 string strError = _("Error: Wallet locked, unable to create transaction ");
2102 printf("SendMoney() : %s", strError.c_str());
2105 if (fWalletUnlockMintOnly)
2107 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2108 printf("SendMoney() : %s", strError.c_str());
2111 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2114 if (nValue + nFeeRequired > GetBalance())
2115 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());
2117 strError = _("Error: Transaction creation failed ");
2118 printf("SendMoney() : %s", strError.c_str());
2122 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2125 if (!CommitTransaction(wtxNew, reservekey))
2126 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.");
2133 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2137 return _("Invalid amount");
2138 if (nValue + nTransactionFee > GetBalance())
2139 return _("Insufficient funds");
2141 // Parse Bitcoin address
2142 CScript scriptPubKey;
2143 scriptPubKey.SetDestination(address);
2145 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2151 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2155 fFirstRunRet = false;
2156 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2157 if (nLoadWalletRet == DB_NEED_REWRITE)
2159 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2162 // Note: can't top-up keypool here, because wallet is locked.
2163 // User will be prompted to unlock wallet the next operation
2164 // the requires a new key.
2168 if (nLoadWalletRet != DB_LOAD_OK)
2169 return nLoadWalletRet;
2170 fFirstRunRet = !vchDefaultKey.IsValid();
2172 NewThread(ThreadFlushWalletDB, &strWalletFile);
2177 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2179 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2180 mapAddressBook[address] = strName;
2181 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2184 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2187 bool CWallet::DelAddressBookName(const CTxDestination& address)
2189 mapAddressBook.erase(address);
2190 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2193 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2197 void CWallet::PrintWallet(const CBlock& block)
2201 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2203 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2204 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2206 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2208 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2209 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2216 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2220 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2221 if (mi != mapWallet.end())
2230 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2234 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2237 vchDefaultKey = vchPubKey;
2241 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2243 if (!pwallet->fFileBacked)
2245 strWalletFileOut = pwallet->strWalletFile;
2250 // Mark old keypool keys as used,
2251 // and generate all new keys
2253 bool CWallet::NewKeyPool()
2257 CWalletDB walletdb(strWalletFile);
2258 BOOST_FOREACH(int64 nIndex, setKeyPool)
2259 walletdb.ErasePool(nIndex);
2265 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2266 for (int i = 0; i < nKeys; i++)
2269 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2270 setKeyPool.insert(nIndex);
2272 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2277 bool CWallet::TopUpKeyPool(unsigned int nSize)
2285 CWalletDB walletdb(strWalletFile);
2288 unsigned int nTargetSize;
2290 nTargetSize = nSize;
2292 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2294 while (setKeyPool.size() < (nTargetSize + 1))
2297 if (!setKeyPool.empty())
2298 nEnd = *(--setKeyPool.end()) + 1;
2299 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2300 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2301 setKeyPool.insert(nEnd);
2302 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2308 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2311 keypool.vchPubKey = CPubKey();
2318 // Get the oldest key
2319 if(setKeyPool.empty())
2322 CWalletDB walletdb(strWalletFile);
2324 nIndex = *(setKeyPool.begin());
2325 setKeyPool.erase(setKeyPool.begin());
2326 if (!walletdb.ReadPool(nIndex, keypool))
2327 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2328 if (!HaveKey(keypool.vchPubKey.GetID()))
2329 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2330 assert(keypool.vchPubKey.IsValid());
2331 if (fDebug && GetBoolArg("-printkeypool"))
2332 printf("keypool reserve %"PRI64d"\n", nIndex);
2336 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2339 LOCK2(cs_main, cs_wallet);
2340 CWalletDB walletdb(strWalletFile);
2342 int64 nIndex = 1 + *(--setKeyPool.end());
2343 if (!walletdb.WritePool(nIndex, keypool))
2344 throw runtime_error("AddReserveKey() : writing added key failed");
2345 setKeyPool.insert(nIndex);
2351 void CWallet::KeepKey(int64 nIndex)
2353 // Remove from key pool
2356 CWalletDB walletdb(strWalletFile);
2357 walletdb.ErasePool(nIndex);
2360 printf("keypool keep %"PRI64d"\n", nIndex);
2363 void CWallet::ReturnKey(int64 nIndex)
2365 // Return to key pool
2368 setKeyPool.insert(nIndex);
2371 printf("keypool return %"PRI64d"\n", nIndex);
2374 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2380 ReserveKeyFromKeyPool(nIndex, keypool);
2383 if (fAllowReuse && vchDefaultKey.IsValid())
2385 result = vchDefaultKey;
2388 if (IsLocked()) return false;
2389 result = GenerateNewKey();
2393 result = keypool.vchPubKey;
2398 int64 CWallet::GetOldestKeyPoolTime()
2402 ReserveKeyFromKeyPool(nIndex, keypool);
2406 return keypool.nTime;
2409 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2411 map<CTxDestination, int64> balances;
2415 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2417 CWalletTx *pcoin = &walletEntry.second;
2419 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2422 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2425 int nDepth = pcoin->GetDepthInMainChain();
2426 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2429 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2431 CTxDestination addr;
2432 if (!IsMine(pcoin->vout[i]))
2434 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2437 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2439 if (!balances.count(addr))
2441 balances[addr] += n;
2449 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2451 set< set<CTxDestination> > groupings;
2452 set<CTxDestination> grouping;
2454 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2456 CWalletTx *pcoin = &walletEntry.second;
2458 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2460 // group all input addresses with each other
2461 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2463 CTxDestination address;
2464 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2466 grouping.insert(address);
2469 // group change with input addresses
2470 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2471 if (IsChange(txout))
2473 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2474 CTxDestination txoutAddr;
2475 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2477 grouping.insert(txoutAddr);
2479 groupings.insert(grouping);
2483 // group lone addrs by themselves
2484 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2485 if (IsMine(pcoin->vout[i]))
2487 CTxDestination address;
2488 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2490 grouping.insert(address);
2491 groupings.insert(grouping);
2496 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2497 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2498 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2500 // make a set of all the groups hit by this new group
2501 set< set<CTxDestination>* > hits;
2502 map< CTxDestination, set<CTxDestination>* >::iterator it;
2503 BOOST_FOREACH(CTxDestination address, grouping)
2504 if ((it = setmap.find(address)) != setmap.end())
2505 hits.insert((*it).second);
2507 // merge all hit groups into a new single group and delete old groups
2508 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2509 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2511 merged->insert(hit->begin(), hit->end());
2512 uniqueGroupings.erase(hit);
2515 uniqueGroupings.insert(merged);
2518 BOOST_FOREACH(CTxDestination element, *merged)
2519 setmap[element] = merged;
2522 set< set<CTxDestination> > ret;
2523 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2525 ret.insert(*uniqueGrouping);
2526 delete uniqueGrouping;
2532 // ppcoin: check 'spent' consistency between wallet and txindex
2533 // ppcoin: fix wallet spent state according to txindex
2534 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2537 nBalanceInQuestion = 0;
2540 vector<CWalletTx*> vCoins;
2541 vCoins.reserve(mapWallet.size());
2542 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2543 vCoins.push_back(&(*it).second);
2546 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2548 // Find the corresponding transaction index
2550 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2552 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2554 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2556 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2557 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2559 nBalanceInQuestion += pcoin->vout[n].nValue;
2562 pcoin->MarkUnspent(n);
2563 pcoin->WriteToDisk();
2566 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2568 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2569 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2571 nBalanceInQuestion += pcoin->vout[n].nValue;
2574 pcoin->MarkSpent(n);
2575 pcoin->WriteToDisk();
2581 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2583 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2586 EraseFromWallet(pcoin->GetHash());
2592 // ppcoin: disable transaction (only for coinstake)
2593 void CWallet::DisableTransaction(const CTransaction &tx)
2595 if (!tx.IsCoinStake() || !IsFromMe(tx))
2596 return; // only disconnecting coinstake requires marking input unspent
2599 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2601 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2602 if (mi != mapWallet.end())
2604 CWalletTx& prev = (*mi).second;
2605 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2607 prev.MarkUnspent(txin.prevout.n);
2614 CPubKey CReserveKey::GetReservedKey()
2619 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2621 vchPubKey = keypool.vchPubKey;
2624 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2625 vchPubKey = pwallet->vchDefaultKey;
2628 assert(vchPubKey.IsValid());
2632 void CReserveKey::KeepKey()
2635 pwallet->KeepKey(nIndex);
2637 vchPubKey = CPubKey();
2640 void CReserveKey::ReturnKey()
2643 pwallet->ReturnKey(nIndex);
2645 vchPubKey = CPubKey();
2648 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2652 CWalletDB walletdb(strWalletFile);
2654 LOCK2(cs_main, cs_wallet);
2655 BOOST_FOREACH(const int64& id, setKeyPool)
2658 if (!walletdb.ReadPool(id, keypool))
2659 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2660 assert(keypool.vchPubKey.IsValid());
2661 CKeyID keyID = keypool.vchPubKey.GetID();
2662 if (!HaveKey(keyID))
2663 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2664 setAddress.insert(keyID);
2668 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2672 // Only notify UI if this transaction is in this wallet
2673 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2674 if (mi != mapWallet.end())
2676 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2677 vMintingWalletUpdated.push_back(hashTx);
2682 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2683 mapKeyBirth.clear();
2685 // get birth times for keys with metadata
2686 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2687 if (it->second.nCreateTime)
2688 mapKeyBirth[it->first] = it->second.nCreateTime;
2690 // map in which we'll infer heights of other keys
2691 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2692 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2693 std::set<CKeyID> setKeys;
2695 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2696 if (mapKeyBirth.count(keyid) == 0)
2697 mapKeyFirstBlock[keyid] = pindexMax;
2701 // if there are no such keys, we're done
2702 if (mapKeyFirstBlock.empty())
2705 // find first block that affects those keys, if there are any left
2706 std::vector<CKeyID> vAffected;
2707 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2708 // iterate over all wallet transactions...
2709 const CWalletTx &wtx = (*it).second;
2710 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2711 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2712 // ... which are already in a block
2713 int nHeight = blit->second->nHeight;
2714 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2715 // iterate over all their outputs
2716 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2717 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2718 // ... and all their affected keys
2719 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2720 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2721 rit->second = blit->second;
2728 // Extract block timestamps for those keys
2729 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2730 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2733 void CWallet::ClearOrphans()
2735 list<uint256> orphans;
2738 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2740 const CWalletTx *wtx = &(*it).second;
2741 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2743 orphans.push_back(wtx->GetHash());
2747 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2748 EraseFromWallet(*it);