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_t, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64_t, 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_t 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))
80 // check if we need to remove from watch-only
82 script.SetDestination(vchPubKey.GetID());
83 if (HaveWatchOnly(script))
84 RemoveWatchOnly(script);
90 if (pwalletdbEncryption)
91 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
93 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
98 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
100 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
101 nTimeFirstKey = meta.nCreateTime;
103 mapKeyMetadata[pubkey.GetID()] = meta;
107 bool CWallet::AddCScript(const CScript& redeemScript)
109 if (!CCryptoKeyStore::AddCScript(redeemScript))
113 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
116 bool CWallet::AddWatchOnly(const CScript &dest)
118 if (!CCryptoKeyStore::AddWatchOnly(dest))
120 nTimeFirstKey = 1; // No birthday information for watch-only keys.
121 NotifyWatchonlyChanged(true);
124 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
127 bool CWallet::RemoveWatchOnly(const CScript &dest)
130 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
132 if (!HaveWatchOnly())
133 NotifyWatchonlyChanged(false);
135 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
141 bool CWallet::LoadWatchOnly(const CScript &dest)
143 return CCryptoKeyStore::AddWatchOnly(dest);
146 // ppcoin: optional setting to unlock wallet for block minting only;
147 // serves to disable the trivial sendmoney when OS account compromised
148 bool fWalletUnlockMintOnly = false;
150 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
156 CKeyingMaterial vMasterKey;
160 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
162 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
164 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
166 if (CCryptoKeyStore::Unlock(vMasterKey))
173 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
175 bool fWasLocked = IsLocked();
182 CKeyingMaterial vMasterKey;
183 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
185 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
187 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
189 if (CCryptoKeyStore::Unlock(vMasterKey))
191 int64_t nStartTime = GetTimeMillis();
192 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
193 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
195 nStartTime = GetTimeMillis();
196 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
197 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
199 if (pMasterKey.second.nDeriveIterations < 25000)
200 pMasterKey.second.nDeriveIterations = 25000;
202 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
204 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
206 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
208 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
219 void CWallet::SetBestChain(const CBlockLocator& loc)
221 CWalletDB walletdb(strWalletFile);
222 walletdb.WriteBestBlock(loc);
225 // This class implements an addrIncoming entry that causes pre-0.4
226 // clients to crash on startup if reading a private-key-encrypted wallet.
227 class CCorruptAddress
232 if (nType & SER_DISK)
237 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
239 if (nWalletVersion >= nVersion)
242 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
243 if (fExplicit && nVersion > nWalletMaxVersion)
244 nVersion = FEATURE_LATEST;
246 nWalletVersion = nVersion;
248 if (nVersion > nWalletMaxVersion)
249 nWalletMaxVersion = nVersion;
253 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
254 if (nWalletVersion >= 40000)
256 // Versions prior to 0.4.0 did not support the "minversion" record.
257 // Use a CCorruptAddress to make them crash instead.
258 CCorruptAddress corruptAddress;
259 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
261 if (nWalletVersion > 40000)
262 pwalletdb->WriteMinVersion(nWalletVersion);
270 bool CWallet::SetMaxVersion(int nVersion)
272 // cannot downgrade below current version
273 if (nWalletVersion > nVersion)
276 nWalletMaxVersion = nVersion;
281 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
286 CKeyingMaterial vMasterKey;
287 RandAddSeedPerfmon();
289 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
290 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
292 CMasterKey kMasterKey(nDerivationMethodIndex);
294 RandAddSeedPerfmon();
295 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
296 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
299 int64_t nStartTime = GetTimeMillis();
300 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
301 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
303 nStartTime = GetTimeMillis();
304 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
305 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
307 if (kMasterKey.nDeriveIterations < 25000)
308 kMasterKey.nDeriveIterations = 25000;
310 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
312 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
314 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
319 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
322 pwalletdbEncryption = new CWalletDB(strWalletFile);
323 if (!pwalletdbEncryption->TxnBegin())
325 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
328 if (!EncryptKeys(vMasterKey))
331 pwalletdbEncryption->TxnAbort();
332 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.
335 // Encryption was introduced in version 0.4.0
336 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
340 if (!pwalletdbEncryption->TxnCommit())
341 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.
343 delete pwalletdbEncryption;
344 pwalletdbEncryption = NULL;
348 Unlock(strWalletPassphrase);
352 // Need to completely rewrite the wallet file; if we don't, bdb might keep
353 // bits of the unencrypted private key in slack space in the database file.
354 CDB::Rewrite(strWalletFile);
357 NotifyStatusChanged(this);
362 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
364 int64_t nRet = nOrderPosNext++;
366 pwalletdb->WriteOrderPosNext(nOrderPosNext);
368 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
373 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
375 CWalletDB walletdb(strWalletFile);
377 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
380 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
381 // would make this much faster for applications that do this a lot.
382 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
384 CWalletTx* wtx = &((*it).second);
385 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
388 walletdb.ListAccountCreditDebit(strAccount, acentries);
389 BOOST_FOREACH(CAccountingEntry& entry, acentries)
391 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
397 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
399 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
400 // Update the wallet spent flag if it doesn't know due to wallet.dat being
401 // restored from backup or the user making copies of wallet.dat.
404 BOOST_FOREACH(const CTxIn& txin, tx.vin)
406 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
407 if (mi != mapWallet.end())
409 CWalletTx& wtx = (*mi).second;
410 if (txin.prevout.n >= wtx.vout.size())
411 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
412 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
414 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
415 wtx.MarkSpent(txin.prevout.n);
417 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
418 vMintingWalletUpdated.push_back(txin.prevout.hash);
425 uint256 hash = tx.GetHash();
426 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
427 CWalletTx& wtx = (*mi).second;
429 BOOST_FOREACH(const CTxOut& txout, tx.vout)
433 wtx.MarkUnspent(&txout - &tx.vout[0]);
435 NotifyTransactionChanged(this, hash, CT_UPDATED);
436 vMintingWalletUpdated.push_back(hash);
444 void CWallet::MarkDirty()
448 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
449 item.second.MarkDirty();
453 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
455 uint256 hash = wtxIn.GetHash();
458 // Inserts only if not already there, returns tx inserted or tx found
459 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
460 CWalletTx& wtx = (*ret.first).second;
461 wtx.BindWallet(this);
462 bool fInsertedNew = ret.second;
465 wtx.nTimeReceived = GetAdjustedTime();
466 wtx.nOrderPos = IncOrderPosNext();
468 wtx.nTimeSmart = wtx.nTimeReceived;
469 if (wtxIn.hashBlock != 0)
471 if (mapBlockIndex.count(wtxIn.hashBlock))
473 unsigned int latestNow = wtx.nTimeReceived;
474 unsigned int latestEntry = 0;
476 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
477 int64_t latestTolerated = latestNow + 300;
478 std::list<CAccountingEntry> acentries;
479 TxItems txOrdered = OrderedTxItems(acentries);
480 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
482 CWalletTx *const pwtx = (*it).second.first;
485 CAccountingEntry *const pacentry = (*it).second.second;
489 nSmartTime = pwtx->nTimeSmart;
491 nSmartTime = pwtx->nTimeReceived;
494 nSmartTime = pacentry->nTime;
495 if (nSmartTime <= latestTolerated)
497 latestEntry = nSmartTime;
498 if (nSmartTime > latestNow)
499 latestNow = nSmartTime;
505 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
506 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
509 printf("AddToWallet() : found %s in block %s not in index\n",
510 wtxIn.GetHash().ToString().substr(0,10).c_str(),
511 wtxIn.hashBlock.ToString().c_str());
515 bool fUpdated = false;
519 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
521 wtx.hashBlock = wtxIn.hashBlock;
524 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
526 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
527 wtx.nIndex = wtxIn.nIndex;
530 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
532 wtx.fFromMe = wtxIn.fFromMe;
535 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
539 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
542 if (fInsertedNew || fUpdated)
543 if (!wtx.WriteToDisk())
546 // If default receiving address gets used, replace it with a new one
547 CScript scriptDefaultKey;
548 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
549 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
551 if (txout.scriptPubKey == scriptDefaultKey)
553 CPubKey newDefaultKey;
554 if (GetKeyFromPool(newDefaultKey, false))
556 SetDefaultKey(newDefaultKey);
557 SetAddressBookName(vchDefaultKey.GetID(), "");
562 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
563 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
565 // Notify UI of new or updated transaction
566 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
567 vMintingWalletUpdated.push_back(hash);
568 // notify an external script when a wallet transaction comes in or is updated
569 std::string strCmd = GetArg("-walletnotify", "");
571 if ( !strCmd.empty())
573 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
574 boost::thread t(runCommand, strCmd); // thread runs free
581 // Add a transaction to the wallet, or update it.
582 // pblock is optional, but should be provided if the transaction is known to be in a block.
583 // If fUpdate is true, existing transactions will be updated.
584 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
586 uint256 hash = tx.GetHash();
589 bool fExisted = mapWallet.count(hash);
590 if (fExisted && !fUpdate) return false;
591 if (fExisted || IsMine(tx) || IsFromMe(tx))
593 CWalletTx wtx(this,tx);
594 // Get merkle branch if transaction was found in a block
596 wtx.SetMerkleBranch(pblock);
597 return AddToWallet(wtx);
600 WalletUpdateSpent(tx);
605 bool CWallet::EraseFromWallet(uint256 hash)
611 if (mapWallet.erase(hash))
612 CWalletDB(strWalletFile).EraseTx(hash);
618 isminetype CWallet::IsMine(const CTxIn &txin) const
622 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
623 if (mi != mapWallet.end())
625 const CWalletTx& prev = (*mi).second;
626 if (txin.prevout.n < prev.vout.size())
627 return IsMine(prev.vout[txin.prevout.n]);
633 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
637 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
638 if (mi != mapWallet.end())
640 const CWalletTx& prev = (*mi).second;
641 if (txin.prevout.n < prev.vout.size())
642 if (IsMine(prev.vout[txin.prevout.n]) & filter)
643 return prev.vout[txin.prevout.n].nValue;
649 bool CWallet::IsChange(const CTxOut& txout) const
651 // TODO: fix handling of 'change' outputs. The assumption is that any
652 // payment to a script that is ours, but isn't in the address book
653 // is change. That assumption is likely to break when we implement multisignature
654 // wallets that return change back into a multi-signature-protected address;
655 // a better way of identifying which outputs are 'the send' and which are
656 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
657 // which output, if any, was change).
658 if (::IsMine(*this, txout.scriptPubKey))
660 CTxDestination address;
661 if (!ExtractDestination(txout.scriptPubKey, address))
665 if (!mapAddressBook.count(address))
671 int64_t CWalletTx::GetTxTime() const
676 int CWalletTx::GetRequestCount() const
678 // Returns -1 if it wasn't being tracked
681 LOCK(pwallet->cs_wallet);
682 if (IsCoinBase() || IsCoinStake())
687 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
688 if (mi != pwallet->mapRequestCount.end())
689 nRequests = (*mi).second;
694 // Did anyone request this transaction?
695 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
696 if (mi != pwallet->mapRequestCount.end())
698 nRequests = (*mi).second;
700 // How about the block it's in?
701 if (nRequests == 0 && hashBlock != 0)
703 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
704 if (mi != pwallet->mapRequestCount.end())
705 nRequests = (*mi).second;
707 nRequests = 1; // If it's in someone else's block it must have got out
715 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
716 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
718 nGeneratedImmature = nGeneratedMature = nFee = 0;
719 listReceived.clear();
721 strSentAccount = strFromAccount;
723 if (IsCoinBase() || IsCoinStake())
725 if (GetBlocksToMaturity() > 0)
726 nGeneratedImmature = pwallet->GetCredit(*this, filter);
728 nGeneratedMature = GetCredit(filter);
733 int64_t nDebit = GetDebit(filter);
734 if (nDebit > 0) // debit>0 means we signed/sent this transaction
736 int64_t nValueOut = GetValueOut();
737 nFee = nDebit - nValueOut;
741 BOOST_FOREACH(const CTxOut& txout, vout)
743 isminetype fIsMine = pwallet->IsMine(txout);
744 // Only need to handle txouts if AT LEAST one of these is true:
745 // 1) they debit from us (sent)
746 // 2) the output is to us (received)
749 // Don't report 'change' txouts
750 if (pwallet->IsChange(txout))
753 else if (!(fIsMine & filter))
756 // In either case, we need to get the destination address
757 CTxDestination address;
758 if (!ExtractDestination(txout.scriptPubKey, address))
760 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
761 this->GetHash().ToString().c_str());
762 address = CNoDestination();
765 // If we are debited by the transaction, add the output as a "sent" entry
767 listSent.push_back(make_pair(address, txout.nValue));
769 // If we are receiving the output, add it as a "received" entry
770 if (fIsMine & filter)
771 listReceived.push_back(make_pair(address, txout.nValue));
776 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
777 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
779 nGenerated = nReceived = nSent = nFee = 0;
781 int64_t allGeneratedImmature, allGeneratedMature, allFee;
782 allGeneratedImmature = allGeneratedMature = allFee = 0;
783 string strSentAccount;
784 list<pair<CTxDestination, int64_t> > listReceived;
785 list<pair<CTxDestination, int64_t> > listSent;
786 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
788 if (strAccount == "")
789 nGenerated = allGeneratedMature;
790 if (strAccount == strSentAccount)
792 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
797 LOCK(pwallet->cs_wallet);
798 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
800 if (pwallet->mapAddressBook.count(r.first))
802 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
803 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
804 nReceived += r.second;
806 else if (strAccount.empty())
808 nReceived += r.second;
814 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
818 const int COPY_DEPTH = 3;
819 if (SetMerkleBranch() < COPY_DEPTH)
821 vector<uint256> vWorkQueue;
822 BOOST_FOREACH(const CTxIn& txin, vin)
823 vWorkQueue.push_back(txin.prevout.hash);
825 // This critsect is OK because txdb is already open
827 LOCK(pwallet->cs_wallet);
828 map<uint256, const CMerkleTx*> mapWalletPrev;
829 set<uint256> setAlreadyDone;
830 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
832 uint256 hash = vWorkQueue[i];
833 if (setAlreadyDone.count(hash))
835 setAlreadyDone.insert(hash);
838 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
839 if (mi != pwallet->mapWallet.end())
842 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
843 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
845 else if (mapWalletPrev.count(hash))
847 tx = *mapWalletPrev[hash];
849 else if (!fClient && txdb.ReadDiskTx(hash, tx))
855 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
859 int nDepth = tx.SetMerkleBranch();
860 vtxPrev.push_back(tx);
862 if (nDepth < COPY_DEPTH)
864 BOOST_FOREACH(const CTxIn& txin, tx.vin)
865 vWorkQueue.push_back(txin.prevout.hash);
871 reverse(vtxPrev.begin(), vtxPrev.end());
874 bool CWalletTx::WriteToDisk()
876 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
879 // Scan the block chain (starting in pindexStart) for transactions
880 // from or to us. If fUpdate is true, found transactions that already
881 // exist in the wallet will be updated.
882 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
886 CBlockIndex* pindex = pindexStart;
892 block.ReadFromDisk(pindex, true);
893 BOOST_FOREACH(CTransaction& tx, block.vtx)
895 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
898 pindex = pindex->pnext;
904 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
907 tx.ReadFromDisk(COutPoint(hashTx, 0));
908 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
913 void CWallet::ReacceptWalletTransactions()
921 vector<CDiskTxPos> vMissingTx;
922 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
924 CWalletTx& wtx = item.second;
925 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
929 bool fUpdated = false;
930 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
932 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
933 if (txindex.vSpent.size() != wtx.vout.size())
935 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
938 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
942 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
946 vMissingTx.push_back(txindex.vSpent[i]);
951 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
958 // Re-accept any txes of ours that aren't already in a block
959 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
960 wtx.AcceptWalletTransaction(txdb, false);
963 if (!vMissingTx.empty())
965 // TODO: optimize this to scan just part of the block chain?
966 if (ScanForWalletTransactions(pindexGenesisBlock))
967 fRepeat = true; // Found missing transactions: re-do re-accept.
972 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
974 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
976 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
978 uint256 hash = tx.GetHash();
979 if (!txdb.ContainsTx(hash))
980 RelayTransaction((CTransaction)tx, hash);
983 if (!(IsCoinBase() || IsCoinStake()))
985 uint256 hash = GetHash();
986 if (!txdb.ContainsTx(hash))
988 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
989 RelayTransaction((CTransaction)*this, hash);
994 void CWalletTx::RelayWalletTransaction()
997 RelayWalletTransaction(txdb);
1000 void CWallet::ResendWalletTransactions()
1002 // Do this infrequently and randomly to avoid giving away
1003 // that these are our transactions.
1004 static int64_t nNextTime;
1005 if (GetTime() < nNextTime)
1007 bool fFirst = (nNextTime == 0);
1008 nNextTime = GetTime() + GetRand(30 * 60);
1012 // Only do it if there's been a new block since last time
1013 static int64_t nLastTime;
1014 if (nTimeBestReceived < nLastTime)
1016 nLastTime = GetTime();
1018 // Rebroadcast any of our txes that aren't in a block yet
1019 printf("ResendWalletTransactions()\n");
1023 // Sort them in chronological order
1024 multimap<unsigned int, CWalletTx*> mapSorted;
1025 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1027 CWalletTx& wtx = item.second;
1028 // Don't rebroadcast until it's had plenty of time that
1029 // it should have gotten in already by now.
1030 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1031 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1033 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1035 CWalletTx& wtx = *item.second;
1036 if (wtx.CheckTransaction())
1037 wtx.RelayWalletTransaction(txdb);
1039 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1049 //////////////////////////////////////////////////////////////////////////////
1055 int64_t CWallet::GetBalance() const
1060 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1062 const CWalletTx* pcoin = &(*it).second;
1063 if (pcoin->IsTrusted())
1064 nTotal += pcoin->GetAvailableCredit();
1071 int64_t CWallet::GetWatchOnlyBalance() const
1076 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1078 const CWalletTx* pcoin = &(*it).second;
1079 if (pcoin->IsTrusted())
1080 nTotal += pcoin->GetAvailableWatchCredit();
1087 int64_t CWallet::GetUnconfirmedBalance() const
1092 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1094 const CWalletTx* pcoin = &(*it).second;
1095 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1096 nTotal += pcoin->GetAvailableCredit();
1102 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1107 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1109 const CWalletTx* pcoin = &(*it).second;
1110 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1111 nTotal += pcoin->GetAvailableWatchCredit();
1117 int64_t CWallet::GetImmatureBalance() const
1122 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1124 const CWalletTx* pcoin = &(*it).second;
1125 nTotal += pcoin->GetImmatureCredit();
1131 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1136 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1138 const CWalletTx* pcoin = &(*it).second;
1139 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1145 // populate vCoins with vector of spendable COutputs
1146 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1152 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1154 const CWalletTx* pcoin = &(*it).second;
1156 if (!pcoin->IsFinal())
1159 if (fOnlyConfirmed && !pcoin->IsTrusted())
1162 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1165 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1168 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1169 isminetype mine = IsMine(pcoin->vout[i]);
1170 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1171 pcoin->vout[i].nValue >= nMinimumInputValue &&
1172 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1174 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1181 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1187 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1189 const CWalletTx* pcoin = &(*it).second;
1191 if (!pcoin->IsFinal())
1194 if(pcoin->GetDepthInMainChain() < nConf)
1197 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1198 isminetype mine = IsMine(pcoin->vout[i]);
1200 // ignore coin if it was already spent or we don't own it
1201 if (pcoin->IsSpent(i) || mine == MINE_NO)
1204 // if coin value is between required limits then add new item to vector
1205 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1206 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1212 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1213 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1215 vector<char> vfIncluded;
1217 vfBest.assign(vValue.size(), true);
1218 nBest = nTotalLower;
1220 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1222 vfIncluded.assign(vValue.size(), false);
1224 bool fReachedTarget = false;
1225 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1227 for (unsigned int i = 0; i < vValue.size(); i++)
1229 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1231 nTotal += vValue[i].first;
1232 vfIncluded[i] = true;
1233 if (nTotal >= nTargetValue)
1235 fReachedTarget = true;
1239 vfBest = vfIncluded;
1241 nTotal -= vValue[i].first;
1242 vfIncluded[i] = false;
1250 int64_t CWallet::GetStake() const
1254 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1256 const CWalletTx* pcoin = &(*it).second;
1257 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1258 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1263 int64_t CWallet::GetWatchOnlyStake() const
1267 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1269 const CWalletTx* pcoin = &(*it).second;
1270 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1271 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1276 int64_t CWallet::GetNewMint() const
1280 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1282 const CWalletTx* pcoin = &(*it).second;
1283 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1284 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1289 int64_t CWallet::GetWatchOnlyNewMint() const
1293 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1295 const CWalletTx* pcoin = &(*it).second;
1296 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1297 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1302 bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1304 setCoinsRet.clear();
1307 // List of values less than target
1308 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1309 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1310 coinLowestLarger.second.first = NULL;
1311 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1312 int64_t nTotalLower = 0;
1314 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1316 BOOST_FOREACH(const COutput &output, vCoins)
1318 if (!output.fSpendable)
1321 const CWalletTx *pcoin = output.tx;
1323 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1328 // Follow the timestamp rules
1329 if (pcoin->nTime > nSpendTime)
1332 int64_t n = pcoin->vout[i].nValue;
1334 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1336 if (n == nTargetValue)
1338 setCoinsRet.insert(coin.second);
1339 nValueRet += coin.first;
1342 else if (n < nTargetValue + CENT)
1344 vValue.push_back(coin);
1347 else if (n < coinLowestLarger.first)
1349 coinLowestLarger = coin;
1353 if (nTotalLower == nTargetValue)
1355 for (unsigned int i = 0; i < vValue.size(); ++i)
1357 setCoinsRet.insert(vValue[i].second);
1358 nValueRet += vValue[i].first;
1363 if (nTotalLower < nTargetValue)
1365 if (coinLowestLarger.second.first == NULL)
1367 setCoinsRet.insert(coinLowestLarger.second);
1368 nValueRet += coinLowestLarger.first;
1372 // Solve subset sum by stochastic approximation
1373 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1374 vector<char> vfBest;
1377 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1378 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1379 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1381 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1382 // or the next bigger coin is closer), return the bigger coin
1383 if (coinLowestLarger.second.first &&
1384 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1386 setCoinsRet.insert(coinLowestLarger.second);
1387 nValueRet += coinLowestLarger.first;
1390 for (unsigned int i = 0; i < vValue.size(); i++)
1393 setCoinsRet.insert(vValue[i].second);
1394 nValueRet += vValue[i].first;
1397 if (fDebug && GetBoolArg("-printpriority"))
1400 printf("SelectCoins() best subset: ");
1401 for (unsigned int i = 0; i < vValue.size(); i++)
1403 printf("%s ", FormatMoney(vValue[i].first).c_str());
1404 printf("total %s\n", FormatMoney(nBest).c_str());
1411 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1413 vector<COutput> vCoins;
1414 AvailableCoins(vCoins, true, coinControl);
1416 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1417 if (coinControl && coinControl->HasSelected())
1419 BOOST_FOREACH(const COutput& out, vCoins)
1423 nValueRet += out.tx->vout[out.i].nValue;
1424 setCoinsRet.insert(make_pair(out.tx, out.i));
1426 return (nValueRet >= nTargetValue);
1429 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1430 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1431 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1434 // Select some coins without random shuffle or best subset approximation
1435 bool CWallet::SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1437 vector<COutput> vCoins;
1438 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1440 setCoinsRet.clear();
1443 BOOST_FOREACH(COutput output, vCoins)
1445 if(!output.fSpendable)
1447 const CWalletTx *pcoin = output.tx;
1450 // Ignore immature coins
1451 if (pcoin->GetBlocksToMaturity() > 0)
1454 // Stop if we've chosen enough inputs
1455 if (nValueRet >= nTargetValue)
1458 // Follow the timestamp rules
1459 if (pcoin->nTime > nSpendTime)
1462 int64_t n = pcoin->vout[i].nValue;
1464 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1466 if (n >= nTargetValue)
1468 // If input value is greater or equal to target then simply insert
1469 // it into the current subset and exit
1470 setCoinsRet.insert(coin.second);
1471 nValueRet += coin.first;
1474 else if (n < nTargetValue + CENT)
1476 setCoinsRet.insert(coin.second);
1477 nValueRet += coin.first;
1484 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1487 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1493 if (vecSend.empty() || nValue < 0)
1496 wtxNew.BindWallet(this);
1499 LOCK2(cs_main, cs_wallet);
1500 // txdb must be opened before the mapWallet lock
1503 nFeeRet = nTransactionFee;
1507 wtxNew.vout.clear();
1508 wtxNew.fFromMe = true;
1510 int64_t nTotalValue = nValue + nFeeRet;
1511 double dPriority = 0;
1512 // vouts to the payees
1513 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1514 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1516 // Choose coins to use
1517 set<pair<const CWalletTx*,unsigned int> > setCoins;
1518 int64_t nValueIn = 0;
1519 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1521 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1523 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1524 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1527 int64_t nChange = nValueIn - nValue - nFeeRet;
1528 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1529 // or until nChange becomes zero
1530 // NOTE: this depends on the exact behaviour of GetMinFee
1531 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1533 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1535 int64_t nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1536 nChange -= nMoveToFee;
1537 nFeeRet += nMoveToFee;
1540 // sub-cent change is moved to fee
1541 if (nChange > 0 && nChange < CENT)
1550 // Fill a vout to ourself
1551 // TODO: pass in scriptChange instead of reservekey so
1552 // change transaction isn't always pay-to-bitcoin-address
1553 CScript scriptChange;
1555 // coin control: send change to custom address
1556 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1557 scriptChange.SetDestination(coinControl->destChange);
1559 // no coin control: send change to newly generated address
1562 // Note: We use a new key here to keep it from being obvious which side is the change.
1563 // The drawback is that by not reusing a previous key, the change may be lost if a
1564 // backup is restored, if the backup doesn't have the new private key for the change.
1565 // If we reused the old key, it would be possible to add code to look for and
1566 // rediscover unknown transactions that were written with keys of ours to recover
1567 // post-backup change.
1569 // Reserve a new key pair from key pool
1570 CPubKey vchPubKey = reservekey.GetReservedKey();
1572 scriptChange.SetDestination(vchPubKey.GetID());
1575 // Insert change txn at random position:
1576 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1577 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1580 reservekey.ReturnKey();
1583 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1584 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1588 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1589 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1593 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1594 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1596 dPriority /= nBytes;
1598 // Check that enough fee is included
1599 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1600 bool fAllowFree = CTransaction::AllowFree(dPriority);
1602 // Disable free transactions until 1 July 2014
1603 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1608 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1610 if (nFeeRet < max(nPayFee, nMinFee))
1612 nFeeRet = max(nPayFee, nMinFee);
1616 // Fill vtxPrev by copying from previous transactions vtxPrev
1617 wtxNew.AddSupportingTransactions(txdb);
1618 wtxNew.fTimeReceivedIsTxTime = true;
1627 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1629 vector< pair<CScript, int64_t> > vecSend;
1630 vecSend.push_back(make_pair(scriptPubKey, nValue));
1631 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1634 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1636 int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime());
1638 // If time weight is lower or equal to zero then weight is zero.
1639 if (nTimeWeight <= 0)
1645 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1646 nWeight = bnCoinDayWeight.getuint64();
1650 // NovaCoin: get current stake miner statistics
1651 void CWallet::GetStakeStats(float &nKernelsRate, float &nCoinDaysRate)
1653 static uint64_t nLastKernels = 0, nLastCoinDays = 0;
1654 static float nLastKernelsRate = 0, nLastCoinDaysRate = 0;
1655 static int64_t nLastTime = GetTime();
1657 if (nKernelsTried < nLastKernels)
1662 nLastTime = GetTime();
1665 int64_t nInterval = GetTime() - nLastTime;
1666 //if (nKernelsTried > 1000 && nInterval > 5)
1669 nKernelsRate = nLastKernelsRate = ( nKernelsTried - nLastKernels ) / (float) nInterval;
1670 nCoinDaysRate = nLastCoinDaysRate = ( nCoinDaysTried - nLastCoinDays ) / (float) nInterval;
1672 nLastKernels = nKernelsTried;
1673 nLastCoinDays = nCoinDaysTried;
1674 nLastTime = GetTime();
1678 nKernelsRate = nLastKernelsRate;
1679 nCoinDaysRate = nLastCoinDaysRate;
1683 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1685 int64_t nBalance = GetBalance();
1687 if (nAmount > nBalance)
1691 int64_t nValueIn = 0;
1692 set<pair<const CWalletTx*,unsigned int> > setCoins;
1694 // Simple coins selection - no randomization
1695 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1698 if (setCoins.empty())
1702 vector<const CWalletTx*> vwtxPrev;
1704 // Reserve a new key pair from key pool
1705 CReserveKey reservekey(this);
1706 CPubKey vchPubKey = reservekey.GetReservedKey();
1709 CScript scriptOutput;
1710 scriptOutput.SetDestination(vchPubKey.GetID());
1713 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1716 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1718 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1720 // Add current coin to inputs list and add its credit to transaction output
1721 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1722 wtxNew.vout[0].nValue += nCredit;
1723 vwtxPrev.push_back(pcoin.first);
1726 // Replaced with estimation for performance purposes
1728 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1729 const CWalletTx *txin = vwtxPrev[i];
1731 // Sign scripts to get actual transaction size for fee calculation
1732 if (!SignSignature(*this, *txin, wtxNew, i))
1737 // Assuming that average scriptsig size is 110 bytes
1738 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1739 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1741 double dFinalPriority = dWeight /= nBytes;
1742 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1744 // Get actual transaction fee according to its estimated size and priority
1745 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1747 // Prepare transaction for commit if sum is enough ot its size is too big
1748 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1750 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1752 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1753 const CWalletTx *txin = vwtxPrev[i];
1756 if (!SignSignature(*this, *txin, wtxNew, i))
1760 // Try to commit, return false on failure
1761 if (!CommitTransaction(wtxNew, reservekey))
1764 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1766 dWeight = 0; // Reset all temporary values
1769 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1773 // Create transactions if there are some unhandled coins left
1774 if (wtxNew.vout[0].nValue > 0) {
1775 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1777 double dFinalPriority = dWeight /= nBytes;
1778 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1780 // Get actual transaction fee according to its size and priority
1781 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1783 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1785 if (wtxNew.vout[0].nValue <= 0)
1788 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1789 const CWalletTx *txin = vwtxPrev[i];
1791 // Sign all scripts again
1792 if (!SignSignature(*this, *txin, wtxNew, i))
1796 // Try to commit, return false on failure
1797 if (!CommitTransaction(wtxNew, reservekey))
1800 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1807 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CTransaction& txNew, CKey& key)
1809 // The following combine threshold is important to security
1810 // Should not be adjusted if you don't understand the consequences
1811 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1813 CBigNum bnTargetPerCoinDay;
1814 bnTargetPerCoinDay.SetCompact(nBits);
1819 // Mark coin stake transaction
1820 CScript scriptEmpty;
1821 scriptEmpty.clear();
1822 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1824 // Choose coins to use
1825 int64_t nBalance = GetBalance();
1826 int64_t nReserveBalance = 0;
1828 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1829 return error("CreateCoinStake : invalid reserve balance amount");
1831 if (nBalance <= nReserveBalance)
1834 vector<const CWalletTx*> vwtxPrev;
1838 LOCK2(cs_main, cs_wallet);
1839 // Cache outputs unless best block or wallet transaction set changed
1840 if (!fCoinsDataActual)
1843 int64_t nValueIn = 0;
1845 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1848 if (setCoins.empty())
1854 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1856 // Load transaction index item
1857 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1860 // Read block header
1861 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1864 uint64_t nStakeModifier = 0;
1865 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1869 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1870 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1873 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1878 printf("Stake miner: %" PRIszu " meta items loaded for %" PRIszu " coins\n", mapMeta.size(), setCoins.size());
1880 fCoinsDataActual = true;
1886 int64_t nCredit = 0;
1887 CScript scriptPubKeyKernel;
1889 KernelSearchSettings settings;
1890 settings.nBits = nBits;
1891 settings.nTime = txNew.nTime;
1892 settings.nOffset = 0;
1893 settings.nLimit = mapMeta.size();
1894 settings.nSearchInterval = nSearchInterval;
1896 unsigned int nTimeTx, nBlockTime;
1897 COutPoint prevoutStake;
1898 CoinsSet::value_type kernelcoin;
1900 if (ScanForStakeKernelHash(mapMeta, settings, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1903 if (fDebug && GetBoolArg("-printcoinstake"))
1904 printf("CreateCoinStake : kernel found\n");
1905 vector<valtype> vSolutions;
1906 txnouttype whichType;
1907 CScript scriptPubKeyOut;
1908 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1909 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1911 if (fDebug && GetBoolArg("-printcoinstake"))
1912 printf("CreateCoinStake : failed to parse kernel\n");
1915 if (fDebug && GetBoolArg("-printcoinstake"))
1916 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1917 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1919 if (fDebug && GetBoolArg("-printcoinstake"))
1920 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1921 return false; // only support pay to public key and pay to address
1923 if (whichType == TX_PUBKEYHASH) // pay to address type
1925 // convert to pay to public key type
1926 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1928 if (fDebug && GetBoolArg("-printcoinstake"))
1929 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1930 return false; // unable to find corresponding public key
1932 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1934 if (whichType == TX_PUBKEY)
1936 valtype& vchPubKey = vSolutions[0];
1937 if (!keystore.GetKey(Hash160(vchPubKey), key))
1939 if (fDebug && GetBoolArg("-printcoinstake"))
1940 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1941 return false; // unable to find corresponding public key
1943 if (key.GetPubKey() != vchPubKey)
1945 if (fDebug && GetBoolArg("-printcoinstake"))
1946 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1947 return false; // keys mismatch
1950 scriptPubKeyOut = scriptPubKeyKernel;
1953 txNew.nTime = nTimeTx;
1954 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1955 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1956 vwtxPrev.push_back(kernelcoin.first);
1957 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1959 if (GetWeight((int64_t)nBlockTime, (int64_t)txNew.nTime) < nStakeMaxAge)
1960 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1961 if (fDebug && GetBoolArg("-printcoinstake"))
1962 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1965 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1968 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1969 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1972 CoinsSet::value_type pcoin = meta_item->second.first.second;
1974 // Attempt to add more inputs
1975 // Only add coins of the same key/address as kernel
1976 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1977 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1979 int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
1981 // Stop adding more inputs if already too many inputs
1982 if (txNew.vin.size() >= 100)
1984 // Stop adding more inputs if value is already pretty significant
1985 if (nCredit > nCombineThreshold)
1987 // Stop adding inputs if reached reserve limit
1988 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1990 // Do not add additional significant input
1991 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1993 // Do not add input that is still too young
1994 if (nTimeWeight < nStakeMaxAge)
1997 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1998 nCredit += pcoin.first->vout[pcoin.second].nValue;
1999 vwtxPrev.push_back(pcoin.first);
2003 // Calculate coin age reward
2007 if (!txNew.GetCoinAge(txdb, nCoinAge))
2008 return error("CreateCoinStake : failed to calculate coin age");
2010 int64_t nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2011 // Refuse to create mint that has zero or negative reward
2018 int64_t nMinFee = 0;
2021 // Set output amount
2022 if (txNew.vout.size() == 3)
2024 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2025 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2028 txNew.vout[1].nValue = nCredit - nMinFee;
2032 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2034 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2035 return error("CreateCoinStake : failed to sign coinstake");
2039 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2040 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2041 return error("CreateCoinStake : exceeded coinstake size limit");
2043 // Check enough fee is paid
2044 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2046 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2047 continue; // try signing again
2051 if (fDebug && GetBoolArg("-printfee"))
2052 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2057 // Successfully generated coinstake
2062 // Call after CreateTransaction unless you want to abort
2063 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2066 LOCK2(cs_main, cs_wallet);
2067 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2069 // This is only to keep the database open to defeat the auto-flush for the
2070 // duration of this scope. This is the only place where this optimization
2071 // maybe makes sense; please don't do it anywhere else.
2072 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2074 // Take key pair from key pool so it won't be used again
2075 reservekey.KeepKey();
2077 // Add tx to wallet, because if it has change it's also ours,
2078 // otherwise just for transaction history.
2079 AddToWallet(wtxNew);
2081 // Mark old coins as spent
2082 set<CWalletTx*> setCoins;
2083 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2085 CWalletTx &coin = mapWallet[txin.prevout.hash];
2086 coin.BindWallet(this);
2087 coin.MarkSpent(txin.prevout.n);
2089 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2090 vMintingWalletUpdated.push_back(coin.GetHash());
2097 // Track how many getdata requests our transaction gets
2098 mapRequestCount[wtxNew.GetHash()] = 0;
2101 if (!wtxNew.AcceptToMemoryPool())
2103 // This must not fail. The transaction has already been signed and recorded.
2104 printf("CommitTransaction() : Error: Transaction not valid");
2107 wtxNew.RelayWalletTransaction();
2115 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2117 CReserveKey reservekey(this);
2118 int64_t nFeeRequired;
2122 string strError = _("Error: Wallet locked, unable to create transaction ");
2123 printf("SendMoney() : %s", strError.c_str());
2126 if (fWalletUnlockMintOnly)
2128 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2129 printf("SendMoney() : %s", strError.c_str());
2132 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2135 if (nValue + nFeeRequired > GetBalance())
2136 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());
2138 strError = _("Error: Transaction creation failed ");
2139 printf("SendMoney() : %s", strError.c_str());
2143 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2146 if (!CommitTransaction(wtxNew, reservekey))
2147 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.");
2154 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2158 return _("Invalid amount");
2159 if (nValue + nTransactionFee > GetBalance())
2160 return _("Insufficient funds");
2162 // Parse Bitcoin address
2163 CScript scriptPubKey;
2164 scriptPubKey.SetDestination(address);
2166 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2172 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2176 fFirstRunRet = false;
2177 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2178 if (nLoadWalletRet == DB_NEED_REWRITE)
2180 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2183 // Note: can't top-up keypool here, because wallet is locked.
2184 // User will be prompted to unlock wallet the next operation
2185 // the requires a new key.
2189 if (nLoadWalletRet != DB_LOAD_OK)
2190 return nLoadWalletRet;
2191 fFirstRunRet = !vchDefaultKey.IsValid();
2193 NewThread(ThreadFlushWalletDB, &strWalletFile);
2198 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2200 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2201 mapAddressBook[address] = strName;
2202 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2205 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2208 bool CWallet::DelAddressBookName(const CTxDestination& address)
2210 mapAddressBook.erase(address);
2211 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2214 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2218 void CWallet::PrintWallet(const CBlock& block)
2222 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2224 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2225 printf(" mine: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2227 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2229 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2230 printf(" stake: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2237 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2241 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2242 if (mi != mapWallet.end())
2251 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2255 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2258 vchDefaultKey = vchPubKey;
2262 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2264 if (!pwallet->fFileBacked)
2266 strWalletFileOut = pwallet->strWalletFile;
2271 // Mark old keypool keys as used,
2272 // and generate all new keys
2274 bool CWallet::NewKeyPool()
2278 CWalletDB walletdb(strWalletFile);
2279 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2280 walletdb.ErasePool(nIndex);
2286 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
2287 for (int i = 0; i < nKeys; i++)
2289 int64_t nIndex = i+1;
2290 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2291 setKeyPool.insert(nIndex);
2293 printf("CWallet::NewKeyPool wrote %" PRId64 " new keys\n", nKeys);
2298 bool CWallet::TopUpKeyPool(unsigned int nSize)
2306 CWalletDB walletdb(strWalletFile);
2309 unsigned int nTargetSize;
2311 nTargetSize = nSize;
2313 nTargetSize = max<unsigned int>(GetArg("-keypool", 100), 0LL);
2315 while (setKeyPool.size() < (nTargetSize + 1))
2318 if (!setKeyPool.empty())
2319 nEnd = *(--setKeyPool.end()) + 1;
2320 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2321 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2322 setKeyPool.insert(nEnd);
2323 printf("keypool added key %" PRId64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2329 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2332 keypool.vchPubKey = CPubKey();
2339 // Get the oldest key
2340 if(setKeyPool.empty())
2343 CWalletDB walletdb(strWalletFile);
2345 nIndex = *(setKeyPool.begin());
2346 setKeyPool.erase(setKeyPool.begin());
2347 if (!walletdb.ReadPool(nIndex, keypool))
2348 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2349 if (!HaveKey(keypool.vchPubKey.GetID()))
2350 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2351 assert(keypool.vchPubKey.IsValid());
2352 if (fDebug && GetBoolArg("-printkeypool"))
2353 printf("keypool reserve %" PRId64 "\n", nIndex);
2357 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2360 LOCK2(cs_main, cs_wallet);
2361 CWalletDB walletdb(strWalletFile);
2363 int64_t nIndex = 1 + *(--setKeyPool.end());
2364 if (!walletdb.WritePool(nIndex, keypool))
2365 throw runtime_error("AddReserveKey() : writing added key failed");
2366 setKeyPool.insert(nIndex);
2372 void CWallet::KeepKey(int64_t nIndex)
2374 // Remove from key pool
2377 CWalletDB walletdb(strWalletFile);
2378 walletdb.ErasePool(nIndex);
2381 printf("keypool keep %" PRId64 "\n", nIndex);
2384 void CWallet::ReturnKey(int64_t nIndex)
2386 // Return to key pool
2389 setKeyPool.insert(nIndex);
2392 printf("keypool return %" PRId64 "\n", nIndex);
2395 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2401 ReserveKeyFromKeyPool(nIndex, keypool);
2404 if (fAllowReuse && vchDefaultKey.IsValid())
2406 result = vchDefaultKey;
2409 if (IsLocked()) return false;
2410 result = GenerateNewKey();
2414 result = keypool.vchPubKey;
2419 int64_t CWallet::GetOldestKeyPoolTime()
2423 ReserveKeyFromKeyPool(nIndex, keypool);
2427 return keypool.nTime;
2430 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2432 map<CTxDestination, int64_t> balances;
2436 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2438 CWalletTx *pcoin = &walletEntry.second;
2440 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2443 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2446 int nDepth = pcoin->GetDepthInMainChain();
2447 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2450 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2452 CTxDestination addr;
2453 if (!IsMine(pcoin->vout[i]))
2455 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2458 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2460 if (!balances.count(addr))
2462 balances[addr] += n;
2470 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2472 set< set<CTxDestination> > groupings;
2473 set<CTxDestination> grouping;
2475 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2477 CWalletTx *pcoin = &walletEntry.second;
2479 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2481 // group all input addresses with each other
2482 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2484 CTxDestination address;
2485 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2487 grouping.insert(address);
2490 // group change with input addresses
2491 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2492 if (IsChange(txout))
2494 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2495 CTxDestination txoutAddr;
2496 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2498 grouping.insert(txoutAddr);
2500 groupings.insert(grouping);
2504 // group lone addrs by themselves
2505 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2506 if (IsMine(pcoin->vout[i]))
2508 CTxDestination address;
2509 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2511 grouping.insert(address);
2512 groupings.insert(grouping);
2517 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2518 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2519 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2521 // make a set of all the groups hit by this new group
2522 set< set<CTxDestination>* > hits;
2523 map< CTxDestination, set<CTxDestination>* >::iterator it;
2524 BOOST_FOREACH(CTxDestination address, grouping)
2525 if ((it = setmap.find(address)) != setmap.end())
2526 hits.insert((*it).second);
2528 // merge all hit groups into a new single group and delete old groups
2529 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2530 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2532 merged->insert(hit->begin(), hit->end());
2533 uniqueGroupings.erase(hit);
2536 uniqueGroupings.insert(merged);
2539 BOOST_FOREACH(CTxDestination element, *merged)
2540 setmap[element] = merged;
2543 set< set<CTxDestination> > ret;
2544 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2546 ret.insert(*uniqueGrouping);
2547 delete uniqueGrouping;
2553 // ppcoin: check 'spent' consistency between wallet and txindex
2554 // ppcoin: fix wallet spent state according to txindex
2555 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2558 nBalanceInQuestion = 0;
2561 vector<CWalletTx*> vCoins;
2562 vCoins.reserve(mapWallet.size());
2563 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2564 vCoins.push_back(&(*it).second);
2567 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2569 // Find the corresponding transaction index
2571 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2573 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2575 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2577 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2578 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2580 nBalanceInQuestion += pcoin->vout[n].nValue;
2583 pcoin->MarkUnspent(n);
2584 pcoin->WriteToDisk();
2587 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2589 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2590 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2592 nBalanceInQuestion += pcoin->vout[n].nValue;
2595 pcoin->MarkSpent(n);
2596 pcoin->WriteToDisk();
2602 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2604 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2607 EraseFromWallet(pcoin->GetHash());
2613 // ppcoin: disable transaction (only for coinstake)
2614 void CWallet::DisableTransaction(const CTransaction &tx)
2616 if (!tx.IsCoinStake() || !IsFromMe(tx))
2617 return; // only disconnecting coinstake requires marking input unspent
2620 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2622 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2623 if (mi != mapWallet.end())
2625 CWalletTx& prev = (*mi).second;
2626 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2628 prev.MarkUnspent(txin.prevout.n);
2635 CPubKey CReserveKey::GetReservedKey()
2640 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2642 vchPubKey = keypool.vchPubKey;
2645 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2646 vchPubKey = pwallet->vchDefaultKey;
2649 assert(vchPubKey.IsValid());
2653 void CReserveKey::KeepKey()
2656 pwallet->KeepKey(nIndex);
2658 vchPubKey = CPubKey();
2661 void CReserveKey::ReturnKey()
2664 pwallet->ReturnKey(nIndex);
2666 vchPubKey = CPubKey();
2669 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2673 CWalletDB walletdb(strWalletFile);
2675 LOCK2(cs_main, cs_wallet);
2676 BOOST_FOREACH(const int64_t& id, setKeyPool)
2679 if (!walletdb.ReadPool(id, keypool))
2680 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2681 assert(keypool.vchPubKey.IsValid());
2682 CKeyID keyID = keypool.vchPubKey.GetID();
2683 if (!HaveKey(keyID))
2684 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2685 setAddress.insert(keyID);
2689 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2693 // Only notify UI if this transaction is in this wallet
2694 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2695 if (mi != mapWallet.end())
2697 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2698 vMintingWalletUpdated.push_back(hashTx);
2703 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2704 mapKeyBirth.clear();
2706 // get birth times for keys with metadata
2707 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2708 if (it->second.nCreateTime)
2709 mapKeyBirth[it->first] = it->second.nCreateTime;
2711 // map in which we'll infer heights of other keys
2712 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2713 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2714 std::set<CKeyID> setKeys;
2716 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2717 if (mapKeyBirth.count(keyid) == 0)
2718 mapKeyFirstBlock[keyid] = pindexMax;
2722 // if there are no such keys, we're done
2723 if (mapKeyFirstBlock.empty())
2726 // find first block that affects those keys, if there are any left
2727 std::vector<CKeyID> vAffected;
2728 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2729 // iterate over all wallet transactions...
2730 const CWalletTx &wtx = (*it).second;
2731 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2732 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2733 // ... which are already in a block
2734 int nHeight = blit->second->nHeight;
2735 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2736 // iterate over all their outputs
2737 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2738 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2739 // ... and all their affected keys
2740 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2741 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2742 rit->second = blit->second;
2749 // Extract block timestamps for those keys
2750 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2751 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2754 void CWallet::ClearOrphans()
2756 list<uint256> orphans;
2759 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2761 const CWalletTx *wtx = &(*it).second;
2762 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2764 orphans.push_back(wtx->GetHash());
2768 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2769 EraseFromWallet(*it);